opencode-commit-guard 1.0.0 → 1.0.2
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 +10 -2
- package/dist/index.js +147 -78
- package/package.json +7 -5
- package/src/plugin.ts +51 -31
- package/src/shell.ts +31 -4
- package/src/types.ts +3 -0
- package/src/validator.ts +111 -52
package/README.md
CHANGED
|
@@ -5,8 +5,8 @@ OpenCode V2 plugin that enforces git commit message format rules during agent se
|
|
|
5
5
|
## Overview
|
|
6
6
|
|
|
7
7
|
`opencode-commit-guard` intercepts `shell` and `bash` tool execution before it runs.
|
|
8
|
-
When an agent attempts a `git commit`, the plugin inspects the command line
|
|
9
|
-
If the commit violates configured formatting standards, the plugin rejects the tool call
|
|
8
|
+
When an agent attempts a `git commit`, the plugin inspects the command line and inline message content.
|
|
9
|
+
If the commit violates configured formatting standards, the plugin rejects the tool call through OpenCode's typed tool-error channel.
|
|
10
10
|
|
|
11
11
|
### Why this approach fits
|
|
12
12
|
|
|
@@ -96,6 +96,14 @@ You can provide this either via flags or directly in the message body:
|
|
|
96
96
|
|
|
97
97
|
If an agent runs `git commit --amend --no-edit` without supplying a new message, the plugin permits execution.
|
|
98
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.
|
|
102
|
+
|
|
103
|
+
### Message input
|
|
104
|
+
|
|
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.
|
|
99
107
|
|
|
100
108
|
## Development
|
|
101
109
|
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// src/plugin.ts
|
|
3
|
-
import { Plugin } from "@opencode/plugin";
|
|
3
|
+
import { Plugin } from "@opencode/plugin/effect";
|
|
4
|
+
import { Tool } from "@opencode/schema/tool";
|
|
5
|
+
import { Effect } from "effect";
|
|
4
6
|
|
|
5
7
|
// src/types.ts
|
|
6
8
|
function isJSONString(value) {
|
|
@@ -483,6 +485,8 @@ function extractInvocation(words, commandStart) {
|
|
|
483
485
|
return;
|
|
484
486
|
wordIndex++;
|
|
485
487
|
const directoryChanges = [...commandStart.directoryChanges];
|
|
488
|
+
let gitDir;
|
|
489
|
+
let workTree;
|
|
486
490
|
let subcommand;
|
|
487
491
|
while (wordIndex < words.length) {
|
|
488
492
|
const argument = words[wordIndex];
|
|
@@ -497,11 +501,25 @@ function extractInvocation(words, commandStart) {
|
|
|
497
501
|
const optionValue = words[wordIndex + 1];
|
|
498
502
|
if (argument === "-C" && optionValue !== undefined) {
|
|
499
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;
|
|
500
508
|
}
|
|
501
509
|
wordIndex += 2;
|
|
502
510
|
continue;
|
|
503
511
|
}
|
|
504
|
-
if (argument.startsWith("--git-dir=")
|
|
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")) {
|
|
505
523
|
wordIndex++;
|
|
506
524
|
continue;
|
|
507
525
|
}
|
|
@@ -525,6 +543,7 @@ function extractInvocation(words, commandStart) {
|
|
|
525
543
|
let hasSignoffFlag = false;
|
|
526
544
|
let isAmend = false;
|
|
527
545
|
let hasNoEdit = false;
|
|
546
|
+
let isFixup = false;
|
|
528
547
|
let isHelp = false;
|
|
529
548
|
const collectMessage = (word) => {
|
|
530
549
|
if (word === undefined)
|
|
@@ -540,6 +559,8 @@ function extractInvocation(words, commandStart) {
|
|
|
540
559
|
const argument = words[index];
|
|
541
560
|
if (argument === undefined)
|
|
542
561
|
break;
|
|
562
|
+
const equalsIndex = argument.indexOf("=");
|
|
563
|
+
const longOptionName = equalsIndex > 0 ? argument.slice(0, equalsIndex) : argument;
|
|
543
564
|
if (argument === "--")
|
|
544
565
|
break;
|
|
545
566
|
if (argument === "-h" || argument === "--help") {
|
|
@@ -564,8 +585,13 @@ function extractInvocation(words, commandStart) {
|
|
|
564
585
|
collectFile(words[index]);
|
|
565
586
|
} else if (argument.startsWith("--file=")) {
|
|
566
587
|
collectFile(argument.slice("--file=".length));
|
|
567
|
-
} else if (
|
|
568
|
-
|
|
588
|
+
} else if (argument === "--fixup" || argument.startsWith("--fixup=")) {
|
|
589
|
+
isFixup = true;
|
|
590
|
+
if (equalsIndex < 0)
|
|
591
|
+
index++;
|
|
592
|
+
} else if (commitLongOptionsWithArg.has(longOptionName)) {
|
|
593
|
+
if (equalsIndex < 0)
|
|
594
|
+
index++;
|
|
569
595
|
} else if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 1) {
|
|
570
596
|
for (let characterIndex = 1;characterIndex < argument.length; characterIndex++) {
|
|
571
597
|
const option = argument[characterIndex];
|
|
@@ -601,8 +627,11 @@ function extractInvocation(words, commandStart) {
|
|
|
601
627
|
hasSignoffFlag,
|
|
602
628
|
isAmend,
|
|
603
629
|
hasNoEdit,
|
|
630
|
+
isFixup,
|
|
604
631
|
isHelp,
|
|
605
|
-
directoryChanges
|
|
632
|
+
directoryChanges,
|
|
633
|
+
gitDir,
|
|
634
|
+
workTree
|
|
606
635
|
};
|
|
607
636
|
}
|
|
608
637
|
function extractGitCommits(command) {
|
|
@@ -624,11 +653,39 @@ function extractGitCommits(command) {
|
|
|
624
653
|
}
|
|
625
654
|
|
|
626
655
|
// src/validator.ts
|
|
627
|
-
import {
|
|
628
|
-
import {
|
|
656
|
+
import { spawnSync } from "child_process";
|
|
657
|
+
import { homedir } from "os";
|
|
658
|
+
import { join, resolve } from "path";
|
|
629
659
|
var scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/;
|
|
630
660
|
var signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i;
|
|
631
|
-
|
|
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
|
+
}
|
|
632
689
|
function hasSignoffTrailer(lines) {
|
|
633
690
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
634
691
|
return subjectIndex >= 0 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
|
|
@@ -664,66 +721,64 @@ ${examples}
|
|
|
664
721
|
Command attempted:
|
|
665
722
|
${originalCommand}`);
|
|
666
723
|
}
|
|
667
|
-
function validateGitCommits(invocations, config, originalCommand, workingDirectory) {
|
|
724
|
+
function validateGitCommits(invocations, config, originalCommand, workingDirectory, canReadLocalRepository = true) {
|
|
668
725
|
const allViolations = [];
|
|
669
726
|
for (const invocation of invocations) {
|
|
670
727
|
if (invocation.isHelp) {
|
|
671
728
|
continue;
|
|
672
729
|
}
|
|
673
|
-
if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0 && invocation.filePaths.length === 0) {
|
|
674
|
-
continue;
|
|
675
|
-
}
|
|
676
730
|
const collectedMessages = [...invocation.messages];
|
|
677
731
|
let messageDirectory = workingDirectory ?? process.cwd();
|
|
678
732
|
for (const directoryChange of invocation.directoryChanges ?? []) {
|
|
679
733
|
messageDirectory = resolve(messageDirectory, directoryChange);
|
|
680
734
|
}
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
if (
|
|
684
|
-
allViolations.push(
|
|
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".');
|
|
685
739
|
continue;
|
|
686
740
|
}
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
allViolations.push(`Commit message file "${filePath}" does not exist.`);
|
|
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".');
|
|
690
743
|
continue;
|
|
691
744
|
}
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
allViolations.push(`Commit message path "${filePath}" is not a regular file.`);
|
|
696
|
-
continue;
|
|
697
|
-
}
|
|
698
|
-
if (fileInfo.size > maxMessageFileSize) {
|
|
699
|
-
allViolations.push(`Commit message file "${filePath}" exceeds the 64 KB size limit.`);
|
|
700
|
-
continue;
|
|
701
|
-
}
|
|
702
|
-
const descriptor = openSync(fullPath, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
703
|
-
try {
|
|
704
|
-
const openedFileInfo = fstatSync(descriptor);
|
|
705
|
-
if (!openedFileInfo.isFile()) {
|
|
706
|
-
allViolations.push(`Commit message path "${filePath}" is not a regular file.`);
|
|
707
|
-
continue;
|
|
708
|
-
}
|
|
709
|
-
const fileContent = Buffer.alloc(maxMessageFileSize + 1);
|
|
710
|
-
const bytesRead = readSync(descriptor, fileContent, 0, fileContent.length, 0);
|
|
711
|
-
if (bytesRead > maxMessageFileSize) {
|
|
712
|
-
allViolations.push(`Commit message file "${filePath}" exceeds the 64 KB size limit.`);
|
|
713
|
-
continue;
|
|
714
|
-
}
|
|
715
|
-
collectedMessages.push(fileContent.toString("utf-8", 0, bytesRead));
|
|
716
|
-
} finally {
|
|
717
|
-
closeSync(descriptor);
|
|
718
|
-
}
|
|
719
|
-
} catch (readError) {
|
|
720
|
-
const errorDetail = readError instanceof Error ? readError.message : "Cannot read file";
|
|
721
|
-
allViolations.push(`Failed to read commit message file "${filePath}": ${errorDetail}`);
|
|
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;
|
|
722
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}`);
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
const existingMessage = result.stdout.replace(/[\r\n]+$/, "");
|
|
765
|
+
if (existingMessage.trim().length === 0) {
|
|
766
|
+
allViolations.push("The existing HEAD commit message is empty.");
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
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;
|
|
723
775
|
}
|
|
724
776
|
if (collectedMessages.length === 0) {
|
|
777
|
+
if (invocation.isFixup === true) {
|
|
778
|
+
continue;
|
|
779
|
+
}
|
|
725
780
|
if (invocation.filePaths.length === 0) {
|
|
726
|
-
allViolations.push('No commit message provided. Commits in OpenCode must provide
|
|
781
|
+
allViolations.push('No commit message provided. Commits in OpenCode must provide an inline message via -m "<scope>: <subject>".');
|
|
727
782
|
}
|
|
728
783
|
continue;
|
|
729
784
|
}
|
|
@@ -733,21 +788,24 @@ function validateGitCommits(invocations, config, originalCommand, workingDirecto
|
|
|
733
788
|
const lines = fullMessage.split(/\r?\n/);
|
|
734
789
|
const firstLine = lines[0] ?? "";
|
|
735
790
|
const subjectLine = firstLine.trim();
|
|
736
|
-
const
|
|
791
|
+
const effectiveSubject = subjectLine.replace(/^(?:(?:fixup|squash)!\s+)+/, "");
|
|
792
|
+
const scopeMatch = effectiveSubject.match(scopePattern);
|
|
737
793
|
if (scopeMatch?.[1] !== undefined && config.allowedScopes !== undefined && config.allowedScopes.length > 0) {
|
|
738
794
|
const scopeViolation = validateAllowedScope(scopeMatch[1], config.allowedScopes);
|
|
739
|
-
if (scopeViolation !== undefined)
|
|
740
|
-
|
|
795
|
+
if (scopeViolation !== undefined) {
|
|
796
|
+
const fullSubjectDetail = effectiveSubject === subjectLine ? "" : ` Subject line: "${subjectLine}".`;
|
|
797
|
+
allViolations.push(`${scopeViolation}${fullSubjectDetail}`);
|
|
798
|
+
}
|
|
741
799
|
}
|
|
742
800
|
if (config.requireScope) {
|
|
743
801
|
if (subjectLine.length === 0) {
|
|
744
802
|
allViolations.push('Subject line is empty. The commit message must begin with "<scope>: <subject>".');
|
|
745
803
|
} else if (scopeMatch === null) {
|
|
746
|
-
if (/^:\s*/.test(
|
|
804
|
+
if (/^:\s*/.test(effectiveSubject)) {
|
|
747
805
|
allViolations.push(`Missing scope before colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
748
|
-
} else if (/^[^:]+:\S/.test(
|
|
806
|
+
} else if (/^[^:]+:\S/.test(effectiveSubject)) {
|
|
749
807
|
allViolations.push(`Missing space after colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
750
|
-
} else if (/^[^:]+:\s*$/.test(
|
|
808
|
+
} else if (/^[^:]+:\s*$/.test(effectiveSubject)) {
|
|
751
809
|
allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
752
810
|
} else {
|
|
753
811
|
allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format (e.g., "kernel: add support for foo" or "feat(parser): add subshell support").`);
|
|
@@ -784,29 +842,40 @@ ${details}`);
|
|
|
784
842
|
// src/plugin.ts
|
|
785
843
|
var plugin = Plugin.define({
|
|
786
844
|
id: "opencode-commit-guard",
|
|
787
|
-
|
|
788
|
-
const config =
|
|
789
|
-
|
|
790
|
-
await ctx.tool.hook("execute.before", async (event) => {
|
|
791
|
-
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
const rawInput = event.input;
|
|
795
|
-
if (!isRecord(rawInput)) {
|
|
796
|
-
return;
|
|
797
|
-
}
|
|
798
|
-
const command = rawInput["command"];
|
|
799
|
-
if (!isJSONString(command)) {
|
|
800
|
-
return;
|
|
801
|
-
}
|
|
802
|
-
const invocations = extractGitCommits(command);
|
|
803
|
-
if (invocations.length === 0) {
|
|
804
|
-
return;
|
|
805
|
-
}
|
|
806
|
-
const workdir = rawInput["workdir"];
|
|
807
|
-
validateGitCommits(invocations, config, command, isJSONString(workdir) ? workdir : sessionDirectory);
|
|
845
|
+
effect: (ctx) => Effect.gen(function* () {
|
|
846
|
+
const config = yield* Effect.sync(() => {
|
|
847
|
+
return parseConfig(ctx.options);
|
|
808
848
|
});
|
|
809
|
-
|
|
849
|
+
const sessionDirectory = ctx.location.directory;
|
|
850
|
+
const canReadLocalRepository = ctx.location.workspaceID === undefined;
|
|
851
|
+
yield* ctx.tool.hook("execute.before", (event) => Effect.try({
|
|
852
|
+
try: () => {
|
|
853
|
+
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
854
|
+
return;
|
|
855
|
+
}
|
|
856
|
+
const rawInput = event.input;
|
|
857
|
+
if (!isRecord(rawInput)) {
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
const command = rawInput["command"];
|
|
861
|
+
if (!isJSONString(command)) {
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if (!command.includes("commit")) {
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
const invocations = extractGitCommits(command);
|
|
868
|
+
if (invocations.length === 0) {
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
const workdir = rawInput["workdir"];
|
|
872
|
+
validateGitCommits(invocations, config, command, isJSONString(workdir) ? resolveLocationPath(sessionDirectory, workdir) : sessionDirectory, canReadLocalRepository);
|
|
873
|
+
},
|
|
874
|
+
catch: (error) => new Tool.Error({
|
|
875
|
+
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
876
|
+
})
|
|
877
|
+
}));
|
|
878
|
+
})
|
|
810
879
|
});
|
|
811
880
|
var plugin_default = plugin;
|
|
812
881
|
export {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-commit-guard",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "OpenCode V2 plugin enforcing git commit format rules",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -17,16 +17,18 @@
|
|
|
17
17
|
"lint": "oxlint .",
|
|
18
18
|
"test": "bun test",
|
|
19
19
|
"typecheck": "tsc --noEmit",
|
|
20
|
-
"build": "bun build index.ts --outdir dist --target bun --format esm --external @opencode/plugin",
|
|
20
|
+
"build": "bun build index.ts --outdir dist --target bun --format esm --external @opencode/plugin --external @opencode/schema --external effect",
|
|
21
21
|
"prepack": "bun run build"
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@opencode/plugin": "2.0.
|
|
24
|
+
"@opencode/plugin": "2.0.3",
|
|
25
|
+
"@opencode/schema": "2.0.3",
|
|
26
|
+
"effect": "4.0.0-rc.112"
|
|
25
27
|
},
|
|
26
28
|
"devDependencies": {
|
|
27
|
-
"@oxlint/plugins": "1.
|
|
29
|
+
"@oxlint/plugins": "1.83.0",
|
|
28
30
|
"@types/bun": "latest",
|
|
29
|
-
"oxlint": "1.
|
|
31
|
+
"oxlint": "1.83.0",
|
|
30
32
|
"typescript": "latest"
|
|
31
33
|
},
|
|
32
34
|
"engines": {
|
package/src/plugin.ts
CHANGED
|
@@ -1,50 +1,70 @@
|
|
|
1
|
-
import { Plugin } from "@opencode/plugin"
|
|
1
|
+
import { Plugin } from "@opencode/plugin/effect"
|
|
2
|
+
import { Tool } from "@opencode/schema/tool"
|
|
3
|
+
import { Effect } from "effect"
|
|
2
4
|
import { parseConfig } from "./config.js"
|
|
3
5
|
import { extractGitCommits } from "./shell.js"
|
|
4
6
|
import { isJSONString, isRecord } from "./types.js"
|
|
5
7
|
import type { JsonValue } from "./types.js"
|
|
6
|
-
import { validateGitCommits } from "./validator.js"
|
|
8
|
+
import { resolveLocationPath, validateGitCommits } from "./validator.js"
|
|
7
9
|
|
|
8
10
|
export const plugin = Plugin.define({
|
|
9
11
|
id: "opencode-commit-guard",
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
effect: (ctx) => Effect.gen(function*() {
|
|
13
|
+
const config = yield* Effect.sync(() => {
|
|
14
|
+
// SAFETY: OpenCode plugin options are passed through ctx.options as JsonValue or undefined.
|
|
15
|
+
return parseConfig(ctx.options as JsonValue | undefined)
|
|
16
|
+
})
|
|
17
|
+
|
|
13
18
|
const sessionDirectory = ctx.location.directory
|
|
19
|
+
const canReadLocalRepository = ctx.location.workspaceID === undefined
|
|
14
20
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
21
|
+
yield* ctx.tool.hook("execute.before", (event) => Effect.try({
|
|
22
|
+
try: () => {
|
|
23
|
+
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
24
|
+
return
|
|
25
|
+
}
|
|
19
26
|
|
|
20
|
-
|
|
21
|
-
|
|
27
|
+
// SAFETY: event.input is an unvalidated tool input payload from OpenCode runtime.
|
|
28
|
+
const rawInput = event.input as JsonValue | undefined
|
|
22
29
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
30
|
+
if (!isRecord(rawInput)) {
|
|
31
|
+
return
|
|
32
|
+
}
|
|
26
33
|
|
|
27
|
-
|
|
34
|
+
const command = rawInput["command"]
|
|
28
35
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
36
|
+
if (!isJSONString(command)) {
|
|
37
|
+
return
|
|
38
|
+
}
|
|
32
39
|
|
|
33
|
-
|
|
40
|
+
if (!command.includes("commit")) {
|
|
41
|
+
return
|
|
42
|
+
}
|
|
34
43
|
|
|
35
|
-
|
|
36
|
-
return
|
|
37
|
-
}
|
|
44
|
+
const invocations = extractGitCommits(command)
|
|
38
45
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
if (invocations.length === 0) {
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
|
|
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
|
+
)
|
|
60
|
+
},
|
|
61
|
+
catch: (error) => new Tool.Error({
|
|
62
|
+
message: error instanceof Error
|
|
63
|
+
? error.message
|
|
64
|
+
: "[commit-guard] Git commit validation failed.",
|
|
65
|
+
}),
|
|
66
|
+
}))
|
|
67
|
+
}),
|
|
48
68
|
})
|
|
49
69
|
|
|
50
70
|
export default plugin
|
package/src/shell.ts
CHANGED
|
@@ -503,6 +503,8 @@ function extractInvocation(
|
|
|
503
503
|
if (executable === undefined || (executable !== "git" && !executable.endsWith("/git"))) return undefined
|
|
504
504
|
wordIndex++
|
|
505
505
|
const directoryChanges = [...commandStart.directoryChanges]
|
|
506
|
+
let gitDir: string | undefined
|
|
507
|
+
let workTree: string | undefined
|
|
506
508
|
|
|
507
509
|
let subcommand: string | undefined
|
|
508
510
|
|
|
@@ -522,15 +524,29 @@ function extractInvocation(
|
|
|
522
524
|
|
|
523
525
|
if (argument === "-C" && optionValue !== undefined) {
|
|
524
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
|
|
525
531
|
}
|
|
526
532
|
|
|
527
533
|
wordIndex += 2
|
|
528
534
|
continue
|
|
529
535
|
}
|
|
530
536
|
|
|
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
|
+
|
|
531
549
|
if (
|
|
532
|
-
argument.startsWith("--git-dir=") ||
|
|
533
|
-
argument.startsWith("--work-tree=") ||
|
|
534
550
|
argument.startsWith("--namespace=") ||
|
|
535
551
|
argument.startsWith("--exec-path=") ||
|
|
536
552
|
argument.startsWith("--super-prefix=") ||
|
|
@@ -563,6 +579,7 @@ function extractInvocation(
|
|
|
563
579
|
let hasSignoffFlag = false
|
|
564
580
|
let isAmend = false
|
|
565
581
|
let hasNoEdit = false
|
|
582
|
+
let isFixup = false
|
|
566
583
|
let isHelp = false
|
|
567
584
|
|
|
568
585
|
const collectMessage = (word: string | undefined): void => {
|
|
@@ -580,6 +597,9 @@ function extractInvocation(
|
|
|
580
597
|
|
|
581
598
|
if (argument === undefined) break
|
|
582
599
|
|
|
600
|
+
const equalsIndex = argument.indexOf("=")
|
|
601
|
+
const longOptionName = equalsIndex > 0 ? argument.slice(0, equalsIndex) : argument
|
|
602
|
+
|
|
583
603
|
if (argument === "--") break
|
|
584
604
|
|
|
585
605
|
if (argument === "-h" || argument === "--help") {
|
|
@@ -604,8 +624,12 @@ function extractInvocation(
|
|
|
604
624
|
collectFile(words[index])
|
|
605
625
|
} else if (argument.startsWith("--file=")) {
|
|
606
626
|
collectFile(argument.slice("--file=".length))
|
|
607
|
-
} else if (
|
|
608
|
-
|
|
627
|
+
} else if (argument === "--fixup" || argument.startsWith("--fixup=")) {
|
|
628
|
+
isFixup = true
|
|
629
|
+
|
|
630
|
+
if (equalsIndex < 0) index++
|
|
631
|
+
} else if (commitLongOptionsWithArg.has(longOptionName)) {
|
|
632
|
+
if (equalsIndex < 0) index++
|
|
609
633
|
} else if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 1) {
|
|
610
634
|
for (let characterIndex = 1; characterIndex < argument.length; characterIndex++) {
|
|
611
635
|
const option = argument[characterIndex]
|
|
@@ -644,8 +668,11 @@ function extractInvocation(
|
|
|
644
668
|
hasSignoffFlag,
|
|
645
669
|
isAmend,
|
|
646
670
|
hasNoEdit,
|
|
671
|
+
isFixup,
|
|
647
672
|
isHelp,
|
|
648
673
|
directoryChanges,
|
|
674
|
+
gitDir,
|
|
675
|
+
workTree,
|
|
649
676
|
}
|
|
650
677
|
}
|
|
651
678
|
|
package/src/types.ts
CHANGED
|
@@ -49,8 +49,11 @@ export interface GitCommitInvocation {
|
|
|
49
49
|
readonly hasSignoffFlag: boolean
|
|
50
50
|
readonly isAmend: boolean
|
|
51
51
|
readonly hasNoEdit?: boolean
|
|
52
|
+
readonly isFixup?: boolean
|
|
52
53
|
readonly isHelp: boolean
|
|
53
54
|
readonly directoryChanges?: readonly string[]
|
|
55
|
+
readonly gitDir?: string
|
|
56
|
+
readonly workTree?: string
|
|
54
57
|
}
|
|
55
58
|
|
|
56
59
|
export interface OverlongLine {
|
package/src/validator.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { spawnSync } from "node:child_process"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { join, resolve } from "node:path"
|
|
3
4
|
import type {
|
|
4
5
|
CommitGuardConfig,
|
|
5
6
|
GitCommitInvocation,
|
|
@@ -10,7 +11,43 @@ const scopePattern = /^([a-zA-Z0-9_\-./]+(?:\([a-zA-Z0-9_\-./]+\))?):\s+(.+)$/
|
|
|
10
11
|
|
|
11
12
|
const signoffPattern = /^\s*Signed-off-by:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/i
|
|
12
13
|
|
|
13
|
-
|
|
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
|
+
}
|
|
14
51
|
|
|
15
52
|
function hasSignoffTrailer(lines: readonly string[]): boolean {
|
|
16
53
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0)
|
|
@@ -60,6 +97,7 @@ export function validateGitCommits(
|
|
|
60
97
|
config: CommitGuardConfig,
|
|
61
98
|
originalCommand: string,
|
|
62
99
|
workingDirectory?: string,
|
|
100
|
+
canReadLocalRepository = true,
|
|
63
101
|
): void {
|
|
64
102
|
const allViolations: string[] = []
|
|
65
103
|
|
|
@@ -68,10 +106,6 @@ export function validateGitCommits(
|
|
|
68
106
|
continue
|
|
69
107
|
}
|
|
70
108
|
|
|
71
|
-
if (invocation.isAmend && invocation.hasNoEdit === true && invocation.messages.length === 0 && invocation.filePaths.length === 0) {
|
|
72
|
-
continue
|
|
73
|
-
}
|
|
74
|
-
|
|
75
109
|
const collectedMessages: string[] = [...invocation.messages]
|
|
76
110
|
let messageDirectory = workingDirectory ?? process.cwd()
|
|
77
111
|
|
|
@@ -79,66 +113,84 @@ export function validateGitCommits(
|
|
|
79
113
|
messageDirectory = resolve(messageDirectory, directoryChange)
|
|
80
114
|
}
|
|
81
115
|
|
|
82
|
-
|
|
116
|
+
if (
|
|
117
|
+
invocation.isAmend &&
|
|
118
|
+
invocation.hasNoEdit === true &&
|
|
119
|
+
invocation.messages.length === 0 &&
|
|
120
|
+
invocation.filePaths.length === 0
|
|
121
|
+
) {
|
|
122
|
+
const hasAmbiguousHomeChange = invocation.directoryChanges?.some((directoryChange) =>
|
|
123
|
+
directoryChange === "~" ||
|
|
124
|
+
directoryChange.startsWith("~/") ||
|
|
125
|
+
(process.platform === "win32" && directoryChange.startsWith("~\\"))
|
|
126
|
+
) === true
|
|
83
127
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
+
)
|
|
87
132
|
continue
|
|
88
133
|
}
|
|
89
134
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
135
|
+
if (!canReadLocalRepository) {
|
|
136
|
+
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".',
|
|
138
|
+
)
|
|
94
139
|
continue
|
|
95
140
|
}
|
|
96
141
|
|
|
97
|
-
|
|
98
|
-
|
|
142
|
+
if (invocation.gitDir !== undefined || invocation.workTree !== undefined) {
|
|
143
|
+
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".',
|
|
145
|
+
)
|
|
146
|
+
continue
|
|
147
|
+
}
|
|
99
148
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
149
|
+
const result = spawnSync("git", ["log", "-1", "--format=%B", "HEAD"], {
|
|
150
|
+
cwd: messageDirectory,
|
|
151
|
+
encoding: "utf-8",
|
|
152
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
153
|
+
})
|
|
104
154
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
155
|
+
if (result.error !== undefined) {
|
|
156
|
+
allViolations.push(`Failed to read the existing HEAD commit message: ${result.error.message}`)
|
|
157
|
+
continue
|
|
158
|
+
}
|
|
109
159
|
|
|
110
|
-
|
|
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
|
+
}
|
|
111
166
|
|
|
112
|
-
|
|
113
|
-
const openedFileInfo = fstatSync(descriptor)
|
|
167
|
+
const existingMessage = result.stdout.replace(/[\r\n]+$/, "")
|
|
114
168
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
169
|
+
if (existingMessage.trim().length === 0) {
|
|
170
|
+
allViolations.push("The existing HEAD commit message is empty.")
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
119
173
|
|
|
120
|
-
|
|
121
|
-
|
|
174
|
+
collectedMessages.push(existingMessage)
|
|
175
|
+
}
|
|
122
176
|
|
|
123
|
-
|
|
124
|
-
allViolations.push(`Commit message file "${filePath}" exceeds the 64 KB size limit.`)
|
|
125
|
-
continue
|
|
126
|
-
}
|
|
177
|
+
const filePath = invocation.filePaths.at(-1)
|
|
127
178
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
const errorDetail = readError instanceof Error ? readError.message : "Cannot read file"
|
|
134
|
-
allViolations.push(`Failed to read commit message file "${filePath}": ${errorDetail}`)
|
|
135
|
-
}
|
|
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
|
|
136
184
|
}
|
|
137
185
|
|
|
138
186
|
if (collectedMessages.length === 0) {
|
|
187
|
+
if (invocation.isFixup === true) {
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
|
|
139
191
|
if (invocation.filePaths.length === 0) {
|
|
140
192
|
allViolations.push(
|
|
141
|
-
'No commit message provided. Commits in OpenCode must provide
|
|
193
|
+
'No commit message provided. Commits in OpenCode must provide an inline message via -m "<scope>: <subject>".',
|
|
142
194
|
)
|
|
143
195
|
}
|
|
144
196
|
|
|
@@ -149,7 +201,8 @@ export function validateGitCommits(
|
|
|
149
201
|
const lines = fullMessage.split(/\r?\n/)
|
|
150
202
|
const firstLine = lines[0] ?? ""
|
|
151
203
|
const subjectLine = firstLine.trim()
|
|
152
|
-
const
|
|
204
|
+
const effectiveSubject = subjectLine.replace(/^(?:(?:fixup|squash)!\s+)+/, "")
|
|
205
|
+
const scopeMatch = effectiveSubject.match(scopePattern)
|
|
153
206
|
|
|
154
207
|
if (
|
|
155
208
|
scopeMatch?.[1] !== undefined &&
|
|
@@ -158,22 +211,28 @@ export function validateGitCommits(
|
|
|
158
211
|
) {
|
|
159
212
|
const scopeViolation = validateAllowedScope(scopeMatch[1], config.allowedScopes)
|
|
160
213
|
|
|
161
|
-
if (scopeViolation !== undefined)
|
|
214
|
+
if (scopeViolation !== undefined) {
|
|
215
|
+
const fullSubjectDetail = effectiveSubject === subjectLine
|
|
216
|
+
? ""
|
|
217
|
+
: ` Subject line: "${subjectLine}".`
|
|
218
|
+
|
|
219
|
+
allViolations.push(`${scopeViolation}${fullSubjectDetail}`)
|
|
220
|
+
}
|
|
162
221
|
}
|
|
163
222
|
|
|
164
223
|
if (config.requireScope) {
|
|
165
224
|
if (subjectLine.length === 0) {
|
|
166
225
|
allViolations.push('Subject line is empty. The commit message must begin with "<scope>: <subject>".')
|
|
167
226
|
} else if (scopeMatch === null) {
|
|
168
|
-
if (/^:\s*/.test(
|
|
227
|
+
if (/^:\s*/.test(effectiveSubject)) {
|
|
169
228
|
allViolations.push(
|
|
170
229
|
`Missing scope before colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`,
|
|
171
230
|
)
|
|
172
|
-
} else if (/^[^:]+:\S/.test(
|
|
231
|
+
} else if (/^[^:]+:\S/.test(effectiveSubject)) {
|
|
173
232
|
allViolations.push(
|
|
174
233
|
`Missing space after colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`,
|
|
175
234
|
)
|
|
176
|
-
} else if (/^[^:]+:\s*$/.test(
|
|
235
|
+
} else if (/^[^:]+:\s*$/.test(effectiveSubject)) {
|
|
177
236
|
allViolations.push(
|
|
178
237
|
`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`,
|
|
179
238
|
)
|