Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions internal/leaf/leaf.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,22 @@ func Parse(content string) (map[string]string, error) {

func unquote(s string) string {
if len(s) >= 2 {
if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {
if s[0] == '\'' && s[len(s)-1] == '\'' {
return s[1 : len(s)-1]
}
if s[0] == '"' && s[len(s)-1] == '"' {
// Decode only the escapes emitted by quote. Other backslash
// sequences (such as literal \n in a path) stay untouched.
var value strings.Builder
for index := 1; index < len(s)-1; index++ {
if s[index] == '\\' && index+1 < len(s)-1 &&
(s[index+1] == '\\' || s[index+1] == '"') {
index++
}
value.WriteByte(s[index])
}
return value.String()
}
}
return s
}
Expand Down Expand Up @@ -129,8 +142,8 @@ func quote(v string) string {
if v == "" {
return v
}
if strings.ContainsAny(v, " \t\"'#\n") {
return `"` + strings.ReplaceAll(v, `"`, `\"`) + `"`
if strings.ContainsAny(v, " \t\"'#\n\\") {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(v) + `"`
}
return v
}
34 changes: 34 additions & 0 deletions internal/leaf/leaf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,37 @@ func TestSerializeWithIgnored(t *testing.T) {
t.Fatalf("round trip lost data: %#v", got)
}
}

func TestSerializeQuotedValuesRoundTrip(t *testing.T) {
for _, value := range []string{
`a"b`, `say "hello"`, `C:\Users\name`, `ends with \`,
`literal \n`, `\"`, `single'quote`, " padded ",
} {
t.Run(value, func(t *testing.T) {
for _, ignored := range []bool{false, true} {
values := map[string]string{"SECRET": value}
content := Serialize(values)
if ignored {
content = SerializeWithIgnored(nil, values)
}
got, err := Parse(content)
if err != nil {
t.Fatal(err)
}
if got["SECRET"] != value {
t.Errorf("ignored=%v: got %q, want %q", ignored, got["SECRET"], value)
}
}
})
}
}

func TestParseSingleQuotedBackslashes(t *testing.T) {
got, err := Parse(`SECRET='literal\" and \\'`)
if err != nil {
t.Fatal(err)
}
if got["SECRET"] != `literal\" and \\` {
t.Fatalf("single-quoted value changed: %q", got["SECRET"])
}
}
Loading