opencode-commit-guard 1.0.2 → 1.0.3

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
@@ -94,16 +94,22 @@ You can provide this either via flags or directly in the message body:
94
94
 
95
95
  ### 5. Amend commits (`--amend`)
96
96
 
97
- If an agent runs `git commit --amend --no-edit` without supplying a new message, the plugin permits execution.
98
- If the agent provides a new message with `-m`, the plugin validates the new message.
99
- No-edit amendments that use `--git-dir` or `--work-tree` must provide a new inline message because the plugin cannot inspect repositories selected outside OpenCode's shell permissions.
100
- In workspace-backed sessions, no-edit amendments must also provide a new inline message because the repository exists in the remote workspace, not on the plugin host.
101
- No-edit amendments with `git -C` or `env -C` paths that start with `~` must provide an inline message because shell quoting changes their meaning.
97
+ Provide an explicit inline message with `-m` when you amend a commit.
98
+ The plugin rejects `git commit --amend --no-edit` without a message because reading the existing message would bypass shell permission checks.
99
+ The plugin validates explicit amendment messages in all repository locations.
102
100
 
103
101
  ### Message input
104
102
 
105
- Provide commit messages inline with `-m` or `--message`.
106
- The plugin rejects `-F`, `--file`, and standard-input message sources because the pre-execution hook cannot read them through OpenCode's file permissions.
103
+ Provide commit messages inline with `-m` or `--message`, or use one quoted heredoc directly on standard input:
104
+
105
+ ```bash
106
+ git commit -s -F - <<'EOF'
107
+ kernel: fix race
108
+ EOF
109
+ ```
110
+
111
+ The plugin rejects file-backed `-F` or `--file` messages without reading the files.
112
+ It also rejects unquoted or ambiguous standard-input sources.
107
113
 
108
114
  ## Development
109
115
 
package/dist/index.js CHANGED
@@ -202,8 +202,25 @@ function pushWord(tokens, value, substitutions) {
202
202
  tokens.push({ type: "word", value });
203
203
  }
204
204
  }
