-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshlex.go
More file actions
94 lines (85 loc) · 1.59 KB
/
Copy pathshlex.go
File metadata and controls
94 lines (85 loc) · 1.59 KB
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
package shellshape
import (
"fmt"
"strings"
)
// shelxSplit splits a string into tokens using POSIX shell-like rules.
// It handles single quotes, double quotes, and escape characters.
// Returns an error on unmatched quotes.
func shelxSplit(s string) ([]string, error) {
var tokens []string
var current strings.Builder
inToken := false
inSingle := false
inDouble := false
i := 0
for i < len(s) {
c := s[i]
if inSingle {
if c == '\'' {
inSingle = false
} else {
current.WriteByte(c)
}
i++
continue
}
if inDouble {
if c == '"' {
inDouble = false
} else if c == '\\' && i+1 < len(s) {
next := s[i+1]
// In double quotes, backslash only escapes: $, `, ", \, newline
if next == '$' || next == '`' || next == '"' || next == '\\' || next == '\n' {
current.WriteByte(next)
i += 2
continue
}
current.WriteByte(c)
} else {
current.WriteByte(c)
}
i++
continue
}
// Outside quotes
switch c {
case '\'':
inSingle = true
inToken = true
i++
case '"':
inDouble = true
inToken = true
i++
case '\\':
if i+1 < len(s) {
current.WriteByte(s[i+1])
inToken = true
i += 2
} else {
current.WriteByte(c)
inToken = true
i++
}
case ' ', '\t':
if inToken {
tokens = append(tokens, current.String())
current.Reset()
inToken = false
}
i++
default:
current.WriteByte(c)
inToken = true
i++
}
}
if inSingle || inDouble {
return nil, fmt.Errorf("unmatched quote")
}
if inToken {
tokens = append(tokens, current.String())
}
return tokens, nil
}