opencode-commit-guard 1.1.0 → 1.1.1
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 +3 -0
- package/dist/index.js +1337 -1668
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { randomUUID as randomUUID2 } from "crypto";
|
|
|
4
4
|
import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { Plugin, Tool } from "@opencode/plugin/effect";
|
|
7
|
-
import { Effect as Effect2
|
|
7
|
+
import { Cause, Effect as Effect2 } from "effect";
|
|
8
8
|
|
|
9
9
|
// src/capture.ts
|
|
10
10
|
import { createHash, randomUUID } from "crypto";
|
|
@@ -27,18 +27,10 @@ import { gzipSync } from "zlib";
|
|
|
27
27
|
import { Effect, Semaphore } from "effect";
|
|
28
28
|
|
|
29
29
|
// src/types.ts
|
|
30
|
-
var isJSONString =
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
var
|
|
34
|
-
return Object.prototype.toString.call(value) === "[object Number]";
|
|
35
|
-
};
|
|
36
|
-
var isJSONBoolean = function isJSONBoolean(value) {
|
|
37
|
-
return Object.prototype.toString.call(value) === "[object Boolean]";
|
|
38
|
-
};
|
|
39
|
-
var isRecord = function isRecord(value) {
|
|
40
|
-
return value instanceof Object && !Array.isArray(value);
|
|
41
|
-
};
|
|
30
|
+
var isJSONString = (value) => Object.prototype.toString.call(value) === "[object String]";
|
|
31
|
+
var isJSONNumber = (value) => Object.prototype.toString.call(value) === "[object Number]";
|
|
32
|
+
var isJSONBoolean = (value) => Object.prototype.toString.call(value) === "[object Boolean]";
|
|
33
|
+
var isRecord = (value) => Object.prototype.toString.call(value) === "[object Object]";
|
|
42
34
|
var defaultConfig = {
|
|
43
35
|
requireScope: true,
|
|
44
36
|
allowedScopes: undefined,
|
|
@@ -53,10 +45,8 @@ var maxBytes = 262144;
|
|
|
53
45
|
var captureTimeout = 20000;
|
|
54
46
|
var policy = "commit-guard-context-v1";
|
|
55
47
|
var storageLock = Semaphore.makeUnsafe(1);
|
|
56
|
-
var digest =
|
|
57
|
-
|
|
58
|
-
};
|
|
59
|
-
var scopeFor = function scopeFor(ctx, sessionID, config, targetDir) {
|
|
48
|
+
var digest = (text) => createHash("sha256").update(text).digest("hex");
|
|
49
|
+
var scopeFor = (ctx, sessionID, config, targetDir) => {
|
|
60
50
|
const { location } = ctx;
|
|
61
51
|
const directory = targetDir ?? location.directory;
|
|
62
52
|
const root = findGitRoot(directory) ?? realpathSync(directory);
|
|
@@ -72,14 +62,14 @@ var scopeFor = function scopeFor(ctx, sessionID, config, targetDir) {
|
|
|
72
62
|
config.maxLineLength
|
|
73
63
|
]));
|
|
74
64
|
};
|
|
75
|
-
var isGitDirectory =
|
|
65
|
+
var isGitDirectory = (dir) => {
|
|
76
66
|
try {
|
|
77
67
|
return existsSync(join(dir, ".git"));
|
|
78
68
|
} catch {
|
|
79
69
|
return false;
|
|
80
70
|
}
|
|
81
71
|
};
|
|
82
|
-
var findGitRoot =
|
|
72
|
+
var findGitRoot = (startDir) => {
|
|
83
73
|
let current;
|
|
84
74
|
try {
|
|
85
75
|
current = realpathSync(startDir);
|
|
@@ -98,9 +88,9 @@ var findGitRoot = function findGitRoot(startDir) {
|
|
|
98
88
|
}
|
|
99
89
|
return;
|
|
100
90
|
};
|
|
101
|
-
var findSubRepos =
|
|
91
|
+
var findSubRepos = (dir, maxDepth = 2) => {
|
|
102
92
|
const repos = [];
|
|
103
|
-
const search =
|
|
93
|
+
const search = (currentDir, currentDepth) => {
|
|
104
94
|
if (currentDepth > maxDepth) {
|
|
105
95
|
return;
|
|
106
96
|
}
|
|
@@ -125,7 +115,7 @@ var findSubRepos = function findSubRepos(dir, maxDepth = 2) {
|
|
|
125
115
|
search(dir, 1);
|
|
126
116
|
return repos;
|
|
127
117
|
};
|
|
128
|
-
var resolveTargetWorkdir =
|
|
118
|
+
var resolveTargetWorkdir = (baseDir, requestedDir) => {
|
|
129
119
|
if (requestedDir !== undefined) {
|
|
130
120
|
const resolvedDir = resolve(baseDir, requestedDir);
|
|
131
121
|
if (!existsSync(resolvedDir)) {
|
|
@@ -166,111 +156,94 @@ Specify which repository to target with the 'workdir' option, for example:
|
|
|
166
156
|
commit_context({ workdir: "${relative(baseDir, subRepos[0])}" })`
|
|
167
157
|
};
|
|
168
158
|
};
|
|
169
|
-
var counterKey =
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
159
|
+
var counterKey = (scope) => `counter/${scope}`;
|
|
160
|
+
var prefix = (scope) => `snap/${scope}/`;
|
|
161
|
+
var counter = (ctx, scope) => Effect.gen(function* readCounter() {
|
|
162
|
+
const value = yield* ctx.storage.get(counterKey(scope));
|
|
163
|
+
if (value === undefined) {
|
|
164
|
+
return 0;
|
|
165
|
+
}
|
|
166
|
+
return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1;
|
|
167
|
+
});
|
|
168
|
+
var invalidate = (ctx, scope) => storageLock.withPermits(1)(Effect.gen(function* incrementCounter() {
|
|
169
|
+
const previous = yield* counter(ctx, scope);
|
|
170
|
+
const next = previous < 0 ? 1 : previous + 1;
|
|
171
|
+
yield* ctx.storage.set(counterKey(scope), next);
|
|
172
|
+
return next;
|
|
173
|
+
}));
|
|
174
|
+
var invalidateOwned = (ctx, attempt) => storageLock.withPermits(1)(Effect.gen(function* invalidateAttempt() {
|
|
175
|
+
if ((yield* counter(ctx, attempt.scope)) === attempt.counter) {
|
|
176
|
+
yield* ctx.storage.set(counterKey(attempt.scope), attempt.counter + 1);
|
|
177
|
+
}
|
|
178
|
+
}));
|
|
179
|
+
var recordState = (ctx, attempt, state, reason = "") => storageLock.withPermits(1)(Effect.gen(function* storeState() {
|
|
180
|
+
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
yield* ctx.storage.set(`state/${attempt.scope}`, {
|
|
184
|
+
state,
|
|
185
|
+
reason: reason.slice(0, 256)
|
|
182
186
|
});
|
|
183
|
-
};
|
|
184
|
-
var
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
const next = previous < 0 ? 1 : previous + 1;
|
|
188
|
-
yield* ctx.storage.set(counterKey(scope), next);
|
|
189
|
-
return next;
|
|
190
|
-
}));
|
|
191
|
-
};
|
|
192
|
-
var invalidateOwned = function invalidateOwned(ctx, attempt) {
|
|
193
|
-
return storageLock.withPermits(1)(Effect.gen(function* invalidateAttempt() {
|
|
194
|
-
if ((yield* counter(ctx, attempt.scope)) === attempt.counter) {
|
|
195
|
-
yield* ctx.storage.set(counterKey(attempt.scope), attempt.counter + 1);
|
|
196
|
-
}
|
|
197
|
-
}));
|
|
198
|
-
};
|
|
199
|
-
var recordState = function recordState(ctx, attempt, state, reason = "") {
|
|
200
|
-
return storageLock.withPermits(1)(Effect.gen(function* storeState() {
|
|
201
|
-
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
yield* ctx.storage.set(`state/${attempt.scope}`, {
|
|
205
|
-
state,
|
|
206
|
-
reason: reason.slice(0, 256)
|
|
207
|
-
});
|
|
208
|
-
}));
|
|
209
|
-
};
|
|
210
|
-
var captureStatus = function captureStatus(ctx, scope) {
|
|
211
|
-
return Effect.gen(function* readCaptureStatus() {
|
|
212
|
-
const value = yield* ctx.storage.get(`state/${scope}`);
|
|
213
|
-
if (!isRecord(value)) {
|
|
214
|
-
return "";
|
|
215
|
-
}
|
|
216
|
-
if (value.state === "expired") {
|
|
217
|
-
return "The previous capture expired before its command was claimed; no matching shell result was observed. ";
|
|
218
|
-
}
|
|
219
|
-
if (value.state === "failed" && isJSONString(value.reason)) {
|
|
220
|
-
return `The previous capture failed: ${value.reason}. `;
|
|
221
|
-
}
|
|
222
|
-
if (value.state === "prepared" || value.state === "claimed") {
|
|
223
|
-
return "The previous capture was interrupted before publication. ";
|
|
224
|
-
}
|
|
187
|
+
}));
|
|
188
|
+
var captureStatus = (ctx, scope) => Effect.gen(function* readCaptureStatus() {
|
|
189
|
+
const value = yield* ctx.storage.get(`state/${scope}`);
|
|
190
|
+
if (!isRecord(value)) {
|
|
225
191
|
return "";
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
192
|
+
}
|
|
193
|
+
if (value.state === "expired") {
|
|
194
|
+
return "The previous capture expired before its command was claimed; no matching shell result was observed. ";
|
|
195
|
+
}
|
|
196
|
+
if (value.state === "failed" && isJSONString(value.reason)) {
|
|
197
|
+
return `The previous capture failed: ${value.reason}. `;
|
|
198
|
+
}
|
|
199
|
+
if (value.state === "prepared" || value.state === "claimed") {
|
|
200
|
+
return "The previous capture was interrupted before publication. ";
|
|
201
|
+
}
|
|
202
|
+
return "";
|
|
203
|
+
});
|
|
204
|
+
var validBaseline = (value) => {
|
|
229
205
|
if (!isRecord(value)) {
|
|
230
206
|
return false;
|
|
231
207
|
}
|
|
232
208
|
return ["directory", "workdir", "gitDir", "commonDir"].every((key) => isJSONString(value[key])) && (value.branch === null || isJSONString(value.branch)) && (value.head === null || isJSONString(value.head) && /^[0-9a-f]{40,64}$/u.test(value.head)) && Array.isArray(value.messages) && value.messages.length <= 10 && value.messages.every((message) => isJSONString(message)) && isJSONString(value.gpgsign) && ["true", "false", "unset", "error"].includes(value.gpgsign) && (value.signingkey === null || value.signingkey === "error" || isJSONString(value.signingkey));
|
|
233
209
|
};
|
|
234
|
-
var
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
}
|
|
268
|
-
after = page.next;
|
|
269
|
-
} while (after !== undefined);
|
|
270
|
-
return newest?.baseline;
|
|
210
|
+
var scanStoragePrefix = (ctx, keyPrefix, visitor) => Effect.gen(function* scan() {
|
|
211
|
+
let after;
|
|
212
|
+
do {
|
|
213
|
+
const page = yield* ctx.storage.scan({
|
|
214
|
+
prefix: keyPrefix,
|
|
215
|
+
after,
|
|
216
|
+
limit: 100
|
|
217
|
+
});
|
|
218
|
+
for (const entry of page.entries) {
|
|
219
|
+
yield* visitor(entry);
|
|
220
|
+
}
|
|
221
|
+
after = page.next;
|
|
222
|
+
} while (after !== undefined);
|
|
223
|
+
});
|
|
224
|
+
var snapshotChecksum = (scope, count, generation, sequence, baseline) => digest(JSON.stringify([version, scope, count, generation, sequence, baseline]));
|
|
225
|
+
var load = (ctx, scope) => storageLock.withPermits(1)(Effect.gen(function* readBaseline() {
|
|
226
|
+
const current = yield* counter(ctx, scope);
|
|
227
|
+
if (current < 0) {
|
|
228
|
+
return yield* Effect.succeed(undefined);
|
|
229
|
+
}
|
|
230
|
+
let newest;
|
|
231
|
+
yield* scanStoragePrefix(ctx, prefix(scope), (record) => Effect.sync(() => {
|
|
232
|
+
const raw = record.value;
|
|
233
|
+
if (!isRecord(raw) || raw.schema !== version || raw.scope !== scope || raw.counter !== current || !isJSONString(raw.generation) || !isJSONString(raw.sequence) || !isJSONString(raw.checksum) || !validBaseline(raw.baseline)) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const { baseline } = raw;
|
|
237
|
+
if (snapshotChecksum(scope, current, raw.generation, raw.sequence, baseline) !== raw.checksum) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (newest === undefined || raw.sequence > newest.sequence) {
|
|
241
|
+
newest = { sequence: raw.sequence, baseline };
|
|
242
|
+
}
|
|
271
243
|
}));
|
|
272
|
-
|
|
273
|
-
|
|
244
|
+
return newest?.baseline;
|
|
245
|
+
}));
|
|
246
|
+
var captureCommand = (path, watchdogSeconds) => {
|
|
274
247
|
if (process.platform === "win32") {
|
|
275
248
|
return windowsCaptureCommand(path);
|
|
276
249
|
}
|
|
@@ -293,7 +266,7 @@ printf "RECEIPT_OK\\n"`;
|
|
|
293
266
|
bash -c "$1" bash "$2" &
|
|
294
267
|
worker=$!
|
|
295
268
|
(
|
|
296
|
-
sleep
|
|
269
|
+
sleep ${watchdogSeconds} &
|
|
297
270
|
timer=$!
|
|
298
271
|
trap "kill $timer 2>/dev/null" EXIT
|
|
299
272
|
trap "exit 0" TERM
|
|
@@ -307,7 +280,7 @@ kill "$watchdog" 2>/dev/null
|
|
|
307
280
|
wait "$watchdog" 2>/dev/null
|
|
308
281
|
exit "$status"' bash '${script.replaceAll("'", "'\\''")}' ${quoted} 2>/dev/null`;
|
|
309
282
|
};
|
|
310
|
-
var windowsCaptureCommand =
|
|
283
|
+
var windowsCaptureCommand = (path) => {
|
|
311
284
|
const script = `$ErrorActionPreference = 'Stop'
|
|
312
285
|
$clock = [Diagnostics.Stopwatch]::StartNew()
|
|
313
286
|
$lines = [Collections.Generic.List[string]]::new()
|
|
@@ -381,7 +354,7 @@ try {
|
|
|
381
354
|
const bootstrap = `$m = [IO.MemoryStream]::new([Convert]::FromBase64String('${compressed}')); $g = [IO.Compression.GZipStream]::new($m, [IO.Compression.CompressionMode]::Decompress); $r = [IO.StreamReader]::new($g, [Text.Encoding]::UTF8); try { Invoke-Expression $r.ReadToEnd() } finally { $r.Dispose(); $g.Dispose(); $m.Dispose() }`;
|
|
382
355
|
return `powershell -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(bootstrap, "utf16le").toString("base64")}`;
|
|
383
356
|
};
|
|
384
|
-
var createPending =
|
|
357
|
+
var createPending = (scope, sessionID, agent, counterValue, workdir, watchdogSeconds = 15) => {
|
|
385
358
|
const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
|
|
386
359
|
try {
|
|
387
360
|
const file = join(directory, randomUUID());
|
|
@@ -397,14 +370,14 @@ var createPending = function createPending(scope, sessionID, agent, counterValue
|
|
|
397
370
|
fd,
|
|
398
371
|
identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid },
|
|
399
372
|
expires: Date.now() + captureTimeout,
|
|
400
|
-
command: captureCommand(file)
|
|
373
|
+
command: captureCommand(file, watchdogSeconds)
|
|
401
374
|
};
|
|
402
375
|
} catch (error) {
|
|
403
376
|
rmSync(directory, { recursive: true, force: true });
|
|
404
377
|
throw error;
|
|
405
378
|
}
|
|
406
379
|
};
|
|
407
|
-
var cleanup =
|
|
380
|
+
var cleanup = (pending) => {
|
|
408
381
|
if (pending.closed === true) {
|
|
409
382
|
return;
|
|
410
383
|
}
|
|
@@ -412,34 +385,46 @@ var cleanup = function cleanup(pending) {
|
|
|
412
385
|
closeSync(pending.fd);
|
|
413
386
|
rmSync(pending.directory, { recursive: true, force: true });
|
|
414
387
|
};
|
|
415
|
-
var decode =
|
|
388
|
+
var decode = (line) => {
|
|
416
389
|
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(line)) {
|
|
417
390
|
throw new Error("Invalid capture framing");
|
|
418
391
|
}
|
|
419
392
|
return Buffer.from(line, "base64").toString("utf-8");
|
|
420
393
|
};
|
|
421
|
-
var
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
}
|
|
435
|
-
return bytes;
|
|
436
|
-
};
|
|
437
|
-
const bytes = readArtifact();
|
|
394
|
+
var readCaptureArtifact = (pending) => {
|
|
395
|
+
const stat = fstatSync(pending.fd);
|
|
396
|
+
if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || process.platform !== "win32" && (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
|
|
397
|
+
throw new Error("Invalid private capture artifact");
|
|
398
|
+
}
|
|
399
|
+
const bytes = Buffer.alloc(stat.size);
|
|
400
|
+
if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size) {
|
|
401
|
+
throw new Error("Incomplete private capture artifact");
|
|
402
|
+
}
|
|
403
|
+
const completed = fstatSync(pending.fd);
|
|
404
|
+
if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino) {
|
|
405
|
+
throw new Error("Capture changed during import");
|
|
406
|
+
}
|
|
438
407
|
const fields = bytes.toString("utf-8").split(`
|
|
439
408
|
`);
|
|
440
409
|
if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "") {
|
|
441
410
|
throw new Error("Incomplete capture");
|
|
442
411
|
}
|
|
412
|
+
return fields;
|
|
413
|
+
};
|
|
414
|
+
var decodeConfigField = (state, field) => {
|
|
415
|
+
if (state === "set") {
|
|
416
|
+
return decode(field).trim();
|
|
417
|
+
}
|
|
418
|
+
return state === "unset" ? null : "error";
|
|
419
|
+
};
|
|
420
|
+
var assertBaselineIdentity = (baseline, fields, rawLog) => {
|
|
421
|
+
const { directory, gitDir, commonDir, head, messages } = baseline;
|
|
422
|
+
if (!isAbsolute(directory) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || directory !== findGitRoot(baseline.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/u.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00"))) {
|
|
423
|
+
throw new Error("Invalid Git baseline");
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
var importCapture = (pending) => {
|
|
427
|
+
const fields = readCaptureArtifact(pending);
|
|
443
428
|
const rawRoot = decode(fields[1]).trimEnd();
|
|
444
429
|
const root = isAbsolute(rawRoot) ? realpathSync(resolve(rawRoot)) : rawRoot;
|
|
445
430
|
const gitDir = decode(fields[2]).trimEnd();
|
|
@@ -448,29 +433,12 @@ var importCapture = function importCapture(pending) {
|
|
|
448
433
|
const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
|
|
449
434
|
const rawLog = decode(fields[8]);
|
|
450
435
|
const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
|
|
451
|
-
const validateIdentity = () => {
|
|
452
|
-
if (!isAbsolute(root) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || root !== findGitRoot(pending.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/u.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00"))) {
|
|
453
|
-
throw new Error("Invalid Git baseline");
|
|
454
|
-
}
|
|
455
|
-
};
|
|
456
|
-
validateIdentity();
|
|
457
|
-
const [configState] = fields.slice(9);
|
|
458
436
|
const value = decode(fields[10]).trim();
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
};
|
|
465
|
-
const readSigningKey = () => {
|
|
466
|
-
if (fields[11] === "set") {
|
|
467
|
-
return decode(fields[12]).trim();
|
|
468
|
-
}
|
|
469
|
-
return fields[11] === "unset" ? null : "error";
|
|
470
|
-
};
|
|
471
|
-
const gpgsign = readSigningPolicy();
|
|
472
|
-
const signingkey = readSigningKey();
|
|
473
|
-
return {
|
|
437
|
+
let gpgsign = fields[9] === "unset" ? "unset" : "error";
|
|
438
|
+
if (fields[9] === "set" && (value === "true" || value === "false")) {
|
|
439
|
+
gpgsign = value;
|
|
440
|
+
}
|
|
441
|
+
const baseline = {
|
|
474
442
|
directory: root,
|
|
475
443
|
workdir: pending.workdir,
|
|
476
444
|
gitDir,
|
|
@@ -479,101 +447,82 @@ var importCapture = function importCapture(pending) {
|
|
|
479
447
|
head,
|
|
480
448
|
messages,
|
|
481
449
|
gpgsign,
|
|
482
|
-
signingkey
|
|
450
|
+
signingkey: decodeConfigField(fields[11], fields[12])
|
|
483
451
|
};
|
|
452
|
+
assertBaselineIdentity(baseline, fields, rawLog);
|
|
453
|
+
return baseline;
|
|
484
454
|
};
|
|
485
|
-
var publish =
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
455
|
+
var publish = (ctx, pending, generation, baseline) => storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
|
|
456
|
+
if ((yield* counter(ctx, pending.scope)) !== pending.counter) {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
|
|
460
|
+
const checksum = snapshotChecksum(pending.scope, pending.counter, generation, sequence, baseline);
|
|
461
|
+
yield* ctx.storage.set(prefix(pending.scope) + sequence, {
|
|
462
|
+
schema: version,
|
|
463
|
+
scope: pending.scope,
|
|
464
|
+
counter: pending.counter,
|
|
465
|
+
generation,
|
|
466
|
+
sequence,
|
|
467
|
+
checksum,
|
|
468
|
+
baseline: { ...baseline, messages: [...baseline.messages] }
|
|
469
|
+
});
|
|
470
|
+
yield* scanStoragePrefix(ctx, prefix(pending.scope), (record) => Effect.gen(function* removeOld() {
|
|
471
|
+
if (record.key < prefix(pending.scope) + sequence) {
|
|
472
|
+
yield* ctx.storage.remove(record.key);
|
|
489
473
|
}
|
|
490
|
-
const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
|
|
491
|
-
const checksum = digest(JSON.stringify([
|
|
492
|
-
version,
|
|
493
|
-
pending.scope,
|
|
494
|
-
pending.counter,
|
|
495
|
-
generation,
|
|
496
|
-
sequence,
|
|
497
|
-
baseline
|
|
498
|
-
]));
|
|
499
|
-
yield* ctx.storage.set(prefix(pending.scope) + sequence, {
|
|
500
|
-
schema: version,
|
|
501
|
-
scope: pending.scope,
|
|
502
|
-
counter: pending.counter,
|
|
503
|
-
generation,
|
|
504
|
-
sequence,
|
|
505
|
-
checksum,
|
|
506
|
-
baseline: { ...baseline, messages: [...baseline.messages] }
|
|
507
|
-
});
|
|
508
|
-
let after;
|
|
509
|
-
do {
|
|
510
|
-
const page = yield* ctx.storage.scan({
|
|
511
|
-
prefix: prefix(pending.scope),
|
|
512
|
-
after,
|
|
513
|
-
limit: 100
|
|
514
|
-
});
|
|
515
|
-
for (const record of page.entries) {
|
|
516
|
-
if (record.key < prefix(pending.scope) + sequence) {
|
|
517
|
-
yield* ctx.storage.remove(record.key);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
after = page.next;
|
|
521
|
-
} while (after !== undefined);
|
|
522
|
-
return true;
|
|
523
474
|
}));
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
// src/config.ts
|
|
527
|
-
import { Schema } from "effect";
|
|
475
|
+
return true;
|
|
476
|
+
}));
|
|
528
477
|
|
|
529
478
|
// src/scope.ts
|
|
530
479
|
var scopePattern = /^(?<scope>[a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(?<subject>.+)$/u;
|
|
531
480
|
|
|
532
481
|
// src/config.ts
|
|
533
|
-
var parseConfig =
|
|
482
|
+
var parseConfig = (options) => {
|
|
534
483
|
if (options === undefined) {
|
|
535
484
|
return defaultConfig;
|
|
536
485
|
}
|
|
537
486
|
if (!isRecord(options)) {
|
|
538
487
|
throw new Error("Invalid plugin options; expected an object.");
|
|
539
488
|
}
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
489
|
+
if (options.requireSignoff !== undefined) {
|
|
490
|
+
throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value. Valid options: requireScope, allowedScopes, maxLineLength.");
|
|
491
|
+
}
|
|
492
|
+
const validOptions = ["requireScope", "allowedScopes", "maxLineLength"];
|
|
493
|
+
const unknownKeys = Object.keys(options).filter((key) => !validOptions.includes(key));
|
|
494
|
+
if (unknownKeys.length > 0) {
|
|
495
|
+
throw new Error(`Unrecognized plugin options: ${unknownKeys.join(", ")}. Valid options: ${validOptions.join(", ")}.`);
|
|
547
496
|
}
|
|
548
|
-
const
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
497
|
+
const {
|
|
498
|
+
requireScope = defaultConfig.requireScope,
|
|
499
|
+
maxLineLength = defaultConfig.maxLineLength,
|
|
500
|
+
allowedScopes: rawScopes
|
|
501
|
+
} = options;
|
|
502
|
+
if (!isJSONBoolean(requireScope)) {
|
|
503
|
+
throw new Error("Invalid plugin option requireScope; expected a boolean.");
|
|
504
|
+
}
|
|
505
|
+
if (!isJSONNumber(maxLineLength) || !Number.isSafeInteger(maxLineLength) || maxLineLength < 0) {
|
|
506
|
+
throw new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0.");
|
|
507
|
+
}
|
|
508
|
+
let allowedScopes;
|
|
509
|
+
if (rawScopes !== undefined) {
|
|
510
|
+
if (!Array.isArray(rawScopes)) {
|
|
552
511
|
throw new TypeError("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
|
|
553
512
|
}
|
|
554
513
|
const scopes = [];
|
|
555
|
-
for (const item of
|
|
514
|
+
for (const item of rawScopes) {
|
|
556
515
|
if (!isJSONString(item) || item.trim().length === 0) {
|
|
557
516
|
throw new Error("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
|
|
558
517
|
}
|
|
559
|
-
|
|
518
|
+
const trimmed = item.trim();
|
|
519
|
+
if (scopePattern.exec(`${trimmed}: Subject`)?.[1] !== trimmed) {
|
|
560
520
|
throw new Error(`Invalid plugin option allowedScopes; scope ${JSON.stringify(item)} cannot match the commit scope syntax.`);
|
|
561
521
|
}
|
|
562
|
-
scopes.push(
|
|
522
|
+
scopes.push(trimmed);
|
|
563
523
|
}
|
|
564
524
|
allowedScopes = scopes.length > 0 ? scopes : undefined;
|
|
565
525
|
}
|
|
566
|
-
const rawMaxLineLength = options.maxLineLength;
|
|
567
|
-
let { maxLineLength } = defaultConfig;
|
|
568
|
-
if (rawMaxLineLength !== undefined) {
|
|
569
|
-
if (!isJSONNumber(rawMaxLineLength) || !Number.isSafeInteger(rawMaxLineLength) || rawMaxLineLength < 0) {
|
|
570
|
-
throw new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0.");
|
|
571
|
-
}
|
|
572
|
-
maxLineLength = rawMaxLineLength;
|
|
573
|
-
}
|
|
574
|
-
if (options.requireSignoff !== undefined) {
|
|
575
|
-
throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value.");
|
|
576
|
-
}
|
|
577
526
|
return {
|
|
578
527
|
requireScope,
|
|
579
528
|
allowedScopes,
|
|
@@ -593,6 +542,13 @@ var gitGlobalOptionsWithArg = new Set([
|
|
|
593
542
|
"--super-prefix",
|
|
594
543
|
"--config-env"
|
|
595
544
|
]);
|
|
545
|
+
var targetGlobalOptions = new Set([
|
|
546
|
+
"-C",
|
|
547
|
+
"-c",
|
|
548
|
+
"--git-dir",
|
|
549
|
+
"--work-tree",
|
|
550
|
+
"--config-env"
|
|
551
|
+
]);
|
|
596
552
|
var commandPrefixes = new Set([
|
|
597
553
|
"!",
|
|
598
554
|
"do",
|
|
@@ -630,276 +586,110 @@ var commitLongOptionsWithArg = new Set([
|
|
|
630
586
|
"--reedit-message",
|
|
631
587
|
"--reuse-message",
|
|
632
588
|
"--squash",
|
|
633
|
-
"--template"
|
|
589
|
+
"--template",
|
|
590
|
+
"--trailer"
|
|
591
|
+
]);
|
|
592
|
+
var simpleAnsiEscapes = new Map(Object.entries({
|
|
593
|
+
a: "\x07",
|
|
594
|
+
b: "\b",
|
|
595
|
+
e: "\x1B",
|
|
596
|
+
E: "\x1B",
|
|
597
|
+
f: "\f",
|
|
598
|
+
n: `
|
|
599
|
+
`,
|
|
600
|
+
r: "\r",
|
|
601
|
+
t: "\t",
|
|
602
|
+
v: "\v",
|
|
603
|
+
"\\": "\\",
|
|
604
|
+
"'": "'",
|
|
605
|
+
'"': '"',
|
|
606
|
+
"?": "?"
|
|
607
|
+
}));
|
|
608
|
+
var hexEscapeWidths = new Map([
|
|
609
|
+
["x", 2],
|
|
610
|
+
["u", 4],
|
|
611
|
+
["U", 8]
|
|
612
|
+
]);
|
|
613
|
+
var twoCharacterOperators = new Set(["&&", "||", "|&", ";;"]);
|
|
614
|
+
var wrapperArgsWithValue = new Map([
|
|
615
|
+
["env", new Set(["-u", "--unset", "-C", "--chdir"])],
|
|
616
|
+
["exec", new Set(["-a"])],
|
|
617
|
+
["command", new Set],
|
|
618
|
+
["nohup", new Set],
|
|
619
|
+
["builtin", new Set]
|
|
620
|
+
]);
|
|
621
|
+
var booleanCommitFlags = new Map([
|
|
622
|
+
["-h", ["isHelp", true]],
|
|
623
|
+
["--help", ["isHelp", true]],
|
|
624
|
+
["--amend", ["isAmend", true]],
|
|
625
|
+
["--no-edit", ["hasNoEdit", true]],
|
|
626
|
+
["--edit", ["hasNoEdit", false]],
|
|
627
|
+
["-s", ["hasSignoffFlag", true]],
|
|
628
|
+
["--signoff", ["hasSignoffFlag", true]],
|
|
629
|
+
["--no-signoff", ["hasSignoffFlag", false]]
|
|
634
630
|
]);
|
|
635
|
-
var
|
|
636
|
-
|
|
637
|
-
|
|
631
|
+
var inspectionError = (message) => new Error(`[commit-guard] Pre-execution shell inspection failed: ${message}`);
|
|
632
|
+
var incompleteHeredoc = () => inspectionError("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
|
|
633
|
+
var isWordSeparator = (character) => /[ \t\r\n;&|()]/u.test(character);
|
|
634
|
+
var isExpansion = (command, i) => command[i] === "$" && /[a-zA-Z0-9_{[*#?@!$-]/u.test(command[i + 1] ?? "");
|
|
635
|
+
var ansiEscape = (command, start) => {
|
|
636
|
+
const escaped = command[start + 1] ?? "";
|
|
637
|
+
const literal = simpleAnsiEscapes.get(escaped);
|
|
638
|
+
if (literal !== undefined) {
|
|
639
|
+
return { content: literal, end: start + 2 };
|
|
640
|
+
}
|
|
641
|
+
const character = command[start + 2];
|
|
642
|
+
if (escaped === "c" && character !== undefined && character !== "'") {
|
|
643
|
+
return {
|
|
644
|
+
content: String.fromCodePoint(character === "?" ? 127 : (character.toUpperCase().codePointAt(0) ?? 0) & 31),
|
|
645
|
+
end: start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3)
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
const count = hexEscapeWidths.get(escaped) ?? 0;
|
|
649
|
+
const digits = count > 0 ? new RegExp(`^[0-9a-fA-F]{1,${count}}`, "u").exec(command.slice(start + 2))?.[0] : /^[0-7]{1,3}/u.exec(command.slice(start + 1))?.[0];
|
|
650
|
+
if (digits === undefined) {
|
|
651
|
+
return { content: `\\${escaped}`, end: start + 2 };
|
|
652
|
+
}
|
|
653
|
+
const radix = count > 0 ? 16 : 8;
|
|
654
|
+
const code = Number.parseInt(digits, radix);
|
|
655
|
+
if (code > 1114111) {
|
|
656
|
+
throw inspectionError("Cannot validate this ANSI-C escape. Supply literal text.");
|
|
657
|
+
}
|
|
658
|
+
const end = start + (count > 0 ? 2 : 1) + digits.length;
|
|
659
|
+
return count === 0 || escaped === "x" ? { content: "", byte: code & 255, end } : { content: String.fromCodePoint(code), end };
|
|
638
660
|
};
|
|
639
|
-
var
|
|
640
|
-
|
|
641
|
-
|
|
661
|
+
var scanSingleQuote = (command, start) => {
|
|
662
|
+
const end = command.indexOf("'", start + 1);
|
|
663
|
+
if (end === -1) {
|
|
664
|
+
throw inspectionError(`Unterminated single quote starting at character ${start + 1}. Close the quote before running the command.`);
|
|
642
665
|
}
|
|
643
|
-
|
|
644
|
-
|
|
666
|
+
return { content: command.slice(start + 1, end), end: end + 1 };
|
|
667
|
+
};
|
|
668
|
+
var scanAnsiQuote = (command, start) => {
|
|
669
|
+
const bytes = [];
|
|
645
670
|
let i = start + 2;
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
break;
|
|
656
|
-
}
|
|
657
|
-
const activeCase = cases.at(-1);
|
|
658
|
-
const consumedQuote = (() => {
|
|
659
|
-
if (quote === "$'") {
|
|
660
|
-
if (character === "'") {
|
|
661
|
-
quote = undefined;
|
|
662
|
-
} else if (character === "\\") {
|
|
663
|
-
i = ansiEscape(command, i).end;
|
|
664
|
-
return true;
|
|
665
|
-
}
|
|
666
|
-
i += 1;
|
|
667
|
-
return true;
|
|
668
|
-
}
|
|
669
|
-
if (quote === "'") {
|
|
670
|
-
if (character === "'") {
|
|
671
|
-
quote = undefined;
|
|
672
|
-
}
|
|
673
|
-
i += 1;
|
|
674
|
-
return true;
|
|
675
|
-
}
|
|
676
|
-
if (quote === '"') {
|
|
677
|
-
if (character === "\\") {
|
|
678
|
-
i += i + 1 < command.length ? 2 : 1;
|
|
679
|
-
} else if (character === '"') {
|
|
680
|
-
quote = undefined;
|
|
681
|
-
i += 1;
|
|
682
|
-
} else if (character === "$" && command[i + 1] === "(") {
|
|
683
|
-
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
684
|
-
} else if (character === "$" && command[i + 1] === "{") {
|
|
685
|
-
i = consumeQuotedParameter(command, i);
|
|
686
|
-
} else if (character === "`") {
|
|
687
|
-
i = consumeBackticks(command, i, true).end;
|
|
688
|
-
} else {
|
|
689
|
-
i += 1;
|
|
690
|
-
}
|
|
691
|
-
return true;
|
|
692
|
-
}
|
|
693
|
-
return false;
|
|
694
|
-
})();
|
|
695
|
-
if (consumedQuote) {
|
|
696
|
-
continue;
|
|
697
|
-
}
|
|
698
|
-
const consumedEscapeOrHeredoc = (() => {
|
|
699
|
-
if (character === "\\") {
|
|
700
|
-
if (command[i + 1] !== `
|
|
701
|
-
`) {
|
|
702
|
-
if (activeCase?.depth === depth && activeCase.phase === "pattern") {
|
|
703
|
-
activeCase.patternStart = false;
|
|
704
|
-
}
|
|
705
|
-
atWordStart = false;
|
|
706
|
-
atCommandStart = false;
|
|
707
|
-
}
|
|
708
|
-
i += i + 1 < command.length ? 2 : 1;
|
|
709
|
-
return true;
|
|
710
|
-
}
|
|
711
|
-
if (arithmeticDepth === undefined && character === "<" && command[i + 1] === "<") {
|
|
712
|
-
if (command[i + 2] === "<") {
|
|
713
|
-
i += 3;
|
|
714
|
-
} else {
|
|
715
|
-
const parsed = tokenizeShellInput(command, i, true, nesting + 1);
|
|
716
|
-
if (parsed.delimiter === undefined) {
|
|
717
|
-
throw incompleteHeredoc();
|
|
718
|
-
}
|
|
719
|
-
pendingHeredocs.push(parsed.delimiter);
|
|
720
|
-
i = parsed.end;
|
|
721
|
-
}
|
|
722
|
-
atWordStart = true;
|
|
723
|
-
return true;
|
|
724
|
-
}
|
|
725
|
-
if (character === `
|
|
726
|
-
` && pendingHeredocs.length > 0) {
|
|
727
|
-
i += 1;
|
|
728
|
-
for (const heredoc of pendingHeredocs) {
|
|
729
|
-
i = consumeHeredoc(command, i, heredoc).end;
|
|
730
|
-
}
|
|
731
|
-
pendingHeredocs.length = 0;
|
|
732
|
-
atWordStart = true;
|
|
733
|
-
atCommandStart = true;
|
|
734
|
-
timeOption = false;
|
|
735
|
-
return true;
|
|
736
|
-
}
|
|
737
|
-
return false;
|
|
738
|
-
})();
|
|
739
|
-
if (consumedEscapeOrHeredoc) {
|
|
740
|
-
continue;
|
|
741
|
-
}
|
|
742
|
-
const consumedCaseTerminator = (() => {
|
|
743
|
-
if (activeCase?.depth === depth && activeCase.phase === "body" && character === ";" && (command[i + 1] === ";" || command[i + 1] === "&")) {
|
|
744
|
-
i += command.slice(i, i + 3) === ";;&" ? 3 : 2;
|
|
745
|
-
activeCase.phase = "pattern";
|
|
746
|
-
activeCase.patternStart = true;
|
|
747
|
-
atWordStart = true;
|
|
748
|
-
atCommandStart = true;
|
|
749
|
-
return true;
|
|
750
|
-
}
|
|
751
|
-
return false;
|
|
752
|
-
})();
|
|
753
|
-
if (consumedCaseTerminator) {
|
|
754
|
-
continue;
|
|
755
|
-
}
|
|
756
|
-
(() => {
|
|
757
|
-
if ((atCommandStart || activeCase?.phase === "word" || activeCase?.phase === "in" || activeCase?.phase === "pattern") && atWordStart && !isWordSeparator(character) && character !== "#") {
|
|
758
|
-
const word = (() => {
|
|
759
|
-
let headerWord = "";
|
|
760
|
-
for (let end = i;end < command.length; end += 1) {
|
|
761
|
-
const next = command[end];
|
|
762
|
-
if (next === "\\" && command[end + 1] === `
|
|
763
|
-
`) {
|
|
764
|
-
end += 1;
|
|
765
|
-
continue;
|
|
766
|
-
}
|
|
767
|
-
if (isWordSeparator(next)) {
|
|
768
|
-
break;
|
|
769
|
-
}
|
|
770
|
-
headerWord += next;
|
|
771
|
-
}
|
|
772
|
-
return headerWord;
|
|
773
|
-
})();
|
|
774
|
-
const patternWord = activeCase?.phase === "pattern";
|
|
775
|
-
(() => {
|
|
776
|
-
if (activeCase?.depth === depth && activeCase.phase === "word") {
|
|
777
|
-
activeCase.phase = "in";
|
|
778
|
-
} else if (activeCase?.depth === depth && activeCase.phase === "in") {
|
|
779
|
-
if (word !== "in") {
|
|
780
|
-
throw inspectionError("Cannot parse case header. Simplify the unsupported syntax.");
|
|
781
|
-
}
|
|
782
|
-
activeCase.phase = "pattern";
|
|
783
|
-
} else if (word === "esac" && activeCase?.depth === depth && (activeCase.phase !== "pattern" || activeCase.patternStart)) {
|
|
784
|
-
cases.pop();
|
|
785
|
-
} else if (word === "case" && activeCase?.phase !== "pattern") {
|
|
786
|
-
cases.push({ depth, phase: "word", patternStart: true });
|
|
787
|
-
}
|
|
788
|
-
})();
|
|
789
|
-
if (activeCase !== undefined && patternWord) {
|
|
790
|
-
activeCase.patternStart = false;
|
|
791
|
-
}
|
|
792
|
-
if (!patternWord && (word === "function" || word === "coproc")) {
|
|
793
|
-
throw inspectionError("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately.");
|
|
794
|
-
}
|
|
795
|
-
(() => {
|
|
796
|
-
atCommandStart = timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "{";
|
|
797
|
-
timeOption = word === "time" || timeOption && word === "-p";
|
|
798
|
-
})();
|
|
799
|
-
}
|
|
800
|
-
})();
|
|
801
|
-
const consumedQuotedStartOrSubstitution = (() => {
|
|
802
|
-
if (character === "$" && command[i + 1] === "'") {
|
|
803
|
-
quote = "$'";
|
|
804
|
-
atWordStart = false;
|
|
805
|
-
i += 2;
|
|
806
|
-
return true;
|
|
807
|
-
}
|
|
808
|
-
if (character === "'") {
|
|
809
|
-
quote = "'";
|
|
810
|
-
atWordStart = false;
|
|
811
|
-
i += 1;
|
|
812
|
-
return true;
|
|
813
|
-
}
|
|
814
|
-
if (character === '"') {
|
|
815
|
-
quote = '"';
|
|
816
|
-
atWordStart = false;
|
|
817
|
-
i += 1;
|
|
818
|
-
return true;
|
|
819
|
-
}
|
|
820
|
-
if (character === "#" && atWordStart) {
|
|
821
|
-
while (i < command.length && command[i] !== `
|
|
822
|
-
`) {
|
|
823
|
-
i += 1;
|
|
824
|
-
}
|
|
825
|
-
return true;
|
|
826
|
-
}
|
|
827
|
-
if (character === "$" && command[i + 1] === "(") {
|
|
828
|
-
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
829
|
-
atWordStart = false;
|
|
830
|
-
return true;
|
|
831
|
-
}
|
|
832
|
-
if (character === "`") {
|
|
833
|
-
i = consumeBackticks(command, i).end;
|
|
834
|
-
atWordStart = false;
|
|
835
|
-
return true;
|
|
836
|
-
}
|
|
837
|
-
return false;
|
|
838
|
-
})();
|
|
839
|
-
if (consumedQuotedStartOrSubstitution) {
|
|
840
|
-
continue;
|
|
841
|
-
}
|
|
842
|
-
let completed;
|
|
843
|
-
const consumedParenthesis = (() => {
|
|
844
|
-
if (character === "(") {
|
|
845
|
-
if (activeCase?.depth === depth && activeCase.phase === "pattern") {
|
|
846
|
-
activeCase.patternStart = false;
|
|
847
|
-
i += 1;
|
|
848
|
-
atWordStart = true;
|
|
849
|
-
return true;
|
|
850
|
-
}
|
|
851
|
-
if (arithmeticDepth === undefined && atCommandStart && command[i + 1] === "(") {
|
|
852
|
-
arithmeticDepth = depth;
|
|
853
|
-
}
|
|
854
|
-
depth += 1;
|
|
855
|
-
i += 1;
|
|
856
|
-
atWordStart = true;
|
|
857
|
-
atCommandStart = true;
|
|
858
|
-
return true;
|
|
859
|
-
}
|
|
860
|
-
if (character === ")") {
|
|
861
|
-
if (activeCase?.depth === depth && activeCase.phase === "pattern") {
|
|
862
|
-
activeCase.phase = "body";
|
|
863
|
-
atCommandStart = true;
|
|
864
|
-
atWordStart = true;
|
|
865
|
-
i += 1;
|
|
866
|
-
return true;
|
|
867
|
-
}
|
|
868
|
-
depth -= 1;
|
|
869
|
-
if (depth === arithmeticDepth) {
|
|
870
|
-
arithmeticDepth = undefined;
|
|
871
|
-
}
|
|
872
|
-
if (depth === 0) {
|
|
873
|
-
if (pendingHeredocs.length > 0) {
|
|
874
|
-
throw incompleteHeredoc();
|
|
875
|
-
}
|
|
876
|
-
completed = { content: command.slice(start + 2, i), end: i + 1 };
|
|
877
|
-
return true;
|
|
878
|
-
}
|
|
879
|
-
atWordStart = true;
|
|
880
|
-
}
|
|
881
|
-
return false;
|
|
882
|
-
})();
|
|
883
|
-
if (completed !== undefined) {
|
|
884
|
-
return completed;
|
|
885
|
-
}
|
|
886
|
-
if (consumedParenthesis) {
|
|
887
|
-
continue;
|
|
888
|
-
}
|
|
889
|
-
if ([";", "&", "|", `
|
|
890
|
-
`, ")"].includes(character)) {
|
|
891
|
-
atCommandStart = true;
|
|
892
|
-
timeOption = false;
|
|
671
|
+
while (i < command.length && command[i] !== "'") {
|
|
672
|
+
if (command[i] === "\\" && i + 1 < command.length) {
|
|
673
|
+
const escaped = ansiEscape(command, i);
|
|
674
|
+
bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
|
|
675
|
+
i = escaped.end;
|
|
676
|
+
} else {
|
|
677
|
+
const literal = String.fromCodePoint(command.codePointAt(i) ?? 0);
|
|
678
|
+
bytes.push(...Buffer.from(literal));
|
|
679
|
+
i += literal.length;
|
|
893
680
|
}
|
|
894
|
-
atWordStart = isWordSeparator(character);
|
|
895
|
-
i += 1;
|
|
896
681
|
}
|
|
897
|
-
if (
|
|
898
|
-
throw
|
|
682
|
+
if (command[i] !== "'") {
|
|
683
|
+
throw inspectionError(`Unterminated ANSI-C quote starting at character ${start + 1}. Close the quote before running the command.`);
|
|
899
684
|
}
|
|
900
|
-
|
|
685
|
+
const nul = bytes.indexOf(0);
|
|
686
|
+
return {
|
|
687
|
+
content: "",
|
|
688
|
+
end: i + 1,
|
|
689
|
+
bytes: nul === -1 ? bytes : bytes.slice(0, nul)
|
|
690
|
+
};
|
|
901
691
|
};
|
|
902
|
-
var consumeBackticks =
|
|
692
|
+
var consumeBackticks = (command, start, doubleQuoted = false) => {
|
|
903
693
|
let content = "";
|
|
904
694
|
for (let i = start + 1;i < command.length; i += 1) {
|
|
905
695
|
if (command[i] === "`") {
|
|
@@ -912,7 +702,7 @@ var consumeBackticks = function consumeBackticks(command, start, doubleQuoted =
|
|
|
912
702
|
}
|
|
913
703
|
throw inspectionError(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`);
|
|
914
704
|
};
|
|
915
|
-
var consumeQuotedParameter =
|
|
705
|
+
var consumeQuotedParameter = (command, start, nesting = 0) => {
|
|
916
706
|
if (nesting > 12) {
|
|
917
707
|
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
918
708
|
}
|
|
@@ -934,82 +724,43 @@ var consumeQuotedParameter = function consumeQuotedParameter(command, start, nes
|
|
|
934
724
|
}
|
|
935
725
|
throw inspectionError("Cannot parse an incomplete double-quoted parameter expansion. Close its quotes and braces or quote literal text.");
|
|
936
726
|
};
|
|
937
|
-
var
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
var ansiEscape = function ansiEscape(command, start) {
|
|
941
|
-
const escaped = command[start + 1] ?? "";
|
|
942
|
-
const simple = new Map(Object.entries({
|
|
943
|
-
a: "\x07",
|
|
944
|
-
b: "\b",
|
|
945
|
-
e: "\x1B",
|
|
946
|
-
E: "\x1B",
|
|
947
|
-
f: "\f",
|
|
948
|
-
n: `
|
|
949
|
-
`,
|
|
950
|
-
r: "\r",
|
|
951
|
-
t: "\t",
|
|
952
|
-
v: "\v",
|
|
953
|
-
"\\": "\\",
|
|
954
|
-
"'": "'",
|
|
955
|
-
'"': '"',
|
|
956
|
-
"?": "?"
|
|
957
|
-
}));
|
|
958
|
-
const literal = simple.get(escaped);
|
|
959
|
-
if (literal !== undefined) {
|
|
960
|
-
return { content: literal, end: start + 2 };
|
|
961
|
-
}
|
|
962
|
-
if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
|
|
963
|
-
const character = command[start + 2];
|
|
964
|
-
const end = start + (character === "\\" && command[start + 3] === "\\" ? 4 : 3);
|
|
965
|
-
return {
|
|
966
|
-
content: String.fromCodePoint(character === "?" ? 127 : (character.toUpperCase().codePointAt(0) ?? 0) & 31),
|
|
967
|
-
end
|
|
968
|
-
};
|
|
969
|
-
}
|
|
970
|
-
const count = new Map([
|
|
971
|
-
["x", 2],
|
|
972
|
-
["u", 4],
|
|
973
|
-
["U", 8]
|
|
974
|
-
]).get(escaped) ?? 0;
|
|
975
|
-
const digits = count > 0 ? new RegExp(`^[0-9a-fA-F]{1,${count}}`, "u").exec(command.slice(start + 2))?.[0] : /^[0-7]{1,3}/u.exec(command.slice(start + 1))?.[0];
|
|
976
|
-
if (digits !== undefined) {
|
|
977
|
-
const radix = count > 0 ? 16 : 8;
|
|
978
|
-
const code = Number.parseInt(digits, radix);
|
|
979
|
-
if (code > 1114111) {
|
|
980
|
-
throw inspectionError("Cannot validate this ANSI-C escape. Supply literal text.");
|
|
981
|
-
}
|
|
982
|
-
const end = start + (count > 0 ? 2 : 1) + digits.length;
|
|
983
|
-
if (count === 0 || escaped === "x") {
|
|
984
|
-
return { content: "", byte: code & 255, end };
|
|
985
|
-
}
|
|
986
|
-
return { content: String.fromCodePoint(code), end };
|
|
987
|
-
}
|
|
988
|
-
return { content: `\\${escaped}`, end: start + 2 };
|
|
989
|
-
};
|
|
990
|
-
var pushWord = function pushWord(tokens, value, substitutions, expansion) {
|
|
991
|
-
const token = substitutions.length > 0 ? { type: "word", value, substitutions } : { type: "word", value };
|
|
992
|
-
tokens.push(expansion ? { ...token, expansion: true } : token);
|
|
993
|
-
};
|
|
994
|
-
var heredocSubstitutions = function heredocSubstitutions(body) {
|
|
727
|
+
var scanDoubleQuote = (command, start, nesting) => {
|
|
728
|
+
let content = "";
|
|
729
|
+
let expansion = false;
|
|
995
730
|
const substitutions = [];
|
|
996
|
-
|
|
997
|
-
|
|
731
|
+
let i = start + 1;
|
|
732
|
+
while (i < command.length && command[i] !== '"') {
|
|
733
|
+
const character = command[i];
|
|
734
|
+
if (character === "\\" && i + 1 < command.length) {
|
|
735
|
+
const escaped = command[i + 1];
|
|
736
|
+
if (escaped !== `
|
|
737
|
+
`) {
|
|
738
|
+
content += ['"', "\\", "$", "`"].includes(escaped) ? escaped : `\\${escaped}`;
|
|
739
|
+
}
|
|
740
|
+
i += 2;
|
|
741
|
+
} else if (character === "$" && command[i + 1] === "(" || character === "`") {
|
|
742
|
+
const result = character === "`" ? consumeBackticks(command, i, true) : consumeCommandSubstitution(command, i, nesting);
|
|
743
|
+
content += command.slice(i, result.end);
|
|
744
|
+
substitutions.push(result.content);
|
|
745
|
+
expansion = true;
|
|
746
|
+
i = result.end;
|
|
747
|
+
} else if (character === "$" && command[i + 1] === "{") {
|
|
748
|
+
const end = consumeQuotedParameter(command, i);
|
|
749
|
+
content += command.slice(i, end);
|
|
750
|
+
expansion = true;
|
|
751
|
+
i = end;
|
|
752
|
+
} else {
|
|
753
|
+
expansion ||= isExpansion(command, i);
|
|
754
|
+
content += character;
|
|
998
755
|
i += 1;
|
|
999
|
-
} else if (body[i] === "`") {
|
|
1000
|
-
throw inspectionError("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
|
|
1001
|
-
} else if (body[i] === "$" && body[i + 1] === "(") {
|
|
1002
|
-
const substitution = consumeCommandSubstitution(body, i);
|
|
1003
|
-
substitutions.push(substitution.content);
|
|
1004
|
-
i = substitution.end - 1;
|
|
1005
756
|
}
|
|
1006
757
|
}
|
|
1007
|
-
|
|
1008
|
-
};
|
|
1009
|
-
|
|
1010
|
-
return
|
|
758
|
+
if (command[i] !== '"') {
|
|
759
|
+
throw inspectionError(`Unterminated double quote starting at character ${start + 1}. Close the quote before running the command.`);
|
|
760
|
+
}
|
|
761
|
+
return { content, end: i + 1, expansion, substitutions };
|
|
1011
762
|
};
|
|
1012
|
-
var consumeHeredoc =
|
|
763
|
+
var consumeHeredoc = (command, start, heredoc) => {
|
|
1013
764
|
let i = start;
|
|
1014
765
|
let body = "";
|
|
1015
766
|
while (i < command.length) {
|
|
@@ -1041,327 +792,434 @@ var consumeHeredoc = function consumeHeredoc(command, start, heredoc) {
|
|
|
1041
792
|
}
|
|
1042
793
|
throw incompleteHeredoc();
|
|
1043
794
|
};
|
|
1044
|
-
var
|
|
1045
|
-
|
|
795
|
+
var advanceCaseState = (cases, depth, word) => {
|
|
796
|
+
const active = cases.at(-1);
|
|
797
|
+
const patternWord = active?.phase === "pattern";
|
|
798
|
+
if (active?.depth === depth && active.phase === "word") {
|
|
799
|
+
active.phase = "in";
|
|
800
|
+
} else if (active?.depth === depth && active.phase === "in") {
|
|
801
|
+
if (word !== "in") {
|
|
802
|
+
throw inspectionError("Cannot parse case header. Simplify the unsupported syntax.");
|
|
803
|
+
}
|
|
804
|
+
active.phase = "pattern";
|
|
805
|
+
} else if (word === "esac" && active?.depth === depth && (!patternWord || active.patternStart)) {
|
|
806
|
+
cases.pop();
|
|
807
|
+
} else if (word === "case" && !patternWord) {
|
|
808
|
+
cases.push({ depth, phase: "word", patternStart: true });
|
|
809
|
+
}
|
|
810
|
+
if (active !== undefined && patternWord) {
|
|
811
|
+
active.patternStart = false;
|
|
812
|
+
}
|
|
1046
813
|
};
|
|
1047
|
-
var
|
|
1048
|
-
const
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
if (
|
|
1055
|
-
break;
|
|
1056
|
-
}
|
|
1057
|
-
const skippedTrivia = (() => {
|
|
1058
|
-
if (character === " " || character === "\t" || character === "\r") {
|
|
1059
|
-
i += 1;
|
|
1060
|
-
return true;
|
|
1061
|
-
}
|
|
1062
|
-
if (character === "\\" && command[i + 1] === `
|
|
1063
|
-
`) {
|
|
1064
|
-
i += 2;
|
|
1065
|
-
return true;
|
|
1066
|
-
}
|
|
1067
|
-
if (character === "#") {
|
|
1068
|
-
while (i < command.length && command[i] !== `
|
|
814
|
+
var trackSubstitutionWord = (command, state) => {
|
|
815
|
+
const phase = state.cases.at(-1)?.phase;
|
|
816
|
+
if (!state.atWordStart || !(state.atCommandStart || ["word", "in", "pattern"].includes(phase ?? ""))) {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
let word = "";
|
|
820
|
+
for (let end = state.i;end < command.length; end += 1) {
|
|
821
|
+
if (command[end] === "\\" && command[end + 1] === `
|
|
1069
822
|
`) {
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
})();
|
|
1076
|
-
if (skippedTrivia) {
|
|
1077
|
-
continue;
|
|
823
|
+
end += 1;
|
|
824
|
+
} else if (isWordSeparator(command[end])) {
|
|
825
|
+
break;
|
|
826
|
+
} else {
|
|
827
|
+
word += command[end];
|
|
1078
828
|
}
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
}
|
|
1094
|
-
if (token.type === "word") {
|
|
1095
|
-
const precedingWord = tokens[index - 1]?.type === "word" ? tokens[index - 1]?.value : undefined;
|
|
1096
|
-
if (index === tokens.length - 1 && token.value === "coproc") {
|
|
1097
|
-
continue;
|
|
1098
|
-
}
|
|
1099
|
-
const followsTime = () => precedingWord === "time" || precedingWord === "-p" && tokens[index - 2]?.type === "word" && tokens[index - 2]?.value === "time";
|
|
1100
|
-
if (token.value === "--" && followsTime()) {
|
|
1101
|
-
continue;
|
|
1102
|
-
}
|
|
1103
|
-
if (index === tokens.length - 1 && (precedingWord === "function" || precedingWord === "coproc") || precedingWord === "time" && token.value === "-p") {
|
|
1104
|
-
index -= 1;
|
|
1105
|
-
continue;
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
if (token.type !== "word" || !commandPrefixes.has(token.value)) {
|
|
1109
|
-
commandPosition = false;
|
|
1110
|
-
break;
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
return commandPosition;
|
|
1114
|
-
})();
|
|
1115
|
-
let braceEnd = i + 1;
|
|
1116
|
-
while (command[braceEnd] === "\\" && command[braceEnd + 1] === `
|
|
829
|
+
}
|
|
830
|
+
advanceCaseState(state.cases, state.depth, word);
|
|
831
|
+
if (phase !== "pattern" && ["function", "coproc"].includes(word)) {
|
|
832
|
+
throw inspectionError("Cannot parse function or coproc declarations inside a command substitution. Run the declaration separately.");
|
|
833
|
+
}
|
|
834
|
+
state.atCommandStart = state.timeOption && (word === "-p" || word === "--") || commandPrefixes.has(word) || word === "for" || word === "{";
|
|
835
|
+
state.timeOption = word === "time" || state.timeOption && word === "-p";
|
|
836
|
+
};
|
|
837
|
+
var stepSubstitutionSyntax = (command, state, nesting) => {
|
|
838
|
+
const { i } = state;
|
|
839
|
+
const character = command[i];
|
|
840
|
+
const active = state.cases.at(-1);
|
|
841
|
+
if (character === "\\") {
|
|
842
|
+
if (command[i + 1] !== `
|
|
1117
843
|
`) {
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
standaloneBrace = braceCommandPosition && (command[braceEnd] === undefined || isWordSeparator(command[braceEnd]) || command[braceEnd] === "<" || command[braceEnd] === ">");
|
|
1121
|
-
}
|
|
1122
|
-
const consumedOperator = (() => {
|
|
1123
|
-
if (twoCharacters === "&&" || twoCharacters === "||" || twoCharacters === "|&" || twoCharacters === ";;") {
|
|
1124
|
-
tokens.push({ type: "operator", value: twoCharacters });
|
|
1125
|
-
i += 2;
|
|
1126
|
-
return true;
|
|
1127
|
-
}
|
|
1128
|
-
if (character === "|" || character === ";" || character === "&" && command[i + 1] !== ">" || character === `
|
|
1129
|
-
` || character === "(" || character === ")" || standaloneBrace) {
|
|
1130
|
-
tokens.push({ type: "operator", value: character });
|
|
1131
|
-
i += 1;
|
|
1132
|
-
if (character === `
|
|
1133
|
-
` && pendingHeredocs.length > 0) {
|
|
1134
|
-
for (const heredoc of pendingHeredocs) {
|
|
1135
|
-
const body = consumeHeredoc(command, i, heredoc);
|
|
1136
|
-
i = body.end;
|
|
1137
|
-
tokens[heredoc.index] = {
|
|
1138
|
-
...tokens[heredoc.index],
|
|
1139
|
-
heredoc: { body: body.content, quoted: heredoc.quoted },
|
|
1140
|
-
substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
|
|
1141
|
-
};
|
|
1142
|
-
}
|
|
1143
|
-
pendingHeredocs.length = 0;
|
|
1144
|
-
}
|
|
1145
|
-
return true;
|
|
844
|
+
if (active?.depth === state.depth && active.phase === "pattern") {
|
|
845
|
+
active.patternStart = false;
|
|
1146
846
|
}
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
if (consumedOperator) {
|
|
1150
|
-
continue;
|
|
847
|
+
state.atWordStart = false;
|
|
848
|
+
state.atCommandStart = false;
|
|
1151
849
|
}
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
850
|
+
state.i += i + 1 < command.length ? 2 : 1;
|
|
851
|
+
return true;
|
|
852
|
+
}
|
|
853
|
+
if (state.arithmeticDepth === undefined && command.slice(i, i + 2) === "<<") {
|
|
854
|
+
if (command[i + 2] === "<") {
|
|
855
|
+
state.i += 3;
|
|
856
|
+
} else {
|
|
857
|
+
const result = readHeredocDelimiter(command, i, nesting + 1);
|
|
858
|
+
state.heredocs.push(result.delimiter);
|
|
859
|
+
state.i = result.end;
|
|
1160
860
|
}
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
861
|
+
state.atWordStart = true;
|
|
862
|
+
return true;
|
|
863
|
+
}
|
|
864
|
+
if (character === `
|
|
865
|
+
` && state.heredocs.length > 0) {
|
|
866
|
+
state.i += 1;
|
|
867
|
+
for (const heredoc of state.heredocs) {
|
|
868
|
+
state.i = consumeHeredoc(command, state.i, heredoc).end;
|
|
869
|
+
}
|
|
870
|
+
state.heredocs.length = 0;
|
|
871
|
+
state.atWordStart = true;
|
|
872
|
+
state.atCommandStart = true;
|
|
873
|
+
state.timeOption = false;
|
|
874
|
+
return true;
|
|
875
|
+
}
|
|
876
|
+
if (active?.depth === state.depth && active.phase === "body" && /^;(?:;|&)/u.test(command.slice(i, i + 2))) {
|
|
877
|
+
state.i += command.slice(i, i + 3) === ";;&" ? 3 : 2;
|
|
878
|
+
active.phase = "pattern";
|
|
879
|
+
active.patternStart = true;
|
|
880
|
+
state.atWordStart = true;
|
|
881
|
+
state.atCommandStart = true;
|
|
882
|
+
return true;
|
|
883
|
+
}
|
|
884
|
+
return false;
|
|
885
|
+
};
|
|
886
|
+
var stepSubstitutionWord = (command, state, nesting) => {
|
|
887
|
+
const { i } = state;
|
|
888
|
+
const character = command[i];
|
|
889
|
+
if (character === "#" && state.atWordStart) {
|
|
890
|
+
const end = command.indexOf(`
|
|
891
|
+
`, i);
|
|
892
|
+
state.i = end === -1 ? command.length : end;
|
|
893
|
+
return true;
|
|
894
|
+
}
|
|
895
|
+
if (!isWordSeparator(character) && character !== "#") {
|
|
896
|
+
trackSubstitutionWord(command, state);
|
|
897
|
+
}
|
|
898
|
+
const result = scanWordFragment(command, i, nesting + 1);
|
|
899
|
+
if (result === undefined) {
|
|
900
|
+
return false;
|
|
901
|
+
}
|
|
902
|
+
state.i = result.end;
|
|
903
|
+
state.atWordStart = false;
|
|
904
|
+
return true;
|
|
905
|
+
};
|
|
906
|
+
var stepSubstitutionParenthesis = (command, state) => {
|
|
907
|
+
const character = command[state.i];
|
|
908
|
+
const active = state.cases.at(-1);
|
|
909
|
+
if (character !== "(" && character !== ")") {
|
|
910
|
+
return false;
|
|
911
|
+
}
|
|
912
|
+
if (active?.depth === state.depth && active.phase === "pattern") {
|
|
913
|
+
if (character === "(") {
|
|
914
|
+
active.patternStart = false;
|
|
915
|
+
} else {
|
|
916
|
+
active.phase = "body";
|
|
917
|
+
state.atCommandStart = true;
|
|
918
|
+
}
|
|
919
|
+
state.i += 1;
|
|
920
|
+
state.atWordStart = true;
|
|
921
|
+
return true;
|
|
922
|
+
}
|
|
923
|
+
if (character === "(") {
|
|
924
|
+
if (state.arithmeticDepth === undefined && state.atCommandStart && command[state.i + 1] === "(") {
|
|
925
|
+
state.arithmeticDepth = state.depth;
|
|
926
|
+
}
|
|
927
|
+
state.depth += 1;
|
|
928
|
+
state.atCommandStart = true;
|
|
929
|
+
} else {
|
|
930
|
+
state.depth -= 1;
|
|
931
|
+
if (state.depth === state.arithmeticDepth) {
|
|
932
|
+
state.arithmeticDepth = undefined;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
state.atWordStart = true;
|
|
936
|
+
return false;
|
|
937
|
+
};
|
|
938
|
+
var consumeCommandSubstitution = (command, start, nesting = 0) => {
|
|
939
|
+
if (nesting > 12) {
|
|
940
|
+
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
941
|
+
}
|
|
942
|
+
const state = {
|
|
943
|
+
i: start + 2,
|
|
944
|
+
depth: 1,
|
|
945
|
+
atWordStart: true,
|
|
946
|
+
atCommandStart: true,
|
|
947
|
+
timeOption: false,
|
|
948
|
+
arithmeticDepth: command[start + 2] === "(" ? 1 : undefined,
|
|
949
|
+
cases: [],
|
|
950
|
+
heredocs: []
|
|
951
|
+
};
|
|
952
|
+
while (state.i < command.length) {
|
|
953
|
+
if (stepSubstitutionSyntax(command, state, nesting) || stepSubstitutionWord(command, state, nesting)) {
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
const character = command[state.i];
|
|
957
|
+
if (stepSubstitutionParenthesis(command, state)) {
|
|
958
|
+
continue;
|
|
959
|
+
}
|
|
960
|
+
if (state.depth === 0) {
|
|
961
|
+
if (state.heredocs.length > 0) {
|
|
962
|
+
throw incompleteHeredoc();
|
|
963
|
+
}
|
|
964
|
+
const content = command[start + 2] === "(" ? command.slice(start + 1, state.i + 1) : command.slice(start + 2, state.i);
|
|
965
|
+
return { content, end: state.i + 1 };
|
|
966
|
+
}
|
|
967
|
+
if ([";", "&", "|", `
|
|
968
|
+
`, ")"].includes(character)) {
|
|
969
|
+
state.atCommandStart = true;
|
|
970
|
+
state.timeOption = false;
|
|
971
|
+
}
|
|
972
|
+
state.atWordStart = isWordSeparator(character);
|
|
973
|
+
state.i += 1;
|
|
974
|
+
}
|
|
975
|
+
if (state.heredocs.length > 0) {
|
|
976
|
+
throw incompleteHeredoc();
|
|
977
|
+
}
|
|
978
|
+
throw inspectionError(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`);
|
|
979
|
+
};
|
|
980
|
+
var heredocSubstitutions = (body) => {
|
|
981
|
+
const substitutions = [];
|
|
982
|
+
for (let i = 0;i < body.length; i += 1) {
|
|
983
|
+
if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
|
|
984
|
+
i += 1;
|
|
985
|
+
} else if (body[i] === "`") {
|
|
986
|
+
throw inspectionError("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
|
|
987
|
+
} else if (body.slice(i, i + 2) === "$(") {
|
|
988
|
+
const result = consumeCommandSubstitution(body, i);
|
|
989
|
+
substitutions.push(result.content);
|
|
990
|
+
i = result.end - 1;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
return substitutions;
|
|
994
|
+
};
|
|
995
|
+
var isBraceCommandPosition = (tokens) => {
|
|
996
|
+
for (let index = tokens.length - 1;index >= 0; index -= 1) {
|
|
997
|
+
const token = tokens[index];
|
|
998
|
+
if (token.type === "operator") {
|
|
999
|
+
break;
|
|
1000
|
+
}
|
|
1001
|
+
const preceding = tokens[index - 1]?.value;
|
|
1002
|
+
if (token.type === "word") {
|
|
1003
|
+
if (index === tokens.length - 1 && token.value === "coproc") {
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
const followsTime = preceding === "time" || preceding === "-p" && tokens[index - 2]?.value === "time";
|
|
1007
|
+
if (token.value === "--" && followsTime) {
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
if (index === tokens.length - 1 && ["function", "coproc"].includes(preceding ?? "") || preceding === "time" && token.value === "-p") {
|
|
1011
|
+
index -= 1;
|
|
1012
|
+
continue;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
if (token.type !== "word" || !commandPrefixes.has(token.value)) {
|
|
1016
|
+
return false;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
return true;
|
|
1020
|
+
};
|
|
1021
|
+
var isArithmeticCommandPosition = (tokens) => isBraceCommandPosition(tokens) || tokens.at(-1)?.type === "word" && tokens.at(-1)?.value === "for" && isBraceCommandPosition(tokens.slice(0, -1));
|
|
1022
|
+
var scanWord = (command, start, nesting) => {
|
|
1023
|
+
let content = "";
|
|
1024
|
+
const bytes = [];
|
|
1025
|
+
const substitutions = [];
|
|
1026
|
+
let quoted = false;
|
|
1027
|
+
let expansion = false;
|
|
1028
|
+
let unsupportedDelimiter;
|
|
1029
|
+
let i = start;
|
|
1030
|
+
while (i < command.length && !isWordSeparator(command[i])) {
|
|
1031
|
+
const character = command[i];
|
|
1032
|
+
if (character === "\\" && command[i + 1] === `
|
|
1174
1033
|
`) {
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1034
|
+
i += 2;
|
|
1035
|
+
continue;
|
|
1036
|
+
}
|
|
1037
|
+
if (character === "\\") {
|
|
1038
|
+
quoted = true;
|
|
1039
|
+
content += command[i + 1] ?? "\\";
|
|
1040
|
+
i += i + 1 < command.length ? 2 : 1;
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1043
|
+
const dollarQuote = /^\$(?:\\\n)*(?<quote>['"])/u.exec(command.slice(i))?.[1];
|
|
1044
|
+
if (dollarQuote !== undefined) {
|
|
1045
|
+
unsupportedDelimiter = dollarQuote === "'" ? "ANSI-C quoted" : "locale-quoted";
|
|
1046
|
+
}
|
|
1047
|
+
const result = scanWordFragment(command, i, nesting);
|
|
1048
|
+
if (result !== undefined) {
|
|
1049
|
+
quoted ||= result.quoted === true;
|
|
1050
|
+
if (result.bytes === undefined) {
|
|
1051
|
+
content += result.content;
|
|
1052
|
+
} else {
|
|
1053
|
+
bytes.push(...Buffer.from(content), ...result.bytes);
|
|
1054
|
+
content = "";
|
|
1055
|
+
}
|
|
1056
|
+
substitutions.push(...result.substitutions ?? []);
|
|
1057
|
+
expansion ||= result.expansion === true;
|
|
1058
|
+
i = result.end;
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
if (/^[<>]/u.test(character)) {
|
|
1062
|
+
break;
|
|
1063
|
+
}
|
|
1064
|
+
expansion ||= isExpansion(command, i);
|
|
1065
|
+
content += character;
|
|
1066
|
+
i += 1;
|
|
1067
|
+
}
|
|
1068
|
+
return {
|
|
1069
|
+
content: bytes.length > 0 ? Buffer.from([...bytes, ...Buffer.from(content)]).toString("utf-8") : content,
|
|
1070
|
+
end: i,
|
|
1071
|
+
quoted,
|
|
1072
|
+
expansion,
|
|
1073
|
+
substitutions,
|
|
1074
|
+
unsupportedDelimiter
|
|
1075
|
+
};
|
|
1076
|
+
};
|
|
1077
|
+
var scanWordFragment = (command, i, nesting) => {
|
|
1078
|
+
const pair = command.slice(i, i + 2);
|
|
1079
|
+
if (pair === "$'") {
|
|
1080
|
+
return { ...scanAnsiQuote(command, i), quoted: true };
|
|
1081
|
+
}
|
|
1082
|
+
if (command[i] === "'") {
|
|
1083
|
+
return { ...scanSingleQuote(command, i), quoted: true };
|
|
1084
|
+
}
|
|
1085
|
+
if (command[i] === '"') {
|
|
1086
|
+
return { ...scanDoubleQuote(command, i, nesting), quoted: true };
|
|
1087
|
+
}
|
|
1088
|
+
if (pair === "$(" || command[i] === "`") {
|
|
1089
|
+
const result = pair === "$(" ? consumeCommandSubstitution(command, i, nesting) : consumeBackticks(command, i);
|
|
1090
|
+
return {
|
|
1091
|
+
content: command.slice(i, result.end),
|
|
1092
|
+
end: result.end,
|
|
1093
|
+
expansion: true,
|
|
1094
|
+
substitutions: [result.content]
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
return;
|
|
1098
|
+
};
|
|
1099
|
+
var skipTrivia = (command, start) => {
|
|
1100
|
+
let i = start;
|
|
1101
|
+
while (i < command.length) {
|
|
1102
|
+
if (/[ \t\r]/u.test(command[i])) {
|
|
1103
|
+
i += 1;
|
|
1104
|
+
} else if (command[i] === "\\" && command[i + 1] === `
|
|
1193
1105
|
`) {
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
(() => {
|
|
1259
|
-
const quoteStart = i;
|
|
1260
|
-
quoted = true;
|
|
1261
|
-
i += 1;
|
|
1262
|
-
while (i < command.length && command[i] !== '"') {
|
|
1263
|
-
const quotedCharacter = command[i];
|
|
1264
|
-
if (quotedCharacter === undefined) {
|
|
1265
|
-
break;
|
|
1266
|
-
}
|
|
1267
|
-
if (quotedCharacter === "\\" && i + 1 < command.length) {
|
|
1268
|
-
const escaped = command[i + 1];
|
|
1269
|
-
if (escaped === `
|
|
1270
|
-
`) {} else if (escaped === '"' || escaped === "\\" || escaped === "$" || escaped === "`") {
|
|
1271
|
-
value += escaped;
|
|
1272
|
-
} else {
|
|
1273
|
-
value += `\\${escaped}`;
|
|
1274
|
-
}
|
|
1275
|
-
i += 2;
|
|
1276
|
-
} else if (quotedCharacter === "$" && command[i + 1] === "(") {
|
|
1277
|
-
const substitution = consumeCommandSubstitution(command, i, nesting);
|
|
1278
|
-
value += command.slice(i, substitution.end);
|
|
1279
|
-
substitutions.push(substitution.content);
|
|
1280
|
-
expansion = true;
|
|
1281
|
-
i = substitution.end;
|
|
1282
|
-
} else if (quotedCharacter === "$" && command[i + 1] === "{") {
|
|
1283
|
-
const end = consumeQuotedParameter(command, i);
|
|
1284
|
-
value += command.slice(i, end);
|
|
1285
|
-
expansion = true;
|
|
1286
|
-
i = end;
|
|
1287
|
-
} else if (quotedCharacter === "`") {
|
|
1288
|
-
const substitution = consumeBackticks(command, i, true);
|
|
1289
|
-
value += command.slice(i, substitution.end);
|
|
1290
|
-
substitutions.push(substitution.content);
|
|
1291
|
-
expansion = true;
|
|
1292
|
-
i = substitution.end;
|
|
1293
|
-
} else {
|
|
1294
|
-
if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/u.test(command[i + 1] ?? "")) {
|
|
1295
|
-
expansion = true;
|
|
1296
|
-
}
|
|
1297
|
-
value += quotedCharacter;
|
|
1298
|
-
i += 1;
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
if (command[i] !== '"') {
|
|
1302
|
-
throw inspectionError(`Unterminated double quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
|
|
1303
|
-
}
|
|
1304
|
-
i += 1;
|
|
1305
|
-
})();
|
|
1306
|
-
continue;
|
|
1307
|
-
}
|
|
1308
|
-
if (current === "$" && command[i + 1] === "(") {
|
|
1309
|
-
const substitution = consumeCommandSubstitution(command, i, nesting);
|
|
1310
|
-
value += command.slice(i, substitution.end);
|
|
1311
|
-
substitutions.push(substitution.content);
|
|
1312
|
-
expansion = true;
|
|
1313
|
-
i = substitution.end;
|
|
1314
|
-
continue;
|
|
1315
|
-
}
|
|
1316
|
-
if (current === "`") {
|
|
1317
|
-
const substitution = consumeBackticks(command, i);
|
|
1318
|
-
value += command.slice(i, substitution.end);
|
|
1319
|
-
substitutions.push(substitution.content);
|
|
1320
|
-
expansion = true;
|
|
1321
|
-
i = substitution.end;
|
|
1322
|
-
continue;
|
|
1323
|
-
}
|
|
1324
|
-
if (current === "$" && /[a-zA-Z0-9_{[*#?@!$-]/u.test(command[i + 1] ?? "")) {
|
|
1325
|
-
expansion = true;
|
|
1106
|
+
i += 2;
|
|
1107
|
+
} else if (command[i] === "#") {
|
|
1108
|
+
const end = command.indexOf(`
|
|
1109
|
+
`, i);
|
|
1110
|
+
i = end === -1 ? command.length : end;
|
|
1111
|
+
} else {
|
|
1112
|
+
break;
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return i;
|
|
1116
|
+
};
|
|
1117
|
+
var readHeredocDelimiter = (command, start, nesting) => {
|
|
1118
|
+
const stripTabs = command[start + 2] === "-";
|
|
1119
|
+
const i = skipTrivia(command, start + (stripTabs ? 3 : 2));
|
|
1120
|
+
if (i >= command.length || isWordSeparator(command[i]) || /[<>]/u.test(command[i])) {
|
|
1121
|
+
throw incompleteHeredoc();
|
|
1122
|
+
}
|
|
1123
|
+
const word = scanWord(command, i, nesting);
|
|
1124
|
+
if (word.unsupportedDelimiter !== undefined) {
|
|
1125
|
+
throw inspectionError(`Cannot validate this ${word.unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`);
|
|
1126
|
+
}
|
|
1127
|
+
return {
|
|
1128
|
+
delimiter: {
|
|
1129
|
+
delimiter: word.content,
|
|
1130
|
+
quoted: word.quoted === true,
|
|
1131
|
+
stripTabs
|
|
1132
|
+
},
|
|
1133
|
+
end: word.end
|
|
1134
|
+
};
|
|
1135
|
+
};
|
|
1136
|
+
var readOperator = (command, i, tokens) => {
|
|
1137
|
+
const pair = command.slice(i, i + 2);
|
|
1138
|
+
if (twoCharacterOperators.has(pair)) {
|
|
1139
|
+
return pair;
|
|
1140
|
+
}
|
|
1141
|
+
const character = command[i];
|
|
1142
|
+
if (`|;
|
|
1143
|
+
()`.includes(character) || character === "&" && command[i + 1] !== ">") {
|
|
1144
|
+
return character;
|
|
1145
|
+
}
|
|
1146
|
+
if ((character === "{" || character === "}") && isBraceCommandPosition(tokens)) {
|
|
1147
|
+
let end = i + 1;
|
|
1148
|
+
while (command[end] === "\\" && command[end + 1] === `
|
|
1149
|
+
`) {
|
|
1150
|
+
end += 2;
|
|
1151
|
+
}
|
|
1152
|
+
if (command[end] === undefined || isWordSeparator(command[end]) || /[<>]/u.test(command[end])) {
|
|
1153
|
+
return character;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
return;
|
|
1157
|
+
};
|
|
1158
|
+
var tokenizeShell = (command) => {
|
|
1159
|
+
const tokens = [];
|
|
1160
|
+
const heredocs = [];
|
|
1161
|
+
let depth = 0;
|
|
1162
|
+
let arithmeticDepth;
|
|
1163
|
+
let i = 0;
|
|
1164
|
+
while ((i = skipTrivia(command, i)) < command.length) {
|
|
1165
|
+
const operator = readOperator(command, i, tokens);
|
|
1166
|
+
if (operator !== undefined) {
|
|
1167
|
+
if (operator === "(") {
|
|
1168
|
+
if (arithmeticDepth === undefined && command[i + 1] === "(" && isArithmeticCommandPosition(tokens)) {
|
|
1169
|
+
arithmeticDepth = depth;
|
|
1326
1170
|
}
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1171
|
+
depth += 1;
|
|
1172
|
+
} else if (operator === ")") {
|
|
1173
|
+
depth -= 1;
|
|
1174
|
+
if (depth === arithmeticDepth) {
|
|
1175
|
+
arithmeticDepth = undefined;
|
|
1330
1176
|
}
|
|
1331
|
-
value += current;
|
|
1332
|
-
i += 1;
|
|
1333
1177
|
}
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
quoted,
|
|
1346
|
-
stripTabs: tokens[pendingDelimiter]?.value.endsWith("-")
|
|
1178
|
+
tokens.push({ type: "operator", value: operator });
|
|
1179
|
+
i += operator.length;
|
|
1180
|
+
if (operator === `
|
|
1181
|
+
`) {
|
|
1182
|
+
for (const heredoc of heredocs) {
|
|
1183
|
+
const body = consumeHeredoc(command, i, heredoc);
|
|
1184
|
+
i = body.end;
|
|
1185
|
+
tokens[heredoc.index] = {
|
|
1186
|
+
...tokens[heredoc.index],
|
|
1187
|
+
heredoc: { body: body.content, quoted: heredoc.quoted },
|
|
1188
|
+
substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
|
|
1347
1189
|
};
|
|
1348
|
-
if (delimiterOnly) {
|
|
1349
|
-
return { tokens, end: i, delimiter };
|
|
1350
|
-
}
|
|
1351
|
-
pendingHeredocs.push({ index: pendingDelimiter, ...delimiter });
|
|
1352
|
-
pendingDelimiter = undefined;
|
|
1353
1190
|
}
|
|
1354
|
-
|
|
1355
|
-
}
|
|
1356
|
-
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
|
|
1191
|
+
heredocs.length = 0;
|
|
1192
|
+
}
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
const redirect = /^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/u.exec(command.slice(i))?.[0];
|
|
1196
|
+
if (redirect !== undefined) {
|
|
1197
|
+
tokens.push({ type: "redirect", value: redirect });
|
|
1198
|
+
if (arithmeticDepth === undefined && /^\d*<<-?$/u.test(redirect)) {
|
|
1199
|
+
const result = readHeredocDelimiter(command, i + redirect.search(/</u), 0);
|
|
1200
|
+
heredocs.push({ ...result.delimiter, index: tokens.length - 1 });
|
|
1201
|
+
tokens.push({ type: "word", value: result.delimiter.delimiter });
|
|
1202
|
+
i = result.end;
|
|
1203
|
+
} else {
|
|
1204
|
+
i += redirect.length;
|
|
1205
|
+
}
|
|
1206
|
+
continue;
|
|
1360
1207
|
}
|
|
1208
|
+
const word = scanWord(command, i, 0);
|
|
1209
|
+
tokens.push({
|
|
1210
|
+
type: "word",
|
|
1211
|
+
value: word.content,
|
|
1212
|
+
substitutions: word.substitutions,
|
|
1213
|
+
expansion: word.expansion
|
|
1214
|
+
});
|
|
1215
|
+
i = word.end;
|
|
1216
|
+
}
|
|
1217
|
+
if (heredocs.length > 0) {
|
|
1218
|
+
throw incompleteHeredoc();
|
|
1361
1219
|
}
|
|
1362
|
-
return
|
|
1220
|
+
return tokens;
|
|
1363
1221
|
};
|
|
1364
|
-
var splitSimpleCommands =
|
|
1222
|
+
var splitSimpleCommands = (tokens) => {
|
|
1365
1223
|
const commands = [];
|
|
1366
1224
|
let current = [];
|
|
1367
1225
|
let precedingPipeline = false;
|
|
@@ -1389,307 +1247,231 @@ var splitSimpleCommands = function splitSimpleCommands(tokens) {
|
|
|
1389
1247
|
}
|
|
1390
1248
|
return commands;
|
|
1391
1249
|
};
|
|
1392
|
-
var extractCommandWords =
|
|
1250
|
+
var extractCommandWords = (tokens) => {
|
|
1393
1251
|
const words = [];
|
|
1394
|
-
let i = 0;
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
if (
|
|
1398
|
-
|
|
1399
|
-
}
|
|
1400
|
-
if (token.type === "redirect") {
|
|
1401
|
-
i += tokens[i + 1]?.type === "word" ? 2 : 1;
|
|
1402
|
-
continue;
|
|
1252
|
+
for (let i = 0;i < tokens.length; i += 1) {
|
|
1253
|
+
if (tokens[i].type === "redirect") {
|
|
1254
|
+
i += tokens[i + 1]?.type === "word" ? 1 : 0;
|
|
1255
|
+
} else if (tokens[i].type === "word") {
|
|
1256
|
+
words.push(tokens[i]);
|
|
1403
1257
|
}
|
|
1404
|
-
if (token.type === "word") {
|
|
1405
|
-
words.push(token);
|
|
1406
|
-
}
|
|
1407
|
-
i += 1;
|
|
1408
1258
|
}
|
|
1409
1259
|
return words;
|
|
1410
1260
|
};
|
|
1411
|
-
var isAssignment =
|
|
1412
|
-
|
|
1413
|
-
};
|
|
1414
|
-
var skipAssignments = function skipAssignments(words, start) {
|
|
1261
|
+
var isAssignment = (word) => /^[a-zA-Z_][a-zA-Z0-9_]*=/u.test(word);
|
|
1262
|
+
var skipWrapperOptions = (words, start, valued) => {
|
|
1415
1263
|
let index = start;
|
|
1416
|
-
while (
|
|
1417
|
-
|
|
1264
|
+
while (index < words.length) {
|
|
1265
|
+
const argument = words[index];
|
|
1266
|
+
if (argument === "--") {
|
|
1267
|
+
return index + 1;
|
|
1268
|
+
}
|
|
1269
|
+
if (!argument.startsWith("-") && !isAssignment(argument)) {
|
|
1270
|
+
break;
|
|
1271
|
+
}
|
|
1272
|
+
index += valued.has(argument) ? 2 : 1;
|
|
1418
1273
|
}
|
|
1419
1274
|
return index;
|
|
1420
1275
|
};
|
|
1421
|
-
var findCommandStart =
|
|
1422
|
-
let index =
|
|
1276
|
+
var findCommandStart = (words) => {
|
|
1277
|
+
let index = 0;
|
|
1423
1278
|
while (index < words.length) {
|
|
1424
1279
|
const word = words[index];
|
|
1425
|
-
if (word
|
|
1426
|
-
index = skipAssignments(words, index + 1);
|
|
1427
|
-
continue;
|
|
1428
|
-
}
|
|
1429
|
-
if (word === "env") {
|
|
1280
|
+
if (isAssignment(word) || commandPrefixes.has(word)) {
|
|
1430
1281
|
index += 1;
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
if (argument === "--") {
|
|
1438
|
-
index += 1;
|
|
1439
|
-
break;
|
|
1440
|
-
}
|
|
1441
|
-
if (argument === "-u" || argument === "--unset") {
|
|
1442
|
-
index += 2;
|
|
1443
|
-
} else if (argument === "-C" || argument === "--chdir") {
|
|
1444
|
-
index += 2;
|
|
1445
|
-
} else if (argument.startsWith("--chdir=") || /^-C.+/u.test(argument)) {
|
|
1446
|
-
index += 1;
|
|
1447
|
-
} else if (argument.startsWith("--unset=") || /^-u.+/u.test(argument)) {
|
|
1448
|
-
index += 1;
|
|
1449
|
-
} else if (argument.startsWith("-")) {
|
|
1450
|
-
index += 1;
|
|
1451
|
-
} else if (isAssignment(argument)) {
|
|
1452
|
-
index += 1;
|
|
1453
|
-
} else {
|
|
1454
|
-
break;
|
|
1455
|
-
}
|
|
1456
|
-
}
|
|
1457
|
-
})();
|
|
1458
|
-
index = skipAssignments(words, index);
|
|
1459
|
-
continue;
|
|
1282
|
+
} else {
|
|
1283
|
+
const valued = wrapperArgsWithValue.get(word);
|
|
1284
|
+
if (valued === undefined) {
|
|
1285
|
+
break;
|
|
1286
|
+
}
|
|
1287
|
+
index = skipWrapperOptions(words, index + 1, valued);
|
|
1460
1288
|
}
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1289
|
+
}
|
|
1290
|
+
return index;
|
|
1291
|
+
};
|
|
1292
|
+
var consumeGitGlobalOptions = (words, start) => {
|
|
1293
|
+
let index = start;
|
|
1294
|
+
let targetError;
|
|
1295
|
+
while (index < words.length) {
|
|
1296
|
+
const token = words[index];
|
|
1297
|
+
const argument = token.value;
|
|
1298
|
+
if (token.expansion === true) {
|
|
1299
|
+
throw inspectionError("Cannot inspect dynamic Git options or subcommands. Use literal command words.");
|
|
1300
|
+
}
|
|
1301
|
+
if (argument === "--") {
|
|
1302
|
+
if (words[index + 1]?.expansion === true) {
|
|
1303
|
+
throw inspectionError("Cannot inspect a dynamic Git subcommand. Use literal command words.");
|
|
1476
1304
|
}
|
|
1477
|
-
index
|
|
1478
|
-
continue;
|
|
1305
|
+
return { index: index + 1, targetError };
|
|
1479
1306
|
}
|
|
1480
|
-
if (
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1307
|
+
if (!argument.startsWith("-")) {
|
|
1308
|
+
break;
|
|
1309
|
+
}
|
|
1310
|
+
const option = /^-[Cc]/u.test(argument) ? argument.slice(0, 2) : argument.split("=")[0];
|
|
1311
|
+
if (targetGlobalOptions.has(option)) {
|
|
1312
|
+
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
1313
|
+
}
|
|
1314
|
+
index += gitGlobalOptionsWithArg.has(argument) ? 2 : 1;
|
|
1315
|
+
}
|
|
1316
|
+
return { index, targetError };
|
|
1317
|
+
};
|
|
1318
|
+
var consumeShortCommitFlags = (words, start, result) => {
|
|
1319
|
+
let index = start;
|
|
1320
|
+
const argument = words[start].value;
|
|
1321
|
+
for (let i = 1;i < argument.length; i += 1) {
|
|
1322
|
+
const option = argument[i];
|
|
1323
|
+
if (option === "s") {
|
|
1324
|
+
result.hasSignoffFlag = true;
|
|
1325
|
+
} else if (option === "h") {
|
|
1326
|
+
result.isHelp = true;
|
|
1327
|
+
} else if (option === "e") {
|
|
1328
|
+
result.hasNoEdit = false;
|
|
1329
|
+
} else if (option === "m" || option === "F") {
|
|
1330
|
+
const attached = argument.slice(i + 1);
|
|
1331
|
+
const input = attached.length > 0 ? attached : words[index += 1]?.value;
|
|
1332
|
+
if (option === "m") {
|
|
1333
|
+
result.messageExpansion ||= words[index]?.expansion === true;
|
|
1334
|
+
}
|
|
1335
|
+
if (input !== undefined) {
|
|
1336
|
+
(option === "m" ? result.messages : result.filePaths).push(input);
|
|
1484
1337
|
}
|
|
1485
|
-
|
|
1486
|
-
|
|
1338
|
+
break;
|
|
1339
|
+
} else if (option === "S" || option === "u") {
|
|
1340
|
+
break;
|
|
1341
|
+
} else if (option === "c" || option === "C" || option === "t") {
|
|
1342
|
+
index += argument.slice(i + 1).length === 0 ? 1 : 0;
|
|
1343
|
+
break;
|
|
1487
1344
|
}
|
|
1488
|
-
break;
|
|
1489
1345
|
}
|
|
1490
1346
|
return index;
|
|
1491
1347
|
};
|
|
1492
|
-
var
|
|
1493
|
-
|
|
1494
|
-
|
|
1348
|
+
var parseCommitArguments = (words, start) => {
|
|
1349
|
+
const result = {
|
|
1350
|
+
messages: [],
|
|
1351
|
+
filePaths: [],
|
|
1352
|
+
hasSignoffFlag: false,
|
|
1353
|
+
isAmend: false,
|
|
1354
|
+
hasNoEdit: false,
|
|
1355
|
+
isFixup: false,
|
|
1356
|
+
isHelp: false,
|
|
1357
|
+
messageExpansion: false,
|
|
1358
|
+
hasTrailer: false
|
|
1359
|
+
};
|
|
1360
|
+
for (let index = start;index < words.length; index += 1) {
|
|
1361
|
+
const argument = words[index].value;
|
|
1362
|
+
if (argument === "--") {
|
|
1363
|
+
break;
|
|
1364
|
+
}
|
|
1365
|
+
const boolean = booleanCommitFlags.get(argument);
|
|
1366
|
+
if (boolean !== undefined) {
|
|
1367
|
+
Object.assign(result, { [boolean[0]]: boolean[1] });
|
|
1368
|
+
continue;
|
|
1369
|
+
}
|
|
1370
|
+
const [option] = argument.split("=");
|
|
1371
|
+
const isMessage = option === "--message" || argument === "-m";
|
|
1372
|
+
const isFile = option === "--file" || argument === "-F";
|
|
1373
|
+
if (isMessage || isFile) {
|
|
1374
|
+
const equals = argument.indexOf("=");
|
|
1375
|
+
const input = equals === -1 ? words[index += 1]?.value : argument.slice(equals + 1);
|
|
1376
|
+
if (isMessage) {
|
|
1377
|
+
result.messageExpansion ||= words[index]?.expansion === true;
|
|
1378
|
+
}
|
|
1379
|
+
if (input !== undefined) {
|
|
1380
|
+
(isMessage ? result.messages : result.filePaths).push(input);
|
|
1381
|
+
}
|
|
1382
|
+
} else if (commitLongOptionsWithArg.has(option)) {
|
|
1383
|
+
result.isFixup ||= option === "--fixup";
|
|
1384
|
+
result.hasTrailer ||= option === "--trailer";
|
|
1385
|
+
index += argument.includes("=") ? 0 : 1;
|
|
1386
|
+
} else if (/^-[^-]/u.test(argument)) {
|
|
1387
|
+
index = consumeShortCommitFlags(words, index, result);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
return result;
|
|
1391
|
+
};
|
|
1392
|
+
var extractInvocation = (words, start) => {
|
|
1393
|
+
const executable = words[start]?.value;
|
|
1495
1394
|
if (executable === undefined || executable !== "git" && !executable.endsWith("/git")) {
|
|
1496
1395
|
return;
|
|
1497
1396
|
}
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
let targetError = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word) || word === "export") ? "Environment or wrapper changes can redirect a Git commit target. Use a direct git commit in the captured workdir." : undefined;
|
|
1501
|
-
const readSubcommand = () => {
|
|
1502
|
-
while (wordIndex < words.length) {
|
|
1503
|
-
const argument = words[wordIndex];
|
|
1504
|
-
if (argument === undefined) {
|
|
1505
|
-
break;
|
|
1506
|
-
}
|
|
1507
|
-
if (wordTokens[wordIndex]?.expansion === true) {
|
|
1508
|
-
throw inspectionError("Cannot inspect dynamic Git options or subcommands. Use literal command words.");
|
|
1509
|
-
}
|
|
1510
|
-
if (argument === "--") {
|
|
1511
|
-
if (wordTokens[wordIndex + 1]?.expansion === true) {
|
|
1512
|
-
throw inspectionError("Cannot inspect a dynamic Git subcommand. Use literal command words.");
|
|
1513
|
-
}
|
|
1514
|
-
subcommand = words[wordIndex + 1];
|
|
1515
|
-
wordIndex += 2;
|
|
1516
|
-
break;
|
|
1517
|
-
}
|
|
1518
|
-
if (gitGlobalOptionsWithArg.has(argument)) {
|
|
1519
|
-
if (["-C", "--git-dir", "--work-tree", "-c", "--config-env"].includes(argument)) {
|
|
1520
|
-
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
1521
|
-
}
|
|
1522
|
-
wordIndex += 2;
|
|
1523
|
-
continue;
|
|
1524
|
-
}
|
|
1525
|
-
const consumedAttachedGlobal = (() => {
|
|
1526
|
-
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--namespace=") || argument.startsWith("--exec-path=") || argument.startsWith("--super-prefix=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
|
|
1527
|
-
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
|
|
1528
|
-
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
1529
|
-
}
|
|
1530
|
-
wordIndex += 1;
|
|
1531
|
-
return true;
|
|
1532
|
-
}
|
|
1533
|
-
return false;
|
|
1534
|
-
})();
|
|
1535
|
-
if (consumedAttachedGlobal) {
|
|
1536
|
-
continue;
|
|
1537
|
-
}
|
|
1538
|
-
if (argument.startsWith("-C")) {
|
|
1539
|
-
targetError = "git -C can change the commit target. Run git commit directly in the captured workdir.";
|
|
1540
|
-
wordIndex += 1;
|
|
1541
|
-
continue;
|
|
1542
|
-
}
|
|
1543
|
-
if (argument.startsWith("-")) {
|
|
1544
|
-
wordIndex += 1;
|
|
1545
|
-
continue;
|
|
1546
|
-
}
|
|
1547
|
-
subcommand = argument;
|
|
1548
|
-
wordIndex += 1;
|
|
1549
|
-
break;
|
|
1550
|
-
}
|
|
1551
|
-
};
|
|
1552
|
-
readSubcommand();
|
|
1553
|
-
if (subcommand !== "commit") {
|
|
1397
|
+
const global = consumeGitGlobalOptions(words, start + 1);
|
|
1398
|
+
if (words[global.index]?.value !== "commit") {
|
|
1554
1399
|
return;
|
|
1555
1400
|
}
|
|
1556
|
-
const
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
let hasNoEdit = false;
|
|
1561
|
-
let isFixup = false;
|
|
1562
|
-
let isHelp = false;
|
|
1563
|
-
let messageExpansion = false;
|
|
1564
|
-
let hasTrailer = false;
|
|
1565
|
-
const collectMessage = (word) => {
|
|
1566
|
-
if (word === undefined) {
|
|
1567
|
-
return;
|
|
1568
|
-
}
|
|
1569
|
-
messages.push(word);
|
|
1570
|
-
};
|
|
1571
|
-
const collectFile = (word) => {
|
|
1572
|
-
if (word === undefined) {
|
|
1573
|
-
return;
|
|
1574
|
-
}
|
|
1575
|
-
filePaths.push(word);
|
|
1401
|
+
const wrapperChange = words.slice(0, start).some((word) => word.value === "env" || isAssignment(word.value));
|
|
1402
|
+
return {
|
|
1403
|
+
...parseCommitArguments(words, global.index + 1),
|
|
1404
|
+
targetError: global.targetError ?? (wrapperChange ? "Environment or wrapper changes can redirect a Git commit target. Use a direct git commit in the captured workdir." : undefined)
|
|
1576
1405
|
};
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1406
|
+
};
|
|
1407
|
+
var consumeShellOptions = (words, start) => {
|
|
1408
|
+
let index = start + 1;
|
|
1409
|
+
let executeString = false;
|
|
1410
|
+
while (index < words.length) {
|
|
1411
|
+
const option = words[index].value;
|
|
1412
|
+
if (option === "--") {
|
|
1413
|
+
index += 1;
|
|
1580
1414
|
break;
|
|
1581
1415
|
}
|
|
1582
|
-
|
|
1583
|
-
const longOptionName = equalsIndex > 0 ? argument.slice(0, equalsIndex) : argument;
|
|
1584
|
-
if (argument === "--") {
|
|
1416
|
+
if (!/^[+-]/u.test(option)) {
|
|
1585
1417
|
break;
|
|
1586
1418
|
}
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
isAmend = true;
|
|
1592
|
-
} else if (argument === "--no-edit") {
|
|
1593
|
-
hasNoEdit = true;
|
|
1594
|
-
} else if (argument === "--edit") {
|
|
1595
|
-
hasNoEdit = false;
|
|
1596
|
-
} else if (argument === "-s" || argument === "--signoff") {
|
|
1597
|
-
hasSignoffFlag = true;
|
|
1598
|
-
} else if (argument === "--no-signoff") {
|
|
1599
|
-
hasSignoffFlag = false;
|
|
1600
|
-
} else {
|
|
1601
|
-
return false;
|
|
1602
|
-
}
|
|
1603
|
-
return true;
|
|
1604
|
-
})();
|
|
1605
|
-
if (consumedBooleanFlag) {
|
|
1606
|
-
continue;
|
|
1419
|
+
executeString ||= /^-[a-zA-Z]*c[a-zA-Z]*$/u.test(option);
|
|
1420
|
+
const shortOptions = /^[+-][a-zA-Z]+$/u.test(option);
|
|
1421
|
+
if (shortOptions && /[oO]/u.test(option) && !/[oO]$/u.test(option)) {
|
|
1422
|
+
throw inspectionError("Cannot parse shell options reliably. Simplify the unsupported syntax.");
|
|
1607
1423
|
}
|
|
1608
|
-
const
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1424
|
+
const next = words[index + 1]?.value;
|
|
1425
|
+
const optionName = next !== undefined && !/^[+-]/u.test(next);
|
|
1426
|
+
index += shortOptions && /[oO]$/u.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
|
|
1427
|
+
}
|
|
1428
|
+
return { index, executeString };
|
|
1429
|
+
};
|
|
1430
|
+
var extractShellCBody = (words, start) => {
|
|
1431
|
+
if (!/^(?:.*\/)?(?:bash|sh|zsh)$/u.test(words[start]?.value ?? "")) {
|
|
1432
|
+
return;
|
|
1433
|
+
}
|
|
1434
|
+
const { index, executeString } = consumeShellOptions(words, start);
|
|
1435
|
+
if (!executeString) {
|
|
1436
|
+
return;
|
|
1437
|
+
}
|
|
1438
|
+
const body = words[index];
|
|
1439
|
+
if (body === undefined || body.expansion === true) {
|
|
1440
|
+
throw inspectionError("Cannot parse an expanded or missing shell -c body reliably. Use a literal shell body; if committing, run git commit directly.");
|
|
1441
|
+
}
|
|
1442
|
+
if (/^(?:.*\/)?sh$/u.test(words[start].value) && body.value.includes("$'")) {
|
|
1443
|
+
throw inspectionError("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body.");
|
|
1444
|
+
}
|
|
1445
|
+
return body.value;
|
|
1446
|
+
};
|
|
1447
|
+
var attachStdinHeredoc = (invocation, tokens, pipeline) => {
|
|
1448
|
+
if (!invocation.filePaths.includes("-")) {
|
|
1449
|
+
return invocation;
|
|
1450
|
+
}
|
|
1451
|
+
const heredocs = tokens.filter((token) => token.type === "redirect" && /^\d*<<$/u.test(token.value));
|
|
1452
|
+
const stdinRedirects = tokens.filter((token) => {
|
|
1453
|
+
if (token.type !== "redirect") {
|
|
1454
|
+
return false;
|
|
1628
1455
|
}
|
|
1629
|
-
(()
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
} else if (commitLongOptionsWithArg.has(longOptionName)) {
|
|
1641
|
-
if (equalsIndex === -1) {
|
|
1642
|
-
index += 1;
|
|
1643
|
-
}
|
|
1644
|
-
} else if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 1) {
|
|
1645
|
-
(() => {
|
|
1646
|
-
for (let characterIndex = 1;characterIndex < argument.length; characterIndex += 1) {
|
|
1647
|
-
const option = argument[characterIndex];
|
|
1648
|
-
if (option === "s") {
|
|
1649
|
-
hasSignoffFlag = true;
|
|
1650
|
-
} else if (option === "h") {
|
|
1651
|
-
isHelp = true;
|
|
1652
|
-
} else if (option === "e") {
|
|
1653
|
-
hasNoEdit = false;
|
|
1654
|
-
} else if (option === "m" || option === "F") {
|
|
1655
|
-
const attached = argument.slice(characterIndex + 1);
|
|
1656
|
-
const input = attached.length > 0 ? attached : words[index += 1];
|
|
1657
|
-
if (option === "m") {
|
|
1658
|
-
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
1659
|
-
collectMessage(input);
|
|
1660
|
-
} else {
|
|
1661
|
-
collectFile(input);
|
|
1662
|
-
}
|
|
1663
|
-
break;
|
|
1664
|
-
} else if (option === "S") {
|
|
1665
|
-
break;
|
|
1666
|
-
} else if (option === "u") {
|
|
1667
|
-
break;
|
|
1668
|
-
} else if (option === "c" || option === "C" || option === "t") {
|
|
1669
|
-
if (argument.slice(characterIndex + 1).length === 0) {
|
|
1670
|
-
index += 1;
|
|
1671
|
-
}
|
|
1672
|
-
break;
|
|
1673
|
-
}
|
|
1674
|
-
}
|
|
1675
|
-
})();
|
|
1676
|
-
}
|
|
1677
|
-
})();
|
|
1456
|
+
const match = /^(?<descriptor>\d*)(?<direction>[<>])/u.exec(token.value);
|
|
1457
|
+
return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0);
|
|
1458
|
+
});
|
|
1459
|
+
const [heredoc] = heredocs;
|
|
1460
|
+
let stdinError;
|
|
1461
|
+
if (pipeline) {
|
|
1462
|
+
stdinError = "Pipelines cannot supply a validated commit message.";
|
|
1463
|
+
} else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
|
|
1464
|
+
stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects.";
|
|
1465
|
+
} else if (heredoc.heredoc?.quoted !== true) {
|
|
1466
|
+
stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
|
|
1678
1467
|
}
|
|
1679
1468
|
return {
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
isAmend,
|
|
1684
|
-
hasNoEdit,
|
|
1685
|
-
isFixup,
|
|
1686
|
-
isHelp,
|
|
1687
|
-
targetError,
|
|
1688
|
-
messageExpansion,
|
|
1689
|
-
hasTrailer
|
|
1469
|
+
...invocation,
|
|
1470
|
+
stdinError,
|
|
1471
|
+
stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined
|
|
1690
1472
|
};
|
|
1691
1473
|
};
|
|
1692
|
-
var extractGitCommits =
|
|
1474
|
+
var extractGitCommits = (command, inheritedDirectoryChange = false, depth = 0) => {
|
|
1693
1475
|
if (depth > 12 || command.length > 262144) {
|
|
1694
1476
|
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
1695
1477
|
}
|
|
@@ -1697,55 +1479,19 @@ var extractGitCommits = function extractGitCommits(command, inheritedDirectoryCh
|
|
|
1697
1479
|
const invocations = [];
|
|
1698
1480
|
let changedDirectory = inheritedDirectoryChange;
|
|
1699
1481
|
for (const simple of splitSimpleCommands(tokens)) {
|
|
1700
|
-
const
|
|
1701
|
-
const
|
|
1702
|
-
const
|
|
1703
|
-
|
|
1704
|
-
if (wordTokens[commandStart]?.expansion === true) {
|
|
1482
|
+
const words = extractCommandWords(simple.tokens);
|
|
1483
|
+
const values = words.map((token) => token.value);
|
|
1484
|
+
const start = findCommandStart(values);
|
|
1485
|
+
if (words[start]?.expansion === true) {
|
|
1705
1486
|
throw inspectionError("Cannot inspect a dynamic command name. Use literal command words.");
|
|
1706
1487
|
}
|
|
1707
|
-
const invocation = extractInvocation(words,
|
|
1708
|
-
const
|
|
1709
|
-
(
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
while (bodyIndex < words.length) {
|
|
1715
|
-
const option = words[bodyIndex];
|
|
1716
|
-
if (option === "--") {
|
|
1717
|
-
bodyIndex += 1;
|
|
1718
|
-
break;
|
|
1719
|
-
}
|
|
1720
|
-
if (!option.startsWith("-") && !option.startsWith("+")) {
|
|
1721
|
-
break;
|
|
1722
|
-
}
|
|
1723
|
-
if (/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(option)) {
|
|
1724
|
-
executeString = true;
|
|
1725
|
-
}
|
|
1726
|
-
const shortOptions = /^[+-][a-zA-Z]+$/u.test(option);
|
|
1727
|
-
if (shortOptions && /[oO]/u.test(option) && !/[oO]$/u.test(option)) {
|
|
1728
|
-
throw inspectionError("Cannot parse shell options reliably. Simplify the unsupported syntax.");
|
|
1729
|
-
}
|
|
1730
|
-
const next = words[bodyIndex + 1];
|
|
1731
|
-
const optionName = next !== undefined && !/^[+-]/u.test(next);
|
|
1732
|
-
bodyIndex += shortOptions && /[oO]$/u.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
|
|
1733
|
-
}
|
|
1734
|
-
})();
|
|
1735
|
-
if (executeString) {
|
|
1736
|
-
const body = wordTokens[bodyIndex];
|
|
1737
|
-
if (body === undefined || body.expansion === true) {
|
|
1738
|
-
throw inspectionError("Cannot parse an expanded or missing shell -c body reliably. Use a literal shell body; if committing, run git commit directly.");
|
|
1739
|
-
}
|
|
1740
|
-
if (/^(?:.*\/)?sh$/u.test(words[commandStart] ?? "") && body.value.includes("$'")) {
|
|
1741
|
-
throw inspectionError("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body.");
|
|
1742
|
-
}
|
|
1743
|
-
const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
|
|
1744
|
-
invocations.push(...extractGitCommits(body.value, directoryChanged || wrapperChange, depth + 1));
|
|
1745
|
-
}
|
|
1746
|
-
}
|
|
1747
|
-
})();
|
|
1748
|
-
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment)) {
|
|
1488
|
+
const invocation = extractInvocation(words, start);
|
|
1489
|
+
const body = extractShellCBody(words, start);
|
|
1490
|
+
if (body !== undefined) {
|
|
1491
|
+
const wrapperChange = values.slice(0, start).some((word) => word === "env" || isAssignment(word));
|
|
1492
|
+
invocations.push(...extractGitCommits(body, changedDirectory || wrapperChange, depth + 1));
|
|
1493
|
+
}
|
|
1494
|
+
if (targetMutators.has(values[start] ?? "") || values.length > 0 && values.every(isAssignment)) {
|
|
1749
1495
|
changedDirectory = true;
|
|
1750
1496
|
}
|
|
1751
1497
|
if (invocation !== undefined) {
|
|
@@ -1753,35 +1499,7 @@ var extractGitCommits = function extractGitCommits(command, inheritedDirectoryCh
|
|
|
1753
1499
|
...invocation,
|
|
1754
1500
|
targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir."
|
|
1755
1501
|
} : invocation;
|
|
1756
|
-
|
|
1757
|
-
invocations.push(target);
|
|
1758
|
-
continue;
|
|
1759
|
-
}
|
|
1760
|
-
const collectStdinMessage = () => {
|
|
1761
|
-
const heredocs = commandTokens.filter((token) => token.type === "redirect" && /^\d*<<$/u.test(token.value));
|
|
1762
|
-
const stdinRedirects = commandTokens.filter((token) => {
|
|
1763
|
-
if (token.type !== "redirect") {
|
|
1764
|
-
return false;
|
|
1765
|
-
}
|
|
1766
|
-
const match = /^(?<descriptor>\d*)(?<direction>[<>])/u.exec(token.value);
|
|
1767
|
-
return match !== null && (match[1] === "" ? match[2] === "<" : Number(match[1]) === 0);
|
|
1768
|
-
});
|
|
1769
|
-
const [heredoc] = heredocs;
|
|
1770
|
-
let stdinError;
|
|
1771
|
-
if (simple.pipeline) {
|
|
1772
|
-
stdinError = "Pipelines cannot supply a validated commit message.";
|
|
1773
|
-
} else if (heredocs.length !== 1 || stdinRedirects.length !== 1 || heredoc?.value !== "<<" && heredoc?.value !== "0<<") {
|
|
1774
|
-
stdinError = "Use exactly one quoted stdin heredoc on git commit -F -, with no other stdin redirects.";
|
|
1775
|
-
} else if (heredoc.heredoc?.quoted !== true) {
|
|
1776
|
-
stdinError = "Use a complete quoted heredoc delimiter, for example: git commit -s -F - <<'EOF'.";
|
|
1777
|
-
}
|
|
1778
|
-
invocations.push({
|
|
1779
|
-
...target,
|
|
1780
|
-
stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined,
|
|
1781
|
-
stdinError
|
|
1782
|
-
});
|
|
1783
|
-
};
|
|
1784
|
-
collectStdinMessage();
|
|
1502
|
+
invocations.push(attachStdinHeredoc(target, simple.tokens, simple.pipeline));
|
|
1785
1503
|
}
|
|
1786
1504
|
}
|
|
1787
1505
|
for (const token of tokens) {
|
|
@@ -1794,192 +1512,441 @@ var extractGitCommits = function extractGitCommits(command, inheritedDirectoryCh
|
|
|
1794
1512
|
|
|
1795
1513
|
// src/validator.ts
|
|
1796
1514
|
var signoffPattern = /^\s*[sS][iI][gG][nN][eE][dD]-[oO][fF][fF]-[bB][yY]:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/u;
|
|
1797
|
-
var
|
|
1798
|
-
|
|
1799
|
-
|
|
1515
|
+
var subjectScopeViolation = (subject, effective) => {
|
|
1516
|
+
if (subject.length === 0) {
|
|
1517
|
+
return 'Subject line is empty. The commit message must begin with "<scope>: <subject>".';
|
|
1518
|
+
}
|
|
1519
|
+
if (scopePattern.test(effective)) {
|
|
1520
|
+
return;
|
|
1521
|
+
}
|
|
1522
|
+
if (/^:\s*/u.test(effective)) {
|
|
1523
|
+
return `Missing scope before colon in subject line "${subject}". Expected format: "<scope>: <subject>".`;
|
|
1524
|
+
}
|
|
1525
|
+
if (/^[^:]+:\S/u.test(effective)) {
|
|
1526
|
+
return `Missing space after colon in subject line "${subject}". Expected format: "<scope>: <subject>".`;
|
|
1527
|
+
}
|
|
1528
|
+
if (/^[^:]+:\s*$/u.test(effective)) {
|
|
1529
|
+
return `Subject text after colon is empty in "${subject}". Expected format: "<scope>: <subject>".`;
|
|
1530
|
+
}
|
|
1531
|
+
return `Missing scope in subject line "${subject}". First line must follow "<scope>: <subject>" format.`;
|
|
1532
|
+
};
|
|
1533
|
+
var resolveMessages = (invocation, violations) => {
|
|
1534
|
+
if (invocation.messageExpansion === true) {
|
|
1535
|
+
violations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
if (invocation.hasTrailer === true) {
|
|
1539
|
+
violations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
const filePath = invocation.filePaths.at(-1);
|
|
1543
|
+
if (filePath === undefined) {
|
|
1544
|
+
return invocation.messages;
|
|
1545
|
+
}
|
|
1546
|
+
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
1547
|
+
violations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1550
|
+
if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || invocation.messages.length > 0) {
|
|
1551
|
+
violations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
|
|
1552
|
+
return;
|
|
1553
|
+
}
|
|
1554
|
+
return [invocation.stdinMessage];
|
|
1555
|
+
};
|
|
1556
|
+
var checkAllowedScope = (subject, effective, allowed) => {
|
|
1557
|
+
const rawScope = scopePattern.exec(effective)?.[1];
|
|
1558
|
+
if (rawScope === undefined || allowed.length === 0) {
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
const conventional = /^(?<type>[^(]+)\((?<scope>[^)]+)\)$/u.exec(rawScope);
|
|
1562
|
+
if ([rawScope, conventional?.[1], conventional?.[2]].some((scope) => scope !== undefined && allowed.includes(scope))) {
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
const detail = effective === subject ? "" : ` Subject line: "${subject}".`;
|
|
1566
|
+
return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowed.join(", ")}.${detail}`;
|
|
1800
1567
|
};
|
|
1801
|
-
var
|
|
1802
|
-
|
|
1803
|
-
const conventionalType = parenthesizedScope?.[1];
|
|
1804
|
-
const innerScope = parenthesizedScope?.[2];
|
|
1805
|
-
const isAllowed = allowedScopes.includes(rawScope) || innerScope !== undefined && allowedScopes.includes(innerScope) || conventionalType !== undefined && allowedScopes.includes(conventionalType);
|
|
1806
|
-
if (isAllowed) {
|
|
1568
|
+
var checkLineLength = (lines, max) => {
|
|
1569
|
+
if (max <= 0) {
|
|
1807
1570
|
return;
|
|
1808
1571
|
}
|
|
1809
|
-
|
|
1572
|
+
const overlong = lines.flatMap((line, index) => line.length > max ? [` - Line ${index + 1} (${line.length} chars, max ${max}): "${line}"`] : []);
|
|
1573
|
+
return overlong.length === 0 ? undefined : `Commit message exceeds maximum line length of ${max} characters:
|
|
1574
|
+
${overlong.join(`
|
|
1575
|
+
`)}
|
|
1576
|
+
Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`;
|
|
1577
|
+
};
|
|
1578
|
+
var validateInvocation = (invocation, config) => {
|
|
1579
|
+
const violations = [];
|
|
1580
|
+
if (invocation.isHelp) {
|
|
1581
|
+
return violations;
|
|
1582
|
+
}
|
|
1583
|
+
const messages = resolveMessages(invocation, violations);
|
|
1584
|
+
if (messages === undefined) {
|
|
1585
|
+
return violations;
|
|
1586
|
+
}
|
|
1587
|
+
if (messages.length === 0) {
|
|
1588
|
+
if (!(invocation.isAmend && invocation.hasNoEdit === true) && invocation.isFixup !== true && invocation.filePaths.length === 0) {
|
|
1589
|
+
violations.push('No commit message provided. Commits in OpenCode must provide an inline message via -m "<scope>: <subject>".');
|
|
1590
|
+
}
|
|
1591
|
+
return violations;
|
|
1592
|
+
}
|
|
1593
|
+
const lines = messages.join(`
|
|
1594
|
+
|
|
1595
|
+
`).split(/\r?\n/u);
|
|
1596
|
+
const subject = (lines[0] ?? "").trim();
|
|
1597
|
+
const effective = subject.replace(/^(?:(?:fixup|squash)!\s+)+/u, "");
|
|
1598
|
+
const checks = [
|
|
1599
|
+
checkAllowedScope(subject, effective, config.allowedScopes ?? []),
|
|
1600
|
+
config.requireScope ? subjectScopeViolation(subject, effective) : undefined,
|
|
1601
|
+
checkLineLength(lines, config.maxLineLength)
|
|
1602
|
+
];
|
|
1603
|
+
violations.push(...checks.filter((violation) => violation !== undefined));
|
|
1604
|
+
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
1605
|
+
const hasTrailer = subjectIndex !== -1 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
|
|
1606
|
+
if (config.enforceSignoff && !invocation.hasSignoffFlag && !hasTrailer) {
|
|
1607
|
+
violations.push("Missing commit signoff. Commit must either include the '-s' or '--signoff' flag, or contain a valid 'Signed-off-by: Name <email>' trailer in the message body.");
|
|
1608
|
+
}
|
|
1609
|
+
return violations;
|
|
1810
1610
|
};
|
|
1811
|
-
var
|
|
1812
|
-
const
|
|
1813
|
-
|
|
1611
|
+
var validateGitCommits = (invocations, config, _originalCommand) => {
|
|
1612
|
+
const violations = invocations.flatMap((invocation) => validateInvocation(invocation, config));
|
|
1613
|
+
if (violations.length === 0) {
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
const details = violations.slice(0, 10).map((text, index) => `${index + 1}. ${text.slice(0, 2048)}`).join(`
|
|
1814
1617
|
|
|
1815
1618
|
`);
|
|
1816
1619
|
const scope = config.allowedScopes?.[0] ?? "scope";
|
|
1817
|
-
const
|
|
1818
|
-
`
|
|
1819
|
-
git commit${config.enforceSignoff ? " -s" : ""} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`;
|
|
1820
|
-
return new Error(`${header}
|
|
1620
|
+
const policy = config.enforceSignoff ? "required: captured commit.gpgsign=true. Keep -s." : "not required: captured commit.gpgsign=false|unset.";
|
|
1621
|
+
throw new Error(`[commit-guard] Git commit rejected: commit message format rules violated.
|
|
1821
1622
|
|
|
1822
1623
|
Violations:
|
|
1823
|
-
${
|
|
1624
|
+
${details}
|
|
1824
1625
|
|
|
1825
|
-
${
|
|
1626
|
+
Signoff ${policy}
|
|
1627
|
+
Example:
|
|
1628
|
+
git commit${config.enforceSignoff ? " -s" : ""} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`);
|
|
1826
1629
|
};
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1630
|
+
|
|
1631
|
+
// src/plugin.ts
|
|
1632
|
+
var { relative: relative2, resolve: resolve2 } = path;
|
|
1633
|
+
var publicationGuidance = 'Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing.';
|
|
1634
|
+
var receiptGuidance = "RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.";
|
|
1635
|
+
var toToolError = (cause) => {
|
|
1636
|
+
if (Cause.isUnknownError(cause)) {
|
|
1637
|
+
return toToolError(cause.cause);
|
|
1638
|
+
}
|
|
1639
|
+
return cause instanceof Tool.Error ? cause : new Tool.Error({
|
|
1640
|
+
message: cause instanceof Error ? cause.message : "[commit-guard] Git commit validation failed.",
|
|
1641
|
+
error: cause
|
|
1642
|
+
});
|
|
1643
|
+
};
|
|
1644
|
+
var signingError = (setting) => `[commit-guard] Git could not read ${setting} as valid. Repeating the capture will not fix it. Inspect with git config --show-origin --get-all ${setting}; fix the value without changing the intended signing policy, then call commit_context with refresh:true.`;
|
|
1645
|
+
var baselineGuidance = (baseline, config) => {
|
|
1646
|
+
if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
1647
|
+
return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey");
|
|
1648
|
+
}
|
|
1649
|
+
const observed = [
|
|
1650
|
+
...new Set(baseline.messages.map((message) => scopePattern.exec(message.split(`
|
|
1651
|
+
`)[0])?.[1]).filter((scope) => scope !== undefined && scope.length <= 40))
|
|
1652
|
+
].slice(0, 3);
|
|
1653
|
+
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
|
|
1654
|
+
` : "";
|
|
1655
|
+
const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
|
|
1656
|
+
const signoff = baseline.gpgsign === "true" ? "Add -s or --signoff." : "Signoff is not required; add it only if repository instructions require it.";
|
|
1657
|
+
return `[commit-guard] Frozen commit baseline for ${baseline.directory.slice(0, 4096)}.
|
|
1658
|
+
` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
|
|
1659
|
+
` + `${scopes}
|
|
1660
|
+
${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
|
|
1661
|
+
` + `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.
|
|
1662
|
+
` + `A second commit_context call is optional.
|
|
1663
|
+
Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.`;
|
|
1664
|
+
};
|
|
1665
|
+
var captureInstructions = (attempt, status) => `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} and background:false. ` + `Do not wrap it or chain another command onto it. ${publicationGuidance} ${receiptGuidance}
|
|
1666
|
+
${attempt.command}`;
|
|
1667
|
+
var sweep = (state) => Effect2.gen(function* sweepPending() {
|
|
1668
|
+
for (const attempt of [...state.pending.values()].slice(0, 32)) {
|
|
1669
|
+
state.pending.delete(attempt.scope);
|
|
1670
|
+
if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
|
|
1671
|
+
cleanup(attempt);
|
|
1672
|
+
yield* recordState(state.ctx, attempt, "expired");
|
|
1673
|
+
yield* invalidateOwned(state.ctx, attempt);
|
|
1674
|
+
} else {
|
|
1675
|
+
state.pending.set(attempt.scope, attempt);
|
|
1836
1676
|
}
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1677
|
+
}
|
|
1678
|
+
});
|
|
1679
|
+
var resolveCanonicalWorkdir = (sessionDirectory, workdir) => {
|
|
1680
|
+
try {
|
|
1681
|
+
return realpathSync2(isJSONString(workdir) ? resolve2(sessionDirectory, workdir) : sessionDirectory);
|
|
1682
|
+
} catch {
|
|
1683
|
+
throw new Error("[commit-guard] Cannot access the shell workdir. Supply an existing checkout directory and call commit_context there.");
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
var validateFields = (input, fields, booleans) => {
|
|
1687
|
+
if (!isRecord(input)) {
|
|
1688
|
+
throw new Error("[commit-guard] Cannot inspect non-object tool input. Supply literal command and workdir fields.");
|
|
1689
|
+
}
|
|
1690
|
+
for (const field of fields) {
|
|
1691
|
+
if (input[field] !== undefined && !isJSONString(input[field])) {
|
|
1692
|
+
throw new Error(`[commit-guard] Invalid ${field}; expected a string.`);
|
|
1840
1693
|
}
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
1846
|
-
allViolations.push("Cannot validate a commit message from -F/--file before permission approval. Use an inline $'...' message or one quoted stdin heredoc.");
|
|
1847
|
-
return false;
|
|
1848
|
-
}
|
|
1849
|
-
if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || collectedMessages.length > 0) {
|
|
1850
|
-
allViolations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} Use one quoted stdin heredoc or an inline $'...' message.`);
|
|
1851
|
-
return false;
|
|
1852
|
-
}
|
|
1853
|
-
collectedMessages.push(invocation.stdinMessage);
|
|
1854
|
-
}
|
|
1855
|
-
return true;
|
|
1856
|
-
};
|
|
1857
|
-
if (!collectFileMessage()) {
|
|
1858
|
-
continue;
|
|
1694
|
+
}
|
|
1695
|
+
for (const field of booleans) {
|
|
1696
|
+
if (input[field] !== undefined && !isJSONBoolean(input[field])) {
|
|
1697
|
+
throw new Error(`[commit-guard] Invalid ${field}; expected a boolean.`);
|
|
1859
1698
|
}
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1699
|
+
}
|
|
1700
|
+
return input;
|
|
1701
|
+
};
|
|
1702
|
+
var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.gen(function* prepare() {
|
|
1703
|
+
const { ctx, pending, config } = state;
|
|
1704
|
+
const previous = pending.get(scope);
|
|
1705
|
+
if (previous !== undefined) {
|
|
1706
|
+
if (request.refresh !== true) {
|
|
1707
|
+
return {
|
|
1708
|
+
content: previous.claimed === undefined ? captureInstructions(previous, "Capture still pending and unclaimed. ") : `Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. ${publicationGuidance} ${receiptGuidance}`
|
|
1709
|
+
};
|
|
1871
1710
|
}
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
const
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
const scopeViolation = validateAllowedScope(scopeMatch[1], config.allowedScopes);
|
|
1882
|
-
if (scopeViolation !== undefined) {
|
|
1883
|
-
const fullSubjectDetail = effectiveSubject === subjectLine ? "" : ` Subject line: "${subjectLine}".`;
|
|
1884
|
-
allViolations.push(`${scopeViolation}${fullSubjectDetail}`);
|
|
1885
|
-
}
|
|
1711
|
+
pending.delete(scope);
|
|
1712
|
+
cleanup(previous);
|
|
1713
|
+
yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
|
|
1714
|
+
yield* invalidateOwned(ctx, previous);
|
|
1715
|
+
}
|
|
1716
|
+
if (request.refresh !== true) {
|
|
1717
|
+
const baseline = yield* load(ctx, scope);
|
|
1718
|
+
if (baseline !== undefined && baseline.directory === findGitRoot(workdir)) {
|
|
1719
|
+
return { content: baselineGuidance(baseline, config) };
|
|
1886
1720
|
}
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
}
|
|
1902
|
-
}
|
|
1721
|
+
}
|
|
1722
|
+
const count = yield* invalidate(ctx, scope);
|
|
1723
|
+
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, workdir));
|
|
1724
|
+
pending.set(scope, attempt);
|
|
1725
|
+
const status = state.failures.get(scope) ?? (yield* captureStatus(ctx, scope));
|
|
1726
|
+
yield* recordState(ctx, attempt, "prepared");
|
|
1727
|
+
return { content: captureInstructions(attempt, status) };
|
|
1728
|
+
});
|
|
1729
|
+
var runCommitContext = (state, input, toolContext) => Effect2.gen(function* context() {
|
|
1730
|
+
yield* sweep(state);
|
|
1731
|
+
const { ctx } = state;
|
|
1732
|
+
if (ctx.location.workspaceID !== undefined) {
|
|
1733
|
+
return {
|
|
1734
|
+
content: "Commit context capture is unavailable for remote workspaces."
|
|
1903
1735
|
};
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
lineNumber: i + 1,
|
|
1913
|
-
length: line.length,
|
|
1914
|
-
text: line
|
|
1915
|
-
});
|
|
1916
|
-
}
|
|
1917
|
-
}
|
|
1918
|
-
if (overlongLines.length > 0) {
|
|
1919
|
-
const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
|
|
1920
|
-
`);
|
|
1921
|
-
allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
|
|
1922
|
-
${details}
|
|
1923
|
-
Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`);
|
|
1924
|
-
}
|
|
1925
|
-
}
|
|
1736
|
+
}
|
|
1737
|
+
const request = yield* Effect2.try(() => validateFields(input, ["workdir", "directory"], ["refresh"]));
|
|
1738
|
+
const session = yield* ctx.session.get({
|
|
1739
|
+
sessionID: toolContext.sessionID
|
|
1740
|
+
});
|
|
1741
|
+
if (session.location.workspaceID !== ctx.location.workspaceID) {
|
|
1742
|
+
return {
|
|
1743
|
+
content: "Commit context capture is unavailable for remote workspaces."
|
|
1926
1744
|
};
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1745
|
+
}
|
|
1746
|
+
const requestedDir = isJSONString(request.workdir) ? request.workdir : request.directory;
|
|
1747
|
+
const explicitDir = isJSONString(requestedDir) ? requestedDir : undefined;
|
|
1748
|
+
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
1749
|
+
let target = resolveTargetWorkdir(sessionDirectory, explicitDir);
|
|
1750
|
+
if (target.workdir === undefined && explicitDir === undefined) {
|
|
1751
|
+
const remembered = state.lastSessionWorkdir.get(toolContext.sessionID);
|
|
1752
|
+
if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
|
|
1753
|
+
target = { workdir: remembered };
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
if (target.error !== undefined || target.workdir === undefined) {
|
|
1757
|
+
return {
|
|
1758
|
+
content: target.error ?? "Could not determine target Git repository."
|
|
1935
1759
|
};
|
|
1936
|
-
validateSignoff();
|
|
1937
1760
|
}
|
|
1938
|
-
|
|
1939
|
-
|
|
1761
|
+
const { workdir } = target;
|
|
1762
|
+
state.lastSessionWorkdir.set(toolContext.sessionID, workdir);
|
|
1763
|
+
const scope = scopeFor(ctx, toolContext.sessionID, state.config, workdir);
|
|
1764
|
+
if (state.preparing.has(scope)) {
|
|
1765
|
+
return {
|
|
1766
|
+
content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions."
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
state.preparing.add(scope);
|
|
1770
|
+
return yield* prepareCapture(state, toolContext, request, workdir, scope).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
1771
|
+
state.preparing.delete(scope);
|
|
1772
|
+
})));
|
|
1773
|
+
}).pipe(Effect2.mapError(toToolError));
|
|
1774
|
+
var claimCapture = (state, event, input, attempt) => Effect2.gen(function* claim() {
|
|
1775
|
+
const session = yield* state.ctx.session.get({
|
|
1776
|
+
sessionID: event.sessionID
|
|
1777
|
+
});
|
|
1778
|
+
yield* Effect2.try(() => {
|
|
1779
|
+
let matchesWorkdir = false;
|
|
1780
|
+
try {
|
|
1781
|
+
matchesWorkdir = resolveCanonicalWorkdir(session.location.directory ?? state.ctx.location.directory, input.workdir) === attempt.workdir;
|
|
1782
|
+
} catch {}
|
|
1783
|
+
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || input.background === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
|
|
1784
|
+
throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.");
|
|
1785
|
+
}
|
|
1786
|
+
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
1787
|
+
});
|
|
1788
|
+
yield* recordState(state.ctx, attempt, "claimed");
|
|
1789
|
+
});
|
|
1790
|
+
var verifyBaselineAndValidate = (state, event, input, command, invocations) => Effect2.gen(function* validate() {
|
|
1791
|
+
const { ctx, config } = state;
|
|
1792
|
+
if (ctx.location.workspaceID !== undefined) {
|
|
1793
|
+
return yield* Effect2.fail(new Error("[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."));
|
|
1794
|
+
}
|
|
1795
|
+
const session = yield* ctx.session.get({ sessionID: event.sessionID });
|
|
1796
|
+
if (session.location.workspaceID !== ctx.location.workspaceID || invocations.some((invocation) => invocation.targetError !== undefined)) {
|
|
1797
|
+
return yield* Effect2.fail(new Error("[commit-guard] Commit target is ambiguous. Use a direct git commit without -C, Git directory/configuration flags, environment overrides, or cd wrappers. Set shell workdir to the captured checkout and call commit_context there."));
|
|
1798
|
+
}
|
|
1799
|
+
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
1800
|
+
const workdir = yield* Effect2.try(() => resolveCanonicalWorkdir(sessionDirectory, input.workdir));
|
|
1801
|
+
const root = findGitRoot(workdir);
|
|
1802
|
+
const baseline = yield* load(ctx, scopeFor(ctx, event.sessionID, config, workdir));
|
|
1803
|
+
if (baseline === undefined || root === undefined || baseline.directory !== root) {
|
|
1804
|
+
const expected = root ?? workdir;
|
|
1805
|
+
const hint = JSON.stringify(relative2(sessionDirectory, expected) || ".");
|
|
1806
|
+
return yield* Effect2.fail(new Error(`[commit-guard] No published baseline for ${expected}. Call commit_context({ workdir: ${hint} }), then run the returned command immediately, unchanged, in the foreground with that workdir and background:false. Do not wrap it or chain another command onto it. ${publicationGuidance} RECEIPT_OK alone is insufficient.`));
|
|
1807
|
+
}
|
|
1808
|
+
if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
1809
|
+
return yield* Effect2.fail(new Error(signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")));
|
|
1810
|
+
}
|
|
1811
|
+
yield* Effect2.try(() => {
|
|
1812
|
+
validateGitCommits(invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, command);
|
|
1813
|
+
});
|
|
1814
|
+
return yield* Effect2.void;
|
|
1815
|
+
});
|
|
1816
|
+
var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
|
|
1817
|
+
yield* sweep(state);
|
|
1818
|
+
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
const input = yield* Effect2.try(() => validateFields(event.input, ["workdir"], ["background"]));
|
|
1822
|
+
if (!isJSONString(input.command)) {
|
|
1823
|
+
yield* Effect2.fail(new Error("[commit-guard] Invalid command; expected a literal command string."));
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
const { command } = input;
|
|
1827
|
+
const attempt = [...state.pending.values()].find((item) => item.command === command);
|
|
1828
|
+
if (attempt !== undefined) {
|
|
1829
|
+
yield* claimCapture(state, event, input, attempt);
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
const invocations = yield* Effect2.try(() => extractGitCommits(command));
|
|
1833
|
+
if (invocations.length > 0 && !invocations.every((invocation) => invocation.isHelp)) {
|
|
1834
|
+
yield* verifyBaselineAndValidate(state, event, input, command, invocations);
|
|
1835
|
+
}
|
|
1836
|
+
}).pipe(Effect2.mapError(toToolError));
|
|
1837
|
+
var isVerifiedShellMetadata = (metadata) => isRecord(metadata) && metadata.status === "completed" && metadata.exit === 0 && metadata.truncated === false && (metadata.timeout === undefined || metadata.timeout === false) && Object.keys(metadata).every((key) => ["status", "exit", "truncated", "timeout"].includes(key));
|
|
1838
|
+
var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* publishAttempt() {
|
|
1839
|
+
const { ctx } = state;
|
|
1840
|
+
if (event.status !== "completed") {
|
|
1841
|
+
return "shell result did not complete successfully";
|
|
1842
|
+
}
|
|
1843
|
+
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
|
|
1844
|
+
return "capture was superseded by a refresh";
|
|
1845
|
+
}
|
|
1846
|
+
if (!isVerifiedShellMetadata(event.result.metadata)) {
|
|
1847
|
+
return "shell result lacks verified foreground completion metadata";
|
|
1848
|
+
}
|
|
1849
|
+
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => null);
|
|
1850
|
+
if (session === null || session.location.workspaceID !== ctx.location.workspaceID) {
|
|
1851
|
+
return "capture session or workspace no longer matches";
|
|
1852
|
+
}
|
|
1853
|
+
const baseline = yield* Effect2.try(() => importCapture(attempt)).pipe(Effect2.orElseSucceed(() => null));
|
|
1854
|
+
if (baseline === null || baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) {
|
|
1855
|
+
return "private artifact is invalid or incomplete (END required)";
|
|
1856
|
+
}
|
|
1857
|
+
if (!(yield* publish(ctx, attempt, state.generation, baseline).pipe(Effect2.catchCause(() => Effect2.succeed(false))))) {
|
|
1858
|
+
return "capture storage failed or its counter changed";
|
|
1859
|
+
}
|
|
1860
|
+
state.failures.delete(attempt.scope);
|
|
1861
|
+
return baseline;
|
|
1862
|
+
});
|
|
1863
|
+
var appendCaptureNote = (result, note) => {
|
|
1864
|
+
const content = isJSONString(result.content) ? [{ type: "text", text: result.content }] : result.content ?? [];
|
|
1865
|
+
const annotated = {
|
|
1866
|
+
...result,
|
|
1867
|
+
content: [...content, { type: "text", text: note }]
|
|
1868
|
+
};
|
|
1869
|
+
return isRecord(result.output) && isJSONString(result.output.output) ? {
|
|
1870
|
+
...annotated,
|
|
1871
|
+
output: {
|
|
1872
|
+
...result.output,
|
|
1873
|
+
output: `${result.output.output}
|
|
1874
|
+
|
|
1875
|
+
${note}`
|
|
1876
|
+
}
|
|
1877
|
+
} : annotated;
|
|
1878
|
+
};
|
|
1879
|
+
var rememberFailure = (state, scope, reason) => {
|
|
1880
|
+
state.failures.delete(scope);
|
|
1881
|
+
state.failures.set(scope, `The previous capture failed: ${reason.slice(0, 256)}. `);
|
|
1882
|
+
if (state.failures.size > 128) {
|
|
1883
|
+
const oldest = state.failures.keys().next().value;
|
|
1884
|
+
if (oldest !== undefined) {
|
|
1885
|
+
state.failures.delete(oldest);
|
|
1886
|
+
}
|
|
1940
1887
|
}
|
|
1941
1888
|
};
|
|
1889
|
+
var handleAfterExecute = (state, event) => Effect2.gen(function* after() {
|
|
1890
|
+
if (event.tool !== "shell") {
|
|
1891
|
+
return;
|
|
1892
|
+
}
|
|
1893
|
+
const attempt = [...state.pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
|
|
1894
|
+
if (attempt === undefined) {
|
|
1895
|
+
return;
|
|
1896
|
+
}
|
|
1897
|
+
let outcome = "capture import or storage failed";
|
|
1898
|
+
yield* Effect2.gen(function* publishing() {
|
|
1899
|
+
outcome = yield* publishCapturedAttempt(state, event, attempt);
|
|
1900
|
+
if (!isJSONString(outcome)) {
|
|
1901
|
+
yield* recordState(state.ctx, attempt, "published");
|
|
1902
|
+
}
|
|
1903
|
+
}).pipe(Effect2.onExit(() => Effect2.gen(function* finalize() {
|
|
1904
|
+
if (state.pending.get(attempt.scope) === attempt) {
|
|
1905
|
+
state.pending.delete(attempt.scope);
|
|
1906
|
+
}
|
|
1907
|
+
if (isJSONString(outcome)) {
|
|
1908
|
+
rememberFailure(state, attempt.scope, outcome);
|
|
1909
|
+
yield* recordState(state.ctx, attempt, "failed", outcome).pipe(Effect2.catchCause(() => Effect2.void));
|
|
1910
|
+
yield* invalidateOwned(state.ctx, attempt);
|
|
1911
|
+
}
|
|
1912
|
+
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
1913
|
+
cleanup(attempt);
|
|
1914
|
+
})), Effect2.catchCause(() => Effect2.void))), Effect2.catchCause(() => Effect2.void));
|
|
1915
|
+
const note = isJSONString(outcome) ? `[commit-guard] This capture did not publish a usable baseline: ${outcome.slice(0, 256)}.
|
|
1916
|
+
RECEIPT_OK alone does not authorize a commit.
|
|
1917
|
+
Call commit_context with the same workdir for status and next steps.` : baselineGuidance(outcome, state.config);
|
|
1918
|
+
if (event.status === "error") {
|
|
1919
|
+
event.error = new Tool.Error({
|
|
1920
|
+
error: event.error.error,
|
|
1921
|
+
metadata: event.error.metadata,
|
|
1922
|
+
message: `${event.error.message}
|
|
1942
1923
|
|
|
1943
|
-
|
|
1944
|
-
|
|
1924
|
+
${note}`
|
|
1925
|
+
});
|
|
1926
|
+
} else {
|
|
1927
|
+
event.result = appendCaptureNote(event.result, note);
|
|
1928
|
+
}
|
|
1929
|
+
});
|
|
1945
1930
|
var plugin = Plugin.define({
|
|
1946
1931
|
id: "opencode-commit-guard",
|
|
1947
|
-
effect: (ctx) => Effect2.gen(function*
|
|
1932
|
+
effect: (ctx) => Effect2.gen(function* setup() {
|
|
1948
1933
|
const config = yield* Effect2.sync(() => parseConfig(ctx.options));
|
|
1949
|
-
const
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
failures
|
|
1957
|
-
if (failures.size > 128) {
|
|
1958
|
-
const oldest = failures.keys().next().value;
|
|
1959
|
-
if (oldest !== undefined) {
|
|
1960
|
-
failures.delete(oldest);
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1934
|
+
const state = {
|
|
1935
|
+
ctx,
|
|
1936
|
+
config,
|
|
1937
|
+
generation: randomUUID2(),
|
|
1938
|
+
pending: new Map,
|
|
1939
|
+
preparing: new Set,
|
|
1940
|
+
lastSessionWorkdir: new Map,
|
|
1941
|
+
failures: new Map
|
|
1963
1942
|
};
|
|
1964
|
-
|
|
1965
|
-
for (const attempt of
|
|
1966
|
-
pending.delete(attempt.scope);
|
|
1967
|
-
if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
|
|
1968
|
-
cleanup(attempt);
|
|
1969
|
-
yield* recordState(ctx, attempt, "expired");
|
|
1970
|
-
yield* invalidateOwned(ctx, attempt);
|
|
1971
|
-
} else {
|
|
1972
|
-
pending.set(attempt.scope, attempt);
|
|
1973
|
-
}
|
|
1974
|
-
}
|
|
1975
|
-
});
|
|
1976
|
-
yield* Effect2.addFinalizer(() => Effect2.gen(function* unloadGuard() {
|
|
1977
|
-
for (const attempt of pending.values()) {
|
|
1943
|
+
yield* Effect2.addFinalizer(() => Effect2.gen(function* unload() {
|
|
1944
|
+
for (const attempt of state.pending.values()) {
|
|
1978
1945
|
cleanup(attempt);
|
|
1979
1946
|
yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
|
|
1980
1947
|
yield* invalidateOwned(ctx, attempt);
|
|
1981
1948
|
}
|
|
1982
|
-
pending.clear();
|
|
1949
|
+
state.pending.clear();
|
|
1983
1950
|
}));
|
|
1984
1951
|
yield* ctx.tool.transform((editor) => {
|
|
1985
1952
|
editor.add({
|
|
@@ -1989,8 +1956,7 @@ Call before your first commit in each session and checkout.
|
|
|
1989
1956
|
Set workdir when targeting another repository.
|
|
1990
1957
|
Run the returned command immediately, unchanged, with the indicated workdir and background:false.
|
|
1991
1958
|
Do not wrap it or chain another command onto it.
|
|
1992
|
-
|
|
1993
|
-
RECEIPT_OK alone is insufficient.
|
|
1959
|
+
${publicationGuidance} ${receiptGuidance}
|
|
1994
1960
|
The shell result includes commit rules; a second call is optional.
|
|
1995
1961
|
Repeat an explicit workdir when checking that checkout.
|
|
1996
1962
|
Set refresh:true after switching branches, changing signing settings, or changing commit instructions.
|
|
@@ -2013,311 +1979,14 @@ Add -s only when the returned policy or repository instructions require it.`,
|
|
|
2013
1979
|
},
|
|
2014
1980
|
additionalProperties: false
|
|
2015
1981
|
},
|
|
2016
|
-
execute: (input, toolContext) =>
|
|
2017
|
-
yield* sweep();
|
|
2018
|
-
if (ctx.location.workspaceID !== undefined) {
|
|
2019
|
-
return {
|
|
2020
|
-
content: "Commit context capture is unavailable for remote workspaces."
|
|
2021
|
-
};
|
|
2022
|
-
}
|
|
2023
|
-
const session = yield* ctx.session.get({
|
|
2024
|
-
sessionID: toolContext.sessionID
|
|
2025
|
-
});
|
|
2026
|
-
if (session.location.workspaceID !== ctx.location.workspaceID) {
|
|
2027
|
-
return {
|
|
2028
|
-
content: "Commit context capture is unavailable for remote workspaces."
|
|
2029
|
-
};
|
|
2030
|
-
}
|
|
2031
|
-
const request = Schema2.is(Schema2.Json)(input) && isRecord(input) ? input : {};
|
|
2032
|
-
let requestedDir;
|
|
2033
|
-
if (isJSONString(request.workdir)) {
|
|
2034
|
-
requestedDir = request.workdir;
|
|
2035
|
-
} else if (isJSONString(request.directory)) {
|
|
2036
|
-
requestedDir = request.directory;
|
|
2037
|
-
}
|
|
2038
|
-
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
2039
|
-
let target = resolveTargetWorkdir(sessionDirectory, requestedDir);
|
|
2040
|
-
if (target.workdir === undefined && requestedDir === undefined) {
|
|
2041
|
-
const remembered = lastSessionWorkdir.get(toolContext.sessionID);
|
|
2042
|
-
if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
|
|
2043
|
-
target = { workdir: remembered };
|
|
2044
|
-
}
|
|
2045
|
-
}
|
|
2046
|
-
if (target.error !== undefined || target.workdir === undefined) {
|
|
2047
|
-
return {
|
|
2048
|
-
content: target.error ?? "Could not determine target Git repository."
|
|
2049
|
-
};
|
|
2050
|
-
}
|
|
2051
|
-
const targetWorkdir = target.workdir;
|
|
2052
|
-
lastSessionWorkdir.set(toolContext.sessionID, targetWorkdir);
|
|
2053
|
-
const scope = scopeFor(ctx, toolContext.sessionID, config, targetWorkdir);
|
|
2054
|
-
if (preparing.has(scope)) {
|
|
2055
|
-
return {
|
|
2056
|
-
content: "A commit context capture is preparing for this session and checkout. Wait for its command, then follow its instructions."
|
|
2057
|
-
};
|
|
2058
|
-
}
|
|
2059
|
-
preparing.add(scope);
|
|
2060
|
-
return yield* Effect2.gen(function* prepareCapture() {
|
|
2061
|
-
const previous = pending.get(scope);
|
|
2062
|
-
if (previous !== undefined) {
|
|
2063
|
-
if (previous.claimed !== undefined && request.refresh !== true) {
|
|
2064
|
-
return {
|
|
2065
|
-
content: 'Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. Commit after it reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.'
|
|
2066
|
-
};
|
|
2067
|
-
}
|
|
2068
|
-
if (request.refresh !== true) {
|
|
2069
|
-
return {
|
|
2070
|
-
content: captureInstructions(previous, "Capture still pending and unclaimed. ")
|
|
2071
|
-
};
|
|
2072
|
-
}
|
|
2073
|
-
pending.delete(scope);
|
|
2074
|
-
cleanup(previous);
|
|
2075
|
-
yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
|
|
2076
|
-
yield* invalidateOwned(ctx, previous);
|
|
2077
|
-
}
|
|
2078
|
-
if (request.refresh !== true) {
|
|
2079
|
-
const baseline = yield* load(ctx, scope);
|
|
2080
|
-
if (baseline !== undefined && baseline.directory === findGitRoot(targetWorkdir)) {
|
|
2081
|
-
return { content: baselineGuidance(baseline, config) };
|
|
2082
|
-
}
|
|
2083
|
-
}
|
|
2084
|
-
const count = yield* invalidate(ctx, scope);
|
|
2085
|
-
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, targetWorkdir));
|
|
2086
|
-
pending.set(scope, attempt);
|
|
2087
|
-
const status = failures.get(scope) ?? (yield* captureStatus(ctx, scope));
|
|
2088
|
-
yield* recordState(ctx, attempt, "prepared");
|
|
2089
|
-
return { content: captureInstructions(attempt, status) };
|
|
2090
|
-
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
2091
|
-
preparing.delete(scope);
|
|
2092
|
-
})));
|
|
2093
|
-
}).pipe(Effect2.mapError(() => new Tool.Error({
|
|
2094
|
-
message: "[commit-guard] Could not access the session or commit context. Call commit_context again from this checkout."
|
|
2095
|
-
})))
|
|
1982
|
+
execute: (input, toolContext) => runCommitContext(state, input, toolContext)
|
|
2096
1983
|
});
|
|
2097
1984
|
});
|
|
2098
|
-
yield* ctx.tool.hook("execute.before", (event) =>
|
|
2099
|
-
|
|
2100
|
-
const rawInput = Schema2.is(Schema2.Json)(event.input) ? event.input : undefined;
|
|
2101
|
-
if ((event.tool === "shell" || event.tool === "bash") && rawInput === undefined) {
|
|
2102
|
-
yield* Effect2.fail(new Tool.Error({
|
|
2103
|
-
message: "[commit-guard] Cannot inspect non-JSON shell input. Supply literal command and workdir fields."
|
|
2104
|
-
}));
|
|
2105
|
-
}
|
|
2106
|
-
const captureSession = (event.tool === "shell" || event.tool === "bash") && [...pending.values()].some((attempt) => isRecord(rawInput) && rawInput.command === attempt.command) ? yield* ctx.session.get({ sessionID: event.sessionID }) : undefined;
|
|
2107
|
-
const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
|
|
2108
|
-
const parsed = yield* Effect2.try({
|
|
2109
|
-
try: () => {
|
|
2110
|
-
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
2111
|
-
return null;
|
|
2112
|
-
}
|
|
2113
|
-
if (!isRecord(rawInput)) {
|
|
2114
|
-
return null;
|
|
2115
|
-
}
|
|
2116
|
-
const { command } = rawInput;
|
|
2117
|
-
if (!isJSONString(command)) {
|
|
2118
|
-
return null;
|
|
2119
|
-
}
|
|
2120
|
-
const rawWorkdir = rawInput.workdir;
|
|
2121
|
-
for (const attempt of pending.values()) {
|
|
2122
|
-
if (command !== attempt.command) {
|
|
2123
|
-
continue;
|
|
2124
|
-
}
|
|
2125
|
-
const matchesWorkdir = rawWorkdir === attempt.workdir || isJSONString(rawWorkdir) && resolve2(captureSessionDirectory, rawWorkdir) === attempt.workdir || rawWorkdir === undefined && captureSessionDirectory === attempt.workdir;
|
|
2126
|
-
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput.background === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
|
|
2127
|
-
throw new Error("[commit-guard] Capture must use its exact foreground shell command in the original session and workdir. Call commit_context to refresh.");
|
|
2128
|
-
}
|
|
2129
|
-
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
2130
|
-
return null;
|
|
2131
|
-
}
|
|
2132
|
-
const invocations = extractGitCommits(command);
|
|
2133
|
-
if (invocations.length === 0) {
|
|
2134
|
-
return null;
|
|
2135
|
-
}
|
|
2136
|
-
return { invocations, command, rawInput };
|
|
2137
|
-
},
|
|
2138
|
-
catch: (error) => new Tool.Error({
|
|
2139
|
-
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
2140
|
-
})
|
|
2141
|
-
});
|
|
2142
|
-
for (const attempt of pending.values()) {
|
|
2143
|
-
if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent) {
|
|
2144
|
-
yield* recordState(ctx, attempt, "claimed");
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
if (parsed === null || parsed.invocations.every((invocation) => invocation.isHelp)) {
|
|
2148
|
-
return;
|
|
2149
|
-
}
|
|
2150
|
-
yield* Effect2.gen(function* validateTarget() {
|
|
2151
|
-
if (ctx.location.workspaceID !== undefined) {
|
|
2152
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
2153
|
-
message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
|
|
2154
|
-
}));
|
|
2155
|
-
}
|
|
2156
|
-
const session = captureSession ?? (yield* ctx.session.get({ sessionID: event.sessionID }));
|
|
2157
|
-
if (session.location.workspaceID !== ctx.location.workspaceID || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
|
|
2158
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
2159
|
-
message: "[commit-guard] Commit target is ambiguous. Use a direct git commit without -C, Git directory/configuration flags, environment overrides, or cd wrappers. Set shell workdir to the captured checkout and call commit_context there."
|
|
2160
|
-
}));
|
|
2161
|
-
}
|
|
2162
|
-
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
2163
|
-
const rawWorkdir = parsed.rawInput.workdir;
|
|
2164
|
-
const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
|
|
2165
|
-
const targetGitRoot = findGitRoot(effectiveWorkdir);
|
|
2166
|
-
const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
|
|
2167
|
-
const baseline = yield* load(ctx, scope);
|
|
2168
|
-
const expectedDir = targetGitRoot ?? effectiveWorkdir;
|
|
2169
|
-
const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
|
|
2170
|
-
if (!baselineValid || baseline === undefined) {
|
|
2171
|
-
const relWorkdir = relative2(sessionDirectory, expectedDir);
|
|
2172
|
-
const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
|
|
2173
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
2174
|
-
message: `[commit-guard] No published baseline for ${expectedDir}. Call commit_context({ workdir: ${workdirHint} }), then run the returned command immediately, unchanged, in the foreground with that workdir and background:false. Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing. RECEIPT_OK alone is insufficient.`
|
|
2175
|
-
}));
|
|
2176
|
-
}
|
|
2177
|
-
if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
2178
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
2179
|
-
message: signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")
|
|
2180
|
-
}));
|
|
2181
|
-
}
|
|
2182
|
-
yield* Effect2.try({
|
|
2183
|
-
try: () => {
|
|
2184
|
-
validateGitCommits(parsed.invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, parsed.command);
|
|
2185
|
-
},
|
|
2186
|
-
catch: (error) => new Tool.Error({
|
|
2187
|
-
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
2188
|
-
})
|
|
2189
|
-
});
|
|
2190
|
-
return yield* Effect2.void;
|
|
2191
|
-
});
|
|
2192
|
-
}).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
|
|
2193
|
-
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
2194
|
-
}))));
|
|
2195
|
-
yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* afterExecution() {
|
|
2196
|
-
if (event.tool !== "shell") {
|
|
2197
|
-
return;
|
|
2198
|
-
}
|
|
2199
|
-
const attempt = [...pending.values()].find((item) => item.claimed?.id === event.id && item.claimed?.messageID === event.messageID && item.sessionID === event.sessionID && item.agent === event.agent);
|
|
2200
|
-
if (attempt === undefined) {
|
|
2201
|
-
return;
|
|
2202
|
-
}
|
|
2203
|
-
let published = false;
|
|
2204
|
-
let captured;
|
|
2205
|
-
let reason = "capture import or storage failed";
|
|
2206
|
-
yield* Effect2.gen(function* publishCapture() {
|
|
2207
|
-
reason = "shell result did not complete successfully";
|
|
2208
|
-
if (event.status !== "completed") {
|
|
2209
|
-
return;
|
|
2210
|
-
}
|
|
2211
|
-
reason = "capture was superseded by a refresh";
|
|
2212
|
-
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
|
|
2213
|
-
return;
|
|
2214
|
-
}
|
|
2215
|
-
const metadata = event.result.metadata;
|
|
2216
|
-
reason = "shell result lacks verified foreground completion metadata";
|
|
2217
|
-
if (!isRecord(metadata)) {
|
|
2218
|
-
return;
|
|
2219
|
-
}
|
|
2220
|
-
if (metadata.status !== "completed" || metadata.exit !== 0 || metadata.truncated !== false || metadata.timeout !== undefined && metadata.timeout !== false || metadata.shellID !== undefined || Object.keys(metadata).some((key) => !["status", "exit", "truncated", "timeout"].includes(key))) {
|
|
2221
|
-
return;
|
|
2222
|
-
}
|
|
2223
|
-
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {});
|
|
2224
|
-
reason = "capture session or workspace no longer matches";
|
|
2225
|
-
if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) {
|
|
2226
|
-
return;
|
|
2227
|
-
}
|
|
2228
|
-
reason = "private artifact is invalid or incomplete (END required)";
|
|
2229
|
-
const baseline = yield* Effect2.try({
|
|
2230
|
-
try: () => importCapture(attempt),
|
|
2231
|
-
catch: () => new Error("Invalid capture")
|
|
2232
|
-
});
|
|
2233
|
-
if (baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) {
|
|
2234
|
-
return;
|
|
2235
|
-
}
|
|
2236
|
-
reason = "capture storage failed or its counter changed";
|
|
2237
|
-
published = yield* publish(ctx, attempt, generation, baseline);
|
|
2238
|
-
if (published) {
|
|
2239
|
-
captured = baseline;
|
|
2240
|
-
failures.delete(attempt.scope);
|
|
2241
|
-
yield* recordState(ctx, attempt, "published");
|
|
2242
|
-
}
|
|
2243
|
-
}).pipe(Effect2.onExit(() => Effect2.gen(function* finalizeCapture() {
|
|
2244
|
-
if (pending.get(attempt.scope) === attempt) {
|
|
2245
|
-
pending.delete(attempt.scope);
|
|
2246
|
-
}
|
|
2247
|
-
if (!published) {
|
|
2248
|
-
rememberFailure(attempt.scope, reason);
|
|
2249
|
-
yield* recordState(ctx, attempt, "failed", reason).pipe(Effect2.catchCause(() => Effect2.void));
|
|
2250
|
-
yield* invalidateOwned(ctx, attempt);
|
|
2251
|
-
}
|
|
2252
|
-
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
2253
|
-
cleanup(attempt);
|
|
2254
|
-
})))), Effect2.catchCause(() => Effect2.void));
|
|
2255
|
-
const note = published && captured !== undefined ? baselineGuidance(captured, config) : `[commit-guard] This capture did not publish a usable baseline: ${reason.slice(0, 256)}.
|
|
2256
|
-
` + `RECEIPT_OK alone does not authorize a commit.
|
|
2257
|
-
` + "Call commit_context with the same workdir for status and next steps.";
|
|
2258
|
-
if (event.status === "error") {
|
|
2259
|
-
event.error = new Tool.Error({
|
|
2260
|
-
error: event.error.error,
|
|
2261
|
-
metadata: event.error.metadata,
|
|
2262
|
-
message: `${event.error.message}
|
|
2263
|
-
|
|
2264
|
-
${note}`
|
|
2265
|
-
});
|
|
2266
|
-
} else {
|
|
2267
|
-
event.result = appendCaptureNote(event.result, note);
|
|
2268
|
-
}
|
|
2269
|
-
}));
|
|
1985
|
+
yield* ctx.tool.hook("execute.before", (event) => handleBeforeExecute(state, event));
|
|
1986
|
+
yield* ctx.tool.hook("execute.after", (event) => handleAfterExecute(state, event));
|
|
2270
1987
|
})
|
|
2271
1988
|
});
|
|
2272
1989
|
var plugin_default = plugin;
|
|
2273
|
-
var captureInstructions = function captureInstructions(attempt, status) {
|
|
2274
|
-
return `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} and background:false. ` + 'Do not wrap it or chain another command onto it. Commit after the shell result reports "Frozen commit baseline"; ' + "otherwise call commit_context again with the same workdir before committing. " + `RECEIPT_OK confirms only that the artifact was written, not that the baseline was published:
|
|
2275
|
-
${attempt.command}`;
|
|
2276
|
-
};
|
|
2277
|
-
var baselineGuidance = function baselineGuidance(baseline, config) {
|
|
2278
|
-
if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
2279
|
-
return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey");
|
|
2280
|
-
}
|
|
2281
|
-
const observed = [
|
|
2282
|
-
...new Set(baseline.messages.map((message) => /^(?<scope>[a-zA-Z0-9_./-]{1,40}): /u.exec(message.split(`
|
|
2283
|
-
`)[0])?.[1]).filter((value) => value !== undefined))
|
|
2284
|
-
].slice(0, 3);
|
|
2285
|
-
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
|
|
2286
|
-
` : "";
|
|
2287
|
-
const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
|
|
2288
|
-
const signoff = baseline.gpgsign === "true" ? "Add -s or --signoff." : "Signoff is not required; add it only if repository instructions require it.";
|
|
2289
|
-
return `[commit-guard] Frozen commit baseline for ${baseline.directory.slice(0, 4096)}.
|
|
2290
|
-
` + `Use <scope>: <subject>${config.requireScope ? " (required)" : " (optional)"}; maximum line length: ${config.maxLineLength || "unlimited"}.
|
|
2291
|
-
` + `${scopes}
|
|
2292
|
-
${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
|
|
2293
|
-
` + `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.
|
|
2294
|
-
` + `A second commit_context call is optional.
|
|
2295
|
-
` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.";
|
|
2296
|
-
};
|
|
2297
|
-
var appendCaptureNote = function appendCaptureNote(result, note) {
|
|
2298
|
-
const content = isJSONString(result.content) ? [{ type: "text", text: result.content }] : result.content ?? [];
|
|
2299
|
-
const rawOutput = result.output;
|
|
2300
|
-
const output = Schema2.is(Schema2.Json)(rawOutput) ? rawOutput : undefined;
|
|
2301
|
-
const annotated = {
|
|
2302
|
-
...result,
|
|
2303
|
-
content: [...content, { type: "text", text: note }]
|
|
2304
|
-
};
|
|
2305
|
-
if (isRecord(output) && isJSONString(output.output)) {
|
|
2306
|
-
return {
|
|
2307
|
-
...annotated,
|
|
2308
|
-
output: {
|
|
2309
|
-
...Object.fromEntries(Object.entries(output)),
|
|
2310
|
-
output: `${output.output}
|
|
2311
|
-
|
|
2312
|
-
${note}`
|
|
2313
|
-
}
|
|
2314
|
-
};
|
|
2315
|
-
}
|
|
2316
|
-
return annotated;
|
|
2317
|
-
};
|
|
2318
|
-
var signingError = function signingError(setting) {
|
|
2319
|
-
return `[commit-guard] Git could not read ${setting} as valid. Repeating the capture will not fix it. Inspect with git config --show-origin --get-all ${setting}; fix the value without changing the intended signing policy, then call commit_context with refresh:true.`;
|
|
2320
|
-
};
|
|
2321
1990
|
export {
|
|
2322
1991
|
plugin_default as default
|
|
2323
1992
|
};
|