205
+ function heredocSubstitutions(body) {
206
+ const substitutions = [];
207
+ for (let i = 0;i < body.length; i++) {
208
+ if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
209
+ i++;
210
+ } else if (body[i] === "`") {
211
+ throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
212
+ } else if (body[i] === "$" && body[i + 1] === "(") {
213
+ const substitution = consumeCommandSubstitution(body, i);
214
+ substitutions.push(substitution.content);
215
+ i = substitution.end - 1;
216
+ }
217
+ }
218
+ return substitutions;
219
+ }
205
220
  function tokenizeShell(command) {
206
221
  const tokens = [];
222
+ const pendingHeredocs = [];
223
+ let pendingDelimiter;
207
224
  let i = 0;
208
225
  while (i < command.length) {
209
226
  const character = command[i];
@@ -234,15 +251,47 @@ function tokenizeShell(command) {
234
251
  ` || character === "(" || character === ")" || character === "{" || character === "}") {
235
252
  tokens.push({ type: "operator", value: character });
236
253
  i++;
254
+ if (character === `
255
+ ` && pendingHeredocs.length > 0) {
256
+ for (const heredoc of pendingHeredocs) {
257
+ const bodyStart = i;
258
+ let complete = false;
259
+ while (i < command.length) {
260
+ const lineEnd = command.indexOf(`
261
+ `, i);
262
+ const end = lineEnd < 0 ? command.length : lineEnd;
263
+ const line = command.slice(i, end);
264
+ i = lineEnd < 0 ? end : end + 1;
265
+ if (line === heredoc.delimiter) {
266
+ complete = true;
267
+ const body = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)));
268
+ tokens[heredoc.index] = {
269
+ ...tokens[heredoc.index],
270
+ heredoc: { body, quoted: heredoc.quoted },
271
+ substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body)
272
+ };
273
+ break;
274
+ }
275
+ }
276
+ if (!complete) {
277
+ throw new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
278
+ }
279
+ }
280
+ pendingHeredocs.length = 0;
281
+ }
237
282
  continue;
238
283
  }
239
284
  const redirectMatch = command.slice(i).match(/^(\d+)?(<<<|>>|<<|>&|<&|>\||>|<)(?:-|\d+)?/);
240
285
  if (redirectMatch !== null && redirectMatch[0] !== undefined) {
241
286
  tokens.push({ type: "redirect", value: redirectMatch[0] });
287
+ if (/^\d*<<$/.test(redirectMatch[0]))
288
+ pendingDelimiter = tokens.length - 1;
242
289
  i += redirectMatch[0].length;
243
290
  continue;
244
291
  }
245
292
  let value = "";
293
+ let quoted = false;
294
+ let unsupportedDelimiter = false;
246
295
  const substitutions = [];
247
296
  while (i < command.length) {
248
297
  const current = command[i];
@@ -254,6 +303,7 @@ function tokenizeShell(command) {
254
303
  continue;
255
304
  }
256
305
  if (current === "\\") {
306
+ quoted = true;
257
307
  if (i + 1 < command.length) {
258
308
  value += command[i + 1];
259
309
  i += 2;
@@ -264,6 +314,8 @@ function tokenizeShell(command) {
264
314
  continue;
265
315
  }
266
316
  if (current === "$" && command[i + 1] === "'") {
317
+ quoted = true;
318
+ unsupportedDelimiter = true;
267
319
  i += 2;
268
320
  while (i < command.length) {
269
321
  const ansiCharacter = command[i];
@@ -299,6 +351,7 @@ function tokenizeShell(command) {
299
351
  continue;
300
352
  }
301
353
  if (current === "'") {
354
+ quoted = true;
302
355
  i++;
303
356
  while (i < command.length && command[i] !== "'") {
304
357
  value += command[i];
@@ -309,6 +362,7 @@ function tokenizeShell(command) {
309
362
  continue;
310
363
  }
311
364
  if (current === '"') {
365
+ quoted = true;
312
366
  i++;
313
367
  while (i < command.length && command[i] !== '"') {
314
368
  const quotedCharacter = command[i];
@@ -354,23 +408,36 @@ function tokenizeShell(command) {
354
408
  i++;
355
409
  }
356
410
  pushWord(tokens, value, substitutions);
411
+ if (pendingDelimiter !== undefined) {
412
+ if (unsupportedDelimiter) {
413
+ throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.");
414
+ }
415
+ pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted });
416
+ pendingDelimiter = undefined;
417
+ }
357
418
  }
358
419
  return tokens;
359
420
  }
360
421
  function splitSimpleCommands(tokens) {
361
422
  const commands = [];
362
423
  let current = [];
424
+ let precedingPipeline = false;
363
425
  for (const token of tokens) {
364
426
  if (token.type === "operator") {
365
- if (current.length > 0)
366
- commands.push(current);
427
+ const isPipeline = token.value === "|" || token.value === "|&";
428
+ const hasCommand = current.length > 0;
429
+ if (hasCommand)
430
+ commands.push({ tokens: current, pipeline: precedingPipeline || isPipeline });
367
431
  current = [];
432
+ if (hasCommand || token.value !== `
433
+ `)
434
+ precedingPipeline = isPipeline;
368
435
  } else {
369
436
  current.push(token);
370
437
  }
371
438
  }
372
439
  if (current.length > 0)
373
- commands.push(current);
440
+ commands.push({ tokens: current, pipeline: precedingPipeline });
374
441
  return commands;
375
442
  }
376
443
  function extractCommandWords(tokens) {
@@ -405,7 +472,6 @@ function skipAssignments(words, start) {
405
472
  }
406
473
  function findCommandStart(words) {
407
474
  let index = skipAssignments(words, 0);
408
- const directoryChanges = [];
409
475
  while (index < words.length) {
410
476
  const word = words[index];
411
477
  if (word !== undefined && commandPrefixes.has(word)) {
@@ -425,16 +491,8 @@ function findCommandStart(words) {
425
491
  if (argument === "-u" || argument === "--unset") {
426
492
  index += 2;
427
493
  } else if (argument === "-C" || argument === "--chdir") {
428
- const directory = words[index + 1];
429
- if (directory !== undefined) {
430
- directoryChanges.push(directory);
431
- }
432
494
  index += 2;
433
- } else if (argument.startsWith("--chdir=")) {
434
- directoryChanges.push(argument.slice("--chdir=".length));
435
- index++;
436
- } else if (/^-C.+/.test(argument)) {
437
- directoryChanges.push(argument.slice(2));
495
+ } else if (argument.startsWith("--chdir=") || /^-C.+/.test(argument)) {
438
496
  index++;
439
497
  } else if (argument.startsWith("--unset=") || /^-u.+/.test(argument)) {
440
498
  index++;
@@ -476,17 +534,14 @@ function findCommandStart(words) {
476
534
  }
477
535
  break;
478
536
  }
479
- return { index, directoryChanges };
537
+ return index;
480
538
  }
481
539
  function extractInvocation(words, commandStart) {
482
- let wordIndex = commandStart.index;
540
+ let wordIndex = commandStart;
483
541
  const executable = words[wordIndex];
484
542
  if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
485
543
  return;
486
544
  wordIndex++;
487
- const directoryChanges = [...commandStart.directoryChanges];
488
- let gitDir;
489
- let workTree;
490
545
  let subcommand;
491
546
  while (wordIndex < words.length) {
492
547
  const argument = words[wordIndex];
@@ -498,33 +553,14 @@ function extractInvocation(words, commandStart) {
498
553
  break;
499
554
  }
500
555
  if (gitGlobalOptionsWithArg.has(argument)) {
501
- const optionValue = words[wordIndex + 1];
502
- if (argument === "-C" && optionValue !== undefined) {
503
- directoryChanges.push(optionValue);
504
- } else if (argument === "--git-dir" && optionValue !== undefined) {
505
- gitDir = optionValue;
506
- } else if (argument === "--work-tree" && optionValue !== undefined) {
507
- workTree = optionValue;
508
- }
509
556
  wordIndex += 2;
510
557
  continue;
511
558
  }
512
- if (argument.startsWith("--git-dir=")) {
513
- gitDir = argument.slice("--git-dir=".length);
514
- wordIndex++;
515
- continue;
516
- }
517
- if (argument.startsWith("--work-tree=")) {
518
- workTree = argument.slice("--work-tree=".length);
519
- wordIndex++;
520
- continue;
521
- }
522
- if (argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("-c")) {
559
+ if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("-c")) {
523
560
  wordIndex++;
524
561
  continue;
525
562
  }
526
563
  if (argument.startsWith("-C")) {
527
- directoryChanges.push(argument.slice(2));
528
564
  wordIndex++;
529
565
  continue;
530
566
  }
@@ -628,21 +664,44 @@ function extractInvocation(words, commandStart) {
628
664
  isAmend,
629
665
  hasNoEdit,
630
666
  isFixup,
631
- isHelp,
632
- directoryChanges,
633
- gitDir,
634
- workTree
667
+ isHelp
635
668
  };
636
669
  }
637
670
  function extractGitCommits(command) {
638
671
  const tokens = tokenizeShell(command);
639
672
  const invocations = [];
640
- for (const commandTokens of splitSimpleCommands(tokens)) {
673
+ for (const simple of splitSimpleCommands(tokens)) {
674
+ const commandTokens = simple.tokens;
641
675
  const words = extractCommandWords(commandTokens);
642
676
  const commandStart = findCommandStart(words);
643
677
  const invocation = extractInvocation(words, commandStart);
644
- if (invocation !== undefined)
645
- invocations.push(invocation);
678
+ if (invocation !== undefined) {
679
+ if (!invocation.filePaths.includes("-")) {
680
+ invocations.push(invocation);
681
+ continue;
682
+ }
683
+ const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/.test(token.value));
684
+ const stdinRedirects = commandTokens.filter((token) => {
685
+ if (token.type !== "redirect")
686
+ return false;
687
+ const match = token.value.match(/^(\d*)([<>])/);
688
+ return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0);
689
+ });
690
+ const heredoc = heredocs[0];
691
+ let stdinError;
692
+ if (simple.pipeline)
693
+ stdinError = "Pipelines cannot supply a validated commit message.";
694
+ else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
695
+ stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects.";
696
+ } else if (heredoc.heredoc?.quoted !== true) {
697
+ stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
698
+ }
699
+ invocations.push({
700
+ ...invocation,
701
+ stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
702
+ stdinError
703
+ });
704
+ }
646
705
  }
647
706
  for (const token of tokens) {
648
707
  for (const substitution of token.substitutions ?? []) {
@@ -653,39 +712,8 @@ function extractGitCommits(command) {
653
712
  }
654
713
 
655
714
  // src/validator.ts
656
- import { spawnSync } from "child_process";
657
- import { homedir } from "os";
658
- import { join, resolve } from "path";
659
715
  var scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/;
660
716
  var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
661
- function normalizeWindowsShellPath(inputPath) {
662
- if (process.platform !== "win32")
663
- return inputPath;
664
- const patterns = [
665
- /^\/([a-zA-Z]):(?:[\\/]|$)/,
666
- /^\/([a-zA-Z])(?:\/|$)/,
667
- /^\/cygdrive\/([a-zA-Z])(?:\/|$)/,
668
- /^\/mnt\/([a-zA-Z])(?:\/|$)/
669
- ];
670
- for (const pattern of patterns) {
671
- const match = inputPath.match(pattern);
672
- const drive = match?.[1];
673
- if (match?.[0] !== undefined && drive !== undefined) {
674
- return `${drive.toUpperCase()}:/${inputPath.slice(match[0].length)}`;
675
- }
676
- }
677
- return inputPath;
678
- }
679
- function resolveLocationPath(baseDirectory, inputPath) {
680
- const homeDirectory = process.env.OPENCODE_TEST_HOME ?? homedir();
681
- const normalizedInput = normalizeWindowsShellPath(inputPath);
682
- if (normalizedInput === "~")
683
- return homeDirectory;
684
- if (normalizedInput.startsWith("~/") || process.platform === "win32" && normalizedInput.startsWith("~\\")) {
685
- return join(homeDirectory, normalizedInput.slice(2));
686
- }
687
- return resolve(baseDirectory, normalizedInput);
688
- }
689
717
  function hasSignoffTrailer(lines) {
690
718
  const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
691
719
  return subjectIndex >= 0 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
@@ -721,57 +749,28 @@ ${examples}
721
749
  Command attempted:
722
750
  ${originalCommand}`);
723
751
  }
724
- function validateGitCommits(invocations, config, originalCommand, workingDirectory, canReadLocalRepository = true) {
752
+ function validateGitCommits(invocations, config, originalCommand) {
725
753
  const allViolations = [];
726
754
  for (const invocation of invocations) {
727
755
  if (invocation.isHelp) {
728
756
  continue;
729
757
  }
730
758
  const collectedMessages = [...invocation.messages];
731
- let messageDirectory = workingDirectory ?? process.cwd();
732
- for (const directoryChange of invocation.directoryChanges ?? []) {
733
- messageDirectory = resolve(messageDirectory, directoryChange);
734
- }
735
- if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0 && invocation.filePaths.length === 0) {
736
- const hasAmbiguousHomeChange = invocation.directoryChanges?.some((directoryChange) => directoryChange === "~" || directoryChange.startsWith("~/") || process.platform === "win32" && directoryChange.startsWith("~\\")) === true;
737
- if (hasAmbiguousHomeChange) {
738
- allViolations.push('Cannot validate an existing commit through a shell directory change that starts with "~". Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
739
- continue;
740
- }
741
- if (!canReadLocalRepository) {
742
- allViolations.push('Cannot validate the existing commit in a workspace-backed location. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
743
- continue;
744
- }
745
- if (invocation.gitDir !== undefined || invocation.workTree !== undefined) {
746
- allViolations.push('Cannot validate an existing commit through --git-dir or --work-tree before shell permissions run. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
747
- continue;
748
- }
749
- const result = spawnSync("git", ["log", "-1", "--format=%B", "HEAD"], {
750
- cwd: messageDirectory,
751
- encoding: "utf-8",
752
- stdio: ["ignore", "pipe", "pipe"]
753
- });
754
- if (result.error !== undefined) {
755
- allViolations.push(`Failed to read the existing HEAD commit message: ${result.error.message}`);
756
- continue;
757
- }
758
- if (result.status !== 0) {
759
- const detail = result.stderr.trim();
760
- const suffix = detail.length > 0 ? `: ${detail}` : ".";
761
- allViolations.push(`Failed to read the existing HEAD commit message${suffix}`);
759
+ if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0) {
760
+ allViolations.push('Cannot validate --amend --no-edit before shell permissions run because it would read the existing commit. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".');
761
+ continue;
762
+ }
763
+ const filePath = invocation.filePaths.at(-1);
764
+ if (filePath !== undefined) {
765
+ if (filePath !== "-" || invocation.filePaths.length !== 1) {
766
+ allViolations.push(`Cannot validate a commit message from file "${filePath}" before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`);
762
767
  continue;
763
768
  }
764
- const existingMessage = result.stdout.replace(/[\r\n]+$/, "");
765
- if (existingMessage.trim().length === 0) {
766
- allViolations.push("The existing HEAD commit message is empty.");
769
+ if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
770
+ allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted heredoc directly on git commit -s -F - <<'EOF', or use -m "kernel: add support for foo".`);
767
771
  continue;
768
772
  }
769
- collectedMessages.push(existingMessage);
770
- }
771
- const filePath = invocation.filePaths.at(-1);
772
- if (filePath !== undefined) {
773
- allViolations.push(`Cannot validate a commit message from ${filePath === "-" ? "standard input" : `file "${filePath}"`} before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`);
774
- continue;
773
+ collectedMessages.push(invocation.stdinMessage);
775
774
  }
776
775
  if (collectedMessages.length === 0) {
777
776
  if (invocation.isFixup === true) {
@@ -846,8 +845,6 @@ var plugin = Plugin.define({
846
845
  const config = yield* Effect.sync(() => {
847
846
  return parseConfig(ctx.options);
848
847
  });
849
- const sessionDirectory = ctx.location.directory;
850
- const canReadLocalRepository = ctx.location.workspaceID === undefined;
851
848
  yield* ctx.tool.hook("execute.before", (event) => Effect.try({
852
849
  try: () => {
853
850
  if (event.tool !== "shell" && event.tool !== "bash") {
@@ -861,15 +858,11 @@ var plugin = Plugin.define({
861
858
  if (!isJSONString(command)) {
862
859
  return;
863
860
  }
864
- if (!command.includes("commit")) {
865
- return;
866
- }
867
861
  const invocations = extractGitCommits(command);
868
862
  if (invocations.length === 0) {
869
863
  return;
870
864
  }
871
- const workdir = rawInput["workdir"];
872
- validateGitCommits(invocations, config, command, isJSONString(workdir) ? resolveLocationPath(sessionDirectory, workdir) : sessionDirectory, canReadLocalRepository);
865
+ validateGitCommits(invocations, config, command);
873
866
  },
874
867
  catch: (error) => new Tool.Error({
875
868
  message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,15 +21,15 @@
21
21
  "prepack": "bun run build"
22
22
  },
23
23
  "dependencies": {
24
- "@opencode/plugin": "2.0.3",
25
- "@opencode/schema": "2.0.3",
24
+ "@opencode/plugin": "2.0.15",
25
+ "@opencode/schema": "2.0.15",
26
26
  "effect": "4.0.0-rc.112"
27
27
  },
28
28
  "devDependencies": {
29
- "@oxlint/plugins": "1.83.0",
30
- "@types/bun": "latest",
31
- "oxlint": "1.83.0",
32
- "typescript": "latest"
29
+ "@oxlint/plugins": "1.85.0",
30
+ "@types/bun": "1.4.2",
31
+ "oxlint": "1.85.0",
32
+ "typescript": "7.0.2"
33
33
  },
34
34
  "engines": {
35
35
  "bun": ">=1.2.0"
package/src/plugin.ts CHANGED
@@ -5,7 +5,7 @@ import { parseConfig } from "./config.js"
5
5
  import { extractGitCommits } from "./shell.js"
6
6
  import { isJSONString, isRecord } from "./types.js"
7
7
  import type { JsonValue } from "./types.js"
8
- import { resolveLocationPath, validateGitCommits } from "./validator.js"
8
+ import { validateGitCommits } from "./validator.js"
9
9
 
10
10
  export const plugin = Plugin.define({
11
11
  id: "opencode-commit-guard",
@@ -15,9 +15,6 @@ export const plugin = Plugin.define({
15
15
  return parseConfig(ctx.options as JsonValue | undefined)
16
16
  })
17
17
 
18
- const sessionDirectory = ctx.location.directory
19
- const canReadLocalRepository = ctx.location.workspaceID === undefined
20
-
21
18
  yield* ctx.tool.hook("execute.before", (event) => Effect.try({
22
19
  try: () => {
23
20
  if (event.tool !== "shell" && event.tool !== "bash") {
@@ -37,26 +34,13 @@ export const plugin = Plugin.define({
37
34
  return
38
35
  }
39
36
 
40
- if (!command.includes("commit")) {
41
- return
42
- }
43
-
44
37
  const invocations = extractGitCommits(command)
45
38
 
46
39
  if (invocations.length === 0) {
47
40
  return
48
41
  }
49
42
 
50
- const workdir = rawInput["workdir"]
51
- validateGitCommits(
52
- invocations,
53
- config,
54
- command,
55
- isJSONString(workdir)
56
- ? resolveLocationPath(sessionDirectory, workdir)
57
- : sessionDirectory,
58
- canReadLocalRepository,
59
- )
43
+ validateGitCommits(invocations, config, command)
60
44
  },
61
45
  catch: (error) => new Tool.Error({
62
46
  message: error instanceof Error
package/src/shell.ts CHANGED
@@ -40,11 +40,6 @@ interface CommandSubstitution {
40
40
  readonly end: number
41
41
  }
42
42
 
43
- interface CommandStart {
44
- readonly index: number
45
- readonly directoryChanges: readonly string[]
46
- }
47
-
48
43
  function isWordSeparator(character: string): boolean {
49
44
  return (
50
45
  character === " " ||
@@ -161,8 +156,29 @@ function pushWord(
161
156
  }
162
157
  }
163
158
 
159
+ function heredocSubstitutions(body: string): string[] {
160
+ const substitutions: string[] = []
161
+
162
+ for (let i = 0; i < body.length; i++) {
163
+ if (body[i] === "\\" && (body[i + 1] === "$" || body[i + 1] === "`")) {
164
+ i++
165
+ } else if (body[i] === "`") {
166
+ throw new Error("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.")
167
+ } else if (body[i] === "$" && body[i + 1] === "(") {
168
+ const substitution = consumeCommandSubstitution(body, i)
169
+
170
+ substitutions.push(substitution.content)
171
+ i = substitution.end - 1
172
+ }
173
+ }
174
+
175
+ return substitutions
176
+ }
177
+
164
178
  export function tokenizeShell(command: string): ShellToken[] {
165
179
  const tokens: ShellToken[] = []
180
+ const pendingHeredocs: { index: number; delimiter: string; quoted: boolean }[] = []
181
+ let pendingDelimiter: number | undefined
166
182
  let i = 0
167
183
 
168
184
  while (i < command.length) {
@@ -210,6 +226,41 @@ export function tokenizeShell(command: string): ShellToken[] {
210
226
  ) {
211
227
  tokens.push({ type: "operator", value: character })
212
228
  i++
229
+
230
+ if (character === "\n" && pendingHeredocs.length > 0) {
231
+ for (const heredoc of pendingHeredocs) {
232
+ const bodyStart = i
233
+ let complete = false
234
+
235
+ while (i < command.length) {
236
+ const lineEnd = command.indexOf("\n", i)
237
+ const end = lineEnd < 0 ? command.length : lineEnd
238
+ const line = command.slice(i, end)
239
+ i = lineEnd < 0 ? end : end + 1
240
+
241
+ if (line === heredoc.delimiter) {
242
+ complete = true
243
+ const body = command.slice(bodyStart, i - (line.length + (lineEnd < 0 ? 0 : 1)))
244
+
245
+ tokens[heredoc.index] = {
246
+ ...tokens[heredoc.index]!,
247
+ heredoc: { body, quoted: heredoc.quoted },
248
+ substitutions: heredoc.quoted
249
+ ? undefined
250
+ : heredocSubstitutions(body),
251
+ }
252
+ break
253
+ }
254
+ }
255
+
256
+ if (!complete) {
257
+ throw new Error("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.")
258
+ }
259
+ }
260
+
261
+ pendingHeredocs.length = 0
262
+ }
263
+
213
264
  continue
214
265
  }
215
266
 
@@ -217,11 +268,15 @@ export function tokenizeShell(command: string): ShellToken[] {
217
268
 
218
269
  if (redirectMatch !== null && redirectMatch[0] !== undefined) {
219
270
  tokens.push({ type: "redirect", value: redirectMatch[0] })
271
+
272
+ if (/^\d*<<$/.test(redirectMatch[0])) pendingDelimiter = tokens.length - 1
220
273
  i += redirectMatch[0].length
221
274
  continue
222
275
  }
223
276
 
224
277
  let value = ""
278
+ let quoted = false
279
+ let unsupportedDelimiter = false
225
280
  const substitutions: string[] = []
226
281
 
227
282
  while (i < command.length) {
@@ -235,6 +290,8 @@ export function tokenizeShell(command: string): ShellToken[] {
235
290
  }
236
291
 
237
292
  if (current === "\\") {
293
+ quoted = true
294
+
238
295
  if (i + 1 < command.length) {
239
296
  value += command[i + 1]
240
297
  i += 2
@@ -247,6 +304,8 @@ export function tokenizeShell(command: string): ShellToken[] {
247
304
  }
248
305
 
249
306
  if (current === "$" && command[i + 1] === "'") {
307
+ quoted = true
308
+ unsupportedDelimiter = true
250
309
  i += 2
251
310
 
252
311
  while (i < command.length) {
@@ -280,6 +339,7 @@ export function tokenizeShell(command: string): ShellToken[] {
280
339
  }
281
340
 
282
341
  if (current === "'") {
342
+ quoted = true
283
343
  i++
284
344
 
285
345
  while (i < command.length && command[i] !== "'") {
@@ -292,6 +352,7 @@ export function tokenizeShell(command: string): ShellToken[] {
292
352
  }
293
353
 
294
354
  if (current === '"') {
355
+ quoted = true
295
356
  i++
296
357
 
297
358
  while (i < command.length && command[i] !== '"') {
@@ -343,25 +404,41 @@ export function tokenizeShell(command: string): ShellToken[] {
343
404
  }
344
405
 
345
406
  pushWord(tokens, value, substitutions)
407
+
408
+ if (pendingDelimiter !== undefined) {
409
+ if (unsupportedDelimiter) {
410
+ throw new Error("Cannot validate an ANSI-C quoted heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.")
411
+ }
412
+
413
+ pendingHeredocs.push({ index: pendingDelimiter, delimiter: value, quoted })
414
+ pendingDelimiter = undefined
415
+ }
346
416
  }
347
417
 
348
418
  return tokens
349
419
  }
350
420
 
351
- function splitSimpleCommands(tokens: readonly ShellToken[]): ShellToken[][] {
352
- const commands: ShellToken[][] = []
421
+ function splitSimpleCommands(tokens: readonly ShellToken[]): { tokens: ShellToken[]; pipeline: boolean }[] {
422
+ const commands: { tokens: ShellToken[]; pipeline: boolean }[] = []
353
423
  let current: ShellToken[] = []
424
+ let precedingPipeline = false
354
425
 
355
426
  for (const token of tokens) {
356
427
  if (token.type === "operator") {
357
- if (current.length > 0) commands.push(current)
428
+ const isPipeline = token.value === "|" || token.value === "|&"
429
+
430
+ const hasCommand = current.length > 0
431
+
432
+ if (hasCommand) commands.push({ tokens: current, pipeline: precedingPipeline || isPipeline })
358
433
  current = []
434
+
435
+ if (hasCommand || token.value !== "\n") precedingPipeline = isPipeline
359
436
  } else {
360
437
  current.push(token)
361
438
  }
362
439
  }
363
440
 
364
- if (current.length > 0) commands.push(current)
441
+ if (current.length > 0) commands.push({ tokens: current, pipeline: precedingPipeline })
365
442
 
366
443
  return commands
367
444
  }
@@ -403,9 +480,8 @@ function skipAssignments(words: readonly string[], start: number): number {
403
480
  return index
404
481
  }
405
482
 
406
- function findCommandStart(words: readonly string[]): CommandStart {
483
+ function findCommandStart(words: readonly string[]): number {
407
484
  let index = skipAssignments(words, 0)
408
- const directoryChanges: string[] = []
409
485
 
410
486
  while (index < words.length) {
411
487
  const word = words[index]
@@ -431,18 +507,8 @@ function findCommandStart(words: readonly string[]): CommandStart {
431
507
  if (argument === "-u" || argument === "--unset") {
432
508
  index += 2
433
509
  } else if (argument === "-C" || argument === "--chdir") {
434
- const directory = words[index + 1]
435
-
436
- if (directory !== undefined) {
437
- directoryChanges.push(directory)
438
- }
439
-
440
510
  index += 2
441
- } else if (argument.startsWith("--chdir=")) {
442
- directoryChanges.push(argument.slice("--chdir=".length))
443
- index++
444
- } else if (/^-C.+/.test(argument)) {
445
- directoryChanges.push(argument.slice(2))
511
+ } else if (argument.startsWith("--chdir=") || /^-C.+/.test(argument)) {
446
512
  index++
447
513
  } else if (argument.startsWith("--unset=") || /^-u.+/.test(argument)) {
448
514
  index++
@@ -490,22 +556,18 @@ function findCommandStart(words: readonly string[]): CommandStart {
490
556
  break
491
557
  }
492
558
 
493
- return { index, directoryChanges }
559
+ return index
494
560
  }
495
561
 
496
562
  function extractInvocation(
497
563
  words: readonly string[],
498
- commandStart: CommandStart,
564
+ commandStart: number,
499
565
  ): GitCommitInvocation | undefined {
500
- let wordIndex = commandStart.index
566
+ let wordIndex = commandStart
501
567
  const executable = words[wordIndex]
502
568
 
503
569
  if (executable === undefined || (executable !== "git" && !executable.endsWith("/git"))) return undefined
504
570
  wordIndex++
505
- const directoryChanges = [...commandStart.directoryChanges]
506
- let gitDir: string | undefined
507
- let workTree: string | undefined
508
-
509
571
  let subcommand: string | undefined
510
572
 
511
573
  while (wordIndex < words.length) {
@@ -520,33 +582,13 @@ function extractInvocation(
520
582
  }
521
583
 
522
584
  if (gitGlobalOptionsWithArg.has(argument)) {
523
- const optionValue = words[wordIndex + 1]
524
-
525
- if (argument === "-C" && optionValue !== undefined) {
526
- directoryChanges.push(optionValue)
527
- } else if (argument === "--git-dir" && optionValue !== undefined) {
528
- gitDir = optionValue
529
- } else if (argument === "--work-tree" && optionValue !== undefined) {
530
- workTree = optionValue
531
- }
532
-
533
585
  wordIndex += 2
534
586
  continue
535
587
  }
536
588
 
537
- if (argument.startsWith("--git-dir=")) {
538
- gitDir = argument.slice("--git-dir=".length)
539
- wordIndex++
540
- continue
541
- }
542
-
543
- if (argument.startsWith("--work-tree=")) {
544
- workTree = argument.slice("--work-tree=".length)
545
- wordIndex++
546
- continue
547
- }
548
-
549
589
  if (
590
+ argument.startsWith("--git-dir=") ||
591
+ argument.startsWith("--work-tree=") ||
550
592
  argument.startsWith("--namespace=") ||
551
593
  argument.startsWith("--exec-path=") ||
552
594
  argument.startsWith("--super-prefix=") ||
@@ -557,7 +599,6 @@ function extractInvocation(
557
599
  }
558
600
 
559
601
  if (argument.startsWith("-C")) {
560
- directoryChanges.push(argument.slice(2))
561
602
  wordIndex++
562
603
  continue
563
604
  }
@@ -670,9 +711,6 @@ function extractInvocation(
670
711
  hasNoEdit,
671
712
  isFixup,
672
713
  isHelp,
673
- directoryChanges,
674
- gitDir,
675
- workTree,
676
714
  }
677
715
  }
678
716
 
@@ -680,12 +718,44 @@ export function extractGitCommits(command: string): GitCommitInvocation[] {
680
718
  const tokens = tokenizeShell(command)
681
719
  const invocations: GitCommitInvocation[] = []
682
720
 
683
- for (const commandTokens of splitSimpleCommands(tokens)) {
721
+ for (const simple of splitSimpleCommands(tokens)) {
722
+ const commandTokens = simple.tokens
684
723
  const words = extractCommandWords(commandTokens)
685
724
  const commandStart = findCommandStart(words)
686
725
  const invocation = extractInvocation(words, commandStart)
687
726
 
688
- if (invocation !== undefined) invocations.push(invocation)
727
+ if (invocation !== undefined) {
728
+ if (!invocation.filePaths.includes("-")) {
729
+ invocations.push(invocation)
730
+ continue
731
+ }
732
+
733
+ const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/.test(token.value))
734
+
735
+ const stdinRedirects = commandTokens.filter((token) => {
736
+ if (token.type !== "redirect") return false
737
+
738
+ const match = token.value.match(/^(\d*)([<>])/)
739
+
740
+ return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0)
741
+ })
742
+
743
+ const heredoc = heredocs[0]
744
+ let stdinError: string | undefined
745
+
746
+ if (simple.pipeline) stdinError = "Pipelines cannot supply a validated commit message."
747
+ else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
748
+ stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects."
749
+ } else if (heredoc.heredoc?.quoted !== true) {
750
+ stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'."
751
+ }
752
+
753
+ invocations.push({
754
+ ...invocation,
755
+ stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
756
+ stdinError,
757
+ })
758
+ }
689
759
  }
690
760
 
691
761
  for (const token of tokens) {
package/src/types.ts CHANGED
@@ -41,19 +41,19 @@ export interface ShellToken {
41
41
  readonly type: ShellTokenType
42
42
  readonly value: string
43
43
  readonly substitutions?: readonly string[]
44
+ readonly heredoc?: { readonly body: string; readonly quoted: boolean }
44
45
  }
45
46
 
46
47
  export interface GitCommitInvocation {
47
48
  readonly messages: readonly string[]
48
49
  readonly filePaths: readonly string[]
50
+ readonly stdinMessage?: string
51
+ readonly stdinError?: string
49
52
  readonly hasSignoffFlag: boolean
50
53
  readonly isAmend: boolean
51
54
  readonly hasNoEdit?: boolean
52
55
  readonly isFixup?: boolean
53
56
  readonly isHelp: boolean
54
- readonly directoryChanges?: readonly string[]
55
- readonly gitDir?: string
56
- readonly workTree?: string
57
57
  }
58
58
 
59
59
  export interface OverlongLine {
package/src/validator.ts CHANGED
@@ -1,6 +1,3 @@
1
- import { spawnSync } from "node:child_process"
2
- import { homedir } from "node:os"
3
- import { join, resolve } from "node:path"
4
1
  import type {
5
2
  CommitGuardConfig,
6
3
  GitCommitInvocation,
@@ -11,44 +8,6 @@ const scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/
11
8
 
12
9
  const signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i
13
10
 
14
- function normalizeWindowsShellPath(inputPath: string): string {
15
- if (process.platform !== "win32") return inputPath
16
-
17
- const patterns = [
18
- /^\/([a-zA-Z]):(?:[\\/]|$)/,
19
- /^\/([a-zA-Z])(?:\/|$)/,
20
- /^\/cygdrive\/([a-zA-Z])(?:\/|$)/,
21
- /^\/mnt\/([a-zA-Z])(?:\/|$)/,
22
- ]
23
-
24
- for (const pattern of patterns) {
25
- const match = inputPath.match(pattern)
26
- const drive = match?.[1]
27
-
28
- if (match?.[0] !== undefined && drive !== undefined) {
29
- return `${drive.toUpperCase()}:/${inputPath.slice(match[0].length)}`
30
- }
31
- }
32
-
33
- return inputPath
34
- }
35
-
36
- export function resolveLocationPath(baseDirectory: string, inputPath: string): string {
37
- const homeDirectory = process.env.OPENCODE_TEST_HOME ?? homedir()
38
- const normalizedInput = normalizeWindowsShellPath(inputPath)
39
-
40
- if (normalizedInput === "~") return homeDirectory
41
-
42
- if (
43
- normalizedInput.startsWith("~/") ||
44
- (process.platform === "win32" && normalizedInput.startsWith("~\\"))
45
- ) {
46
- return join(homeDirectory, normalizedInput.slice(2))
47
- }
48
-
49
- return resolve(baseDirectory, normalizedInput)
50
- }
51
-
52
11
  function hasSignoffTrailer(lines: readonly string[]): boolean {
53
12
  const subjectIndex = lines.findIndex((line) => line.trim().length > 0)
54
13
 
@@ -96,8 +55,6 @@ export function validateGitCommits(
96
55
  invocations: readonly GitCommitInvocation[],
97
56
  config: CommitGuardConfig,
98
57
  originalCommand: string,
99
- workingDirectory?: string,
100
- canReadLocalRepository = true,
101
58
  ): void {
102
59
  const allViolations: string[] = []
103
60
 
@@ -107,80 +64,36 @@ export function validateGitCommits(
107
64
  }
108
65
 
109
66
  const collectedMessages: string[] = [...invocation.messages]
110
- let messageDirectory = workingDirectory ?? process.cwd()
111
-
112
- for (const directoryChange of invocation.directoryChanges ?? []) {
113
- messageDirectory = resolve(messageDirectory, directoryChange)
114
- }
115
67
 
116
68
  if (
117
69
  invocation.isAmend &&
118
70
  invocation.hasNoEdit === true &&
119
- invocation.messages.length === 0 &&
120
- invocation.filePaths.length === 0
71
+ invocation.messages.length === 0
121
72
  ) {
122
- const hasAmbiguousHomeChange = invocation.directoryChanges?.some((directoryChange) =>
123
- directoryChange === "~" ||
124
- directoryChange.startsWith("~/") ||
125
- (process.platform === "win32" && directoryChange.startsWith("~\\"))
126
- ) === true
73
+ allViolations.push(
74
+ 'Cannot validate --amend --no-edit before shell permissions run because it would read the existing commit. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".',
75
+ )
76
+ continue
77
+ }
127
78
 
128
- if (hasAmbiguousHomeChange) {
129
- allViolations.push(
130
- 'Cannot validate an existing commit through a shell directory change that starts with "~". Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".',
131
- )
132
- continue
133
- }
79
+ const filePath = invocation.filePaths.at(-1)
134
80
 
135
- if (!canReadLocalRepository) {
81
+ if (filePath !== undefined) {
82
+ if (filePath !== "-" || invocation.filePaths.length !== 1) {
136
83
  allViolations.push(
137
- 'Cannot validate the existing commit in a workspace-backed location. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".',
84
+ `Cannot validate a commit message from file "${filePath}" before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`,
138
85
  )
139
86
  continue
140
87
  }
141
88
 
142
- if (invocation.gitDir !== undefined || invocation.workTree !== undefined) {
89
+ if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
143
90
  allViolations.push(
144
- 'Cannot validate an existing commit through --git-dir or --work-tree before shell permissions run. Provide an explicit inline message, for example: git commit --amend -s -m "kernel: fix race".',
91
+ `${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted heredoc directly on git commit -s -F - <<'EOF', or use -m "kernel: add support for foo".`,
145
92
  )
146
93
  continue
147
94
  }
148
95
 
149
- const result = spawnSync("git", ["log", "-1", "--format=%B", "HEAD"], {
150
- cwd: messageDirectory,
151
- encoding: "utf-8",
152
- stdio: ["ignore", "pipe", "pipe"],
153
- })
154
-
155
- if (result.error !== undefined) {
156
- allViolations.push(`Failed to read the existing HEAD commit message: ${result.error.message}`)
157
- continue
158
- }
159
-
160
- if (result.status !== 0) {
161
- const detail = result.stderr.trim()
162
- const suffix = detail.length > 0 ? `: ${detail}` : "."
163
- allViolations.push(`Failed to read the existing HEAD commit message${suffix}`)
164
- continue
165
- }
166
-
167
- const existingMessage = result.stdout.replace(/[\r\n]+$/, "")
168
-
169
- if (existingMessage.trim().length === 0) {
170
- allViolations.push("The existing HEAD commit message is empty.")
171
- continue
172
- }
173
-
174
- collectedMessages.push(existingMessage)
175
- }
176
-
177
- const filePath = invocation.filePaths.at(-1)
178
-
179
- if (filePath !== undefined) {
180
- allViolations.push(
181
- `Cannot validate a commit message from ${filePath === "-" ? "standard input" : `file "${filePath}"`} before shell permissions run. Use an inline message, for example: git commit -s -m "kernel: add support for foo".`,
182
- )
183
- continue
96
+ collectedMessages.push(invocation.stdinMessage)
184
97
  }
185
98
 
186
99
  if (collectedMessages.length === 0) {