opencode-commit-guard 1.0.6 → 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/README.md CHANGED
@@ -158,6 +158,11 @@ It also rejects unquoted or ambiguous standard-input sources.
158
158
  Supply the final message literally; message words containing shell expansion are rejected without evaluation.
159
159
  Single quotes and ANSI-C quotes (`$'...'`) supply literal text.
160
160
  The parser inspects commits inside command substitutions, backticks, and literal `bash`, `sh`, or `zsh` `-c` bodies.
161
+ Use simple double-quoted parameters such as `"${HOME}"`; nested quoting, escapes, and expansions inside these parameters are rejected.
162
+ Run `case` commands outside command substitutions; the parser rejects their ambiguous parentheses.
163
+ Run function and `coproc` declarations outside command substitutions; their compound bodies are rejected there.
164
+ Use `bash -c` or `zsh -c` instead of `sh -c` for bodies containing `$'` quoting; the guard rejects this nonportable syntax under `sh`.
165
+ Unquoted heredoc delimiters match after backslash-newline continuations are removed; quote the delimiter to preserve literal body text.
161
166
  Run Git directly if a shell body is dynamic or cannot be parsed reliably.
162
167
  Put trailers in the literal message body or use `-s`; `--trailer` is rejected.
163
168
  The guard resolves the signing baseline before reporting message-format violations.
package/dist/index.js CHANGED
@@ -445,7 +445,7 @@ var commitLongOptionsWithArg = new Set([
445
445
  ]);
446
446
  function isWordSeparator(character) {
447
447
  return character === " " || character === "\t" || character === "\r" || character === `
448
- ` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")" || character === "{" || character === "}";
448
+ ` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")";
449
449
  }
450
450
  function consumeCommandSubstitution(command, start, nesting = 0) {
451
451
  if (nesting > 12)
@@ -454,10 +454,24 @@ function consumeCommandSubstitution(command, start, nesting = 0) {
454
454
  let quote;
455
455
  let i = start + 2;
456
456
  let atWordStart = true;
457
+ let atCommandStart = true;
458
+ let timeOption = false;
459
+ let arithmeticDepth = command[start + 2] === "(" ? 1 : undefined;
460
+ const pendingHeredocs = [];
457
461
  while (i < command.length) {
458
462
  const character = command[i];
459
463
  if (character === undefined)
460
464
  break;
465
+ if (quote === "$'") {
466
+ if (character === "'")
467
+ quote = undefined;
468
+ else if (character === "\\") {
469
+ i = ansiEscape(command, i).end;
470
+ continue;
471
+ }
472
+ i++;
473
+ continue;
474
+ }
461
475
  if (quote === "'") {
462
476
  if (character === "'")
463
477
  quote = undefined;
@@ -472,6 +486,10 @@ function consumeCommandSubstitution(command, start, nesting = 0) {
472
486
  i++;
473
487
  } else if (character === "$" && command[i + 1] === "(") {
474
488
  i = consumeCommandSubstitution(command, i, nesting + 1).end;
489
+ } else if (character === "$" && command[i + 1] === "{") {
490
+ i = consumeQuotedParameter(command, i);
491
+ } else if (character === "`") {
492
+ i = consumeBackticks(command, i, true).end;
475
493
  } else {
476
494
  i++;
477
495
  }
@@ -479,11 +497,65 @@ function consumeCommandSubstitution(command, start, nesting = 0) {
479
497
  }
