-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathins_parser.go
63 lines (56 loc) · 1.67 KB
/
ins_parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package pkg
import (
"fmt"
"strings"
)
// install instruction
type InsTriple struct {
First string
Second string
Third string
}
// todo parse multiple space, and `\"`
func ParseIns(insStr string) (ins InsTriple, err error) {
insStr = strings.Trim(insStr, " ")
// parse cmd (the first) of instruction.
cmdAndLater := strings.SplitN(insStr, " ", 2)
if len(cmdAndLater) != 2 && len(cmdAndLater) != 1 {
return ins, fmt.Errorf("syntax error of instruction `%s`", insStr)
} else {
ins.First = cmdAndLater[0]
}
// first only
if len(cmdAndLater) == 1 {
return ins, nil
}
// parse second of instruction.
if strings.HasPrefix(cmdAndLater[1], `"`) {
// example: `CP "../path" "./des" `
secondAndLater := strings.SplitN(cmdAndLater[1][1:], `"`, 2)
// there must at least 2 ", so len must be 2.
if len(secondAndLater) != 2 {
return ins, fmt.Errorf("syntax error of instruction `%s`", insStr)
} else {
ins.Second = strings.TrimSpace(secondAndLater[0])
ins.Third = strings.TrimSpace(secondAndLater[1]) // may with `"`
}
} else {
// example: `CP ../path ./des`, `CP ../path`, `CP ../path "./des"`,
secondAndLater := strings.SplitN(cmdAndLater[1], ` `, 2)
if len(secondAndLater) == 2 {
ins.Second = secondAndLater[0]
ins.Third = secondAndLater[1]
} else if len(secondAndLater) == 1 {
ins.Second = secondAndLater[0]
} else {
return ins, fmt.Errorf("syntax error of instruction `%s`", insStr)
}
}
// parse third
ins.Third = strings.TrimSpace(ins.Third)
if strings.HasPrefix(ins.Third, `"`) && strings.HasSuffix(ins.Third, `"`) {
// it does not process instructions like `echo "hello"`
ins.Third = strings.Trim(ins.Third, `"`)
}
return ins, err
}