|
1 | 1 | package secrethub |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "bytes" |
5 | 4 | "fmt" |
6 | | - "io" |
7 | 5 | "io/ioutil" |
| 6 | + "os" |
8 | 7 | "regexp" |
9 | 8 | "strings" |
10 | 9 |
|
@@ -36,25 +35,30 @@ func (cmd *MigrateConfigTemplatesCommand) Run() error { |
36 | 35 | return ErrReadFile(filepath, err) |
37 | 36 | } |
38 | 37 |
|
39 | | - replaceCount, err := migrateTemplateTags(bytes.NewBuffer(inFileContents), filepath, refMapping, "{{ %s }}") |
| 38 | + output, replaceCount, err := migrateTemplateTags(string(inFileContents), refMapping, "{{ %s }}") |
40 | 39 | if err != nil { |
41 | 40 | return err |
42 | 41 | } |
43 | 42 |
|
44 | | - 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) |
45 | 54 | } |
46 | 55 |
|
47 | 56 | return nil |
48 | 57 | } |
49 | 58 |
|
50 | | -func migrateTemplateTags(inFile io.Reader, outFile string, mapping referenceMapping, formatString string) ([]string, error) { |
51 | | - raw, err := ioutil.ReadAll(inFile) |
52 | | - if err != nil { |
53 | | - return nil, ErrReadFile(inFile, err) |
54 | | - } |
55 | | - |
| 59 | +func migrateTemplateTags(inFileContents string, mapping referenceMapping, formatString string) (string, int, error) { |
56 | 60 | var hits, misses []string |
57 | | - output := regexpSecretTemplateTags.ReplaceAllStringFunc(string(raw), func(templateTag string) string { |
| 61 | + output := regexpSecretTemplateTags.ReplaceAllStringFunc(inFileContents, func(templateTag string) string { |
58 | 62 | path := regexpSecretTemplatePath.FindString(templateTag) |
59 | 63 | if path == "" { |
60 | 64 | misses = append(misses, templateTag) |
@@ -85,15 +89,10 @@ func migrateTemplateTags(inFile io.Reader, outFile string, mapping referenceMapp |
85 | 89 | errMsg += "\nDid you specify every possible value for your template variables? E.g. --var varname1=a,b,c,d --var varname2=x,y,z" |
86 | 90 | } |
87 | 91 |
|
88 | | - return nil, fmt.Errorf(errMsg) |
89 | | - } |
90 | | - |
91 | | - err = ioutil.WriteFile(outFile, []byte(output), 0666) |
92 | | - if err != nil { |
93 | | - return nil, err |
| 92 | + return "", 0, fmt.Errorf(errMsg) |
94 | 93 | } |
95 | 94 |
|
96 | | - return hits, nil |
| 95 | + return output, len(hits), nil |
97 | 96 | } |
98 | 97 |
|
99 | 98 | type MigrateConfigTemplatesCommand struct { |
|
0 commit comments