480
498
  if (character === "\\") {
481
499
  if (command[i + 1] !== `
482
- `)
500
+ `) {
483
501
  atWordStart = false;
502
+ atCommandStart = false;
503
+ }
484
504
  i += i + 1 < command.length ? 2 : 1;
485
505
  continue;
486
506
  }
507
+ if (arithmeticDepth === undefined && character === "<" && command[i + 1] === "<") {
508
+ if (command[i + 2] === "<") {
509
+ i += 3;
510
+ } else {
511
+ const parsed = tokenizeShellInput(command, i, true, nesting + 1);
512
+ if (parsed.delimiter === undefined)
513
+ throw incompleteHeredoc();
514
+ pendingHeredocs.push(parsed.delimiter);
515
+ i = parsed.end;
516
+ }
517
+ atWordStart = true;
518
+ continue;
519
+ }
520
+ if (character === `
521
+ ` && pendingHeredocs.length > 0) {
522
+ i++;
523
+ for (const heredoc of pendingHeredocs)
524
+ i = consumeHeredoc(command, i, heredoc).end;
525
+ pendingHeredocs.length = 0;
526
+ atWordStart = true;
527
+ atCommandStart = true;
528
+ timeOption = false;
529
+ continue;
530
+ }
531
+ if (atCommandStart && atWordStart && !isWordSeparator(character) && character !== "#") {
532
+ let word = "";
533
+ for (let end = i;end < command.length; end++) {
534
+ const next = command[end];
535
+ if (next === "\\" && command[end + 1] === `
536
+ `) {
537
+ end++;
538
+ continue;
539
+ }
540
+ if (isWordSeparator(next))
541
+ break;
542
+ word += next;
543
+ }
544
+ if (word === "case") {
545
+ throw new Error("Cannot parse case patterns inside a command substitution. Run the case command separately or run git commit directly.");
546
+ }
547
+ if (word === "function" || word === "coproc") {
548
+ throw new Error("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately or run git commit directly.");
549
+ }
550
+ atCommandStart = timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "{";
551
+ timeOption = word === "time" || timeOption && word === "-p";
552
+ }
553
+ if (character === "$" && command[i + 1] === "'") {
554
+ quote = "$'";
555
+ atWordStart = false;
556
+ i += 2;
557
+ continue;
558
+ }
487
559
  if (character === "'") {
488
560
  quote = "'";
489
561
  atWordStart = false;
@@ -507,37 +579,66 @@ function consumeCommandSubstitution(command, start, nesting = 0) {
507
579
  atWordStart = false;
508
580
  continue;
509
581
  }
582
+ if (character === "`") {
583
+ i = consumeBackticks(command, i).end;
584
+ atWordStart = false;
585
+ continue;
586
+ }
510
587
  if (character === "(") {
588
+ if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(")
589
+ arithmeticDepth = depth;
511
590
  depth++;
512
591
  i++;
513
592
  atWordStart = true;
593
+ atCommandStart = true;
514
594
  continue;
515
595
  }
516
596
  if (character === ")") {
517
597
  depth--;
598
+ if (depth === arithmeticDepth)
599
+ arithmeticDepth = undefined;
518
600
  if (depth === 0) {
601
+ if (pendingHeredocs.length > 0)
602
+ throw incompleteHeredoc();
519
603
  return { content: command.slice(start + 2, i), end: i + 1 };
520
604
  }
521
605
  atWordStart = true;
522
606
  }
607
+ if ([";", "&", "|", `
608
+ `, ")"].includes(character)) {
609
+ atCommandStart = true;
610
+ timeOption = false;
611
+ }
523
612
  if (isWordSeparator(character))
524
613
  atWordStart = true;
525
614
  else
526
615
  atWordStart = false;
527
616
  i++;
528
617
  }
529
- throw new Error("Cannot parse shell substitution reliably. Run git commit directly.");
618
+ if (pendingHeredocs.length > 0)
619
+ throw incompleteHeredoc();
620
+ throw new Error(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`);
530
621
  }
531
- function consumeBackticks(command, start) {
622
+ function consumeBackticks(command, start, doubleQuoted = false) {
532
623
  let content = "";
533
624
  for (let i = start + 1;i < command.length; i++) {
534
625
  if (command[i] === "`")
535
626
  return { content, end: i + 1 };
536
- if (command[i] === "\\" && ["$", "`", "\\"].includes(command[i + 1] ?? ""))
627
+ if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"'))
537
628
  i++;
538
629
  content += command[i];
539
630
  }
540
- throw new Error("Cannot parse backtick substitution reliably. Run git commit directly.");
631
+ throw new Error(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`);
632
+ }
633
+ function consumeQuotedParameter(command, start) {
634
+ for (let i = start + 2;i < command.length; i++) {
635
+ const character = command[i];
636
+ if (character === "}")
637
+ return i + 1;
638
+ if (["'", '"', "\\", "`", "$", "{"].includes(character))
639
+ break;
640
+ }
641
+ 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.');
541
642
  }
