-
Notifications
You must be signed in to change notification settings - Fork 5
/
parse.go
48 lines (43 loc) · 827 Bytes
/
parse.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
package cmdr
import (
"strings"
"unicode"
)
// Parse parses a string
// resulting into a *Command
func Parse(cmd string) *Command {
var (
cmdStr string
parts []string
args []string
)
parts = parseComplex(cmd)
cmdStr = parts[0]
args = parts[1:len(parts)]
return &Command{
Command: cmdStr,
Args: args,
}
}
// by @jg_19 on https://t.me/go_br
func parseComplex(cmd string) []string {
lastRune := rune(0)
cControl := false
startRune := rune(0)
f := func(c rune) (r bool) {
switch {
case startRune == c:
startRune = 0
r = cControl
case (c == rune('\'') || c == rune('"')) && startRune == 0:
startRune = c
cControl = unicode.IsSpace(lastRune)
r = cControl
default:
r = unicode.IsSpace(c) && startRune == 0
}
lastRune = c
return
}
return strings.FieldsFunc(cmd, f)
}