Skip to content

Commit d806ee6

Browse files
committed
parse cmds
1 parent f660217 commit d806ee6

4 files changed

Lines changed: 79 additions & 4 deletions

File tree

cmd/scanner/cmd.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
"encoding/json"
6+
"strings"
7+
)
8+
9+
func parseCmd(cmd string) ([]string, bool) {
10+
var args []string
11+
if err := json.Unmarshal([]byte(cmd), &args); err != nil {
12+
s := bufio.NewScanner(strings.NewReader(cmd))
13+
s.Split(scanWords)
14+
15+
for s.Scan() {
16+
arg := s.Text()
17+
args = append(args, arg)
18+
}
19+
}
20+
21+
return args, len(args) >= 1
22+
}

cmd/scanner/cmd_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package main
2+
3+
import (
4+
"os/exec"
5+
"reflect"
6+
"testing"
7+
)
8+
9+
func Test_parseCmd(t *testing.T) {
10+
type args struct {
11+
cmd string
12+
}
13+
tests := []struct {
14+
name string
15+
args args
16+
want []string
17+
want1 bool
18+
}{
19+
{
20+
name: "string array",
21+
args: args{cmd: `["foo","--bar","haha"]`},
22+
want: []string{"foo", "--bar", "haha"},
23+
want1: true,
24+
},
25+
{
26+
name: "string",
27+
args: args{cmd: "foo --bar haha"},
28+
want: []string{"foo", "--bar", "haha"},
29+
want1: true,
30+
},
31+
{
32+
name: "with quote",
33+
args: args{cmd: `./group --debug --name "haha xixi"`},
34+
want: []string{"./group", "--debug", "--name", `"haha xixi"`},
35+
want1: true,
36+
},
37+
}
38+
for _, tt := range tests {
39+
t.Run(tt.name, func(t *testing.T) {
40+
got, got1 := parseCmd(tt.args.cmd)
41+
if !reflect.DeepEqual(got, tt.want) {
42+
t.Errorf("parseCmd() got = %v, want %v", got, tt.want)
43+
}
44+
if got1 != tt.want1 {
45+
t.Errorf("parseCmd() got1 = %v, want %v", got1, tt.want1)
46+
}
47+
48+
if got1 {
49+
cmd := exec.Command(got[0], got[1:]...)
50+
t.Log(cmd.String())
51+
}
52+
})
53+
}
54+
}

cmd/scanner/log.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ func parseLog(token []byte, log *Entry) {
7373

7474
for k, v := range values {
7575
value := cast.ToString(v)
76-
// value = removeSurroundingQuotes(value)
7776

7877
switch k {
7978
case fieldNameLevel:

cmd/scanner/main.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"bytes"
66
"context"
77
"encoding/base64"
8-
"encoding/json"
98
"flag"
109
"io"
1110
"os"
@@ -43,8 +42,9 @@ func main() {
4342

4443
var input io.Reader = os.Stdin
4544

46-
var args []string
47-
if _ = json.Unmarshal([]byte(*cmd), &args); len(args) > 0 {
45+
if args, ok := parseCmd(*cmd); ok {
46+
logrus.Infoln("scan:", args)
47+
4848
pr, pw, err := os.Pipe()
4949
if err != nil {
5050
logrus.Panicln("os.Pipe", err)

0 commit comments

Comments
 (0)