Merge pull request #202 from jonboulle/env

environment: write new keys in consistent order
This commit is contained in:
Jonathan Boulle 2014-08-11 22:40:42 -07:00
commit 735d6c6161
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", "$public_ipv4": "1.2.3.4",
"$private_ipv4": "5.6.7.8", "$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-") dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
if err != nil { if err != nil {

View File

@ -7,6 +7,7 @@ import (
"os" "os"
"path" "path"
"regexp" "regexp"
"sort"
) )
type EnvFile struct { 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, // mergeEnvContents: Update the existing file contents with new values,
// preserving variable ordering and all content this code doesn't understand. // 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 { func mergeEnvContents(old []byte, pending map[string]string) []byte {
var buf bytes.Buffer var buf bytes.Buffer
var match [][]byte 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) fmt.Fprintf(&buf, "%s=%s\n", key, value)
} }
@ -87,3 +89,12 @@ func WriteEnvFile(ef *EnvFile, root string) error {
_, err = WriteFile(ef.File, root) _, err = WriteFile(ef.File, root)
return err 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
}