From f1c97cb4d5cf89dd4a8a46119163dbab6e8dac31 Mon Sep 17 00:00:00 2001 From: Jonathan Boulle Date: Mon, 11 Aug 2014 18:24:58 -0700 Subject: [PATCH] environment: write new keys in consistent order --- initialize/env_test.go | 2 +- system/env_file.go | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/initialize/env_test.go b/initialize/env_test.go index d5178a5..61d929f 100644 --- a/initialize/env_test.go +++ b/initialize/env_test.go @@ -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 { diff --git a/system/env_file.go b/system/env_file.go index 83521ea..295a599 100644 --- a/system/env_file.go +++ b/system/env_file.go @@ -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 +}