opencode-commit-guard 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/shell.ts CHANGED
@@ -38,7 +38,6 @@ const commitLongOptionsWithArg = new Set([
38
38
  "--reuse-message",
39
39
  "--squash",
40
40
  "--template",
41
- "--trailer",
42
41
  ])
43
42
 
44
43
  interface CommandSubstitution {
@@ -46,6 +45,22 @@ interface CommandSubstitution {
46
45
  readonly end: number
47
46
  }
48
47
 
48
+ interface ANSIEscape extends CommandSubstitution {
49
+ readonly byte?: number
50
+ }
51
+
52
+ interface HeredocDelimiter {
53
+ readonly delimiter: string
54
+ readonly quoted: boolean
55
+ readonly stripTabs: boolean
56
+ }
57
+
58
+ interface Tokenization {
59
+ readonly tokens: ShellToken[]
60
+ readonly end: number
61
+ readonly delimiter?: HeredocDelimiter
62
+ }
63
+
49
64
  function isWordSeparator(character: string): boolean {
50
65
  return (
51
66
  character === " " ||
@@ -56,23 +71,37 @@ function isWordSeparator(character: string): boolean {
56
71
  character === "&" ||
57
72
  character === "|" ||
58
73
  character === "(" ||
59
- character === ")" ||
60
- character === "{" ||
61
- character === "}"
74
+ character === ")"
62
75
  )
63
76
  }
64
77
 
65
- function consumeCommandSubstitution(command: string, start: number): CommandSubstitution {
78
+ function consumeCommandSubstitution(command: string, start: number, nesting = 0): CommandSubstitution {
79
+ if (nesting > 12) throw new Error("Shell parsing limit exceeded. Run git commit directly.")
66
80
  let depth = 1
67
- let quote: "'" | '"' | undefined
81
+ let quote: "'" | '"' | "$'" | undefined
68
82
  let i = start + 2
69
83
  let atWordStart = true
84
+ let atCommandStart = true
85
+ let timeOption = false
86
+ let arithmeticDepth: number | undefined = command[start + 2] === "(" ? 1 : undefined
87
+ const pendingHeredocs: HeredocDelimiter[] = []
70
88
 
71
89
  while (i < command.length) {
72
90
  const character = command[i]
73
91
 
74
92
  if (character === undefined) break
75
93
 
94
+ if (quote === "$'") {
95
+ if (character === "'") quote = undefined
96
+ else if (character === "\\") {
97
+ i = ansiEscape(command, i).end
98
+ continue
99
+ }
100
+
101
+ i++
102
+ continue
103
+ }
104
+
76
105
  if (quote === "'") {
77
106
  if (character === "'") quote = undefined
78
107
  i++
@@ -86,7 +115,11 @@ function consumeCommandSubstitution(command: string, start: number): CommandSubs
86
115
  quote = undefined
87
116
  i++
88
117
  } else if (character === "$" && command[i + 1] === "(") {
89
- i = consumeCommandSubstitution(command, i).end
118
+ i = consumeCommandSubstitution(command, i, nesting + 1).end
119
+ } else if (character === "$" && command[i + 1] === "{") {
120
+ i = consumeQuotedParameter(command, i)
121
+ } else if (character === "`") {
122
+ i = consumeBackticks(command, i, true).end
90
123
  } else {
91
124
  i++
92
125
  }
@@ -95,11 +128,75 @@ function consumeCommandSubstitution(command: string, start: number): CommandSubs
95
128
  }
96
129
 
97
130
  if (character === "\\") {
98
- if (command[i + 1] !== "\n") atWordStart = false
131
+ if (command[i + 1] !== "\n") {
132
+ atWordStart = false
133
+ atCommandStart = false
134
+ }
135
+
99
136
  i += i + 1 < command.length ? 2 : 1
100
137
  continue
101
138
  }
102
139
 
140
+ if (arithmeticDepth === undefined && character === "<" && command[i + 1] === "<") {
141
+ if (command[i + 2] === "<") {
142
+ i += 3
143
+ } else {
144
+ const parsed = tokenizeShellInput(command, i, true, nesting + 1)
145
+
146
+ if (parsed.delimiter === undefined) throw incompleteHeredoc()
147
+ pendingHeredocs.push(parsed.delimiter)
148
+ i = parsed.end
149
+ }
150
+
151
+ atWordStart = true
152
+ continue
153
+ }
154
+
155
+ if (character === "\n" && pendingHeredocs.length > 0) {
156
+ i++
157
+
158
+ for (const heredoc of pendingHeredocs) i = consumeHeredoc(command, i, heredoc).end
159
+ pendingHeredocs.length = 0
160
+ atWordStart = true
161
+ atCommandStart = true
162
+ timeOption = false
163
+ continue
164
+ }
165
+
166
+ if (atCommandStart && atWordStart && !isWordSeparator(character) && character !== "#") {
167
+ let word = ""
168
+
169
+ for (let end = i; end < command.length; end++) {
170
+ const next = command[end]!
171
+
172
+ if (next === "\\" && command[end + 1] === "\n") {
173
+ end++
174
+ continue
175
+ }
176
+
177
+ if (isWordSeparator(next)) break
178
+ word += next
179
+ }
180
+
181
+ if (word === "case") {
182
+ throw new Error("Cannot parse case patterns inside a command substitution. Run the case command separately or run git commit directly.")
183
+ }
184
+
185
+ if (word === "function" || word === "coproc") {
186
+ throw new Error("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately or run git commit directly.")
187
+ }
188
+
189
+ atCommandStart = timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "{"
190
+ timeOption = word === "time" || timeOption && word === "-p"
191
+ }
192
+
193
+ if (character === "$" && command[i + 1] === "'") {
194
+ quote = "$'"
195
+ atWordStart = false
196
+ i += 2
197
+ continue
198
+ }
199
+
103
200
  if (character === "'") {
104
201
  quote = "'"
105
202
  atWordStart = false
@@ -120,53 +217,129 @@ function consumeCommandSubstitution(command: string, start: number): CommandSubs
120
217
  }
121
218
 
122
219
  if (character === "$" && command[i + 1] === "(") {
123
- i = consumeCommandSubstitution(command, i).end
220
+ i = consumeCommandSubstitution(command, i, nesting + 1).end
221
+ atWordStart = false
222
+ continue
223
+ }
224
+
225
+ if (character === "`") {
226
+ i = consumeBackticks(command, i).end
124
227
  atWordStart = false
125
228
  continue
126
229
  }
127
230
 
128
231
  if (character === "(") {
232
+ if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(") arithmeticDepth = depth
129
233
  depth++
130
234
  i++
131
235
  atWordStart = true
236
+ atCommandStart = true
132
237
  continue
133
238
  }
134
239
 
135
240
  if (character === ")") {
136
241
  depth--
137
242
 
243
+ if (depth === arithmeticDepth) arithmeticDepth = undefined
244
+
138
245
  if (depth === 0) {
246
+ if (pendingHeredocs.length > 0) throw incompleteHeredoc()
247
+
139
248
  return { content: command.slice(start + 2, i), end: i + 1 }
140
249
  }
141
250
 
142
251
  atWordStart = true
143
252
  }
144
253
 
254
+ if ([";", "&", "|", "\n", ")"].includes(character)) {
255
+ atCommandStart = true
256
+ timeOption = false
257
+ }
258
+
145
259
  if (isWordSeparator(character)) atWordStart = true
146
260
  else atWordStart = false
147
261
  i++
148
262
  }
149
263
 
150
- return { content: command.slice(start + 2), end: command.length }
264
+ if (pendingHeredocs.length > 0) throw incompleteHeredoc()
265
+ throw new Error(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`)
266
+ }
267
+
268
+ function consumeBackticks(command: string, start: number, doubleQuoted = false): CommandSubstitution {
269
+ let content = ""
270
+
271
+ for (let i = start + 1; i < command.length; i++) {
272
+ if (command[i] === "`") return { content, end: i + 1 }
273
+
274
+ if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"')) i++
275
+ content += command[i]
276
+ }
277
+
278
+ throw new Error(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`)
279
+ }
280
+
281
+ function consumeQuotedParameter(command: string, start: number): number {
282
+ for (let i = start + 2; i < command.length; i++) {
283
+ const character = command[i]!
284
+
285
+ if (character === "}") return i + 1
286
+
287
+ if (["'", '"', "\\", "`", "$", "{"].includes(character)) break
288
+ }
289
+
290
+ throw new Error("Cannot parse nested quoting or expansions in a double-quoted parameter expansion. Use a simple parameter such as \"${HOME}\" or run git commit directly.")
291
+ }
292
+
293
+ function ansiEscape(command: string, start: number): ANSIEscape {
294
+ const escaped = command[start + 1] ?? ""
295
+ const simple = new Map(Object.entries({ a: "\x07", b: "\b", e: "\x1b", E: "\x1b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" }))
296
+ const literal = simple.get(escaped)
297
+
298
+ if (literal !== undefined) return { content: literal, end: start + 2 }
299
+
300
+ if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
301
+ const character = command[start + 2]!
302
+ const end = start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3)
303
+
304
+ return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end }
305
+ }
306
+
307
+ const count = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0
308
+
309
+ const digits = count > 0 ? command.slice(start + 2).match(new RegExp(`^[0-9a-fA-F]{1,${count}}`))?.[0] :
310
+ command.slice(start + 1).match(/^[0-7]{1,3}/)?.[0]
311
+
312
+ if (digits !== undefined) {
313
+ const code = Number.parseInt(digits, count > 0 ? 16 : 8)
314
+
315
+ if (code > 0x10ffff) throw new Error("Cannot validate this ANSI-C escape. Supply the message literally.")
316
+
317
+ const end = start + (count > 0 ? 2 : 1) + digits.length
318
+
319
+ if (count === 0 || escaped === "x") return { content: "", byte: code & 255, end }
320
+
321
+ return { content: String.fromCodePoint(code), end }
322
+ }
323
+
324
+ return { content: `\\${escaped}`, end: start + 2 }
151
325
  }
152
326
 
153
327
  function pushWord(
154
328
  tokens: ShellToken[],
155
329
  value: string,
156
330
  substitutions: readonly string[],
331
+ expansion: boolean,
157
332
  ): void {
158
- if (substitutions.length > 0) {
159
- tokens.push({ type: "word", value, substitutions })
160
- } else {
161
- tokens.push({ type: "word", value })
162
- }
333
+ const token: ShellToken = substitutions.length > 0 ? { type: "word", value, substitutions } : { type: "word", value }
334
+
335
+ tokens.push(expansion ? { ...token, expansion: true } : token)
163
336
  }
164
337
 
165
338
  function heredocSubstitutions(body: string): string[] {
166
339
  const substitutions: string[] = []
167
340
 
168
341
  for (let i = 0; i < body.length; i++) {
169
- if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
342
+ if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
170
343
  i++
171
344
  } else if (body[i] === "`") {
172
345
  throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.")
@@ -181,11 +354,55 @@ function heredocSubstitutions(body: string): string[] {
181
354
  return substitutions
182
355
  }
183
356
 
357
+ function incompleteHeredoc(): Error {
358
+ return new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.")
359
+ }
360
+
361
+ function consumeHeredoc(command: string, start: number, heredoc: HeredocDelimiter): CommandSubstitution {
362
+ let i = start
363
+ let body = ""
364
+
365
+ while (i < command.length) {
366
+ let line = ""
367
+ let newline = false
368
+
369
+ while (i < command.length) {
370
+ const lineEnd = command.indexOf("\n", i)
371
+ const end = lineEnd < 0 ? command.length : lineEnd
372
+ const physicalLine = command.slice(i, end)
373
+ const backslashes = physicalLine.match(/\\+$/)?.[0].length ?? 0
374
+
375
+ newline = lineEnd >= 0
376
+ i = newline ? end + 1 : end
377
+
378
+ if (!heredoc.quoted && newline && backslashes % 2 === 1) {
379
+ line += physicalLine.slice(0, -1)
380
+ continue
381
+ }
382
+
383
+ line += physicalLine
384
+ break
385
+ }
386
+
387
+ if (heredoc.stripTabs) line = line.replace(/^\t+/, "")
388
+
389
+ if (line === heredoc.delimiter) return { content: body, end: i }
390
+
391
+ body += line + (newline ? "\n" : "")
392
+ }
393
+
394
+ throw incompleteHeredoc()
395
+ }
396
+
184
397
  export function tokenizeShell(command: string): ShellToken[] {
398
+ return tokenizeShellInput(command).tokens
399
+ }
400
+
401
+ function tokenizeShellInput(command: string, start = 0, delimiterOnly = false, nesting = 0): Tokenization {
185
402
  const tokens: ShellToken[] = []
186
- const pendingHeredocs: { index: number; delimiter: string; quoted: boolean }[] = []
403
+ const pendingHeredocs: (HeredocDelimiter & { index: number })[] = []
187
404
  let pendingDelimiter: number | undefined
188
- let i = 0
405
+ let i = start
189
406
 
190
407
  while (i < command.length) {
191
408
  const character = command[i]
@@ -208,6 +425,48 @@ export function tokenizeShell(command: string): ShellToken[] {
208
425
  }
209
426
 
210
427
  const twoCharacters = command.slice(i, i + 2)
428
+ let standaloneBrace = false
429
+
430
+ if (delimiterOnly && pendingDelimiter !== undefined && (isWordSeparator(character) || character === "<" || character === ">")) {
431
+ throw incompleteHeredoc()
432
+ }
433
+
434
+ if (character === "{" || character === "}") {
435
+ let commandPosition = true
436
+
437
+ for (let index = tokens.length - 1; index >= 0; index--) {
438
+ const token = tokens[index]!
439
+
440
+ if (token.type === "operator") break
441
+
442
+ if (token.type === "word") {
443
+ const precedingWord = tokens[index - 1]?.type === "word" ? tokens[index - 1]?.value : undefined
444
+
445
+ if (index === tokens.length - 1 && token.value === "coproc") continue
446
+
447
+ if (token.value === "--" && (precedingWord === "time" || precedingWord === "-p" &&
448
+ tokens[index - 2]?.type === "word" && tokens[index - 2]?.value === "time")) continue
449
+
450
+ if (index === tokens.length - 1 && (precedingWord === "function" || precedingWord === "coproc") ||
451
+ precedingWord === "time" && token.value === "-p") {
452
+ index--
453
+ continue
454
+ }
455
+ }
456
+
457
+ if (token.type !== "word" || !commandPrefixes.has(token.value)) {
458
+ commandPosition = false
459
+ break
460
+ }
461
+ }
462
+
463
+ let braceEnd = i + 1
464
+
465
+ while (command[braceEnd] === "\\" && command[braceEnd + 1] === "\n") braceEnd += 2
466
+
467
+ standaloneBrace = commandPosition &&
468
+ (command[braceEnd] === undefined || isWordSeparator(command[braceEnd]!) || command[braceEnd] === "<" || command[braceEnd] === ">")
469
+ }
211
470
 
212
471
  if (
213
472
  twoCharacters === "&&" ||
@@ -223,44 +482,24 @@ export function tokenizeShell(command: string): ShellToken[] {
223
482
  if (
224
483
  character === "|" ||
225
484
  character === ";" ||
226
- character === "&" ||
485
+ character === "&" && command[i + 1] !== ">" ||
227
486
  character === "\n" ||
228
487
  character === "(" ||
229
488
  character === ")" ||
230
- character === "{" ||
231
- character === "}"
489
+ standaloneBrace
232
490
  ) {
233
491
  tokens.push({ type: "operator", value: character })
234
492
  i++
235
493
 
236
494
  if (character === "\n" && pendingHeredocs.length > 0) {
237
495
  for (const heredoc of pendingHeredocs) {
238
- const bodyStart = i
239
- let complete = false
240
-
241
- while (i < command.length) {
242
- const lineEnd = command.indexOf("\n", i)
243
- const end = lineEnd < 0 ? command.length : lineEnd
244
- const line = command.slice(i, end)
245
- i = lineEnd < 0 ? end : end + 1
246
-
247
- if (line === heredoc.delimiter) {
248
- complete = true
249
- const body = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)))
250
-
251
- tokens[heredoc.index] = {
252
- ...tokens[heredoc.index]!,
253
- heredoc: { body, quoted: heredoc.quoted },
254
- substitutions: heredoc.quoted
255
- ? undefined
256
- : heredocSubstitutions(body),
257
- }
258
- break
259
- }
260
- }
496
+ const body = consumeHeredoc(command, i, heredoc)
261
497
 
262
- if (!complete) {
263
- throw new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.")
498
+ i = body.end
499
+ tokens[heredoc.index] = {
500
+ ...tokens[heredoc.index]!,
501
+ heredoc: { body: body.content, quoted: heredoc.quoted },
502
+ substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content),
264
503
  }
265
504
  }
266
505
 
@@ -270,19 +509,21 @@ export function tokenizeShell(command: string): ShellToken[] {
270
509
  continue
271
510
  }
272
511
 
273
- const redirectMatch = command.slice(i).match(/^(\d+)?(<<<|>>|<<|>&|<&|>\||>|<)(?:-|\d+)?/)
512
+ const redirectMatch = command.slice(i).match(/^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/)
274
513
 
275
514
  if (redirectMatch !== null && redirectMatch[0] !== undefined) {
276
515
  tokens.push({ type: "redirect", value: redirectMatch[0] })
277
516
 
278
- if (/^\d*<<$/.test(redirectMatch[0])) pendingDelimiter = tokens.length - 1
517
+ if (/^\d*<<-?$/.test(redirectMatch[0])) pendingDelimiter = tokens.length - 1
279
518
  i += redirectMatch[0].length
280
519
  continue
281
520
  }
282
521
 
283
522
  let value = ""
523
+ const wordBytes: number[] = []
284
524
  let quoted = false
285
- let unsupportedDelimiter = false
525
+ let unsupportedDelimiter: "ANSI-C quoted" | "locale-quoted" | undefined
526
+ let expansion = false
286
527
  const substitutions: string[] = []
287
528
 
288
529
  while (i < command.length) {
@@ -309,10 +550,25 @@ export function tokenizeShell(command: string): ShellToken[] {
309
550
  continue
310
551
  }
311
552
 
553
+ if (current === "$") {
554
+ let quoteStart = i + 1
555
+
556
+ while (command[quoteStart] === "\\" && command[quoteStart + 1] === "\n") quoteStart += 2
557
+
558
+ if (command[quoteStart] === '"') unsupportedDelimiter = "locale-quoted"
559
+ else if (command[quoteStart] === "'") unsupportedDelimiter = "ANSI-C quoted"
560
+ }
561
+
312
562
  if (current === "$" && command[i + 1] === "'") {
563
+ const quoteStart = i
564
+
565
+ wordBytes.push(...Buffer.from(value))
566
+ value = ""
313
567
  quoted = true
314
- unsupportedDelimiter = true
568
+ unsupportedDelimiter = "ANSI-C quoted"
315
569
  i += 2
570
+ const bytes: number[] = []
571
+ let complete = false
316
572
 
317
573
  while (i < command.length) {
318
574
  const ansiCharacter = command[i]
@@ -321,30 +577,37 @@ export function tokenizeShell(command: string): ShellToken[] {
321
577
 
322
578
  if (ansiCharacter === "'") {
323
579
  i++
580
+ complete = true
324
581
  break
325
582
  }
326
583
 
327
584
  if (ansiCharacter === "\\" && i + 1 < command.length) {
328
- const escaped = command[i + 1]
585
+ const escaped = ansiEscape(command, i)
329
586
 
330
- if (escaped === "n") value += "\n"
331
- else if (escaped === "t") value += "\t"
332
- else if (escaped === "r") value += "\r"
333
- else if (escaped === "\\") value += "\\"
334
- else if (escaped === "'") value += "'"
335
- else if (escaped === '"') value += '"'
336
- else value += escaped
337
- i += 2
587
+ bytes.push(...(escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]))
588
+ i = escaped.end
338
589
  } else {
339
- value += ansiCharacter
340
- i++
590
+ const literal = String.fromCodePoint(command.codePointAt(i)!)
591
+
592
+ bytes.push(...Buffer.from(literal))
593
+ i += literal.length
341
594
  }
342
595
  }
343
596
 
597
+ if (!complete) throw new Error(
598
+ `Unterminated ANSI-C quote starting at character ${quoteStart + 1}. Close the quote before running the command.`,
599
+ )
600
+
601
+ const nul = bytes.indexOf(0)
602
+
603
+ wordBytes.push(...(nul < 0 ? bytes : bytes.slice(0, nul)))
604
+
344
605
  continue
345
606
  }
346
607
 
347
608
  if (current === "'") {
609
+ const quoteStart = i
610
+
348
611
  quoted = true
349
612
  i++
350
613
 
@@ -353,11 +616,17 @@ export function tokenizeShell(command: string): ShellToken[] {
353
616
  i++
354
617
  }
355
618
 
356
- if (command[i] === "'") i++
619
+ if (command[i] !== "'") throw new Error(
620
+ `Unterminated single quote starting at character ${quoteStart + 1}. Close the quote before running the command.`,
621
+ )
622
+
623
+ i++
357
624
  continue
358
625
  }
359
626
 
360
627
  if (current === '"') {
628
+ const quoteStart = i
629
+
361
630
  quoted = true
362
631
  i++
363
632
 
@@ -379,29 +648,61 @@ export function tokenizeShell(command: string): ShellToken[] {
379
648
  i += 2
380
649
  }
381
650
  } else if (quotedCharacter === "$" && command[i + 1] === "(") {
382
- const substitution = consumeCommandSubstitution(command, i)
651
+ const substitution = consumeCommandSubstitution(command, i, nesting)
383
652
  value += command.slice(i, substitution.end)
384
653
  substitutions.push(substitution.content)
654
+ expansion = true
655
+ i = substitution.end
656
+ } else if (quotedCharacter === "$" && command[i + 1] === "{") {
657
+ const end = consumeQuotedParameter(command, i)
658
+
659
+ value += command.slice(i, end)
660
+ expansion = true
661
+ i = end
662
+ } else if (quotedCharacter === "`") {
663
+ const substitution = consumeBackticks(command, i, true)
664
+
665
+ value += command.slice(i, substitution.end)
666
+ substitutions.push(substitution.content)
667
+ expansion = true
385
668
  i = substitution.end
386
669
  } else {
670
+ if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? "")) expansion = true
387
671
  value += quotedCharacter
388
672
  i++
389
673
  }
390
674
  }
391
675
 
392
- if (command[i] === '"') i++
676
+ if (command[i] !== '"') throw new Error(
677
+ `Unterminated double quote starting at character ${quoteStart + 1}. Close the quote before running the command.`,
678
+ )
679
+
680
+ i++
393
681
  continue
394
682
  }
395
683
 
396
684
  if (current === "$" && command[i + 1] === "(") {
397
- const substitution = consumeCommandSubstitution(command, i)
685
+ const substitution = consumeCommandSubstitution(command, i, nesting)
398
686
  value += command.slice(i, substitution.end)
399
687
  substitutions.push(substitution.content)
688
+ expansion = true
400
689
  i = substitution.end
401
690
  continue
402
691
  }
403
692
 
404
- const nextRedirect = command.slice(i).match(/^(\d+)?(<<<|>>|<<|>&|<&|>\||>|<)(?:-|\d+)?/)
693
+ if (current === "`") {
694
+ const substitution = consumeBackticks(command, i)
695
+
696
+ value += command.slice(i, substitution.end)
697
+ substitutions.push(substitution.content)
698
+ expansion = true
699
+ i = substitution.end
700
+ continue
701
+ }
702
+
703
+ if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? "")) expansion = true
704
+
705
+ const nextRedirect = command.slice(i).match(/^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/)
405
706
 
406
707
  if (nextRedirect !== null) break
407
708
 
@@ -409,19 +710,23 @@ export function tokenizeShell(command: string): ShellToken[] {
409
710
  i++
410
711
  }
411
712
 
412
- pushWord(tokens, value, substitutions)
713
+ if (wordBytes.length > 0) value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf8")
714
+ pushWord(tokens, value, substitutions, expansion)
413
715
 
414
716
  if (pendingDelimiter !== undefined) {
415
- if (unsupportedDelimiter) {
416
- throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.")
717
+ if (unsupportedDelimiter !== undefined) {
718
+ throw new Error(`Cannot validate this ${unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`)
417
719
  }
418
720
 
419
- pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted })
721
+ const delimiter = { delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true }
722
+
723
+ if (delimiterOnly) return { tokens, end: i, delimiter }
724
+ pendingHeredocs.push({ index: pendingDelimiter, ...delimiter })
420
725
  pendingDelimiter = undefined
421
726
  }
