opencode-commit-guard 1.0.4 → 1.0.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-commit-guard",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "OpenCode V2 plugin enforcing git commit format rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -21,14 +21,14 @@
21
21
  "prepack": "bun run build"
22
22
  },
23
23
  "dependencies": {
24
- "@opencode/plugin": "2.0.15",
25
- "@opencode/schema": "2.0.15",
26
- "effect": "4.0.0-rc.112"
24
+ "@opencode/plugin": "2.2.1",
25
+ "@opencode/schema": "2.2.1",
26
+ "effect": "4.0.1"
27
27
  },
28
28
  "devDependencies": {
29
- "@oxlint/plugins": "1.85.0",
30
- "@types/bun": "1.4.2",
31
- "oxlint": "1.85.0",
29
+ "@oxlint/plugins": "1.90.0",
30
+ "@types/bun": "1.4.4",
31
+ "oxlint": "1.90.0",
32
32
  "typescript": "7.0.2"
33
33
  },
34
34
  "engines": {
package/src/capture.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto"
2
- import { closeSync, constants, fstatSync, mkdtempSync, openSync, readSync, rmSync } from "node:fs"
2
+ import { closeSync, constants, existsSync, fstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, statSync } from "node:fs"
3
3
  import { tmpdir } from "node:os"
4
- import { join, relative } from "node:path"
4
+ import { dirname, join, relative, resolve } from "node:path"
5
5
  import type { Plugin } from "@opencode/plugin/effect"
6
6
  import { Effect, Semaphore } from "effect"
7
7
  import { isJSONString, isRecord } from "./types.js"
@@ -50,13 +50,140 @@ function digest(text: string): string {
50
50
  return createHash("sha256").update(text).digest("hex")
51
51
  }
52
52
 
53
- export function scopeFor(ctx: Context, sessionID: string, config: CommitGuardConfig): string {
53
+ export function scopeFor(ctx: Context, sessionID: string, config: CommitGuardConfig, targetDir?: string): string {
54
54
  const location = ctx.location
55
55
 
56
- return digest(JSON.stringify([version, location.project.id, sessionID, location.directory, location.workspaceID ?? null,
56
+ const directory = targetDir ?? location.directory
57
+ const root = findGitRoot(directory) ?? realpathSync(directory)
58
+
59
+ return digest(JSON.stringify([version, location.project.id, sessionID, root, location.workspaceID ?? null,
57
60
  policy, config.requireScope, config.allowedScopes ?? null, config.maxLineLength]))
58
61
  }
59
62
 
63
+ export function isGitDirectory(dir: string): boolean {
64
+ try {
65
+ return existsSync(join(dir, ".git"))
66
+ } catch {
67
+ return false
68
+ }
69
+ }
70
+
71
+ export function findGitRoot(startDir: string): string | undefined {
72
+ let current: string
73
+
74
+ try {
75
+ current = realpathSync(startDir)
76
+ } catch {
77
+ return undefined
78
+ }
79
+
80
+ while (true) {
81
+ if (isGitDirectory(current)) {
82
+ return current
83
+ }
84
+
85
+ const parent = dirname(current)
86
+
87
+ if (parent === current) {
88
+ break
89
+ }
90
+
91
+ current = parent
92
+ }
93
+
94
+ return undefined
95
+ }
96
+
97
+ export interface ResolvedTargetWorkdir {
98
+ readonly workdir?: string
99
+ readonly error?: string
100
+ }
101
+
102
+ export function findSubRepos(dir: string, maxDepth = 2): string[] {
103
+ const repos: string[] = []
104
+
105
+ function search(currentDir: string, currentDepth: number): void {
106
+ if (currentDepth > maxDepth) return
107
+
108
+ try {
109
+ const entries = readdirSync(currentDir, { withFileTypes: true })
110
+
111
+ for (const entry of entries) {
112
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
113
+
114
+ if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") continue
115
+
116
+ const fullPath = join(currentDir, entry.name)
117
+
118
+ if (isGitDirectory(fullPath)) {
119
+ repos.push(fullPath)
120
+ } else if (currentDepth < maxDepth) {
121
+ search(fullPath, currentDepth + 1)
122
+ }
123
+ }
124
+ } catch {
125
+ // Inaccessible directory
126
+ }
127
+ }
128
+
129
+ search(dir, 1)
130
+
131
+ return repos
132
+ }
133
+
134
+ export function resolveTargetWorkdir(
135
+ baseDir: string,
136
+ requestedDir?: string,
137
+ ): ResolvedTargetWorkdir {
138
+ if (requestedDir !== undefined) {
139
+ const resolvedDir = resolve(baseDir, requestedDir)
140
+
141
+ if (!existsSync(resolvedDir)) {
142
+ return { error: `Directory "${requestedDir}" does not exist.` }
143
+ }
144
+
145
+ try {
146
+ if (!statSync(resolvedDir).isDirectory()) {
147
+ return { error: `Path "${requestedDir}" is not a directory.` }
148
+ }
149
+ } catch {
150
+ return { error: `Could not access directory "${requestedDir}".` }
151
+ }
152
+
153
+ const gitRoot = findGitRoot(resolvedDir)
154
+
155
+ if (gitRoot === undefined) {
156
+ return { error: `Directory "${requestedDir}" is not a Git repository or inside one.` }
157
+ }
158
+
159
+ return { workdir: realpathSync(resolvedDir) }
160
+ }
161
+
162
+ const currentGitRoot = findGitRoot(baseDir)
163
+
164
+ if (currentGitRoot !== undefined) {
165
+ return { workdir: realpathSync(baseDir) }
166
+ }
167
+
168
+ const subRepos = findSubRepos(baseDir)
169
+
170
+ if (subRepos.length === 1) {
171
+ return { workdir: realpathSync(subRepos[0]!) }
172
+ }
173
+
174
+ if (subRepos.length === 0) {
175
+ return {
176
+ error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`,
177
+ }
178
+ }
179
+
180
+ const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ")
181
+
182
+ return {
183
+ error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.\nSpecify which repository to target with the 'workdir' option, for example:\ncommit_context({ workdir: "${relative(baseDir, subRepos[0]!)}" })`,
184
+ }
185
+ }
186
+
60
187
  function counterKey(scope: string): string { return `counter/${scope}` }
61
188
 
62
189
  function prefix(scope: string): string { return `snap/${scope}/` }
@@ -71,14 +198,52 @@ export function counter(ctx: Context, scope: string): Effect.Effect<number> {
71
198
  })
72
199
  }
73
200
 
74
- export function invalidate(ctx: Context, scope: string): Effect.Effect<void> {
201
+ export function invalidate(ctx: Context, scope: string): Effect.Effect<number> {
75
202
  return storageLock.withPermits(1)(Effect.gen(function*() {
76
203
  const previous = yield* counter(ctx, scope)
77
204
 
78
- yield* ctx.storage.set(counterKey(scope), previous < 0 ? 1 : previous + 1)
205
+ const next = previous < 0 ? 1 : previous + 1
206
+
207
+ yield* ctx.storage.set(counterKey(scope), next)
208
+
209
+ return next
79
210
  }))
80
211
  }
81
212
 
213
+ export function invalidateOwned(ctx: Context, attempt: Pending): Effect.Effect<void> {
214
+ return storageLock.withPermits(1)(Effect.gen(function*() {
215
+ if ((yield* counter(ctx, attempt.scope)) === attempt.counter) {
216
+ yield* ctx.storage.set(counterKey(attempt.scope), attempt.counter + 1)
217
+ }
218
+ }))
219
+ }
220
+
221
+ export type CaptureState = "prepared" | "claimed" | "published" | "expired" | "failed"
222
+
223
+ export function recordState(ctx: Context, attempt: Pending, state: CaptureState, reason = ""): Effect.Effect<void> {
224
+ return storageLock.withPermits(1)(Effect.gen(function*() {
225
+ if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) return
226
+ yield* ctx.storage.set(`state/${attempt.scope}`, { state, reason: reason.slice(0, 256) })
227
+ }))
228
+ }
229
+
230
+ export function captureStatus(ctx: Context, scope: string): Effect.Effect<string> {
231
+ return Effect.gen(function*() {
232
+ // SAFETY: Plugin storage contains JSON; validate the record before reading its fields.
233
+ const value = (yield* ctx.storage.get(`state/${scope}`)) as JsonValue | undefined
234
+
235
+ if (!isRecord(value)) return ""
236
+
237
+ if (value["state"] === "expired") return "The previous capture expired before its command was claimed; no matching shell result was observed. "
238
+
239
+ if (value["state"] === "failed" && isJSONString(value["reason"])) return `The previous capture failed: ${value["reason"]}. `
240
+
241
+ if (value["state"] === "prepared" || value["state"] === "claimed") return "The previous capture was interrupted before publication. "
242
+
243
+ return ""
244
+ })
245
+ }
246
+
82
247
  function validBaseline(value: JsonValue | undefined): value is Baseline & Record<string, JsonValue> {
83
248
  if (!isRecord(value)) return false
84
249
 
@@ -202,7 +367,7 @@ export function importCapture(pending: Pending): Baseline {
202
367
  const messages = head === null ? [] : rawLog.split("\0\0").filter((message) => message.length > 0)
203
368
 
204
369
  if (!root.startsWith("/") || !gitDir.startsWith("/") || !commonDir.startsWith("/") ||
205
- relative(root, pending.workdir).startsWith("..") ||
370
+ root !== findGitRoot(pending.workdir) ||
206
371
  !["branch", "detached"].includes(fields[4]!) || !["head", "unborn"].includes(fields[6]!) ||
207
372
  (head !== null && !/^[a-f0-9]{40,64}$/.test(head)) ||
208
373
  (head === null && rawLog !== "") || (head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\0\0")))) throw new Error("Invalid Git baseline")
package/src/config.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  isRecord,
7
7
  } from "./types.js"
8
8
  import type { CommitGuardConfig, JsonValue } from "./types.js"
9
+ import { scopePattern } from "./scope.js"
9
10
 
10
11
  export function parseConfig(options: JsonValue | undefined): CommitGuardConfig {
11
12
  if (options === undefined) {
@@ -42,6 +43,10 @@ export function parseConfig(options: JsonValue | undefined): CommitGuardConfig {
42
43
  throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.")
43
44
  }
44
45
 
46
+ if (scopePattern.exec(`${item.trim()}: Subject`)?.[1] !== item.trim()) {
47
+ throw new Error(`Invalid plugin option allowedScopes; scope ${JSON.stringify(item)} cannot match the commit scope syntax.`)
48
+ }
49
+
45
50
  scopes.push(item.trim())
46
51
  }
47
52