542
643
  function ansiEscape(command, start) {
543
644
  const escaped = command[start + 1] ?? "";
@@ -546,9 +647,10 @@ function ansiEscape(command, start) {
546
647
  const literal = simple.get(escaped);
547
648
  if (literal !== undefined)
548
649
  return { content: literal, end: start + 2 };
549
- if (escaped === "c" && command[start + 2] !== undefined) {
650
+ if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
550
651
  const character = command[start + 2];
551
- return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end: start + 3 };
652
+ const end = start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3);
653
+ return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end };
552
654
  }
553
655
  const count = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
554
656
  const digits = count > 0 ? command.slice(start + 2).match(new RegExp(`^[0-9a-fA-F]{1,${count}}`))?.[0] : command.slice(start + 1).match(/^[0-7]{1,3}/)?.[0];
@@ -570,7 +672,7 @@ function pushWord(tokens, value, substitutions, expansion) {
570
672
  function heredocSubstitutions(body) {
571
673
  const substitutions = [];
572
674
  for (let i = 0;i < body.length; i++) {
573
- if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
675
+ if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
574
676
  i++;
575
677
  } else if (body[i] === "`") {
576
678
  throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
@@ -582,11 +684,47 @@ function heredocSubstitutions(body) {
582
684
  }
583
685
  return substitutions;
584
686
  }
687
+ function incompleteHeredoc() {
688
+ return new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
689
+ }
690
+ function consumeHeredoc(command, start, heredoc) {
691
+ let i = start;
692
+ let body = "";
693
+ while (i < command.length) {
694
+ let line = "";
695
+ let newline = false;
696
+ while (i < command.length) {
697
+ const lineEnd = command.indexOf(`
698
+ `, i);
699
+ const end = lineEnd < 0 ? command.length : lineEnd;
700
+ const physicalLine = command.slice(i, end);
701
+ const backslashes = physicalLine.match(/\\+$/)?.[0].length ?? 0;
702
+ newline = lineEnd >= 0;
703
+ i = newline ? end + 1 : end;
704
+ if (!heredoc.quoted && newline && backslashes % 2 === 1) {
705
+ line += physicalLine.slice(0, -1);
706
+ continue;
707
+ }
708
+ line += physicalLine;
709
+ break;
710
+ }
711
+ if (heredoc.stripTabs)
712
+ line = line.replace(/^\t+/, "");
713
+ if (line === heredoc.delimiter)
714
+ return { content: body, end: i };
715
+ body += line + (newline ? `
716
+ ` : "");
717
+ }
718
+ throw incompleteHeredoc();
719
+ }
585
720
  function tokenizeShell(command) {
721
+ return tokenizeShellInput(command).tokens;
722
+ }
723
+ function tokenizeShellInput(command, start = 0, delimiterOnly = false, nesting = 0) {
586
724
  const tokens = [];
587
725
  const pendingHeredocs = [];
588
726
  let pendingDelimiter;
589
- let i = 0;
727
+ let i = start;
590
728
  while (i < command.length) {
591
729
  const character = command[i];
592
730
  if (character === undefined)
@@ -607,41 +745,57 @@ function tokenizeShell(command) {
607
745
  continue;
608
746
  }
609
747
  const twoCharacters = command.slice(i, i + 2);
748
+ let standaloneBrace = false;
749
+ if (delimiterOnly && pendingDelimiter !== undefined && (isWordSeparator(character) || character === "<" || character === ">")) {
750
+ throw incompleteHeredoc();
751
+ }
752
+ if (character === "{" || character === "}") {
753
+ let commandPosition = true;
754
+ for (let index = tokens.length - 1;index >= 0; index--) {
755
+ const token = tokens[index];
756
+ if (token.type === "operator")
757
+ break;
758
+ if (token.type === "word") {
759
+ const precedingWord = tokens[index - 1]?.type === "word" ? tokens[index - 1]?.value : undefined;
760
+ if (index === tokens.length - 1 && token.value === "coproc")
761
+ continue;
762
+ if (token.value === "--" && (precedingWord === "time" || precedingWord === "-p" && tokens[index - 2]?.type === "word" && tokens[index - 2]?.value === "time"))
763
+ continue;
764
+ if (index === tokens.length - 1 && (precedingWord === "function" || precedingWord === "coproc") || precedingWord === "time" && token.value === "-p") {
765
+ index--;
766
+ continue;
767
+ }
768
+ }
769
+ if (token.type !== "word" || !commandPrefixes.has(token.value)) {
770
+ commandPosition = false;
771
+ break;
772
+ }
773
+ }
774
+ let braceEnd = i + 1;
775
+ while (command[braceEnd] === "\\" && command[braceEnd + 1] === `
776
+ `)
777
+ braceEnd += 2;
778
+ standaloneBrace = commandPosition && (command[braceEnd] === undefined || isWordSeparator(command[braceEnd]) || command[braceEnd] === "<" || command[braceEnd] === ">");
779
+ }
610
780
  if (twoCharacters === "&&" || twoCharacters === "||" || twoCharacters === "|&" || twoCharacters === ";;") {
611
781
  tokens.push({ type: "operator", value: twoCharacters });
612
782
  i += 2;
613
783
  continue;
614
784
  }
615
785
  if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
616
- ` || character === "(" || character === ")" || character === "{" || character === "}") {
786
+ ` || character === "(" || character === ")" || standaloneBrace) {
617
787
  tokens.push({ type: "operator", value: character });
618
788
  i++;
619
789
  if (character === `
620
790
  ` && pendingHeredocs.length > 0) {
621
791
  for (const heredoc of pendingHeredocs) {
622
- const bodyStart = i;
623
- let complete = false;
624
- while (i < command.length) {
625
- const lineEnd = command.indexOf(`
626
- `, i);
627
- const end = lineEnd < 0 ? command.length : lineEnd;
628
- const line = command.slice(i, end);
629
- i = lineEnd < 0 ? end : end + 1;
630
- if ((heredoc.stripTabs ? line.replace(/^\t+/, "") : line) === heredoc.delimiter) {
631
- complete = true;
632
- const rawBody = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)));
633
- const body = heredoc.stripTabs ? rawBody.replace(/^\t+/gm, "") : rawBody;
634
- tokens[heredoc.index] = {
635
- ...tokens[heredoc.index],
636
- heredoc: { body, quoted: heredoc.quoted },
637
- substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body)
638
- };
639
- break;
640
- }
641
- }
642
- if (!complete) {
643
- throw new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
644
- }
792
+ const body = consumeHeredoc(command, i, heredoc);
793
+ i = body.end;
794
+ tokens[heredoc.index] = {
795
+ ...tokens[heredoc.index],
796
+ heredoc: { body: body.content, quoted: heredoc.quoted },
797
+ substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
798
+ };
645
799
  }
646
800
  pendingHeredocs.length = 0;
647
801
  }