422
727
  }
423
728
 
424
- return tokens
729
+ return { tokens, end: i }
425
730
  }
426
731
 
427
732
  function splitSimpleCommands(tokens: readonly ShellToken[]): { tokens: ShellToken[]; pipeline: boolean }[] {
@@ -449,8 +754,8 @@ function splitSimpleCommands(tokens: readonly ShellToken[]): { tokens: ShellToke
449
754
  return commands
450
755
  }
451
756
 
452
- function extractCommandWords(tokens: readonly ShellToken[]): string[] {
453
- const words: string[] = []
757
+ function extractCommandWords(tokens: readonly ShellToken[]): ShellToken[] {
758
+ const words: ShellToken[] = []
454
759
  let i = 0
455
760
 
456
761
  while (i < tokens.length) {
@@ -459,13 +764,13 @@ function extractCommandWords(tokens: readonly ShellToken[]): string[] {
459
764
  if (token === undefined) break
460
765
 
461
766
  if (token.type === "redirect") {
462
- if (!token.value.includes("&") && tokens[i + 1]?.type === "word") i += 2
767
+ if (tokens[i + 1]?.type === "word") i += 2
463
768
  else i++
464
769
  continue
465
770
  }
466
771
 
467
772
  if (token.type === "word") {
468
- words.push(token.value)
773
+ words.push(token)
469
774
  }
470
775
 
471
776
  i++
@@ -568,6 +873,7 @@ function findCommandStart(words: readonly string[]): number {
568
873
  function extractInvocation(
569
874
  words: readonly string[],
570
875
  commandStart: number,
876
+ wordTokens: readonly ShellToken[],
571
877
  ): GitCommitInvocation | undefined {
572
878
  let wordIndex = commandStart
573
879
  const executable = words[wordIndex]
@@ -642,6 +948,8 @@ function extractInvocation(
642
948
  let hasNoEdit = false
643
949
  let isFixup = false
644
950
  let isHelp = false
951
+ let messageExpansion = false
952
+ let hasTrailer = false
645
953
 
646
954
  const collectMessage = (word: string | undefined): void => {
647
955
  if (word === undefined) return
@@ -677,8 +985,10 @@ function extractInvocation(
677
985
  hasSignoffFlag = false
678
986
  } else if (argument === "-m" || argument === "--message") {
679
987
  index++
988
+ messageExpansion ||= wordTokens[index]?.expansion === true
680
989
  collectMessage(words[index])
681
990
  } else if (argument.startsWith("--message=")) {
991
+ messageExpansion ||= wordTokens[index]?.expansion === true
682
992
  collectMessage(argument.slice("--message=".length))
683
993
  } else if (argument === "-F" || argument === "--file") {
684
994
  index++
@@ -688,6 +998,10 @@ function extractInvocation(
688
998
  } else if (argument === "--fixup" || argument.startsWith("--fixup=")) {
689
999
  isFixup = true
690
1000
 
1001
+ if (equalsIndex < 0) index++
1002
+ } else if (longOptionName === "--trailer") {
1003
+ hasTrailer = true
1004
+
691
1005
  if (equalsIndex < 0) index++
692
1006
  } else if (commitLongOptionsWithArg.has(longOptionName)) {
693
1007
  if (equalsIndex < 0) index++
@@ -708,7 +1022,10 @@ function extractInvocation(
708
1022
  ? attached
709
1023
  : words[++index]
710
1024
 
711
- if (option === "m") collectMessage(input)
1025
+ if (option === "m") {
1026
+ messageExpansion ||= wordTokens[index]?.expansion === true
1027
+ collectMessage(input)
1028
+ }
712
1029
  else collectFile(input)
713
1030
  break
714
1031
  } else if (option === "S") {
@@ -732,19 +1049,65 @@ function extractInvocation(
732
1049
  isFixup,
733
1050
  isHelp,
734
1051
  targetError,
1052
+ messageExpansion,
1053
+ hasTrailer,
735
1054
  }
736
1055
  }
737
1056
 
738
- export function extractGitCommits(command: string, inheritedDirectoryChange = false): GitCommitInvocation[] {
1057
+ export function extractGitCommits(command: string, inheritedDirectoryChange = false, depth = 0): GitCommitInvocation[] {
1058
+ if (depth > 12 || command.length > 262144) throw new Error("Shell parsing limit exceeded. Run git commit directly.")
739
1059
  const tokens = tokenizeShell(command)
740
1060
  const invocations: GitCommitInvocation[] = []
741
1061
  let changedDirectory = inheritedDirectoryChange
742
1062
 
743
1063
  for (const simple of splitSimpleCommands(tokens)) {
744
1064
  const commandTokens = simple.tokens
745
- const words = extractCommandWords(commandTokens)
1065
+ const wordTokens = extractCommandWords(commandTokens)
1066
+ const words = wordTokens.map((token) => token.value)
746
1067
  const commandStart = findCommandStart(words)
747
- const invocation = extractInvocation(words, commandStart)
1068
+ const invocation = extractInvocation(words, commandStart, wordTokens)
1069
+
1070
+ if (/^(?:.*\/)?(?:bash|sh|zsh)$/.test(words[commandStart] ?? "")) {
1071
+ let bodyIndex = commandStart + 1
1072
+ let executeString = false
1073
+
1074
+ while (bodyIndex < words.length) {
1075
+ const option = words[bodyIndex]!
1076
+
1077
+ if (option === "--") {
1078
+ bodyIndex++
1079
+ break
1080
+ }
1081
+
1082
+ if (!option.startsWith("-") && !option.startsWith("+")) break
1083
+
1084
+ if (/^-[a-zA-Z]*c[a-zA-Z]*$/.test(option)) executeString = true
1085
+ const shortOptions = /^[+-][a-zA-Z]+$/.test(option)
1086
+
1087
+ if (shortOptions && /[oO]/.test(option) && !/[oO]$/.test(option)) {
1088
+ throw new Error("Cannot parse shell options reliably. Run git commit directly.")
1089
+ }
1090
+
1091
+ const next = words[bodyIndex + 1]
1092
+ const optionName = next !== undefined && !/^[+-]/.test(next)
1093
+
1094
+ bodyIndex += shortOptions && /[oO]$/.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1
1095
+ }
1096
+
1097
+ if (executeString) {
1098
+ const body = wordTokens[bodyIndex]
1099
+
1100
+ if (body === undefined || body.expansion) throw new Error("Cannot parse shell -c body reliably. Run git commit directly.")
1101
+
1102
+ if (/^(?:.*\/)?sh$/.test(words[commandStart] ?? "") && body.value.includes("$'")) {
1103
+ throw new Error("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body, or run git commit directly.")
1104
+ }
1105
+
1106
+ const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word))
1107
+
1108
+ invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1))
1109
+ }
1110
+ }
748
1111
 
749
1112
  if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment)) changedDirectory = true
750
1113
 
@@ -788,7 +1151,7 @@ export function extractGitCommits(command: string, inheritedDirectoryChange = fa
788
1151
 
789
1152
  for (const token of tokens) {
790
1153
  for (const substitution of token.substitutions ?? []) {
791
- invocations.push(...extractGitCommits(substitution, changedDirectory))
1154
+ invocations.push(...extractGitCommits(substitution, changedDirectory, depth + 1))
792
1155
  }
793
1156
  }
794
1157