Skip to content
This repository has been archived by the owner on Sep 4, 2024. It is now read-only.

Commit

Permalink
client: Fix param parsing when spaces are used
Browse files Browse the repository at this point in the history
Up until now we only recognized dynamic parameters passed in the
following format:

    $ mistry -- --foo=bar --a=b --b=c

With this patch, the above can also be written as:
the above:

    $ mistry -- --foo bar --a b --b c

Fixes #23
  • Loading branch information
agis committed Jul 1, 2019
1 parent c1be30e commit f209061
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 11 deletions.
34 changes: 23 additions & 11 deletions cmd/mistry/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,17 +208,7 @@ EXAMPLES:
return fmt.Errorf("invalid transport argument (%v)", transport)
}

// Normalize dynamic arguments by trimming the `--` and
// creating the params map with the result.
var dynamicArgs []string
for _, v := range c.Args() {
dynamicArgs = append(dynamicArgs, strings.TrimLeft(v, "--"))
}
params := make(map[string]string)
for _, v := range dynamicArgs {
arg := strings.Split(v, "=")
params[arg[0]] = arg[1]
}
params := parseDynamicArgs(c.Args())

// Dynamic arguments starting with `@` are considered actual
// files in the filesystem.
Expand Down Expand Up @@ -345,3 +335,25 @@ func isTimeout(err error) bool {
urlErr, ok := err.(*url.Error)
return ok && urlErr.Timeout()
}

func parseDynamicArgs(args cli.Args) map[string]string {
parsed := make(map[string]string)

for i := 0; i < len(args); {
arg := strings.TrimLeft(args[i], "--")

if strings.Contains(arg, "=") {
parts := strings.Split(arg, "=")
parsed[parts[0]] = parts[1]
i++
} else if i+1 < len(args) {
parsed[arg] = args[i+1]
i = i + 2
} else {
i++

}
}

return parsed
}
44 changes: 44 additions & 0 deletions cmd/mistry/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package main

import (
"reflect"
"testing"

"github.com/urfave/cli"
)

func TestParseDynamicArgs(t *testing.T) {
cases := []struct {
In cli.Args
Expected map[string]string
}{
{cli.Args{"--a", "b", "c=d", "e=f", "--g", "h"},
map[string]string{"a": "b", "c": "d", "e": "f", "g": "h"}},

{cli.Args{"a=b", "--@c", "d", "e=f", "--g", "h"},
map[string]string{"a": "b", "@c": "d", "e": "f", "g": "h"}},

{cli.Args{"a=b", "--c", "d"},
map[string]string{"a": "b", "c": "d"}},

{cli.Args{"--a", "b", "@c=d"},
map[string]string{"a": "b", "@c": "d"}},

{cli.Args{"a=b", "c=d"},
map[string]string{"a": "b", "c": "d"}},

{cli.Args{"a", "b", "--c", "d"},
map[string]string{"a": "b", "c": "d"}},

{cli.Args{"--a", "b"}, map[string]string{"a": "b"}},
{cli.Args{"a=b"}, map[string]string{"a": "b"}},
}

for _, c := range cases {
actual := parseDynamicArgs(c.In)

if !reflect.DeepEqual(actual, c.Expected) {
t.Errorf("expected %v, got %v", c.Expected, actual)
}
}
}

0 comments on commit f209061

Please sign in to comment.