Merge pull request #42 from alexquick/feature-sorted-output

Sort output of Marshal/Write
This commit is contained in:
John Barton
2017-09-18 16:32:10 +10:00
committed by GitHub
2 changed files with 9 additions and 4 deletions

View File

@ -21,6 +21,7 @@ import (
"os" "os"
"os/exec" "os/exec"
"regexp" "regexp"
"sort"
"strings" "strings"
) )
@ -165,6 +166,7 @@ func Marshal(envMap map[string]string) (string, error) {
for k, v := range envMap { for k, v := range envMap {
lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v))) lines = append(lines, fmt.Sprintf(`%s="%s"`, k, doubleQuoteEscape(v)))
} }
sort.Strings(lines)
return strings.Join(lines, "\n"), nil return strings.Join(lines, "\n"), nil
} }

View File

@ -348,23 +348,26 @@ func TestWrite(t *testing.T) {
writeAndCompare(`key=va'lu'e`, `key="va'lu'e"`) writeAndCompare(`key=va'lu'e`, `key="va'lu'e"`)
// newlines, backslashes, and some other special chars are escaped // newlines, backslashes, and some other special chars are escaped
writeAndCompare(`foo="$ba\n\r\\r!"`, `foo="\$ba\n\r\\r\!"`) writeAndCompare(`foo="$ba\n\r\\r!"`, `foo="\$ba\n\r\\r\!"`)
// lines should be sorted
writeAndCompare("foo=bar\nbaz=buzz", "baz=\"buzz\"\nfoo=\"bar\"")
} }
func TestRoundtrip(t *testing.T) { func TestRoundtrip(t *testing.T) {
fixtures := []string{"equals.env", "exported.env", "invalid1.env", "plain.env", "quoted.env"} fixtures := []string{"equals.env", "exported.env", "plain.env", "quoted.env"}
for _, fixture := range fixtures { for _, fixture := range fixtures {
fixtureFilename := fmt.Sprintf("fixtures/%s", fixture) fixtureFilename := fmt.Sprintf("fixtures/%s", fixture)
env, err := readFile(fixtureFilename) env, err := readFile(fixtureFilename)
if err != nil { if err != nil {
continue t.Errorf("Expected '%s' to read without error (%v)", fixtureFilename, err)
} }
rep, err := Marshal(env) rep, err := Marshal(env)
if err != nil { if err != nil {
continue t.Errorf("Expected '%s' to Marshal (%v)", fixtureFilename, err)
} }
roundtripped, err := Unmarshal(rep) roundtripped, err := Unmarshal(rep)
if err != nil { if err != nil {
continue t.Errorf("Expected '%s' to Mashal and Unmarshal (%v)", fixtureFilename, err)
} }
if !reflect.DeepEqual(env, roundtripped) { if !reflect.DeepEqual(env, roundtripped) {
t.Errorf("Expected '%s' to roundtrip as '%v', got '%v' instead", fixtureFilename, env, roundtripped) t.Errorf("Expected '%s' to roundtrip as '%v', got '%v' instead", fixtureFilename, env, roundtripped)