-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalize.go
More file actions
438 lines (395 loc) · 9.81 KB
/
Copy pathnormalize.go
File metadata and controls
438 lines (395 loc) · 9.81 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package shellshape
import (
"regexp"
"strings"
)
// Normalize returns a stable shape for the given bash command.
func Normalize(command string) string {
command = strings.TrimSpace(command)
if command == "" {
return ""
}
command = joinContinuations(command)
command = collapseHeredocs(command)
command = stripComments(command)
command = strings.TrimSpace(command)
if command == "" {
return ""
}
parts := splitTopLevel(command, splitOps)
if len(parts) == 1 && parts[0].sep == "" {
return collapseRepeatedPlaceholders(normalizeSegment(parts[0].text))
}
var rendered []string
lastWasSegment := false
for _, part := range parts {
seg := normalizeSegment(strings.TrimSpace(part.text))
if seg != "" {
rendered = append(rendered, seg)
lastWasSegment = true
}
if part.sep != "" && lastWasSegment {
rendered = append(rendered, part.sep)
lastWasSegment = false
}
}
// Drop trailing separator.
if len(rendered) > 0 {
last := rendered[len(rendered)-1]
for _, op := range splitOps {
if last == op || last == ";" {
rendered = rendered[:len(rendered)-1]
break
}
}
}
out := strings.Join(rendered, " ")
out = strings.TrimSpace(out)
out = collapseWhitespace(out)
out = collapseRepeatedPlaceholders(out)
out = collapseRepeatedSegments(out)
return out
}
// ExecutableOf returns the leading executable name from a shape string.
func ExecutableOf(shape string) string {
if shape == "" {
return ""
}
// Take the first segment (before any operator).
for _, op := range splitOps {
needle := " " + op + " "
if idx := strings.Index(shape, needle); idx != -1 {
shape = shape[:idx]
}
}
tokens := strings.Fields(shape)
i := 0
for i < len(tokens) && IsEnvAssignment(tokens[i]) {
i++
}
if i < len(tokens) {
return tokens[i]
}
return ""
}
// Interpreters that accept inline code via -c / -e / --command.
var interpretersWithCodeFlag = map[string]bool{
"python": true, "python3": true, "node": true, "deno": true,
"bash": true, "sh": true, "zsh": true,
"ruby": true, "perl": true, "lua": true, "php": true,
}
var codeFlags = map[string]bool{"-c": true, "-e": true, "--command": true}
// Shells used as script runners.
var shellScriptRunners = map[string]bool{"bash": true, "sh": true, "zsh": true}
// normalizeSegment routes a single segment to either compound or simple normalization.
func normalizeSegment(seg string) string {
seg = strings.TrimSpace(seg)
if isCompoundCommand(seg) {
return normalizeCompound(seg)
}
return normalizeSingleCommand(seg)
}
func normalizeSingleCommand(seg string) string {
seg = strings.TrimSpace(seg)
if seg == "" {
return ""
}
// Recursively normalize $(...) substitutions.
seg = normalizeSubstitutions(seg)
tokens, err := shelxSplit(seg)
if err != nil {
return fallbackNormalize(seg)
}
if len(tokens) == 0 {
return ""
}
// Strip leading env var assignments.
var envParts []string
i := 0
for i < len(tokens) && IsEnvAssignment(tokens[i]) {
name := tokens[i][:strings.Index(tokens[i], "=")+1]
envParts = append(envParts, name+"<val>")
i++
}
if i >= len(tokens) {
return strings.Join(envParts, " ")
}
exe := tokens[i]
i++
// Absolute-path or tilde-path executables: strip to basename.
// Relative paths (./script.sh, ../bin/run) are left alone.
if (strings.HasPrefix(exe, "/") || strings.HasPrefix(exe, "~")) && strings.Contains(exe, "/") {
parts := strings.Split(exe, "/")
exe = parts[len(parts)-1]
}
// Shell-as-script-runner.
if shellScriptRunners[exe] && i < len(tokens) {
firstArg := tokens[i]
if !strings.HasPrefix(firstArg, "-") && strings.Contains(firstArg, "/") {
parts := strings.Split(firstArg, "/")
exe = parts[len(parts)-1]
i++
} else if !strings.HasPrefix(firstArg, "-") && strings.Contains(firstArg, ".") {
exe = firstArg
i++
}
}
result := append(envParts, exe)
var subcommand string
// Subcommand detection. Leading flags (and their values for handlers
// that opt in with a whitelist) are left for the per-executable handler
// so they can be classified properly.
if hasSubcommands(exe) && i < len(tokens) && isValidSubcommand(exe, tokens[i]) {
subcommand = tokens[i]
result = append(result, tokens[i])
i++
}
// Per-executable handler.
if handler, ok := handlers[exe]; ok {
result = append(result, handler(subcommand, tokens[i:])...)
return strings.Join(result, " ")
}
// Generic per-token classification.
interpWithCode := interpretersWithCodeFlag[exe]
for i < len(tokens) {
tok := tokens[i]
if RedirectConsumeNext[tok] && i+1 < len(tokens) {
placeholder := "<path>"
if tok == "<<<" {
placeholder = "<str>"
}
result = append(result, tok, placeholder)
i += 2
continue
}
if RedirectStandalone[tok] {
result = append(result, tok)
i++
continue
}
if interpWithCode && codeFlags[tok] && i+1 < len(tokens) {
result = append(result, tok, "<code>")
i += 2
continue
}
result = append(result, ClassifyToken(tok))
i++
}
return strings.Join(result, " ")
}
func normalizeSubstitutions(s string) string {
var out strings.Builder
i := 0
// Track outer shell quoting context. Bash does NOT expand $(…) or `…`
// inside single quotes, so the replacement must be skipped there —
// otherwise the emitted `'$(<subshell>)'` wrapper would break the
// containing quotes and cause shlex to split the body into many tokens.
inSingle := false
inDouble := false
for i < len(s) {
c := s[i]
if inSingle {
out.WriteByte(c)
if c == '\'' {
inSingle = false
}
i++
continue
}
if c == '\'' {
out.WriteByte(c)
inSingle = true
i++
continue
}
if c == '"' {
out.WriteByte(c)
inDouble = !inDouble
i++
continue
}
if c == '\\' && i+1 < len(s) {
out.WriteByte(c)
out.WriteByte(s[i+1])
i += 2
continue
}
if c == '`' {
j := i + 1
for j < len(s) && s[j] != '`' {
j++
}
if j < len(s) {
out.WriteString("'$(<subshell>)'")
i = j + 1
continue
}
// Unbalanced: treat as literal.
out.WriteByte(c)
i++
continue
}
if c == '$' && i+1 < len(s) && s[i+1] == '(' {
// Find matching close paren with depth tracking. The inner
// scan has its own local quote state because the subshell body
// is its own shell context.
depth := 1
j := i + 2
localSingle := false
localDouble := false
for j < len(s) && depth > 0 {
cc := s[j]
if localSingle {
if cc == '\'' {
localSingle = false
}
} else if localDouble {
if cc == '"' {
localDouble = false
}
} else {
switch cc {
case '\'':
localSingle = true
case '"':
localDouble = true
case '(':
depth++
case ')':
depth--
if depth == 0 {
break
}
}
}
if depth > 0 {
j++
}
}
if depth == 0 {
inner := s[i+2 : j]
normalizedInner := Normalize(inner)
// Single-quote-wrap so shlex keeps the subshell atomic.
out.WriteString("'$(")
out.WriteString(normalizedInner)
out.WriteString(")'")
i = j + 1
continue
}
// Unbalanced: treat rest as opaque.
out.WriteString(s[i:])
return out.String()
}
out.WriteByte(c)
i++
}
return out.String()
}
// collapseRepeatedPlaceholders collapses runs of 2+ identical <...> placeholders.
var collapsibleRE = regexp.MustCompile(`^<[a-z][-a-z]*>$`)
func collapseRepeatedPlaceholders(shape string) string {
if shape == "" {
return shape
}
tokens := strings.Split(shape, " ")
var out []string
i := 0
for i < len(tokens) {
tok := tokens[i]
if collapsibleRE.MatchString(tok) {
j := i + 1
for j < len(tokens) && tokens[j] == tok {
j++
}
if j-i >= 2 {
out = append(out, tok+"+")
} else {
out = append(out, tok)
}
i = j
} else {
out = append(out, tok)
i++
}
}
return strings.Join(out, " ")
}
// collapseRepeatedSegments collapses consecutive identical segments separated
// by ";" into a single instance with ";+". Only ";" is collapsed since "&&" and
// "||" imply ordering dependency that is semantically meaningful.
func collapseRepeatedSegments(shape string) string {
// Split into tokens of (segment, operator) pairs.
// We only collapse on ";", so split on " ; " boundaries.
const sep = " ; "
if !strings.Contains(shape, sep) {
return shape
}
// Split on " ; " only — leave && and || intact within segments.
parts := splitOnSemicolon(shape)
if len(parts) <= 1 {
return shape
}
// Find consecutive runs of identical segments and collapse them.
type segment struct {
text string
collapsed bool
}
var segments []segment
i := 0
for i < len(parts) {
j := i + 1
for j < len(parts) && parts[j] == parts[i] {
j++
}
segments = append(segments, segment{parts[i], j-i >= 2})
i = j
}
// Rebuild the shape string.
var b strings.Builder
for idx, seg := range segments {
if idx > 0 {
// After a collapsed segment, just a space (the ";+" acts as separator).
// Between non-collapsed segments, restore " ; ".
if segments[idx-1].collapsed {
b.WriteString(" ")
} else {
b.WriteString(" ; ")
}
}
b.WriteString(seg.text)
if seg.collapsed {
b.WriteString(" ;+")
}
}
return b.String()
}
// splitOnSemicolon splits a shape string on " ; " boundaries, but only at
// the top level (not inside segments that contain && or ||).
func splitOnSemicolon(shape string) []string {
var parts []string
rest := shape
for {
idx := strings.Index(rest, " ; ")
if idx < 0 {
parts = append(parts, rest)
break
}
parts = append(parts, rest[:idx])
rest = rest[idx+len(" ; "):]
}
return parts
}
func fallbackNormalize(seg string) string {
words := strings.Fields(seg)
if len(words) == 0 {
return ""
}
result := []string{words[0]}
for _, w := range words[1:] {
result = append(result, ClassifyToken(w))
}
return strings.Join(result, " ")
}
func collapseWhitespace(s string) string {
return regexp.MustCompile(`\s+`).ReplaceAllString(s, " ")
}