@@ -658,7 +812,7 @@ function tokenizeShell(command) {
658
812
  let value = "";
659
813
  const wordBytes = [];
660
814
  let quoted = false;
661
- let unsupportedDelimiter = false;
815
+ let unsupportedDelimiter;
662
816
  let expansion = false;
663
817
  const substitutions = [];
664
818
  while (i < command.length) {
@@ -681,11 +835,22 @@ function tokenizeShell(command) {
681
835
  }
682
836
  continue;
683
837
  }
838
+ if (current === "$") {
839
+ let quoteStart = i + 1;
840
+ while (command[quoteStart] === "\\" && command[quoteStart + 1] === `
841
+ `)
842
+ quoteStart += 2;
843
+ if (command[quoteStart] === '"')
844
+ unsupportedDelimiter = "locale-quoted";
845
+ else if (command[quoteStart] === "'")
846
+ unsupportedDelimiter = "ANSI-C quoted";
847
+ }
684
848
  if (current === "$" && command[i + 1] === "'") {
849
+ const quoteStart = i;
685
850
  wordBytes.push(...Buffer.from(value));
686
851
  value = "";
687
852
  quoted = true;
688
- unsupportedDelimiter = true;
853
+ unsupportedDelimiter = "ANSI-C quoted";
689
854
  i += 2;
690
855
  const bytes = [];
691
856
  let complete = false;
@@ -709,12 +874,13 @@ function tokenizeShell(command) {
709
874
  }
710
875
  }
711
876
  if (!complete)
712
- throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
877
+ throw new Error(`Unterminated ANSI-C quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
713
878
  const nul = bytes.indexOf(0);
714
879
  wordBytes.push(...nul < 0 ? bytes : bytes.slice(0, nul));
715
880
  continue;
716
881
  }
717
882
  if (current === "'") {
883
+ const quoteStart = i;
718
884
  quoted = true;
719
885
  i++;
720
886
  while (i < command.length && command[i] !== "'") {
@@ -722,11 +888,12 @@ function tokenizeShell(command) {
722
888
  i++;
723
889
  }
724
890
  if (command[i] !== "'")
725
- throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
891
+ throw new Error(`Unterminated single quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
726
892
  i++;
727
893
  continue;
728
894
  }
729
895
  if (current === '"') {
896
+ const quoteStart = i;
730
897
  quoted = true;
731
898
  i++;
732
899
  while (i < command.length && command[i] !== '"') {
@@ -746,13 +913,18 @@ function tokenizeShell(command) {
746
913
  i += 2;
747
914
  }
748
915
  } else if (quotedCharacter === "$" && command[i + 1] === "(") {
749
- const substitution = consumeCommandSubstitution(command, i);
916
+ const substitution = consumeCommandSubstitution(command, i, nesting);
750
917
  value += command.slice(i, substitution.end);
751
918
  substitutions.push(substitution.content);
752
919
  expansion = true;
753
920
  i = substitution.end;
921
+ } else if (quotedCharacter === "$" && command[i + 1] === "{") {
922
+ const end = consumeQuotedParameter(command, i);
923
+ value += command.slice(i, end);
924
+ expansion = true;
925
+ i = end;
754
926
  } else if (quotedCharacter === "`") {
755
- const substitution = consumeBackticks(command, i);
927
+ const substitution = consumeBackticks(command, i, true);
756
928
  value += command.slice(i, substitution.end);
757
929
  substitutions.push(substitution.content);
758
930
  expansion = true;
@@ -765,12 +937,12 @@ function tokenizeShell(command) {
765
937
  }
766
938
  }
767
939
  if (command[i] !== '"')
768
- throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
940
+ throw new Error(`Unterminated double quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
769
941
  i++;
770
942
  continue;
771
943
  }
772
944
  if (current === "$" && command[i + 1] === "(") {
773
- const substitution = consumeCommandSubstitution(command, i);
945
+ const substitution = consumeCommandSubstitution(command, i, nesting);
774
946
  value += command.slice(i, substitution.end);
775
947
  substitutions.push(substitution.content);
776
948
  expansion = true;
@@ -797,14 +969,17 @@ function tokenizeShell(command) {
797
969
  value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf8");
798
970
  pushWord(tokens, value, substitutions, expansion);
799
971
  if (pendingDelimiter !== undefined) {
800
- if (unsupportedDelimiter) {
801
- throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.");
972
+ if (unsupportedDelimiter !== undefined) {
973
+ throw new Error(`Cannot validate this ${unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`);
802
974
  }
803
- pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true });
975
+ const delimiter = { delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true };
976
+ if (delimiterOnly)
977
+ return { tokens, end: i, delimiter };
978
+ pendingHeredocs.push({ index: pendingDelimiter, ...delimiter });
804
979
  pendingDelimiter = undefined;
805
980
  }
806
981
  }
807
- return tokens;
982
+ return { tokens, end: i };
808
983
  }
809
984
  function splitSimpleCommands(tokens) {
810
985
  const commands = [];
@@ -1112,6 +1287,9 @@ function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0)
1112
1287
  const body = wordTokens[bodyIndex];
1113
1288
  if (body === undefined || body.expansion)
1114
1289
  throw new Error("Cannot parse shell -c body reliably. Run git commit directly.");
1290
+ if (/^(?:.*\/)?sh$/.test(words[commandStart] ?? "") && body.value.includes("$'")) {
1291
+ throw new Error("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body, or run git commit directly.");
1292
+ }
1115
1293
  const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
1116
1294
  invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1));
1117
1295
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,9 +26,9 @@
26
26
  "effect": "4.0.1"
27
27
  },
28
28
  "devDependencies": {
29
- "@oxlint/plugins": "1.90.0",
30
29
  "@types/bun": "1.4.4",
31
30
  "oxlint": "1.90.0",
31
+ "oxlint-plugin-anti-slop": "github:dmmulroy/anti-slop#c44ef22ca116d0ba62a3ff663a0bd13a3f3fa40b",
32
32
  "typescript": "7.0.2"
33
33
  },
34
34
  "engines": {
package/src/shell.ts CHANGED
@@ -49,6 +49,18 @@ interface ANSIEscape extends CommandSubstitution {
49
49
  readonly byte?: number
50
50
  }
51
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
+
52
64
  function isWordSeparator(character: string): boolean {
53
65
  return (
54
66
  character === " " ||
@@ -59,24 +71,37 @@ function isWordSeparator(character: string): boolean {
59
71
  character === "&" ||
60
72
  character === "|" ||
61
73
  character === "(" ||
62
- character === ")" ||
63
- character === "{" ||
64
- character === "}"
74
+ character === ")"
65
75
  )
66
76
  }
67
77
 
68
78
  function consumeCommandSubstitution(command: string, start: number, nesting = 0): CommandSubstitution {
69
79
  if (nesting > 12) throw new Error("Shell parsing limit exceeded. Run git commit directly.")
70
80
  let depth = 1
71
- let quote: "'" | '"' | undefined
81
+ let quote: "'" | '"' | "$'" | undefined
72
82
  let i = start + 2
73
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[] = []
74
88
 
75
89
  while (i < command.length) {
76
90
  const character = command[i]
77
91
 
78
92
  if (character === undefined) break
79
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
+
80
105
  if (quote === "'") {
81
106
  if (character === "'") quote = undefined
82
107
  i++
@@ -91,6 +116,10 @@ function consumeCommandSubstitution(command: string, start: number, nesting = 0)
91
116
  i++
92
117
  } else if (character === "$" && command[i + 1] === "(") {
93
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
94
123
  } else {
95
124
  i++
96
125
  }
@@ -99,11 +128,75 @@ function consumeCommandSubstitution(command: string, start: number, nesting = 0)
99
128
  }
100
129
 
101
130
  if (character === "\\") {
102
- if (command[i + 1] !== "\n") atWordStart = false
131
+ if (command[i + 1] !== "\n") {
132
+ atWordStart = false
133
+ atCommandStart = false
134
+ }
135
+
103
136
  i += i + 1 < command.length ? 2 : 1
104
137
  continue
105
138
  }
106
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
+
107
200
  if (character === "'") {
108
201
  quote = "'"
109
202
  atWordStart = false
@@ -129,42 +222,72 @@ function consumeCommandSubstitution(command: string, start: number, nesting = 0)
129
222
  continue
130
223
  }
131
224
 
225
+ if (character === "`") {
226
+ i = consumeBackticks(command, i).end
227
+ atWordStart = false
228
+ continue
229
+ }
230
+
132
231
  if (character === "(") {
232
+ if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(") arithmeticDepth = depth
133
233
  depth++
134
234
  i++
135
235
  atWordStart = true
236
+ atCommandStart = true
136
237
  continue
137
238
  }
138
239
 
139
240
  if (character === ")") {
140
241
  depth--
141
242
 
243
+ if (depth === arithmeticDepth) arithmeticDepth = undefined
244
+
142
245
  if (depth === 0) {
246
+ if (pendingHeredocs.length > 0) throw incompleteHeredoc()
247
+
143
248
  return { content: command.slice(start + 2, i), end: i + 1 }
144
249
  }
145
250
 
146
251
  atWordStart = true
147
252
  }
148
253
 
254
+ if ([";", "&", "|", "\n", ")"].includes(character)) {
255
+ atCommandStart = true
256
+ timeOption = false
257
+ }
258
+
149
259
  if (isWordSeparator(character)) atWordStart = true
150
260
  else atWordStart = false
151
261
  i++
152
262
  }
153
263
 
154
- throw new Error("Cannot parse shell substitution reliably. Run git commit directly.")
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.`)
155
266
  }
156
267
 
157
- function consumeBackticks(command: string, start: number): CommandSubstitution {
268
+ function consumeBackticks(command: string, start: number, doubleQuoted = false): CommandSubstitution {
158
269
  let content = ""
159
270
 
160
271
  for (let i = start + 1; i < command.length; i++) {
161
272
  if (command[i] === "`") return { content, end: i + 1 }
162
273
 
163
- if (command[i] === "\\" && ["$", "`", "\\"].includes(command[i + 1] ?? "")) i++
274
+ if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"')) i++
164
275
  content += command[i]
165
276
  }
166
277
 
167
- throw new Error("Cannot parse backtick substitution reliably. Run git commit directly.")
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.")
168
291
  }
169
292
 
170
293
  function ansiEscape(command: string, start: number): ANSIEscape {
@@ -174,10 +297,11 @@ function ansiEscape(command: string, start: number): ANSIEscape {
174
297
 
175
298
  if (literal !== undefined) return { content: literal, end: start + 2 }
176
299
 
177
- if (escaped === "c" && command[start + 2] !== undefined) {
300
+ if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
178
301
  const character = command[start + 2]!
302
+ const end = start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3)
179
303
 
180
- return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end: start + 3 }
304
+ return { content: String.fromCharCode(character === "?" ? 127 : character.toUpperCase().charCodeAt(0) & 31), end }
181
305
  }
182
306
 
183
307
  const count = escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0
@@ -215,7 +339,7 @@ function heredocSubstitutions(body: string): string[] {
215
339
  const substitutions: string[] = []
216
340
 
217
341
  for (let i = 0; i < body.length; i++) {
218
- if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
342
+ if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
219
343
  i++
220
344
  } else if (body[i] === "`") {
221
345
  throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.")
@@ -230,11 +354,55 @@ function heredocSubstitutions(body: string): string[] {
230
354
  return substitutions
231
355
  }
232
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
+
233
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 {
234
402
  const tokens: ShellToken[] = []
235
- const pendingHeredocs: { index: number; delimiter: string; quoted: boolean; stripTabs: boolean }[] = []
403
+ const pendingHeredocs: (HeredocDelimiter & { index: number })[] = []
236
404
  let pendingDelimiter: number | undefined
237
- let i = 0
405
+ let i = start
238
406
 
239
407
  while (i < command.length) {
240
408
  const character = command[i]
@@ -257,6 +425,48 @@ export function tokenizeShell(command: string): ShellToken[] {
257
425
  }
258
426
 
259
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
+ }
260
470
 
261
471
  if (
262
472
  twoCharacters === "&&" ||
@@ -276,41 +486,20 @@ export function tokenizeShell(command: string): ShellToken[] {
276
486
  character === "\n" ||
277
487
  character === "(" ||
278
488
  character === ")" ||
279
- character === "{" ||
280
- character === "}"
489
+ standaloneBrace
281
490
  ) {
282
491
  tokens.push({ type: "operator", value: character })
283
492
  i++
284
493
 
285
494
  if (character === "\n" && pendingHeredocs.length > 0) {
286
495
  for (const heredoc of pendingHeredocs) {
287
- const bodyStart = i
288
- let complete = false
289
-
290
- while (i < command.length) {
291
- const lineEnd = command.indexOf("\n", i)
292
- const end = lineEnd < 0 ? command.length : lineEnd
293
- const line = command.slice(i, end)
294
- i = lineEnd < 0 ? end : end + 1
295
-
296
- if ((heredoc.stripTabs ? line.replace(/^\t+/, "") : line) === heredoc.delimiter) {
297
- complete = true
298
- const rawBody = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)))
299
- const body = heredoc.stripTabs ? rawBody.replace(/^\t+/gm, "") : rawBody
300
-
301
- tokens[heredoc.index] = {
302
- ...tokens[heredoc.index]!,
303
- heredoc: { body, quoted: heredoc.quoted },
304
- substitutions: heredoc.quoted
305
- ? undefined
306
- : heredocSubstitutions(body),
307
- }
308
- break
309
- }
310
- }
496
+ const body = consumeHeredoc(command, i, heredoc)
311
497
 
312
- if (!complete) {
313
- 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),
314
503
  }
315
504
  }
316
505
 
@@ -333,7 +522,7 @@ export function tokenizeShell(command: string): ShellToken[] {
333
522
  let value = ""
334
523
  const wordBytes: number[] = []
335
524
  let quoted = false
336
- let unsupportedDelimiter = false
525
+ let unsupportedDelimiter: "ANSI-C quoted" | "locale-quoted" | undefined
337
526
  let expansion = false
338
527
  const substitutions: string[] = []
339
528
 
@@ -361,11 +550,22 @@ export function tokenizeShell(command: string): ShellToken[] {
361
550
  continue
362
551
  }
363
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
+
364
562
  if (current === "$" && command[i + 1] === "'") {
563
+ const quoteStart = i
564
+
365
565
  wordBytes.push(...Buffer.from(value))
366
566
  value = ""
367
567
  quoted = true
368
- unsupportedDelimiter = true
568
+ unsupportedDelimiter = "ANSI-C quoted"
369
569
  i += 2
370
570
  const bytes: number[] = []
371
571
  let complete = false
@@ -394,7 +594,10 @@ export function tokenizeShell(command: string): ShellToken[] {
394
594
  }
395
595
  }
396
596
 
397
- if (!complete) throw new Error("Cannot parse shell quotes reliably. Run git commit directly.")
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
+
398
601
  const nul = bytes.indexOf(0)
399
602
 
400
603
  wordBytes.push(...(nul < 0 ? bytes : bytes.slice(0, nul)))
@@ -403,6 +606,8 @@ export function tokenizeShell(command: string): ShellToken[] {
403
606
  }
404
607
 
405
608
  if (current === "'") {
609
+ const quoteStart = i
610
+
406
611
  quoted = true
407
612
  i++
408
613
 
@@ -411,12 +616,17 @@ export function tokenizeShell(command: string): ShellToken[] {
411
616
  i++
412
617
  }
413
618
 
414
- if (command[i] !== "'") throw new Error("Cannot parse shell quotes reliably. Run git commit directly.")
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
+
415
623
  i++
416
624
  continue
417
625
  }
418
626
 
419
627
  if (current === '"') {
628
+ const quoteStart = i
629
+
420
630
  quoted = true
421
631
  i++
422
632
 
@@ -438,13 +648,19 @@ export function tokenizeShell(command: string): ShellToken[] {
438
648
  i += 2
439
649
  }
440
650
  } else if (quotedCharacter === "$" && command[i + 1] === "(") {
441
- const substitution = consumeCommandSubstitution(command, i)
651
+ const substitution = consumeCommandSubstitution(command, i, nesting)
442
652
  value += command.slice(i, substitution.end)
443
653
  substitutions.push(substitution.content)
444
654
  expansion = true
445
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
446
662
  } else if (quotedCharacter === "`") {
447
- const substitution = consumeBackticks(command, i)
663
+ const substitution = consumeBackticks(command, i, true)
448
664
 
449
665
  value += command.slice(i, substitution.end)
450
666
  substitutions.push(substitution.content)
@@ -457,13 +673,16 @@ export function tokenizeShell(command: string): ShellToken[] {
457
673
  }
458
674
  }
459
675
 
460
- if (command[i] !== '"') throw new Error("Cannot parse shell quotes reliably. Run git commit directly.")
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
+
461
680
  i++
462
681
  continue
463
682
  }
464
683
 
465
684
  if (current === "$" && command[i + 1] === "(") {
466
- const substitution = consumeCommandSubstitution(command, i)
685
+ const substitution = consumeCommandSubstitution(command, i, nesting)
467
686
  value += command.slice(i, substitution.end)
468
687
  substitutions.push(substitution.content)
469
688
  expansion = true
@@ -495,16 +714,19 @@ export function tokenizeShell(command: string): ShellToken[] {
495
714
  pushWord(tokens, value, substitutions, expansion)
496
715
 
497
716
  if (pendingDelimiter !== undefined) {
498
- if (unsupportedDelimiter) {
499
- 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'.`)
500
719
  }
501
720
 
502
- pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted, stripTabs: tokens[pendingDelimiter]?.value.endsWith("-") === true })
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 })
503
725
  pendingDelimiter = undefined
504
726
  }
505
727
  }
506
728
 
507
- return tokens
729
+ return { tokens, end: i }
508
730
  }
509
731
 
510
732
  function splitSimpleCommands(tokens: readonly ShellToken[]): { tokens: ShellToken[]; pipeline: boolean }[] {
@@ -876,6 +1098,11 @@ export function extractGitCommits(command: string, inheritedDirectoryChange = fa
876
1098
  const body = wordTokens[bodyIndex]
877
1099
 
878
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
+
879
1106
  const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word))
880
1107
 
881
1108
  invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1))