improvement: make command-line parsing more robust

This commit is contained in:
Bryan Boreham
2020-06-09 21:21:56 +00:00
parent 70240fc82d
commit 5318498d9a
2 changed files with 12 additions and 6 deletions

View File

@@ -120,13 +120,16 @@ func (e *BillingEmitter) Add(ctx context.Context, rep report.Report, buf []byte)
}
func commandParameter(cmd, flag string) (string, bool) {
if strings.Contains(cmd, flag) {
cmds := strings.SplitAfter(cmd, flag)
aft := strings.Split(cmds[1], " ")
if aft[0] == "" {
return aft[1], true
i := strings.Index(cmd, flag)
if i != -1 {
// here we expect the command looks like `-foo=bar` or `-foo bar`
aft := strings.Fields(cmd[i+len(flag):])
if len(aft) > 0 && len(aft[0]) > 0 {
if aft[0][0] == '=' {
return aft[0][1:], true
}
return aft[0], true
}
return aft[0][1:], true
}
return "", false
}

View File

@@ -15,6 +15,9 @@ func Test_intervalFromCommand(t *testing.T) {
{cmd: "/home/weave/scope --mode=probe --probe-only --probe.kubernetes.role=host --probe.publish.interval=4500ms --probe.spy.interval=10s --probe.docker.bridge=docker0 --probe.docker=true --probe.ebpf.connections=false --probe.conntrack=false https://redacted@cloud.weave.works.", want: "10s", name: "higher-spy-interval"},
{cmd: "/bin/prometheus --config.file=/etc/prometheus/prometheus.yml --web.listen-address=:8080 --storage.tsdb.retention.time=2h --web.enable-lifecycle", want: "", name: "notscope"},
{cmd: "", want: "", name: "blank"},
{cmd: "/home/weave/scope --probe.publish.interval=3s", want: "3s", name: "at-end"},
{cmd: "/home/weave/scope --probe.publish.interval=", want: "", name: "equals-blank"},
{cmd: "/home/weave/scope --probe.publish.interval", want: "", name: "no-value"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {