-
Notifications
You must be signed in to change notification settings - Fork 12
/
getoken.go
113 lines (94 loc) · 1.73 KB
/
getoken.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright [2020-2021] [guonaihong]
// Apache 2.0
package pcurl
import (
"errors"
"strings"
)
var (
ErrSingleQuotes = errors.New("unquoted single quote")
ErrDoubleQuotes = errors.New("unquoted double quote")
ErrUnknown = errors.New("pcurl:GetArgsToken:unknown error")
)
type Sign int
const (
Unused Sign = iota
DoubleQuotes //双引号
SingleQuotes //单引号
WordEnd
)
// TODO 考虑转义
// TODO 各种换行符号
func GetArgsToken(curlString string) (curl []string, err error) {
var (
sign Sign
needSpace bool
word Sign
)
var buf strings.Builder
for _, b := range curlString {
// 先处理有作用域的符号
if sign == Unused {
switch b {
case '"':
needSpace = true
sign = DoubleQuotes
continue
case '\'':
needSpace = true
sign = SingleQuotes
continue
}
}
// 处理作用域右边的"
if b == '"' {
if sign == DoubleQuotes {
sign = Unused
needSpace = false
continue
}
}
// 处理作用域右边的'
if b == '\'' {
if sign == SingleQuotes {
sign = Unused
needSpace = false
continue
}
}
//
if !needSpace && b == ' ' {
word = WordEnd
continue
}
//fmt.Printf("(%c):%d, %t\n", b, sign, word == WordEnd)
if word == WordEnd {
curl = append(curl, buf.String())
buf.Reset()
//sign = Unused
word = Unused
//needSpace = false
}
buf.WriteRune(b)
}
if buf.Len() > 0 {
curl = append(curl, buf.String())
buf.Reset()
}
if sign != Unused {
return nil, toErr(sign)
}
return
}
func toErr(sign Sign) error {
switch sign {
case SingleQuotes:
return ErrSingleQuotes
case DoubleQuotes:
return ErrDoubleQuotes
case Unused:
return nil
default:
return ErrUnknown
}
}