Skip to content

Commit

Permalink
Add functionality for escaping quote characters.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaholaz committed May 12, 2024
1 parent e77788c commit 7c151c8
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ Foo = "ba"r"
# Gets parsed as "bar"
```

If a string containing double quotes is desired, they can be escaped:
```bash
Foo = "ba\"r"
# Gets parsed as "ba"r"
```

#### Lists of key-values

Often a simple Key => Value mapping is not sufficient, and you want a
Expand Down
9 changes: 8 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,14 @@ func parseVal(rawVal string) (*string, error) {
val = val[:groups[2*2]]
}

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

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 @@ -390,3 +390,27 @@ Could not parse config correctly with wierd syntax correctly.
got: %#v`, want, config)
}
}

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

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

want := Config{
Foo: "hel\"lo",
}
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/escapedquote.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Foo = hel\"lo

0 comments on commit 7c151c8

Please sign in to comment.