Skip to content

Commit

Permalink
relax whitespace rules when parsing parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
icholy committed Nov 4, 2024
1 parent afecfbf commit 8fa4da0
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
34 changes: 30 additions & 4 deletions internal/param/param.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func Parse(s string) ([]Param, error) {
var pp []Param
br := bufio.NewReader(strings.NewReader(s))
for i := 0; true; i++ {
// skip whitespace
_ = skipWhite(br)
// see if there's more to read
if _, err := br.Peek(1); err == io.EOF {
break
Expand Down Expand Up @@ -110,21 +112,37 @@ func parseString(br *bufio.Reader) (string, error) {
return string(s), nil
}

func skipComma(br *bufio.Reader) error {
func skipWhite(br *bufio.Reader) error {
for {
b, err := br.ReadByte()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
if b != ' ' && b != ',' {
if b != ' ' {
return br.UnreadByte()
}
}
}

func parseParam(br *bufio.Reader, first bool) (Param, error) {
// skip whitespace
if err := skipWhite(br); err != nil {
return Param{}, err
}
if !first {
if err := skipComma(br); err != nil {
// read the comma separator
comma, err := br.ReadByte()
if err != nil {
return Param{}, err
}
if comma != ',' {
return Param{}, fmt.Errorf("expected ',', got '%c'", comma)
}
// skip whitespace
if err := skipWhite(br); err != nil {
return Param{}, err
}
}
Expand All @@ -133,13 +151,21 @@ func parseParam(br *bufio.Reader, first bool) (Param, error) {
if err != nil {
return Param{}, err
}
// skip whitespace
if err := skipWhite(br); err != nil {
return Param{}, err
}
// read the equals sign
eq, err := br.ReadByte()
if err != nil {
return Param{}, err
}
if eq != '=' {
return Param{}, fmt.Errorf("expected '=', got %c", eq)
return Param{}, fmt.Errorf("expected '=', got '%c'", eq)
}
// skip whitespace
if err := skipWhite(br); err != nil {
return Param{}, err
}
// read the value
var value string
Expand Down
14 changes: 13 additions & 1 deletion internal/param/param_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
func TestParam(t *testing.T) {
tests := []struct {
input string
output string
err string
params []Param
}{
Expand Down Expand Up @@ -84,6 +85,13 @@ func TestParam(t *testing.T) {
{Key: "key", Value: "Hello, 世界", Quote: true},
},
},
{
input: " key = value ",
output: "key=value",
params: []Param{
{Key: "key", Value: "value"},
},
},
}
for i, tt := range tests {
tt := tt
Expand All @@ -101,7 +109,11 @@ func TestParam(t *testing.T) {
if tt.err != "" {
return
}
assert.DeepEqual(t, Format(tt.params...), tt.input)
output := tt.output
if output == "" {
output = tt.input
}
assert.DeepEqual(t, Format(tt.params...), output)
})
})
}
Expand Down

0 comments on commit 8fa4da0

Please sign in to comment.