Skip to content

Commit

Permalink
Properly handle repeated quotes.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaholaz committed May 13, 2024
1 parent e70d136 commit 48fc1fa
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
18 changes: 12 additions & 6 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,13 +70,19 @@ func parseVal(rawVal string) (*string, error) {
val = val[:groups[2*2]]
}

// Remove all '"', and replace '\"' with '"'
nonEscapedQuotes := regexp.MustCompile(`[^\\]"`)
val = nonEscapedQuotes.ReplaceAllStringFunc(val, func(s string) string { return s[:len(s)-1] })
if val[0] == '"' {
val = val[1:]
var sb strings.Builder
for i, r := range val {
if r == '"' {
continue
}

if val[i] == '\\' && val[i+1] == '"' {
sb.WriteRune('"')
} else {
sb.WriteRune(r)
}
}
val = strings.ReplaceAll(val, `\"`, `"`)
val = sb.String()

return &val, nil
}
Expand Down
24 changes: 24 additions & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -438,3 +438,27 @@ Could not parse config correctly with quotes inside correctly.
got: %#v`, want, config)
}
}

func TestTwoQuote(t *testing.T) {
type Config struct {
Foo string
}

config := Config{
Foo: "",
}
err := LoadConfig("test_configs/twoquotes.cfg", &config)
if err != nil {
t.Fatalf("Could not parse config with escaped quote: %s", err.Error())
}

want := Config{
Foo: "testing",
}
if want != config {
t.Fatalf(`
Could not parse config correctly with quotes inside correctly.
expected: %#v
got: %#v`, want, config)
}
}
1 change: 1 addition & 0 deletions test_configs/twoquotes.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Foo = test""ing

0 comments on commit 48fc1fa

Please sign in to comment.