environment: write new keys in consistent order

This commit is contained in:
Jonathan Boulle 2014-08-11 18:24:58 -07:00
parent 97d5538533
commit f1c97cb4d5
2 changed files with 14 additions and 3 deletions

View File

@ -66,7 +66,7 @@ func TestEnvironmentFile(t *testing.T) {
"$public_ipv4": "1.2.3.4",
"$private_ipv4": "5.6.7.8",
}
expect := "COREOS_PUBLIC_IPV4=1.2.3.4\nCOREOS_PRIVATE_IPV4=5.6.7.8\n"
expect := "COREOS_PRIVATE_IPV4=5.6.7.8\nCOREOS_PUBLIC_IPV4=1.2.3.4\n"
dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
if err != nil {

View File

@ -7,6 +7,7 @@ import (
"os"
"path"
"regexp"
"sort"
)
type EnvFile struct {
@ -24,7 +25,7 @@ var lineLexer = regexp.MustCompile(`(?m)^((?:([a-zA-Z0-9_]+)=)?.*?)\r?\n`)
// mergeEnvContents: Update the existing file contents with new values,
// preserving variable ordering and all content this code doesn't understand.
// All new values are appended to the bottom of the old.
// All new values are appended to the bottom of the old, sorted by key.
func mergeEnvContents(old []byte, pending map[string]string) []byte {
var buf bytes.Buffer
var match [][]byte
@ -44,7 +45,8 @@ func mergeEnvContents(old []byte, pending map[string]string) []byte {
}
}
for key, value := range pending {
for _, key := range keys(pending) {
value := pending[key]
fmt.Fprintf(&buf, "%s=%s\n", key, value)
}
@ -87,3 +89,12 @@ func WriteEnvFile(ef *EnvFile, root string) error {
_, err = WriteFile(ef.File, root)
return err
}
// keys returns the keys of a map in sorted order
func keys(m map[string]string) (s []string) {
for k, _ := range m {
s = append(s, k)
}
sort.Strings(s)
return
}