@@ -2,7 +2,6 @@ package secrethub
22
33import (
44 "fmt"
5- "io"
65 "io/ioutil"
76 "os"
87 "regexp"
@@ -31,31 +30,35 @@ func (cmd *MigrateConfigTemplatesCommand) Run() error {
3130 refMapping .stripSecretHubURIScheme ()
3231
3332 for _ , filepath := range cmd .inFiles {
34- file , err := os . Open (filepath )
33+ inFileContents , err := ioutil . ReadFile (filepath )
3534 if err != nil {
3635 return ErrReadFile (filepath , err )
3736 }
38- defer file .Close ()
3937
40- replaceCount , err := migrateTemplateTags (file , file , refMapping , "{{ %s }}" )
38+ output , replaceCount , err := migrateTemplateTags (string ( inFileContents ) , refMapping , "{{ %s }}" )
4139 if err != nil {
4240 return err
4341 }
4442
45- fmt .Fprintf (cmd .io .Output (), "Updated %s with %d op:// references\n " , filepath , len (replaceCount ))
43+ inFileInfo , err := os .Stat (filepath )
44+ if err != nil {
45+ return ErrReadFile (filepath , err )
46+ }
47+
48+ err = ioutil .WriteFile (filepath , []byte (output ), inFileInfo .Mode ())
49+ if err != nil {
50+ return err
51+ }
52+
53+ fmt .Fprintf (cmd .io .Output (), "Updated %s with %d op:// references\n " , filepath , replaceCount )
4654 }
4755
4856 return nil
4957}
5058
51- func migrateTemplateTags (inFile io.Reader , outFile io.Writer , mapping referenceMapping , formatString string ) ([]string , error ) {
52- raw , err := ioutil .ReadAll (inFile )
53- if err != nil {
54- return nil , ErrReadFile (inFile , err )
55- }
56-
59+ func migrateTemplateTags (inFileContents string , mapping referenceMapping , formatString string ) (string , int , error ) {
5760 var hits , misses []string
58- output := regexpSecretTemplateTags .ReplaceAllStringFunc (string ( raw ) , func (templateTag string ) string {
61+ output := regexpSecretTemplateTags .ReplaceAllStringFunc (inFileContents , func (templateTag string ) string {
5962 path := regexpSecretTemplatePath .FindString (templateTag )
6063 if path == "" {
6164 misses = append (misses , templateTag )
@@ -86,15 +89,10 @@ func migrateTemplateTags(inFile io.Reader, outFile io.Writer, mapping referenceM
8689 errMsg += "\n Did you specify every possible value for your template variables? E.g. --var varname1=a,b,c,d --var varname2=x,y,z"
8790 }
8891
89- return nil , fmt .Errorf (errMsg )
90- }
91-
92- _ , err = io .WriteString (outFile , output )
93- if err != nil {
94- return nil , err
92+ return "" , 0 , fmt .Errorf (errMsg )
9593 }
9694
97- return hits , nil
95+ return output , len ( hits ) , nil
9896}
9997
10098type MigrateConfigTemplatesCommand struct {
0 commit comments