opencode-commit-guard 1.0.6 → 1.1.0
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 +25 -6
- package/dist/index.js +1566 -831
- package/package.json +31 -29
- package/index.ts +0 -1
- package/src/capture.ts +0 -415
- package/src/config.ts +0 -78
- package/src/plugin.ts +0 -418
- package/src/scope.ts +0 -1
- package/src/shell.ts +0 -932
- package/src/types.ts +0 -67
- package/src/validator.ts +0 -197
package/dist/index.js
CHANGED
|
@@ -1,32 +1,44 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
// src/plugin.ts
|
|
3
|
-
import { Plugin } from "@opencode/plugin/effect";
|
|
4
|
-
import { Tool } from "@opencode/schema/tool";
|
|
5
|
-
import { Effect as Effect2 } from "effect";
|
|
6
3
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
7
4
|
import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
|
|
8
|
-
import
|
|
5
|
+
import path from "path";
|
|
6
|
+
import { Plugin, Tool } from "@opencode/plugin/effect";
|
|
7
|
+
import { Effect as Effect2, Schema as Schema2 } from "effect";
|
|
9
8
|
|
|
10
9
|
// src/capture.ts
|
|
11
10
|
import { createHash, randomUUID } from "crypto";
|
|
12
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
closeSync,
|
|
13
|
+
constants,
|
|
14
|
+
existsSync,
|
|
15
|
+
fstatSync,
|
|
16
|
+
mkdtempSync,
|
|
17
|
+
openSync,
|
|
18
|
+
readdirSync,
|
|
19
|
+
readSync,
|
|
20
|
+
realpathSync,
|
|
21
|
+
rmSync,
|
|
22
|
+
statSync
|
|
23
|
+
} from "fs";
|
|
13
24
|
import { tmpdir } from "os";
|
|
14
|
-
import
|
|
25
|
+
import nodePath from "path";
|
|
26
|
+
import { gzipSync } from "zlib";
|
|
15
27
|
import { Effect, Semaphore } from "effect";
|
|
16
28
|
|
|
17
29
|
// src/types.ts
|
|
18
|
-
function isJSONString(value) {
|
|
30
|
+
var isJSONString = function isJSONString(value) {
|
|
19
31
|
return Object.prototype.toString.call(value) === "[object String]";
|
|
20
|
-
}
|
|
21
|
-
function isJSONNumber(value) {
|
|
32
|
+
};
|
|
33
|
+
var isJSONNumber = function isJSONNumber(value) {
|
|
22
34
|
return Object.prototype.toString.call(value) === "[object Number]";
|
|
23
|
-
}
|
|
24
|
-
function isJSONBoolean(value) {
|
|
35
|
+
};
|
|
36
|
+
var isJSONBoolean = function isJSONBoolean(value) {
|
|
25
37
|
return Object.prototype.toString.call(value) === "[object Boolean]";
|
|
26
|
-
}
|
|
27
|
-
function isRecord(value) {
|
|
38
|
+
};
|
|
39
|
+
var isRecord = function isRecord(value) {
|
|
28
40
|
return value instanceof Object && !Array.isArray(value);
|
|
29
|
-
}
|
|
41
|
+
};
|
|
30
42
|
var defaultConfig = {
|
|
31
43
|
requireScope: true,
|
|
32
44
|
allowedScopes: undefined,
|
|
@@ -35,16 +47,17 @@ var defaultConfig = {
|
|
|
35
47
|
};
|
|
36
48
|
|
|
37
49
|
// src/capture.ts
|
|
50
|
+
var { dirname, isAbsolute, join, relative, resolve } = nodePath;
|
|
38
51
|
var version = 1;
|
|
39
52
|
var maxBytes = 262144;
|
|
40
53
|
var captureTimeout = 20000;
|
|
41
54
|
var policy = "commit-guard-context-v1";
|
|
42
55
|
var storageLock = Semaphore.makeUnsafe(1);
|
|
43
|
-
function digest(text) {
|
|
56
|
+
var digest = function digest(text) {
|
|
44
57
|
return createHash("sha256").update(text).digest("hex");
|
|
45
|
-
}
|
|
46
|
-
function scopeFor(ctx, sessionID, config, targetDir) {
|
|
47
|
-
const location = ctx
|
|
58
|
+
};
|
|
59
|
+
var scopeFor = function scopeFor(ctx, sessionID, config, targetDir) {
|
|
60
|
+
const { location } = ctx;
|
|
48
61
|
const directory = targetDir ?? location.directory;
|
|
49
62
|
const root = findGitRoot(directory) ?? realpathSync(directory);
|
|
50
63
|
return digest(JSON.stringify([
|
|
@@ -58,15 +71,15 @@ function scopeFor(ctx, sessionID, config, targetDir) {
|
|
|
58
71
|
config.allowedScopes ?? null,
|
|
59
72
|
config.maxLineLength
|
|
60
73
|
]));
|
|
61
|
-
}
|
|
62
|
-
function isGitDirectory(dir) {
|
|
74
|
+
};
|
|
75
|
+
var isGitDirectory = function isGitDirectory(dir) {
|
|
63
76
|
try {
|
|
64
77
|
return existsSync(join(dir, ".git"));
|
|
65
78
|
} catch {
|
|
66
79
|
return false;
|
|
67
80
|
}
|
|
68
|
-
}
|
|
69
|
-
function findGitRoot(startDir) {
|
|
81
|
+
};
|
|
82
|
+
var findGitRoot = function findGitRoot(startDir) {
|
|
70
83
|
let current;
|
|
71
84
|
try {
|
|
72
85
|
current = realpathSync(startDir);
|
|
@@ -84,19 +97,22 @@ function findGitRoot(startDir) {
|
|
|
84
97
|
current = parent;
|
|
85
98
|
}
|
|
86
99
|
return;
|
|
87
|
-
}
|
|
88
|
-
function findSubRepos(dir, maxDepth = 2) {
|
|
100
|
+
};
|
|
101
|
+
var findSubRepos = function findSubRepos(dir, maxDepth = 2) {
|
|
89
102
|
const repos = [];
|
|
90
|
-
function search(currentDir, currentDepth) {
|
|
91
|
-
if (currentDepth > maxDepth)
|
|
103
|
+
const search = function search(currentDir, currentDepth) {
|
|
104
|
+
if (currentDepth > maxDepth) {
|
|
92
105
|
return;
|
|
106
|
+
}
|
|
93
107
|
try {
|
|
94
108
|
const entries = readdirSync(currentDir, { withFileTypes: true });
|
|
95
109
|
for (const entry of entries) {
|
|
96
|
-
if (!entry.isDirectory() && !entry.isSymbolicLink())
|
|
110
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
97
111
|
continue;
|
|
98
|
-
|
|
112
|
+
}
|
|
113
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") {
|
|
99
114
|
continue;
|
|
115
|
+
}
|
|
100
116
|
const fullPath = join(currentDir, entry.name);
|
|
101
117
|
if (isGitDirectory(fullPath)) {
|
|
102
118
|
repos.push(fullPath);
|
|
@@ -105,11 +121,11 @@ function findSubRepos(dir, maxDepth = 2) {
|
|
|
105
121
|
}
|
|
106
122
|
}
|
|
107
123
|
} catch {}
|
|
108
|
-
}
|
|
124
|
+
};
|
|
109
125
|
search(dir, 1);
|
|
110
126
|
return repos;
|
|
111
|
-
}
|
|
112
|
-
function resolveTargetWorkdir(baseDir, requestedDir) {
|
|
127
|
+
};
|
|
128
|
+
var resolveTargetWorkdir = function resolveTargetWorkdir(baseDir, requestedDir) {
|
|
113
129
|
if (requestedDir !== undefined) {
|
|
114
130
|
const resolvedDir = resolve(baseDir, requestedDir);
|
|
115
131
|
if (!existsSync(resolvedDir)) {
|
|
@@ -124,7 +140,9 @@ function resolveTargetWorkdir(baseDir, requestedDir) {
|
|
|
124
140
|
}
|
|
125
141
|
const gitRoot = findGitRoot(resolvedDir);
|
|
126
142
|
if (gitRoot === undefined) {
|
|
127
|
-
return {
|
|
143
|
+
return {
|
|
144
|
+
error: `Directory "${requestedDir}" is not a Git repository or inside one.`
|
|
145
|
+
};
|
|
128
146
|
}
|
|
129
147
|
return { workdir: realpathSync(resolvedDir) };
|
|
130
148
|
}
|
|
@@ -147,93 +165,121 @@ function resolveTargetWorkdir(baseDir, requestedDir) {
|
|
|
147
165
|
Specify which repository to target with the 'workdir' option, for example:
|
|
148
166
|
commit_context({ workdir: "${relative(baseDir, subRepos[0])}" })`
|
|
149
167
|
};
|
|
150
|
-
}
|
|
151
|
-
function counterKey(scope) {
|
|
168
|
+
};
|
|
169
|
+
var counterKey = function counterKey(scope) {
|
|
152
170
|
return `counter/${scope}`;
|
|
153
|
-
}
|
|
154
|
-
function prefix(scope) {
|
|
171
|
+
};
|
|
172
|
+
var prefix = function prefix(scope) {
|
|
155
173
|
return `snap/${scope}/`;
|
|
156
|
-
}
|
|
157
|
-
function counter(ctx, scope) {
|
|
158
|
-
return Effect.gen(function* () {
|
|
174
|
+
};
|
|
175
|
+
var counter = function counter(ctx, scope) {
|
|
176
|
+
return Effect.gen(function* readCounter() {
|
|
159
177
|
const value = yield* ctx.storage.get(counterKey(scope));
|
|
160
|
-
if (value === undefined)
|
|
178
|
+
if (value === undefined) {
|
|
161
179
|
return 0;
|
|
180
|
+
}
|
|
162
181
|
return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : -1;
|
|
163
182
|
});
|
|
164
|
-
}
|
|
165
|
-
function invalidate(ctx, scope) {
|
|
166
|
-
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
183
|
+
};
|
|
184
|
+
var invalidate = function invalidate(ctx, scope) {
|
|
185
|
+
return storageLock.withPermits(1)(Effect.gen(function* incrementCounter() {
|
|
167
186
|
const previous = yield* counter(ctx, scope);
|
|
168
187
|
const next = previous < 0 ? 1 : previous + 1;
|
|
169
188
|
yield* ctx.storage.set(counterKey(scope), next);
|
|
170
189
|
return next;
|
|
171
190
|
}));
|
|
172
|
-
}
|
|
173
|
-
function invalidateOwned(ctx, attempt) {
|
|
174
|
-
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
191
|
+
};
|
|
192
|
+
var invalidateOwned = function invalidateOwned(ctx, attempt) {
|
|
193
|
+
return storageLock.withPermits(1)(Effect.gen(function* invalidateAttempt() {
|
|
175
194
|
if ((yield* counter(ctx, attempt.scope)) === attempt.counter) {
|
|
176
195
|
yield* ctx.storage.set(counterKey(attempt.scope), attempt.counter + 1);
|
|
177
196
|
}
|
|
178
197
|
}));
|
|
179
|
-
}
|
|
180
|
-
function recordState(ctx, attempt, state, reason = "") {
|
|
181
|
-
return storageLock.withPermits(1)(Effect.gen(function* () {
|
|
182
|
-
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
|
|
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) {
|
|
183
202
|
return;
|
|
184
|
-
|
|
203
|
+
}
|
|
204
|
+
yield* ctx.storage.set(`state/${attempt.scope}`, {
|
|
205
|
+
state,
|
|
206
|
+
reason: reason.slice(0, 256)
|
|
207
|
+
});
|
|
185
208
|
}));
|
|
186
|
-
}
|
|
187
|
-
function captureStatus(ctx, scope) {
|
|
188
|
-
return Effect.gen(function* () {
|
|
209
|
+
};
|
|
210
|
+
var captureStatus = function captureStatus(ctx, scope) {
|
|
211
|
+
return Effect.gen(function* readCaptureStatus() {
|
|
189
212
|
const value = yield* ctx.storage.get(`state/${scope}`);
|
|
190
|
-
if (!isRecord(value))
|
|
213
|
+
if (!isRecord(value)) {
|
|
191
214
|
return "";
|
|
192
|
-
|
|
215
|
+
}
|
|
216
|
+
if (value.state === "expired") {
|
|
193
217
|
return "The previous capture expired before its command was claimed; no matching shell result was observed. ";
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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") {
|
|
197
223
|
return "The previous capture was interrupted before publication. ";
|
|
224
|
+
}
|
|
198
225
|
return "";
|
|
199
226
|
});
|
|
200
|
-
}
|
|
201
|
-
function validBaseline(value) {
|
|
202
|
-
if (!isRecord(value))
|
|
227
|
+
};
|
|
228
|
+
var validBaseline = function validBaseline(value) {
|
|
229
|
+
if (!isRecord(value)) {
|
|
203
230
|
return false;
|
|
204
|
-
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
|
|
231
|
+
}
|
|
232
|
+
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
|
+
};
|
|
234
|
+
var load = function load(ctx, scope) {
|
|
235
|
+
return storageLock.withPermits(1)(Effect.gen(function* readBaseline() {
|
|
208
236
|
const current = yield* counter(ctx, scope);
|
|
209
|
-
if (current < 0)
|
|
210
|
-
return;
|
|
237
|
+
if (current < 0) {
|
|
238
|
+
return yield* Effect.succeed(undefined);
|
|
239
|
+
}
|
|
211
240
|
let after;
|
|
212
241
|
let newest;
|
|
213
242
|
do {
|
|
214
|
-
const page = yield* ctx.storage.scan({
|
|
243
|
+
const page = yield* ctx.storage.scan({
|
|
244
|
+
prefix: prefix(scope),
|
|
245
|
+
after,
|
|
246
|
+
limit: 100
|
|
247
|
+
});
|
|
215
248
|
for (const record of page.entries) {
|
|
216
249
|
const raw = record.value;
|
|
217
|
-
if (!isRecord(raw) || raw
|
|
250
|
+
if (!isRecord(raw) || raw.schema !== version || raw.scope !== scope || raw.counter !== current || !isJSONString(raw.generation) || !isJSONString(raw.sequence) || !isJSONString(raw.checksum) || !validBaseline(raw.baseline)) {
|
|
218
251
|
continue;
|
|
219
|
-
|
|
220
|
-
|
|
252
|
+
}
|
|
253
|
+
const { baseline } = raw;
|
|
254
|
+
if (digest(JSON.stringify([
|
|
255
|
+
version,
|
|
256
|
+
scope,
|
|
257
|
+
current,
|
|
258
|
+
raw.generation,
|
|
259
|
+
raw.sequence,
|
|
260
|
+
baseline
|
|
261
|
+
])) !== raw.checksum) {
|
|
221
262
|
continue;
|
|
222
|
-
|
|
223
|
-
|
|
263
|
+
}
|
|
264
|
+
if (newest === undefined || raw.sequence > newest.sequence) {
|
|
265
|
+
newest = { sequence: raw.sequence, baseline };
|
|
266
|
+
}
|
|
224
267
|
}
|
|
225
268
|
after = page.next;
|
|
226
269
|
} while (after !== undefined);
|
|
227
270
|
return newest?.baseline;
|
|
228
271
|
}));
|
|
229
|
-
}
|
|
230
|
-
function captureCommand(path) {
|
|
272
|
+
};
|
|
273
|
+
var captureCommand = function captureCommand(path) {
|
|
274
|
+
if (process.platform === "win32") {
|
|
275
|
+
return windowsCaptureCommand(path);
|
|
276
|
+
}
|
|
231
277
|
const quoted = `'${path.replaceAll("'", "'\\''")}'`;
|
|
232
|
-
|
|
278
|
+
const script = `set -euo pipefail
|
|
233
279
|
ulimit -f 256
|
|
234
280
|
out=$1
|
|
235
281
|
printf "CTX1\\n" > "$out"
|
|
236
|
-
field() { "$@" 2>/dev/null | base64 -
|
|
282
|
+
field() { "$@" 2>/dev/null | base64 | tr -d "\\r\\n" >> "$out"; printf "\\n" >> "$out"; }
|
|
237
283
|
field git rev-parse --show-toplevel
|
|
238
284
|
field git rev-parse --absolute-git-dir
|
|
239
285
|
field git rev-parse --path-format=absolute --git-common-dir
|
|
@@ -242,9 +288,100 @@ if git rev-parse --verify HEAD >/dev/null 2>&1; then printf "head\\n" >> "$out";
|
|
|
242
288
|
if git config --type=bool --get commit.gpgsign >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --type=bool --get commit.gpgsign; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
|
|
243
289
|
if git config --get user.signingkey >/dev/null 2>&1; then printf "set\\n" >> "$out"; field git config --get user.signingkey; else status=$?; if [ "$status" -eq 1 ]; then printf "unset\\n\\n" >> "$out"; else printf "error\\n\\n" >> "$out"; fi; fi
|
|
244
290
|
printf "END\\n" >> "$out"
|
|
245
|
-
printf "RECEIPT_OK\\n"
|
|
291
|
+
printf "RECEIPT_OK\\n"`;
|
|
292
|
+
return `bash -c 'set -m
|
|
293
|
+
bash -c "$1" bash "$2" &
|
|
294
|
+
worker=$!
|
|
295
|
+
(
|
|
296
|
+
sleep 15 &
|
|
297
|
+
timer=$!
|
|
298
|
+
trap "kill $timer 2>/dev/null" EXIT
|
|
299
|
+
trap "exit 0" TERM
|
|
300
|
+
wait "$timer"
|
|
301
|
+
kill -KILL -- "-$worker" 2>/dev/null
|
|
302
|
+
) &
|
|
303
|
+
watchdog=$!
|
|
304
|
+
wait "$worker"
|
|
305
|
+
status=$?
|
|
306
|
+
kill "$watchdog" 2>/dev/null
|
|
307
|
+
wait "$watchdog" 2>/dev/null
|
|
308
|
+
exit "$status"' bash '${script.replaceAll("'", "'\\''")}' ${quoted} 2>/dev/null`;
|
|
309
|
+
};
|
|
310
|
+
var windowsCaptureCommand = function windowsCaptureCommand(path) {
|
|
311
|
+
const script = `$ErrorActionPreference = 'Stop'
|
|
312
|
+
$clock = [Diagnostics.Stopwatch]::StartNew()
|
|
313
|
+
$lines = [Collections.Generic.List[string]]::new()
|
|
314
|
+
$lines.Add('CTX1')
|
|
315
|
+
function gitResult([string]$arguments) {
|
|
316
|
+
$info = [Diagnostics.ProcessStartInfo]::new('git', $arguments)
|
|
317
|
+
$info.UseShellExecute = $false
|
|
318
|
+
$info.CreateNoWindow = $true
|
|
319
|
+
$info.RedirectStandardOutput = $true
|
|
320
|
+
$info.RedirectStandardError = $true
|
|
321
|
+
$p = [Diagnostics.Process]::new()
|
|
322
|
+
$p.StartInfo = $info
|
|
323
|
+
$memory = [IO.MemoryStream]::new()
|
|
324
|
+
try {
|
|
325
|
+
if (!$p.Start()) { throw 'Git did not start' }
|
|
326
|
+
$p.BeginErrorReadLine()
|
|
327
|
+
$buffer = [byte[]]::new(4096)
|
|
328
|
+
while ($true) {
|
|
329
|
+
$task = $p.StandardOutput.BaseStream.ReadAsync($buffer, 0, $buffer.Length)
|
|
330
|
+
$remaining = 15000 - [int]$clock.ElapsedMilliseconds
|
|
331
|
+
if ($remaining -le 0 -or !$task.Wait($remaining)) { throw 'Capture timed out' }
|
|
332
|
+
$count = $task.Result
|
|
333
|
+
if ($count -eq 0) { break }
|
|
334
|
+
if ($memory.Length + $count -gt ${maxBytes}) { throw 'Capture exceeds size limit' }
|
|
335
|
+
$memory.Write($buffer, 0, $count)
|
|
336
|
+
}
|
|
337
|
+
$remaining = 15000 - [int]$clock.ElapsedMilliseconds
|
|
338
|
+
if ($remaining -le 0 -or !$p.WaitForExit($remaining)) { throw 'Capture timed out' }
|
|
339
|
+
return @{ Code = $p.ExitCode; Bytes = $memory.ToArray() }
|
|
340
|
+
} finally {
|
|
341
|
+
if ($p.Id -and !$p.HasExited) { & taskkill.exe /PID $p.Id /T /F > $null 2>&1 }
|
|
342
|
+
$p.Dispose()
|
|
343
|
+
$memory.Dispose()
|
|
344
|
+
}
|
|
246
345
|
}
|
|
247
|
-
function
|
|
346
|
+
function field([string]$arguments) {
|
|
347
|
+
$result = gitResult $arguments
|
|
348
|
+
if ($result.Code -ne 0) { throw 'Git capture failed' }
|
|
349
|
+
$lines.Add([Convert]::ToBase64String($result.Bytes))
|
|
350
|
+
}
|
|
351
|
+
try {
|
|
352
|
+
field 'rev-parse --show-toplevel'
|
|
353
|
+
field 'rev-parse --absolute-git-dir'
|
|
354
|
+
field 'rev-parse --path-format=absolute --git-common-dir'
|
|
355
|
+
$branch = gitResult 'symbolic-ref -q --short HEAD'
|
|
356
|
+
if ($branch.Code -eq 0) { $lines.Add('branch'); $lines.Add([Convert]::ToBase64String($branch.Bytes)) }
|
|
357
|
+
elseif ($branch.Code -eq 1) { $lines.Add('detached'); $lines.Add('') }
|
|
358
|
+
else { throw 'Invalid branch' }
|
|
359
|
+
$head = gitResult 'rev-parse --verify HEAD'
|
|
360
|
+
if ($head.Code -eq 0) {
|
|
361
|
+
$lines.Add('head'); $lines.Add([Convert]::ToBase64String($head.Bytes))
|
|
362
|
+
field 'log -10 -z --format=%B%x00'
|
|
363
|
+
} elseif ($head.Code -eq 128 -and (gitResult 'symbolic-ref -q HEAD').Code -eq 0 -and (gitResult 'status --porcelain').Code -eq 0) {
|
|
364
|
+
$lines.Add('unborn'); $lines.Add(''); $lines.Add('')
|
|
365
|
+
} else { throw 'Invalid HEAD' }
|
|
366
|
+
foreach ($arguments in @('config --type=bool --get commit.gpgsign', 'config --get user.signingkey')) {
|
|
367
|
+
$result = gitResult $arguments
|
|
368
|
+
if ($result.Code -eq 0) { $lines.Add('set'); $lines.Add([Convert]::ToBase64String($result.Bytes)) }
|
|
369
|
+
elseif ($result.Code -eq 1) { $lines.Add('unset'); $lines.Add('') }
|
|
370
|
+
else { $lines.Add('error'); $lines.Add('') }
|
|
371
|
+
}
|
|
372
|
+
$lines.Add('END')
|
|
373
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes(($lines -join "\`n") + "\`n")
|
|
374
|
+
if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge 15000) { throw 'Capture exceeds limits' }
|
|
375
|
+
$path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(path).toString("base64")}'))
|
|
376
|
+
$file = [IO.FileStream]::new($path, [IO.FileMode]::Truncate, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)
|
|
377
|
+
try { $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() }
|
|
378
|
+
[Console]::Write("RECEIPT_OK\`n")
|
|
379
|
+
} catch { exit 1 }`;
|
|
380
|
+
const compressed = gzipSync(Buffer.from(script)).toString("base64");
|
|
381
|
+
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
|
+
return `powershell -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(bootstrap, "utf16le").toString("base64")}`;
|
|
383
|
+
};
|
|
384
|
+
var createPending = function createPending(scope, sessionID, agent, counterValue, workdir) {
|
|
248
385
|
const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
|
|
249
386
|
try {
|
|
250
387
|
const file = join(directory, randomUUID());
|
|
@@ -266,55 +403,99 @@ function createPending(scope, sessionID, agent, counterValue, workdir) {
|
|
|
266
403
|
rmSync(directory, { recursive: true, force: true });
|
|
267
404
|
throw error;
|
|
268
405
|
}
|
|
269
|
-
}
|
|
270
|
-
function cleanup(pending) {
|
|
271
|
-
if (pending.closed === true)
|
|
406
|
+
};
|
|
407
|
+
var cleanup = function cleanup(pending) {
|
|
408
|
+
if (pending.closed === true) {
|
|
272
409
|
return;
|
|
410
|
+
}
|
|
273
411
|
pending.closed = true;
|
|
274
412
|
closeSync(pending.fd);
|
|
275
413
|
rmSync(pending.directory, { recursive: true, force: true });
|
|
276
|
-
}
|
|
277
|
-
function decode(line) {
|
|
278
|
-
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)
|
|
414
|
+
};
|
|
415
|
+
var decode = function decode(line) {
|
|
416
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(line)) {
|
|
279
417
|
throw new Error("Invalid capture framing");
|
|
280
|
-
return Buffer.from(line, "base64").toString("utf8");
|
|
281
|
-
}
|
|
282
|
-
function importCapture(pending) {
|
|
283
|
-
const stat = fstatSync(pending.fd);
|
|
284
|
-
if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
|
|
285
|
-
throw new Error("Invalid private capture artifact");
|
|
286
418
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
419
|
+
return Buffer.from(line, "base64").toString("utf-8");
|
|
420
|
+
};
|
|
421
|
+
var importCapture = function importCapture(pending) {
|
|
422
|
+
const readArtifact = () => {
|
|
423
|
+
const stat = fstatSync(pending.fd);
|
|
424
|
+
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) {
|
|
425
|
+
throw new Error("Invalid private capture artifact");
|
|
426
|
+
}
|
|
427
|
+
const bytes = Buffer.alloc(stat.size);
|
|
428
|
+
if (readSync(pending.fd, bytes, 0, stat.size, 0) !== stat.size) {
|
|
429
|
+
throw new Error("Incomplete private capture artifact");
|
|
430
|
+
}
|
|
431
|
+
const completed = fstatSync(pending.fd);
|
|
432
|
+
if (completed.size !== stat.size || completed.dev !== stat.dev || completed.ino !== stat.ino) {
|
|
433
|
+
throw new Error("Capture changed during import");
|
|
434
|
+
}
|
|
435
|
+
return bytes;
|
|
436
|
+
};
|
|
437
|
+
const bytes = readArtifact();
|
|
438
|
+
const fields = bytes.toString("utf-8").split(`
|
|
294
439
|
`);
|
|
295
|
-
if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "")
|
|
440
|
+
if (fields.length !== 15 || fields[0] !== "CTX1" || fields[13] !== "END" || fields[14] !== "") {
|
|
296
441
|
throw new Error("Incomplete capture");
|
|
297
|
-
|
|
442
|
+
}
|
|
443
|
+
const rawRoot = decode(fields[1]).trimEnd();
|
|
444
|
+
const root = isAbsolute(rawRoot) ? realpathSync(resolve(rawRoot)) : rawRoot;
|
|
298
445
|
const gitDir = decode(fields[2]).trimEnd();
|
|
299
446
|
const commonDir = decode(fields[3]).trimEnd();
|
|
300
447
|
const branch = fields[4] === "branch" ? decode(fields[5]).trimEnd() : null;
|
|
301
448
|
const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
|
|
302
449
|
const rawLog = decode(fields[8]);
|
|
303
450
|
const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
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);
|
|
307
458
|
const value = decode(fields[10]).trim();
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
459
|
+
const readSigningPolicy = () => {
|
|
460
|
+
if (configState === "set" && (value === "true" || value === "false")) {
|
|
461
|
+
return value;
|
|
462
|
+
}
|
|
463
|
+
return configState === "unset" ? "unset" : "error";
|
|
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 {
|
|
474
|
+
directory: root,
|
|
475
|
+
workdir: pending.workdir,
|
|
476
|
+
gitDir,
|
|
477
|
+
commonDir,
|
|
478
|
+
branch,
|
|
479
|
+
head,
|
|
480
|
+
messages,
|
|
481
|
+
gpgsign,
|
|
482
|
+
signingkey
|
|
483
|
+
};
|
|
484
|
+
};
|
|
485
|
+
var publish = function publish(ctx, pending, generation, baseline) {
|
|
486
|
+
return storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
|
|
487
|
+
if ((yield* counter(ctx, pending.scope)) !== pending.counter) {
|
|
315
488
|
return false;
|
|
489
|
+
}
|
|
316
490
|
const sequence = `${Date.now().toString().padStart(15, "0")}-${randomUUID()}`;
|
|
317
|
-
const checksum = digest(JSON.stringify([
|
|
491
|
+
const checksum = digest(JSON.stringify([
|
|
492
|
+
version,
|
|
493
|
+
pending.scope,
|
|
494
|
+
pending.counter,
|
|
495
|
+
generation,
|
|
496
|
+
sequence,
|
|
497
|
+
baseline
|
|
498
|
+
]));
|
|
318
499
|
yield* ctx.storage.set(prefix(pending.scope) + sequence, {
|
|
319
500
|
schema: version,
|
|
320
501
|
scope: pending.scope,
|
|
@@ -326,41 +507,49 @@ function publish(ctx, pending, generation, baseline) {
|
|
|
326
507
|
});
|
|
327
508
|
let after;
|
|
328
509
|
do {
|
|
329
|
-
const page = yield* ctx.storage.scan({
|
|
510
|
+
const page = yield* ctx.storage.scan({
|
|
511
|
+
prefix: prefix(pending.scope),
|
|
512
|
+
after,
|
|
513
|
+
limit: 100
|
|
514
|
+
});
|
|
330
515
|
for (const record of page.entries) {
|
|
331
|
-
if (record.key < prefix(pending.scope) + sequence)
|
|
516
|
+
if (record.key < prefix(pending.scope) + sequence) {
|
|
332
517
|
yield* ctx.storage.remove(record.key);
|
|
518
|
+
}
|
|
333
519
|
}
|
|
334
520
|
after = page.next;
|
|
335
521
|
} while (after !== undefined);
|
|
336
522
|
return true;
|
|
337
523
|
}));
|
|
338
|
-
}
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
// src/config.ts
|
|
527
|
+
import { Schema } from "effect";
|
|
339
528
|
|
|
340
529
|
// src/scope.ts
|
|
341
|
-
var scopePattern = /^([a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(
|
|
530
|
+
var scopePattern = /^(?<scope>[a-zA-Z0-9_./-]+(?:\([a-zA-Z0-9_./-]+\))?):\s+(?<subject>.+)$/u;
|
|
342
531
|
|
|
343
532
|
// src/config.ts
|
|
344
|
-
function parseConfig(options) {
|
|
533
|
+
var parseConfig = function parseConfig(options) {
|
|
345
534
|
if (options === undefined) {
|
|
346
535
|
return defaultConfig;
|
|
347
536
|
}
|
|
348
537
|
if (!isRecord(options)) {
|
|
349
538
|
throw new Error("Invalid plugin options; expected an object.");
|
|
350
539
|
}
|
|
351
|
-
const rawRequireScope = options
|
|
352
|
-
let requireScope = defaultConfig
|
|
540
|
+
const rawRequireScope = options.requireScope;
|
|
541
|
+
let { requireScope } = defaultConfig;
|
|
353
542
|
if (rawRequireScope !== undefined) {
|
|
354
543
|
if (!isJSONBoolean(rawRequireScope)) {
|
|
355
544
|
throw new Error("Invalid plugin option requireScope; expected a boolean.");
|
|
356
545
|
}
|
|
357
546
|
requireScope = rawRequireScope;
|
|
358
547
|
}
|
|
359
|
-
const rawAllowedScopes = options
|
|
548
|
+
const rawAllowedScopes = options.allowedScopes;
|
|
360
549
|
let allowedScopes = defaultConfig.allowedScopes;
|
|
361
550
|
if (rawAllowedScopes !== undefined) {
|
|
362
|
-
if (!Array.
|
|
363
|
-
throw new
|
|
551
|
+
if (!Schema.is(Schema.Array(Schema.Json))(rawAllowedScopes)) {
|
|
552
|
+
throw new TypeError("Invalid plugin option allowedScopes; expected an array of non-empty strings.");
|
|
364
553
|
}
|
|
365
554
|
const scopes = [];
|
|
366
555
|
for (const item of rawAllowedScopes) {
|
|
@@ -374,15 +563,15 @@ function parseConfig(options) {
|
|
|
374
563
|
}
|
|
375
564
|
allowedScopes = scopes.length > 0 ? scopes : undefined;
|
|
376
565
|
}
|
|
377
|
-
const rawMaxLineLength = options
|
|
378
|
-
let maxLineLength = defaultConfig
|
|
566
|
+
const rawMaxLineLength = options.maxLineLength;
|
|
567
|
+
let { maxLineLength } = defaultConfig;
|
|
379
568
|
if (rawMaxLineLength !== undefined) {
|
|
380
569
|
if (!isJSONNumber(rawMaxLineLength) || !Number.isSafeInteger(rawMaxLineLength) || rawMaxLineLength < 0) {
|
|
381
570
|
throw new Error("Invalid plugin option maxLineLength; expected an integer greater than or equal to 0.");
|
|
382
571
|
}
|
|
383
572
|
maxLineLength = rawMaxLineLength;
|
|
384
573
|
}
|
|
385
|
-
if (options
|
|
574
|
+
if (options.requireSignoff !== undefined) {
|
|
386
575
|
throw new Error("Plugin option requireSignoff has been removed; signoff follows the captured effective commit.gpgsign value.");
|
|
387
576
|
}
|
|
388
577
|
return {
|
|
@@ -391,7 +580,7 @@ function parseConfig(options) {
|
|
|
391
580
|
maxLineLength,
|
|
392
581
|
enforceSignoff: defaultConfig.enforceSignoff
|
|
393
582
|
};
|
|
394
|
-
}
|
|
583
|
+
};
|
|
395
584
|
|
|
396
585
|
// src/shell.ts
|
|
397
586
|
var gitGlobalOptionsWithArg = new Set([
|
|
@@ -443,137 +632,372 @@ var commitLongOptionsWithArg = new Set([
|
|
|
443
632
|
"--squash",
|
|
444
633
|
"--template"
|
|
445
634
|
]);
|
|
446
|
-
function isWordSeparator(character) {
|
|
635
|
+
var isWordSeparator = function isWordSeparator(character) {
|
|
447
636
|
return character === " " || character === "\t" || character === "\r" || character === `
|
|
448
|
-
` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")"
|
|
449
|
-
}
|
|
450
|
-
function consumeCommandSubstitution(command, start, nesting = 0) {
|
|
451
|
-
if (nesting > 12)
|
|
452
|
-
throw
|
|
637
|
+
` || character === ";" || character === "&" || character === "|" || character === "(" || character === ")";
|
|
638
|
+
};
|
|
639
|
+
var consumeCommandSubstitution = function consumeCommandSubstitution(command, start, nesting = 0) {
|
|
640
|
+
if (nesting > 12) {
|
|
641
|
+
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
642
|
+
}
|
|
453
643
|
let depth = 1;
|
|
454
644
|
let quote;
|
|
455
645
|
let i = start + 2;
|
|
456
646
|
let atWordStart = true;
|
|
647
|
+
let atCommandStart = true;
|
|
648
|
+
let timeOption = false;
|
|
649
|
+
let arithmeticDepth = command[start + 2] === "(" ? 1 : undefined;
|
|
650
|
+
const pendingHeredocs = [];
|
|
651
|
+
const cases = [];
|
|
457
652
|
while (i < command.length) {
|
|
458
653
|
const character = command[i];
|
|
459
|
-
if (character === undefined)
|
|
654
|
+
if (character === undefined) {
|
|
460
655
|
break;
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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) {
|
|
465
696
|
continue;
|
|
466
697
|
}
|
|
467
|
-
|
|
698
|
+
const consumedEscapeOrHeredoc = (() => {
|
|
468
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
|
+
}
|
|
469
708
|
i += i + 1 < command.length ? 2 : 1;
|
|
470
|
-
|
|
471
|
-
quote = undefined;
|
|
472
|
-
i++;
|
|
473
|
-
} else if (character === "$" && command[i + 1] === "(") {
|
|
474
|
-
i = consumeCommandSubstitution(command, i, nesting + 1).end;
|
|
475
|
-
} else {
|
|
476
|
-
i++;
|
|
709
|
+
return true;
|
|
477
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) {
|
|
478
740
|
continue;
|
|
479
741
|
}
|
|
480
|
-
|
|
481
|
-
if (command[i + 1]
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
}
|
|
493
|
-
if (character === '"') {
|
|
494
|
-
quote = '"';
|
|
495
|
-
atWordStart = false;
|
|
496
|
-
i++;
|
|
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) {
|
|
497
754
|
continue;
|
|
498
755
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
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) {
|
|
503
840
|
continue;
|
|
504
841
|
}
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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;
|
|
509
885
|
}
|
|
510
|
-
if (
|
|
511
|
-
depth++;
|
|
512
|
-
i++;
|
|
513
|
-
atWordStart = true;
|
|
886
|
+
if (consumedParenthesis) {
|
|
514
887
|
continue;
|
|
515
888
|
}
|
|
516
|
-
if (
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
}
|
|
521
|
-
atWordStart = true;
|
|
889
|
+
if ([";", "&", "|", `
|
|
890
|
+
`, ")"].includes(character)) {
|
|
891
|
+
atCommandStart = true;
|
|
892
|
+
timeOption = false;
|
|
522
893
|
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
else
|
|
526
|
-
atWordStart = false;
|
|
527
|
-
i++;
|
|
894
|
+
atWordStart = isWordSeparator(character);
|
|
895
|
+
i += 1;
|
|
528
896
|
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
897
|
+
if (pendingHeredocs.length > 0) {
|
|
898
|
+
throw incompleteHeredoc();
|
|
899
|
+
}
|
|
900
|
+
throw inspectionError(`Unterminated $( substitution starting at character ${start + 1}. Close it with ) or use single quotes for literal text.`);
|
|
901
|
+
};
|
|
902
|
+
var consumeBackticks = function consumeBackticks(command, start, doubleQuoted = false) {
|
|
532
903
|
let content = "";
|
|
533
|
-
for (let i = start + 1;i < command.length; i
|
|
534
|
-
if (command[i] === "`")
|
|
904
|
+
for (let i = start + 1;i < command.length; i += 1) {
|
|
905
|
+
if (command[i] === "`") {
|
|
535
906
|
return { content, end: i + 1 };
|
|
536
|
-
|
|
537
|
-
|
|
907
|
+
}
|
|
908
|
+
if (command[i] === "\\" && (["$", "`", "\\"].includes(command[i + 1] ?? "") || doubleQuoted && command[i + 1] === '"')) {
|
|
909
|
+
i += 1;
|
|
910
|
+
}
|
|
538
911
|
content += command[i];
|
|
539
912
|
}
|
|
540
|
-
throw
|
|
541
|
-
}
|
|
542
|
-
function
|
|
913
|
+
throw inspectionError(`Unterminated backtick substitution starting at character ${start + 1}. Close it, escape a literal backtick as \\\`, or use single quotes.`);
|
|
914
|
+
};
|
|
915
|
+
var consumeQuotedParameter = function consumeQuotedParameter(command, start, nesting = 0) {
|
|
916
|
+
if (nesting > 12) {
|
|
917
|
+
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
918
|
+
}
|
|
919
|
+
let quote = false;
|
|
920
|
+
for (let i = start + 2;i < command.length; i += 1) {
|
|
921
|
+
const character = command[i];
|
|
922
|
+
if (character === "`" || character === "$" && command[i + 1] === "(") {
|
|
923
|
+
throw inspectionError("Cannot inspect command substitutions inside a double-quoted parameter expansion. Run substitutions separately or quote literal text.");
|
|
924
|
+
}
|
|
925
|
+
if (character === "\\") {
|
|
926
|
+
i += 1;
|
|
927
|
+
} else if (character === '"') {
|
|
928
|
+
quote = !quote;
|
|
929
|
+
} else if (character === "$" && command[i + 1] === "{") {
|
|
930
|
+
i = consumeQuotedParameter(command, i, nesting + 1) - 1;
|
|
931
|
+
} else if (character === "}" && !quote) {
|
|
932
|
+
return i + 1;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
throw inspectionError("Cannot parse an incomplete double-quoted parameter expansion. Close its quotes and braces or quote literal text.");
|
|
936
|
+
};
|
|
937
|
+
var inspectionError = function inspectionError(message) {
|
|
938
|
+
return new Error(`[commit-guard] Pre-execution shell inspection failed: ${message}`);
|
|
939
|
+
};
|
|
940
|
+
var ansiEscape = function ansiEscape(command, start) {
|
|
543
941
|
const escaped = command[start + 1] ?? "";
|
|
544
|
-
const simple = new Map(Object.entries({
|
|
545
|
-
|
|
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
|
+
}));
|
|
546
958
|
const literal = simple.get(escaped);
|
|
547
|
-
if (literal !== undefined)
|
|
959
|
+
if (literal !== undefined) {
|
|
548
960
|
return { content: literal, end: start + 2 };
|
|
549
|
-
|
|
961
|
+
}
|
|
962
|
+
if (escaped === "c" && command[start + 2] !== undefined && command[start + 2] !== "'") {
|
|
550
963
|
const character = command[start + 2];
|
|
551
|
-
|
|
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
|
+
};
|
|
552
969
|
}
|
|
553
|
-
const count =
|
|
554
|
-
|
|
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];
|
|
555
976
|
if (digits !== undefined) {
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
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
|
+
}
|
|
559
982
|
const end = start + (count > 0 ? 2 : 1) + digits.length;
|
|
560
|
-
if (count === 0 || escaped === "x")
|
|
983
|
+
if (count === 0 || escaped === "x") {
|
|
561
984
|
return { content: "", byte: code & 255, end };
|
|
985
|
+
}
|
|
562
986
|
return { content: String.fromCodePoint(code), end };
|
|
563
987
|
}
|
|
564
988
|
return { content: `\\${escaped}`, end: start + 2 };
|
|
565
|
-
}
|
|
566
|
-
function pushWord(tokens, value, substitutions, expansion) {
|
|
989
|
+
};
|
|
990
|
+
var pushWord = function pushWord(tokens, value, substitutions, expansion) {
|
|
567
991
|
const token = substitutions.length > 0 ? { type: "word", value, substitutions } : { type: "word", value };
|
|
568
992
|
tokens.push(expansion ? { ...token, expansion: true } : token);
|
|
569
|
-
}
|
|
570
|
-
function heredocSubstitutions(body) {
|
|
993
|
+
};
|
|
994
|
+
var heredocSubstitutions = function heredocSubstitutions(body) {
|
|
571
995
|
const substitutions = [];
|
|
572
|
-
for (let i = 0;i < body.length; i
|
|
573
|
-
if (body[i] === "\\" &&
|
|
574
|
-
i
|
|
996
|
+
for (let i = 0;i < body.length; i += 1) {
|
|
997
|
+
if (body[i] === "\\" && ["\\", "$", "`"].includes(body[i + 1] ?? "")) {
|
|
998
|
+
i += 1;
|
|
575
999
|
} else if (body[i] === "`") {
|
|
576
|
-
throw
|
|
1000
|
+
throw inspectionError("Cannot validate command substitutions in an unquoted heredoc. Quote the delimiter, for example: <<'EOF'.");
|
|
577
1001
|
} else if (body[i] === "$" && body[i + 1] === "(") {
|
|
578
1002
|
const substitution = consumeCommandSubstitution(body, i);
|
|
579
1003
|
substitutions.push(substitution.content);
|
|
@@ -581,232 +1005,363 @@ function heredocSubstitutions(body) {
|
|
|
581
1005
|
}
|
|
582
1006
|
}
|
|
583
1007
|
return substitutions;
|
|
584
|
-
}
|
|
585
|
-
function
|
|
1008
|
+
};
|
|
1009
|
+
var incompleteHeredoc = function incompleteHeredoc() {
|
|
1010
|
+
return inspectionError("Cannot validate an incomplete heredoc. Close its delimiter on a separate line before running the command.");
|
|
1011
|
+
};
|
|
1012
|
+
var consumeHeredoc = function consumeHeredoc(command, start, heredoc) {
|
|
1013
|
+
let i = start;
|
|
1014
|
+
let body = "";
|
|
1015
|
+
while (i < command.length) {
|
|
1016
|
+
let line = "";
|
|
1017
|
+
let newline = false;
|
|
1018
|
+
while (i < command.length) {
|
|
1019
|
+
const lineEnd = command.indexOf(`
|
|
1020
|
+
`, i);
|
|
1021
|
+
const end = lineEnd === -1 ? command.length : lineEnd;
|
|
1022
|
+
const physicalLine = command.slice(i, end);
|
|
1023
|
+
const backslashes = /\\+$/u.exec(physicalLine)?.[0].length ?? 0;
|
|
1024
|
+
newline = lineEnd !== -1;
|
|
1025
|
+
i = newline ? end + 1 : end;
|
|
1026
|
+
if (!heredoc.quoted && newline && backslashes % 2 === 1) {
|
|
1027
|
+
line += physicalLine.slice(0, -1);
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
line += physicalLine;
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
if (heredoc.stripTabs) {
|
|
1034
|
+
line = line.replace(/^\t+/u, "");
|
|
1035
|
+
}
|
|
1036
|
+
if (line === heredoc.delimiter) {
|
|
1037
|
+
return { content: body, end: i };
|
|
1038
|
+
}
|
|
1039
|
+
body += line + (newline ? `
|
|
1040
|
+
` : "");
|
|
1041
|
+
}
|
|
1042
|
+
throw incompleteHeredoc();
|
|
1043
|
+
};
|
|
1044
|
+
var tokenizeShell = function tokenizeShell(command) {
|
|
1045
|
+
return tokenizeShellInput(command).tokens;
|
|
1046
|
+
};
|
|
1047
|
+
var tokenizeShellInput = function tokenizeShellInput(command, start = 0, delimiterOnly = false, nesting = 0) {
|
|
586
1048
|
const tokens = [];
|
|
587
1049
|
const pendingHeredocs = [];
|
|
588
1050
|
let pendingDelimiter;
|
|
589
|
-
let i =
|
|
1051
|
+
let i = start;
|
|
590
1052
|
while (i < command.length) {
|
|
591
1053
|
const character = command[i];
|
|
592
|
-
if (character === undefined)
|
|
1054
|
+
if (character === undefined) {
|
|
593
1055
|
break;
|
|
594
|
-
if (character === " " || character === "\t" || character === "\r") {
|
|
595
|
-
i++;
|
|
596
|
-
continue;
|
|
597
1056
|
}
|
|
598
|
-
|
|
1057
|
+
const skippedTrivia = (() => {
|
|
1058
|
+
if (character === " " || character === "\t" || character === "\r") {
|
|
1059
|
+
i += 1;
|
|
1060
|
+
return true;
|
|
1061
|
+
}
|
|
1062
|
+
if (character === "\\" && command[i + 1] === `
|
|
599
1063
|
`) {
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
`)
|
|
606
|
-
|
|
1064
|
+
i += 2;
|
|
1065
|
+
return true;
|
|
1066
|
+
}
|
|
1067
|
+
if (character === "#") {
|
|
1068
|
+
while (i < command.length && command[i] !== `
|
|
1069
|
+
`) {
|
|
1070
|
+
i += 1;
|
|
1071
|
+
}
|
|
1072
|
+
return true;
|
|
1073
|
+
}
|
|
1074
|
+
return false;
|
|
1075
|
+
})();
|
|
1076
|
+
if (skippedTrivia) {
|
|
607
1077
|
continue;
|
|
608
1078
|
}
|
|
609
1079
|
const twoCharacters = command.slice(i, i + 2);
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
if (
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
heredoc: { body, quoted: heredoc.quoted },
|
|
637
|
-
substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body)
|
|
638
|
-
};
|
|
639
|
-
break;
|
|
1080
|
+
let standaloneBrace = false;
|
|
1081
|
+
(() => {
|
|
1082
|
+
if (delimiterOnly && pendingDelimiter !== undefined && (isWordSeparator(character) || character === "<" || character === ">")) {
|
|
1083
|
+
throw incompleteHeredoc();
|
|
1084
|
+
}
|
|
1085
|
+
})();
|
|
1086
|
+
if (character === "{" || character === "}") {
|
|
1087
|
+
const braceCommandPosition = (() => {
|
|
1088
|
+
let commandPosition = true;
|
|
1089
|
+
for (let index = tokens.length - 1;index >= 0; index -= 1) {
|
|
1090
|
+
const token = tokens[index];
|
|
1091
|
+
if (token.type === "operator") {
|
|
1092
|
+
break;
|
|
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;
|
|
640
1106
|
}
|
|
641
1107
|
}
|
|
642
|
-
if (!
|
|
643
|
-
|
|
1108
|
+
if (token.type !== "word" || !commandPrefixes.has(token.value)) {
|
|
1109
|
+
commandPosition = false;
|
|
1110
|
+
break;
|
|
644
1111
|
}
|
|
645
1112
|
}
|
|
646
|
-
|
|
1113
|
+
return commandPosition;
|
|
1114
|
+
})();
|
|
1115
|
+
let braceEnd = i + 1;
|
|
1116
|
+
while (command[braceEnd] === "\\" && command[braceEnd + 1] === `
|
|
1117
|
+
`) {
|
|
1118
|
+
braceEnd += 2;
|
|
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;
|
|
647
1146
|
}
|
|
1147
|
+
return false;
|
|
1148
|
+
})();
|
|
1149
|
+
if (consumedOperator) {
|
|
648
1150
|
continue;
|
|
649
1151
|
}
|
|
650
|
-
const redirectMatch =
|
|
1152
|
+
const redirectMatch = /^(?:\d+)?(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)|^&>>?/u.exec(command.slice(i));
|
|
651
1153
|
if (redirectMatch !== null && redirectMatch[0] !== undefined) {
|
|
652
1154
|
tokens.push({ type: "redirect", value: redirectMatch[0] });
|
|
653
|
-
if (/^\d
|
|
1155
|
+
if (/^\d*<<-?$/u.test(redirectMatch[0])) {
|
|
654
1156
|
pendingDelimiter = tokens.length - 1;
|
|
1157
|
+
}
|
|
655
1158
|
i += redirectMatch[0].length;
|
|
656
1159
|
continue;
|
|
657
1160
|
}
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
1161
|
+
const result = (() => {
|
|
1162
|
+
let value = "";
|
|
1163
|
+
const wordBytes = [];
|
|
1164
|
+
let quoted = false;
|
|
1165
|
+
let unsupportedDelimiter;
|
|
1166
|
+
let expansion = false;
|
|
1167
|
+
const substitutions = [];
|
|
1168
|
+
while (i < command.length) {
|
|
1169
|
+
const current = command[i];
|
|
1170
|
+
if (current === undefined || isWordSeparator(current)) {
|
|
1171
|
+
break;
|
|
1172
|
+
}
|
|
1173
|
+
if (current === "\\" && command[i + 1] === `
|
|
669
1174
|
`) {
|
|
670
|
-
i += 2;
|
|
671
|
-
continue;
|
|
672
|
-
}
|
|
673
|
-
if (current === "\\") {
|
|
674
|
-
quoted = true;
|
|
675
|
-
if (i + 1 < command.length) {
|
|
676
|
-
value += command[i + 1];
|
|
677
1175
|
i += 2;
|
|
678
|
-
|
|
679
|
-
value += "\\";
|
|
680
|
-
i++;
|
|
1176
|
+
continue;
|
|
681
1177
|
}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
quoted = true;
|
|
688
|
-
unsupportedDelimiter = true;
|
|
689
|
-
i += 2;
|
|
690
|
-
const bytes = [];
|
|
691
|
-
let complete = false;
|
|
692
|
-
while (i < command.length) {
|
|
693
|
-
const ansiCharacter = command[i];
|
|
694
|
-
if (ansiCharacter === undefined)
|
|
695
|
-
break;
|
|
696
|
-
if (ansiCharacter === "'") {
|
|
697
|
-
i++;
|
|
698
|
-
complete = true;
|
|
699
|
-
break;
|
|
700
|
-
}
|
|
701
|
-
if (ansiCharacter === "\\" && i + 1 < command.length) {
|
|
702
|
-
const escaped = ansiEscape(command, i);
|
|
703
|
-
bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
|
|
704
|
-
i = escaped.end;
|
|
1178
|
+
if (current === "\\") {
|
|
1179
|
+
quoted = true;
|
|
1180
|
+
if (i + 1 < command.length) {
|
|
1181
|
+
value += command[i + 1];
|
|
1182
|
+
i += 2;
|
|
705
1183
|
} else {
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
i += literal.length;
|
|
1184
|
+
value += "\\";
|
|
1185
|
+
i += 1;
|
|
709
1186
|
}
|
|
1187
|
+
continue;
|
|
710
1188
|
}
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
continue;
|
|
716
|
-
}
|
|
717
|
-
if (current === "'") {
|
|
718
|
-
quoted = true;
|
|
719
|
-
i++;
|
|
720
|
-
while (i < command.length && command[i] !== "'") {
|
|
721
|
-
value += command[i];
|
|
722
|
-
i++;
|
|
723
|
-
}
|
|
724
|
-
if (command[i] !== "'")
|
|
725
|
-
throw new Error("Cannot parse shell quotes reliably. Run git commit directly.");
|
|
726
|
-
i++;
|
|
727
|
-
continue;
|
|
728
|
-
}
|
|
729
|
-
if (current === '"') {
|
|
730
|
-
quoted = true;
|
|
731
|
-
i++;
|
|
732
|
-
while (i < command.length && command[i] !== '"') {
|
|
733
|
-
const quotedCharacter = command[i];
|
|
734
|
-
if (quotedCharacter === undefined)
|
|
735
|
-
break;
|
|
736
|
-
if (quotedCharacter === "\\" && i + 1 < command.length) {
|
|
737
|
-
const escaped = command[i + 1];
|
|
738
|
-
if (escaped === `
|
|
1189
|
+
(() => {
|
|
1190
|
+
if (current === "$") {
|
|
1191
|
+
let quoteStart = i + 1;
|
|
1192
|
+
while (command[quoteStart] === "\\" && command[quoteStart + 1] === `
|
|
739
1193
|
`) {
|
|
740
|
-
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
} else {
|
|
745
|
-
|
|
746
|
-
i += 2;
|
|
1194
|
+
quoteStart += 2;
|
|
1195
|
+
}
|
|
1196
|
+
if (command[quoteStart] === '"') {
|
|
1197
|
+
unsupportedDelimiter = "locale-quoted";
|
|
1198
|
+
} else if (command[quoteStart] === "'") {
|
|
1199
|
+
unsupportedDelimiter = "ANSI-C quoted";
|
|
747
1200
|
}
|
|
748
|
-
} else if (quotedCharacter === "$" && command[i + 1] === "(") {
|
|
749
|
-
const substitution = consumeCommandSubstitution(command, i);
|
|
750
|
-
value += command.slice(i, substitution.end);
|
|
751
|
-
substitutions.push(substitution.content);
|
|
752
|
-
expansion = true;
|
|
753
|
-
i = substitution.end;
|
|
754
|
-
} else if (quotedCharacter === "`") {
|
|
755
|
-
const substitution = consumeBackticks(command, i);
|
|
756
|
-
value += command.slice(i, substitution.end);
|
|
757
|
-
substitutions.push(substitution.content);
|
|
758
|
-
expansion = true;
|
|
759
|
-
i = substitution.end;
|
|
760
|
-
} else {
|
|
761
|
-
if (quotedCharacter === "$" && /[a-zA-Z0-9_{[*#?@!$-]/.test(command[i + 1] ?? ""))
|
|
762
|
-
expansion = true;
|
|
763
|
-
value += quotedCharacter;
|
|
764
|
-
i++;
|
|
765
1201
|
}
|
|
1202
|
+
})();
|
|
1203
|
+
if (current === "$" && command[i + 1] === "'") {
|
|
1204
|
+
(() => {
|
|
1205
|
+
const quoteStart = i;
|
|
1206
|
+
wordBytes.push(...Buffer.from(value));
|
|
1207
|
+
value = "";
|
|
1208
|
+
quoted = true;
|
|
1209
|
+
unsupportedDelimiter = "ANSI-C quoted";
|
|
1210
|
+
i += 2;
|
|
1211
|
+
const bytes = [];
|
|
1212
|
+
let complete = false;
|
|
1213
|
+
while (i < command.length) {
|
|
1214
|
+
const ansiCharacter = command[i];
|
|
1215
|
+
if (ansiCharacter === undefined) {
|
|
1216
|
+
break;
|
|
1217
|
+
}
|
|
1218
|
+
if (ansiCharacter === "'") {
|
|
1219
|
+
i += 1;
|
|
1220
|
+
complete = true;
|
|
1221
|
+
break;
|
|
1222
|
+
}
|
|
1223
|
+
if (ansiCharacter === "\\" && i + 1 < command.length) {
|
|
1224
|
+
const escaped = ansiEscape(command, i);
|
|
1225
|
+
bytes.push(...escaped.byte === undefined ? Buffer.from(escaped.content) : [escaped.byte]);
|
|
1226
|
+
i = escaped.end;
|
|
1227
|
+
} else {
|
|
1228
|
+
const literal = String.fromCodePoint(command.codePointAt(i) ?? 0);
|
|
1229
|
+
bytes.push(...Buffer.from(literal));
|
|
1230
|
+
i += literal.length;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
if (!complete) {
|
|
1234
|
+
throw inspectionError(`Unterminated ANSI-C quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
|
|
1235
|
+
}
|
|
1236
|
+
const nul = bytes.indexOf(0);
|
|
1237
|
+
wordBytes.push(...nul === -1 ? bytes : bytes.slice(0, nul));
|
|
1238
|
+
})();
|
|
1239
|
+
continue;
|
|
766
1240
|
}
|
|
767
|
-
if (
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
1241
|
+
if (current === "'") {
|
|
1242
|
+
(() => {
|
|
1243
|
+
const quoteStart = i;
|
|
1244
|
+
quoted = true;
|
|
1245
|
+
i += 1;
|
|
1246
|
+
while (i < command.length && command[i] !== "'") {
|
|
1247
|
+
value += command[i];
|
|
1248
|
+
i += 1;
|
|
1249
|
+
}
|
|
1250
|
+
if (command[i] !== "'") {
|
|
1251
|
+
throw inspectionError(`Unterminated single quote starting at character ${quoteStart + 1}. Close the quote before running the command.`);
|
|
1252
|
+
}
|
|
1253
|
+
i += 1;
|
|
1254
|
+
})();
|
|
1255
|
+
continue;
|
|
1256
|
+
}
|
|
1257
|
+
if (current === '"') {
|
|
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;
|
|
1326
|
+
}
|
|
1327
|
+
const nextRedirect = /^(?:<<<|<<-|>>|<<|>&|<&|<>|>\||>|<)/u.exec(command.slice(i));
|
|
1328
|
+
if (nextRedirect !== null) {
|
|
1329
|
+
break;
|
|
1330
|
+
}
|
|
1331
|
+
value += current;
|
|
1332
|
+
i += 1;
|
|
802
1333
|
}
|
|
803
|
-
|
|
804
|
-
|
|
1334
|
+
const finishedWord = (() => {
|
|
1335
|
+
if (wordBytes.length > 0) {
|
|
1336
|
+
value = Buffer.from([...wordBytes, ...Buffer.from(value)]).toString("utf-8");
|
|
1337
|
+
}
|
|
1338
|
+
pushWord(tokens, value, substitutions, expansion);
|
|
1339
|
+
if (pendingDelimiter !== undefined) {
|
|
1340
|
+
if (unsupportedDelimiter !== undefined) {
|
|
1341
|
+
throw inspectionError(`Cannot validate this ${unsupportedDelimiter} heredoc delimiter. Use a plain quoted delimiter such as <<'EOF'.`);
|
|
1342
|
+
}
|
|
1343
|
+
const delimiter = {
|
|
1344
|
+
delimiter: value,
|
|
1345
|
+
quoted,
|
|
1346
|
+
stripTabs: tokens[pendingDelimiter]?.value.endsWith("-")
|
|
1347
|
+
};
|
|
1348
|
+
if (delimiterOnly) {
|
|
1349
|
+
return { tokens, end: i, delimiter };
|
|
1350
|
+
}
|
|
1351
|
+
pendingHeredocs.push({ index: pendingDelimiter, ...delimiter });
|
|
1352
|
+
pendingDelimiter = undefined;
|
|
1353
|
+
}
|
|
1354
|
+
return null;
|
|
1355
|
+
})();
|
|
1356
|
+
return finishedWord;
|
|
1357
|
+
})();
|
|
1358
|
+
if (result !== null) {
|
|
1359
|
+
return result;
|
|
805
1360
|
}
|
|
806
1361
|
}
|
|
807
|
-
return tokens;
|
|
808
|
-
}
|
|
809
|
-
function splitSimpleCommands(tokens) {
|
|
1362
|
+
return { tokens, end: i };
|
|
1363
|
+
};
|
|
1364
|
+
var splitSimpleCommands = function splitSimpleCommands(tokens) {
|
|
810
1365
|
const commands = [];
|
|
811
1366
|
let current = [];
|
|
812
1367
|
let precedingPipeline = false;
|
|
@@ -814,51 +1369,56 @@ function splitSimpleCommands(tokens) {
|
|
|
814
1369
|
if (token.type === "operator") {
|
|
815
1370
|
const isPipeline = token.value === "|" || token.value === "|&";
|
|
816
1371
|
const hasCommand = current.length > 0;
|
|
817
|
-
if (hasCommand)
|
|
818
|
-
commands.push({
|
|
1372
|
+
if (hasCommand) {
|
|
1373
|
+
commands.push({
|
|
1374
|
+
tokens: current,
|
|
1375
|
+
pipeline: precedingPipeline || isPipeline
|
|
1376
|
+
});
|
|
1377
|
+
}
|
|
819
1378
|
current = [];
|
|
820
1379
|
if (hasCommand || token.value !== `
|
|
821
|
-
`)
|
|
1380
|
+
`) {
|
|
822
1381
|
precedingPipeline = isPipeline;
|
|
1382
|
+
}
|
|
823
1383
|
} else {
|
|
824
1384
|
current.push(token);
|
|
825
1385
|
}
|
|
826
1386
|
}
|
|
827
|
-
if (current.length > 0)
|
|
1387
|
+
if (current.length > 0) {
|
|
828
1388
|
commands.push({ tokens: current, pipeline: precedingPipeline });
|
|
1389
|
+
}
|
|
829
1390
|
return commands;
|
|
830
|
-
}
|
|
831
|
-
function extractCommandWords(tokens) {
|
|
1391
|
+
};
|
|
1392
|
+
var extractCommandWords = function extractCommandWords(tokens) {
|
|
832
1393
|
const words = [];
|
|
833
1394
|
let i = 0;
|
|
834
1395
|
while (i < tokens.length) {
|
|
835
1396
|
const token = tokens[i];
|
|
836
|
-
if (token === undefined)
|
|
1397
|
+
if (token === undefined) {
|
|
837
1398
|
break;
|
|
1399
|
+
}
|
|
838
1400
|
if (token.type === "redirect") {
|
|
839
|
-
|
|
840
|
-
i += 2;
|
|
841
|
-
else
|
|
842
|
-
i++;
|
|
1401
|
+
i += tokens[i + 1]?.type === "word" ? 2 : 1;
|
|
843
1402
|
continue;
|
|
844
1403
|
}
|
|
845
1404
|
if (token.type === "word") {
|
|
846
1405
|
words.push(token);
|
|
847
1406
|
}
|
|
848
|
-
i
|
|
1407
|
+
i += 1;
|
|
849
1408
|
}
|
|
850
1409
|
return words;
|
|
851
|
-
}
|
|
852
|
-
function isAssignment(word) {
|
|
853
|
-
return /^[a-zA-Z_][a-zA-Z0-9_]
|
|
854
|
-
}
|
|
855
|
-
function skipAssignments(words, start) {
|
|
1410
|
+
};
|
|
1411
|
+
var isAssignment = function isAssignment(word) {
|
|
1412
|
+
return /^[a-zA-Z_][a-zA-Z0-9_]*=/u.test(word);
|
|
1413
|
+
};
|
|
1414
|
+
var skipAssignments = function skipAssignments(words, start) {
|
|
856
1415
|
let index = start;
|
|
857
|
-
while (words[index] !== undefined && isAssignment(words[index]))
|
|
858
|
-
index
|
|
1416
|
+
while (words[index] !== undefined && isAssignment(words[index])) {
|
|
1417
|
+
index += 1;
|
|
1418
|
+
}
|
|
859
1419
|
return index;
|
|
860
|
-
}
|
|
861
|
-
function findCommandStart(words) {
|
|
1420
|
+
};
|
|
1421
|
+
var findCommandStart = function findCommandStart(words) {
|
|
862
1422
|
let index = skipAssignments(words, 0);
|
|
863
1423
|
while (index < words.length) {
|
|
864
1424
|
const word = words[index];
|
|
@@ -867,109 +1427,132 @@ function findCommandStart(words) {
|
|
|
867
1427
|
continue;
|
|
868
1428
|
}
|
|
869
1429
|
if (word === "env") {
|
|
870
|
-
index
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
1430
|
+
index += 1;
|
|
1431
|
+
(() => {
|
|
1432
|
+
while (index < words.length) {
|
|
1433
|
+
const argument = words[index];
|
|
1434
|
+
if (argument === undefined) {
|
|
1435
|
+
break;
|
|
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
|
+
}
|
|
893
1456
|
}
|
|
894
|
-
}
|
|
1457
|
+
})();
|
|
895
1458
|
index = skipAssignments(words, index);
|
|
896
1459
|
continue;
|
|
897
1460
|
}
|
|
898
1461
|
if (word === "exec") {
|
|
899
|
-
index
|
|
1462
|
+
index += 1;
|
|
900
1463
|
while (index < words.length) {
|
|
901
1464
|
const argument = words[index];
|
|
902
1465
|
if (argument === "--") {
|
|
903
|
-
index
|
|
1466
|
+
index += 1;
|
|
904
1467
|
break;
|
|
905
1468
|
}
|
|
906
|
-
if (argument === "-a")
|
|
1469
|
+
if (argument === "-a") {
|
|
907
1470
|
index += 2;
|
|
908
|
-
else if (argument !== undefined && argument.startsWith("-"))
|
|
909
|
-
index
|
|
910
|
-
else
|
|
1471
|
+
} else if (argument !== undefined && argument.startsWith("-")) {
|
|
1472
|
+
index += 1;
|
|
1473
|
+
} else {
|
|
911
1474
|
break;
|
|
1475
|
+
}
|
|
912
1476
|
}
|
|
913
1477
|
index = skipAssignments(words, index);
|
|
914
1478
|
continue;
|
|
915
1479
|
}
|
|
916
1480
|
if (word === "command" || word === "nohup" || word === "builtin") {
|
|
917
|
-
index
|
|
918
|
-
while (words[index]?.startsWith("-"))
|
|
919
|
-
index
|
|
1481
|
+
index += 1;
|
|
1482
|
+
while (words[index]?.startsWith("-")) {
|
|
1483
|
+
index += 1;
|
|
1484
|
+
}
|
|
920
1485
|
index = skipAssignments(words, index);
|
|
921
1486
|
continue;
|
|
922
1487
|
}
|
|
923
1488
|
break;
|
|
924
1489
|
}
|
|
925
1490
|
return index;
|
|
926
|
-
}
|
|
927
|
-
function extractInvocation(words, commandStart, wordTokens) {
|
|
1491
|
+
};
|
|
1492
|
+
var extractInvocation = function extractInvocation(words, commandStart, wordTokens) {
|
|
928
1493
|
let wordIndex = commandStart;
|
|
929
1494
|
const executable = words[wordIndex];
|
|
930
|
-
if (executable === undefined || executable !== "git" && !executable.endsWith("/git"))
|
|
1495
|
+
if (executable === undefined || executable !== "git" && !executable.endsWith("/git")) {
|
|
931
1496
|
return;
|
|
932
|
-
|
|
1497
|
+
}
|
|
1498
|
+
wordIndex += 1;
|
|
933
1499
|
let subcommand;
|
|
934
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;
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
subcommand = words[wordIndex + 1];
|
|
941
|
-
wordIndex += 2;
|
|
942
|
-
break;
|
|
943
|
-
}
|
|
944
|
-
if (gitGlobalOptionsWithArg.has(argument)) {
|
|
945
|
-
if (argument === "-C" || argument === "--git-dir" || argument === "--work-tree" || argument === "-c" || argument === "--config-env") {
|
|
946
|
-
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
1501
|
+
const readSubcommand = () => {
|
|
1502
|
+
while (wordIndex < words.length) {
|
|
1503
|
+
const argument = words[wordIndex];
|
|
1504
|
+
if (argument === undefined) {
|
|
1505
|
+
break;
|
|
947
1506
|
}
|
|
948
|
-
wordIndex
|
|
949
|
-
|
|
950
|
-
}
|
|
951
|
-
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")) {
|
|
952
|
-
if (argument.startsWith("--git-dir=") || argument.startsWith("--work-tree=") || argument.startsWith("--config-env=") || argument.startsWith("-c")) {
|
|
953
|
-
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
1507
|
+
if (wordTokens[wordIndex]?.expansion === true) {
|
|
1508
|
+
throw inspectionError("Cannot inspect dynamic Git options or subcommands. Use literal command words.");
|
|
954
1509
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
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;
|
|
966
1550
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
}
|
|
971
|
-
if (subcommand !== "commit")
|
|
1551
|
+
};
|
|
1552
|
+
readSubcommand();
|
|
1553
|
+
if (subcommand !== "commit") {
|
|
972
1554
|
return;
|
|
1555
|
+
}
|
|
973
1556
|
const messages = [];
|
|
974
1557
|
const filePaths = [];
|
|
975
1558
|
let hasSignoffFlag = false;
|
|
@@ -980,87 +1563,118 @@ function extractInvocation(words, commandStart, wordTokens) {
|
|
|
980
1563
|
let messageExpansion = false;
|
|
981
1564
|
let hasTrailer = false;
|
|
982
1565
|
const collectMessage = (word) => {
|
|
983
|
-
if (word === undefined)
|
|
1566
|
+
if (word === undefined) {
|
|
984
1567
|
return;
|
|
1568
|
+
}
|
|
985
1569
|
messages.push(word);
|
|
986
1570
|
};
|
|
987
1571
|
const collectFile = (word) => {
|
|
988
|
-
if (word === undefined)
|
|
1572
|
+
if (word === undefined) {
|
|
989
1573
|
return;
|
|
1574
|
+
}
|
|
990
1575
|
filePaths.push(word);
|
|
991
1576
|
};
|
|
992
|
-
for (let index = wordIndex;index < words.length; index
|
|
1577
|
+
for (let index = wordIndex;index < words.length; index += 1) {
|
|
993
1578
|
const argument = words[index];
|
|
994
|
-
if (argument === undefined)
|
|
1579
|
+
if (argument === undefined) {
|
|
995
1580
|
break;
|
|
1581
|
+
}
|
|
996
1582
|
const equalsIndex = argument.indexOf("=");
|
|
997
1583
|
const longOptionName = equalsIndex > 0 ? argument.slice(0, equalsIndex) : argument;
|
|
998
|
-
if (argument === "--")
|
|
1584
|
+
if (argument === "--") {
|
|
999
1585
|
break;
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
} else if (argument.startsWith("--message=")) {
|
|
1017
|
-
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
1018
|
-
collectMessage(argument.slice("--message=".length));
|
|
1019
|
-
} else if (argument === "-F" || argument === "--file") {
|
|
1020
|
-
index++;
|
|
1021
|
-
collectFile(words[index]);
|
|
1022
|
-
} else if (argument.startsWith("--file=")) {
|
|
1023
|
-
collectFile(argument.slice("--file=".length));
|
|
1024
|
-
} else if (argument === "--fixup" || argument.startsWith("--fixup=")) {
|
|
1025
|
-
isFixup = true;
|
|
1026
|
-
if (equalsIndex < 0)
|
|
1027
|
-
index++;
|
|
1028
|
-
} else if (longOptionName === "--trailer") {
|
|
1029
|
-
hasTrailer = true;
|
|
1030
|
-
if (equalsIndex < 0)
|
|
1031
|
-
index++;
|
|
1032
|
-
} else if (commitLongOptionsWithArg.has(longOptionName)) {
|
|
1033
|
-
if (equalsIndex < 0)
|
|
1034
|
-
index++;
|
|
1035
|
-
} else if (argument.startsWith("-") && !argument.startsWith("--") && argument.length > 1) {
|
|
1036
|
-
for (let characterIndex = 1;characterIndex < argument.length; characterIndex++) {
|
|
1037
|
-
const option = argument[characterIndex];
|
|
1038
|
-
if (option === "s") {
|
|
1039
|
-
hasSignoffFlag = true;
|
|
1040
|
-
} else if (option === "h") {
|
|
1041
|
-
isHelp = true;
|
|
1042
|
-
} else if (option === "e") {
|
|
1043
|
-
hasNoEdit = false;
|
|
1044
|
-
} else if (option === "m" || option === "F") {
|
|
1045
|
-
const attached = argument.slice(characterIndex + 1);
|
|
1046
|
-
const input = attached.length > 0 ? attached : words[++index];
|
|
1047
|
-
if (option === "m") {
|
|
1048
|
-
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
1049
|
-
collectMessage(input);
|
|
1050
|
-
} else
|
|
1051
|
-
collectFile(input);
|
|
1052
|
-
break;
|
|
1053
|
-
} else if (option === "S") {
|
|
1054
|
-
break;
|
|
1055
|
-
} else if (option === "u") {
|
|
1056
|
-
break;
|
|
1057
|
-
} else if (option === "c" || option === "C" || option === "t") {
|
|
1058
|
-
if (argument.slice(characterIndex + 1).length === 0)
|
|
1059
|
-
index++;
|
|
1060
|
-
break;
|
|
1061
|
-
}
|
|
1586
|
+
}
|
|
1587
|
+
const consumedBooleanFlag = (() => {
|
|
1588
|
+
if (argument === "-h" || argument === "--help") {
|
|
1589
|
+
isHelp = true;
|
|
1590
|
+
} else if (argument === "--amend") {
|
|
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;
|
|
1062
1602
|
}
|
|
1603
|
+
return true;
|
|
1604
|
+
})();
|
|
1605
|
+
if (consumedBooleanFlag) {
|
|
1606
|
+
continue;
|
|
1063
1607
|
}
|
|
1608
|
+
const consumedMessageOption = (() => {
|
|
1609
|
+
if (argument === "-m" || argument === "--message") {
|
|
1610
|
+
index += 1;
|
|
1611
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
1612
|
+
collectMessage(words[index]);
|
|
1613
|
+
} else if (argument.startsWith("--message=")) {
|
|
1614
|
+
messageExpansion ||= wordTokens[index]?.expansion === true;
|
|
1615
|
+
collectMessage(argument.slice("--message=".length));
|
|
1616
|
+
} else if (argument === "-F" || argument === "--file") {
|
|
1617
|
+
index += 1;
|
|
1618
|
+
collectFile(words[index]);
|
|
1619
|
+
} else if (argument.startsWith("--file=")) {
|
|
1620
|
+
collectFile(argument.slice("--file=".length));
|
|
1621
|
+
} else {
|
|
1622
|
+
return false;
|
|
1623
|
+
}
|
|
1624
|
+
return true;
|
|
1625
|
+
})();
|
|
1626
|
+
if (consumedMessageOption) {
|
|
1627
|
+
continue;
|
|
1628
|
+
}
|
|
1629
|
+
(() => {
|
|
1630
|
+
if (argument === "--fixup" || argument.startsWith("--fixup=")) {
|
|
1631
|
+
isFixup = true;
|
|
1632
|
+
if (equalsIndex === -1) {
|
|
1633
|
+
index += 1;
|
|
1634
|
+
}
|
|
1635
|
+
} else if (longOptionName === "--trailer") {
|
|
1636
|
+
hasTrailer = true;
|
|
1637
|
+
if (equalsIndex === -1) {
|
|
1638
|
+
index += 1;
|
|
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
|
+
})();
|
|
1064
1678
|
}
|
|
1065
1679
|
return {
|
|
1066
1680
|
messages,
|
|
@@ -1074,10 +1688,11 @@ function extractInvocation(words, commandStart, wordTokens) {
|
|
|
1074
1688
|
messageExpansion,
|
|
1075
1689
|
hasTrailer
|
|
1076
1690
|
};
|
|
1077
|
-
}
|
|
1078
|
-
function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0) {
|
|
1079
|
-
if (depth > 12 || command.length > 262144)
|
|
1080
|
-
throw
|
|
1691
|
+
};
|
|
1692
|
+
var extractGitCommits = function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0) {
|
|
1693
|
+
if (depth > 12 || command.length > 262144) {
|
|
1694
|
+
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
1695
|
+
}
|
|
1081
1696
|
const tokens = tokenizeShell(command);
|
|
1082
1697
|
const invocations = [];
|
|
1083
1698
|
let changedDirectory = inheritedDirectoryChange;
|
|
@@ -1086,65 +1701,87 @@ function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0)
|
|
|
1086
1701
|
const wordTokens = extractCommandWords(commandTokens);
|
|
1087
1702
|
const words = wordTokens.map((token) => token.value);
|
|
1088
1703
|
const commandStart = findCommandStart(words);
|
|
1704
|
+
if (wordTokens[commandStart]?.expansion === true) {
|
|
1705
|
+
throw inspectionError("Cannot inspect a dynamic command name. Use literal command words.");
|
|
1706
|
+
}
|
|
1089
1707
|
const invocation = extractInvocation(words, commandStart, wordTokens);
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
bodyIndex
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1708
|
+
const directoryChanged = changedDirectory;
|
|
1709
|
+
(() => {
|
|
1710
|
+
if (/^(?:.*\/)?(?:bash|sh|zsh)$/u.test(words[commandStart] ?? "")) {
|
|
1711
|
+
let bodyIndex = commandStart + 1;
|
|
1712
|
+
let executeString = false;
|
|
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));
|
|
1106
1745
|
}
|
|
1107
|
-
const next = words[bodyIndex + 1];
|
|
1108
|
-
const optionName = next !== undefined && !/^[+-]/.test(next);
|
|
1109
|
-
bodyIndex += shortOptions && /[oO]$/.test(option) && optionName || ["--rcfile", "--init-file"].includes(option) ? 2 : 1;
|
|
1110
1746
|
}
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
if (body === undefined || body.expansion)
|
|
1114
|
-
throw new Error("Cannot parse shell -c body reliably. Run git commit directly.");
|
|
1115
|
-
const wrapperChange = words.slice(0, commandStart).some((word) => word === "env" || isAssignment(word));
|
|
1116
|
-
invocations.push(...extractGitCommits(body.value, changedDirectory || wrapperChange, depth + 1));
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment))
|
|
1747
|
+
})();
|
|
1748
|
+
if (targetMutators.has(words[commandStart] ?? "") || words.length > 0 && words.every(isAssignment)) {
|
|
1120
1749
|
changedDirectory = true;
|
|
1750
|
+
}
|
|
1121
1751
|
if (invocation !== undefined) {
|
|
1122
|
-
const target = changedDirectory ? {
|
|
1752
|
+
const target = changedDirectory ? {
|
|
1753
|
+
...invocation,
|
|
1754
|
+
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
|
+
} : invocation;
|
|
1123
1756
|
if (!invocation.filePaths.includes("-")) {
|
|
1124
1757
|
invocations.push(target);
|
|
1125
1758
|
continue;
|
|
1126
1759
|
}
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
stdinError
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
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();
|
|
1148
1785
|
}
|
|
1149
1786
|
}
|
|
1150
1787
|
for (const token of tokens) {
|
|
@@ -1153,24 +1790,25 @@ function extractGitCommits(command, inheritedDirectoryChange = false, depth = 0)
|
|
|
1153
1790
|
}
|
|
1154
1791
|
}
|
|
1155
1792
|
return invocations;
|
|
1156
|
-
}
|
|
1793
|
+
};
|
|
1157
1794
|
|
|
1158
1795
|
// src/validator.ts
|
|
1159
|
-
var signoffPattern = /^\s*
|
|
1160
|
-
function hasSignoffTrailer(lines) {
|
|
1796
|
+
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 hasSignoffTrailer = function hasSignoffTrailer(lines) {
|
|
1161
1798
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
1162
|
-
return subjectIndex
|
|
1163
|
-
}
|
|
1164
|
-
function validateAllowedScope(rawScope, allowedScopes) {
|
|
1165
|
-
const parenthesizedScope =
|
|
1799
|
+
return subjectIndex !== -1 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
|
|
1800
|
+
};
|
|
1801
|
+
var validateAllowedScope = function validateAllowedScope(rawScope, allowedScopes) {
|
|
1802
|
+
const parenthesizedScope = /^(?<type>[^(]+)\((?<scope>[^)]+)\)$/u.exec(rawScope);
|
|
1166
1803
|
const conventionalType = parenthesizedScope?.[1];
|
|
1167
1804
|
const innerScope = parenthesizedScope?.[2];
|
|
1168
1805
|
const isAllowed = allowedScopes.includes(rawScope) || innerScope !== undefined && allowedScopes.includes(innerScope) || conventionalType !== undefined && allowedScopes.includes(conventionalType);
|
|
1169
|
-
if (isAllowed)
|
|
1806
|
+
if (isAllowed) {
|
|
1170
1807
|
return;
|
|
1808
|
+
}
|
|
1171
1809
|
return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowedScopes.join(", ")}.`;
|
|
1172
|
-
}
|
|
1173
|
-
function createCommitGuardError(violations, config) {
|
|
1810
|
+
};
|
|
1811
|
+
var createCommitGuardError = function createCommitGuardError(violations, config) {
|
|
1174
1812
|
const header = "[commit-guard] Git commit rejected: commit message format rules violated.";
|
|
1175
1813
|
const violationText = violations.map((v, i) => `${i + 1}. ${v}`).join(`
|
|
1176
1814
|
|
|
@@ -1185,33 +1823,39 @@ Violations:
|
|
|
1185
1823
|
${violationText}
|
|
1186
1824
|
|
|
1187
1825
|
${examples}`);
|
|
1188
|
-
}
|
|
1189
|
-
function validateGitCommits(invocations, config, _originalCommand) {
|
|
1826
|
+
};
|
|
1827
|
+
var validateGitCommits = function validateGitCommits(invocations, config, _originalCommand) {
|
|
1190
1828
|
const allViolations = [];
|
|
1191
1829
|
for (const invocation of invocations) {
|
|
1192
1830
|
if (invocation.isHelp) {
|
|
1193
1831
|
continue;
|
|
1194
1832
|
}
|
|
1195
|
-
if (invocation.messageExpansion) {
|
|
1833
|
+
if (invocation.messageExpansion === true) {
|
|
1196
1834
|
allViolations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
|
|
1197
1835
|
continue;
|
|
1198
1836
|
}
|
|
1199
|
-
if (invocation.hasTrailer) {
|
|
1837
|
+
if (invocation.hasTrailer === true) {
|
|
1200
1838
|
allViolations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
|
|
1201
1839
|
continue;
|
|
1202
1840
|
}
|
|
1203
1841
|
const collectedMessages = [...invocation.messages];
|
|
1204
1842
|
const filePath = invocation.filePaths.at(-1);
|
|
1205
|
-
|
|
1206
|
-
if (filePath !==
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1843
|
+
const collectFileMessage = () => {
|
|
1844
|
+
if (filePath !== undefined) {
|
|
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);
|
|
1213
1854
|
}
|
|
1214
|
-
|
|
1855
|
+
return true;
|
|
1856
|
+
};
|
|
1857
|
+
if (!collectFileMessage()) {
|
|
1858
|
+
continue;
|
|
1215
1859
|
}
|
|
1216
1860
|
if (collectedMessages.length === 0) {
|
|
1217
1861
|
if (invocation.isAmend && invocation.hasNoEdit === true) {
|
|
@@ -1228,10 +1872,10 @@ function validateGitCommits(invocations, config, _originalCommand) {
|
|
|
1228
1872
|
const fullMessage = collectedMessages.join(`
|
|
1229
1873
|
|
|
1230
1874
|
`);
|
|
1231
|
-
const lines = fullMessage.split(/\r?\n/);
|
|
1875
|
+
const lines = fullMessage.split(/\r?\n/u);
|
|
1232
1876
|
const firstLine = lines[0] ?? "";
|
|
1233
1877
|
const subjectLine = firstLine.trim();
|
|
1234
|
-
const effectiveSubject = subjectLine.replace(/^(?:(?:fixup|squash)!\s+)
|
|
1878
|
+
const effectiveSubject = subjectLine.replace(/^(?:(?:fixup|squash)!\s+)+/u, "");
|
|
1235
1879
|
const scopeMatch = effectiveSubject.match(scopePattern);
|
|
1236
1880
|
if (scopeMatch?.[1] !== undefined && config.allowedScopes !== undefined && config.allowedScopes.length > 0) {
|
|
1237
1881
|
const scopeViolation = validateAllowedScope(scopeMatch[1], config.allowedScopes);
|
|
@@ -1240,56 +1884,68 @@ function validateGitCommits(invocations, config, _originalCommand) {
|
|
|
1240
1884
|
allViolations.push(`${scopeViolation}${fullSubjectDetail}`);
|
|
1241
1885
|
}
|
|
1242
1886
|
}
|
|
1243
|
-
|
|
1244
|
-
if (
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
if (
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1887
|
+
const validateSubject = () => {
|
|
1888
|
+
if (config.requireScope) {
|
|
1889
|
+
if (subjectLine.length === 0) {
|
|
1890
|
+
allViolations.push('Subject line is empty. The commit message must begin with "<scope>: <subject>".');
|
|
1891
|
+
} else if (scopeMatch === null) {
|
|
1892
|
+
if (/^:\s*/u.test(effectiveSubject)) {
|
|
1893
|
+
allViolations.push(`Missing scope before colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
1894
|
+
} else if (/^[^:]+:\S/u.test(effectiveSubject)) {
|
|
1895
|
+
allViolations.push(`Missing space after colon in subject line "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
1896
|
+
} else if (/^[^:]+:\s*$/u.test(effectiveSubject)) {
|
|
1897
|
+
allViolations.push(`Subject text after colon is empty in "${subjectLine}". Expected format: "<scope>: <subject>".`);
|
|
1898
|
+
} else {
|
|
1899
|
+
allViolations.push(`Missing scope in subject line "${subjectLine}". First line must follow "<scope>: <subject>" format.`);
|
|
1900
|
+
}
|
|
1255
1901
|
}
|
|
1256
1902
|
}
|
|
1257
|
-
}
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
const
|
|
1262
|
-
|
|
1263
|
-
|
|
1903
|
+
};
|
|
1904
|
+
validateSubject();
|
|
1905
|
+
const validateLength = () => {
|
|
1906
|
+
if (config.maxLineLength > 0) {
|
|
1907
|
+
const overlongLines = [];
|
|
1908
|
+
for (let i = 0;i < lines.length; i += 1) {
|
|
1909
|
+
const line = lines[i];
|
|
1910
|
+
if (line !== undefined && line.length > config.maxLineLength) {
|
|
1911
|
+
overlongLines.push({
|
|
1912
|
+
lineNumber: i + 1,
|
|
1913
|
+
length: line.length,
|
|
1914
|
+
text: line
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1264
1917
|
}
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
|
|
1918
|
+
if (overlongLines.length > 0) {
|
|
1919
|
+
const details = overlongLines.map((l) => ` - Line ${l.lineNumber} (${l.length} chars, max ${config.maxLineLength}): "${l.text}"`).join(`
|
|
1268
1920
|
`);
|
|
1269
|
-
|
|
1921
|
+
allViolations.push(`Commit message exceeds maximum line length of ${config.maxLineLength} characters:
|
|
1270
1922
|
${details}
|
|
1271
1923
|
Each -m becomes one paragraph line. Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`);
|
|
1924
|
+
}
|
|
1272
1925
|
}
|
|
1273
|
-
}
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
if (
|
|
1277
|
-
|
|
1926
|
+
};
|
|
1927
|
+
validateLength();
|
|
1928
|
+
const validateSignoff = () => {
|
|
1929
|
+
if (config.enforceSignoff) {
|
|
1930
|
+
const hasSignoff = invocation.hasSignoffFlag || hasSignoffTrailer(lines);
|
|
1931
|
+
if (!hasSignoff) {
|
|
1932
|
+
allViolations.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.");
|
|
1933
|
+
}
|
|
1278
1934
|
}
|
|
1279
|
-
}
|
|
1935
|
+
};
|
|
1936
|
+
validateSignoff();
|
|
1280
1937
|
}
|
|
1281
1938
|
if (allViolations.length > 0) {
|
|
1282
1939
|
throw createCommitGuardError(allViolations.slice(0, 10).map((text) => text.slice(0, 2048)), config);
|
|
1283
1940
|
}
|
|
1284
|
-
}
|
|
1941
|
+
};
|
|
1285
1942
|
|
|
1286
1943
|
// src/plugin.ts
|
|
1944
|
+
var { relative: relative2, resolve: resolve2 } = path;
|
|
1287
1945
|
var plugin = Plugin.define({
|
|
1288
1946
|
id: "opencode-commit-guard",
|
|
1289
|
-
effect: (ctx) => Effect2.gen(function* () {
|
|
1290
|
-
const config = yield* Effect2.sync(() =>
|
|
1291
|
-
return parseConfig(ctx.options);
|
|
1292
|
-
});
|
|
1947
|
+
effect: (ctx) => Effect2.gen(function* setupGuard() {
|
|
1948
|
+
const config = yield* Effect2.sync(() => parseConfig(ctx.options));
|
|
1293
1949
|
const generation = randomUUID2();
|
|
1294
1950
|
const pending = new Map;
|
|
1295
1951
|
const preparing = new Set;
|
|
@@ -1298,21 +1954,26 @@ var plugin = Plugin.define({
|
|
|
1298
1954
|
const rememberFailure = (scope, reason) => {
|
|
1299
1955
|
failures.delete(scope);
|
|
1300
1956
|
failures.set(scope, `The previous capture failed: ${reason.slice(0, 256)}. `);
|
|
1301
|
-
if (failures.size > 128)
|
|
1302
|
-
failures.
|
|
1957
|
+
if (failures.size > 128) {
|
|
1958
|
+
const oldest = failures.keys().next().value;
|
|
1959
|
+
if (oldest !== undefined) {
|
|
1960
|
+
failures.delete(oldest);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1303
1963
|
};
|
|
1304
|
-
const sweep = () => Effect2.gen(function* () {
|
|
1964
|
+
const sweep = () => Effect2.gen(function* sweepPending() {
|
|
1305
1965
|
for (const attempt of [...pending.values()].slice(0, 32)) {
|
|
1306
1966
|
pending.delete(attempt.scope);
|
|
1307
1967
|
if (attempt.claimed === undefined && Date.now() >= attempt.expires) {
|
|
1308
1968
|
cleanup(attempt);
|
|
1309
1969
|
yield* recordState(ctx, attempt, "expired");
|
|
1310
1970
|
yield* invalidateOwned(ctx, attempt);
|
|
1311
|
-
} else
|
|
1971
|
+
} else {
|
|
1312
1972
|
pending.set(attempt.scope, attempt);
|
|
1973
|
+
}
|
|
1313
1974
|
}
|
|
1314
1975
|
});
|
|
1315
|
-
yield* Effect2.addFinalizer(() => Effect2.gen(function* () {
|
|
1976
|
+
yield* Effect2.addFinalizer(() => Effect2.gen(function* unloadGuard() {
|
|
1316
1977
|
for (const attempt of pending.values()) {
|
|
1317
1978
|
cleanup(attempt);
|
|
1318
1979
|
yield* recordState(ctx, attempt, "failed", "plugin unloaded before publication");
|
|
@@ -1320,9 +1981,10 @@ var plugin = Plugin.define({
|
|
|
1320
1981
|
}
|
|
1321
1982
|
pending.clear();
|
|
1322
1983
|
}));
|
|
1323
|
-
yield* ctx.tool.transform((editor) =>
|
|
1324
|
-
|
|
1325
|
-
|
|
1984
|
+
yield* ctx.tool.transform((editor) => {
|
|
1985
|
+
editor.add({
|
|
1986
|
+
name: "commit_context",
|
|
1987
|
+
description: String.raw`Prepare a Git baseline. Run the returned command unchanged in the foreground; require "Frozen commit baseline".
|
|
1326
1988
|
Call before your first commit in each session and checkout.
|
|
1327
1989
|
Set workdir when targeting another repository.
|
|
1328
1990
|
Run the returned command immediately, unchanged, with the indicated workdir and background:false.
|
|
@@ -1336,106 +1998,140 @@ Use literal message text and real body newlines.
|
|
|
1336
1998
|
Example: git commit -m $'scope: Subject\n\nBody line one.\nBody line two.'
|
|
1337
1999
|
Replace scope and follow the returned line-length and signoff rules.
|
|
1338
2000
|
Add -s only when the returned policy or repository instructions require it.`,
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
2001
|
+
input: {
|
|
2002
|
+
type: "object",
|
|
2003
|
+
properties: {
|
|
2004
|
+
refresh: { type: "boolean" },
|
|
2005
|
+
workdir: {
|
|
2006
|
+
type: "string",
|
|
2007
|
+
description: "Working directory of the Git repository relative to the session directory or absolute."
|
|
2008
|
+
},
|
|
2009
|
+
directory: {
|
|
2010
|
+
type: "string",
|
|
2011
|
+
description: "Path to the Git repository checkout (alias for workdir)."
|
|
2012
|
+
}
|
|
2013
|
+
},
|
|
2014
|
+
additionalProperties: false
|
|
1345
2015
|
},
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
const session = yield* ctx.session.get({ sessionID: toolContext.sessionID });
|
|
1353
|
-
if (session.location.workspaceID !== ctx.location.workspaceID) {
|
|
1354
|
-
return { content: "Commit context capture is unavailable for remote workspaces." };
|
|
1355
|
-
}
|
|
1356
|
-
const request = input;
|
|
1357
|
-
const requestedDir = isJSONString(request.workdir) ? request.workdir : isJSONString(request.directory) ? request.directory : undefined;
|
|
1358
|
-
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
1359
|
-
let target = resolveTargetWorkdir(sessionDirectory, requestedDir);
|
|
1360
|
-
if (target.workdir === undefined && requestedDir === undefined) {
|
|
1361
|
-
const remembered = lastSessionWorkdir.get(toolContext.sessionID);
|
|
1362
|
-
if (remembered !== undefined && existsSync2(remembered) && findGitRoot(remembered) !== undefined) {
|
|
1363
|
-
target = { workdir: remembered };
|
|
2016
|
+
execute: (input, toolContext) => Effect2.gen(function* execute() {
|
|
2017
|
+
yield* sweep();
|
|
2018
|
+
if (ctx.location.workspaceID !== undefined) {
|
|
2019
|
+
return {
|
|
2020
|
+
content: "Commit context capture is unavailable for remote workspaces."
|
|
2021
|
+
};
|
|
1364
2022
|
}
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
if (
|
|
1378
|
-
|
|
1379
|
-
return { 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.' };
|
|
1380
|
-
}
|
|
1381
|
-
if (request.refresh !== true) {
|
|
1382
|
-
return { content: captureInstructions(previous, "Capture still pending and unclaimed. ") };
|
|
1383
|
-
}
|
|
1384
|
-
pending.delete(scope);
|
|
1385
|
-
cleanup(previous);
|
|
1386
|
-
yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
|
|
1387
|
-
yield* invalidateOwned(ctx, previous);
|
|
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;
|
|
1388
2037
|
}
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
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 };
|
|
1393
2044
|
}
|
|
1394
2045
|
}
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
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
|
+
})))
|
|
2096
|
+
});
|
|
2097
|
+
});
|
|
2098
|
+
yield* ctx.tool.hook("execute.before", (event) => Effect2.gen(function* beforeExecution() {
|
|
1409
2099
|
yield* sweep();
|
|
1410
|
-
const
|
|
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;
|
|
1411
2107
|
const captureSessionDirectory = captureSession?.location.directory ?? ctx.location.directory;
|
|
1412
2108
|
const parsed = yield* Effect2.try({
|
|
1413
2109
|
try: () => {
|
|
1414
2110
|
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
1415
|
-
return;
|
|
2111
|
+
return null;
|
|
1416
2112
|
}
|
|
1417
|
-
const rawInput = event.input;
|
|
1418
2113
|
if (!isRecord(rawInput)) {
|
|
1419
|
-
return;
|
|
2114
|
+
return null;
|
|
1420
2115
|
}
|
|
1421
|
-
const command = rawInput
|
|
2116
|
+
const { command } = rawInput;
|
|
1422
2117
|
if (!isJSONString(command)) {
|
|
1423
|
-
return;
|
|
2118
|
+
return null;
|
|
1424
2119
|
}
|
|
1425
|
-
const rawWorkdir = rawInput
|
|
2120
|
+
const rawWorkdir = rawInput.workdir;
|
|
1426
2121
|
for (const attempt of pending.values()) {
|
|
1427
|
-
if (command !== attempt.command)
|
|
2122
|
+
if (command !== attempt.command) {
|
|
1428
2123
|
continue;
|
|
2124
|
+
}
|
|
1429
2125
|
const matchesWorkdir = rawWorkdir === attempt.workdir || isJSONString(rawWorkdir) && resolve2(captureSessionDirectory, rawWorkdir) === attempt.workdir || rawWorkdir === undefined && captureSessionDirectory === attempt.workdir;
|
|
1430
|
-
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput
|
|
2126
|
+
if (event.tool !== "shell" || event.sessionID !== attempt.sessionID || event.agent !== attempt.agent || !matchesWorkdir || rawInput.background === true || Date.now() >= attempt.expires || attempt.claimed !== undefined) {
|
|
1431
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.");
|
|
1432
2128
|
}
|
|
1433
2129
|
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
1434
|
-
return;
|
|
2130
|
+
return null;
|
|
1435
2131
|
}
|
|
1436
2132
|
const invocations = extractGitCommits(command);
|
|
1437
2133
|
if (invocations.length === 0) {
|
|
1438
|
-
return;
|
|
2134
|
+
return null;
|
|
1439
2135
|
}
|
|
1440
2136
|
return { invocations, command, rawInput };
|
|
1441
2137
|
},
|
|
@@ -1444,81 +2140,99 @@ Add -s only when the returned policy or repository instructions require it.`,
|
|
|
1444
2140
|
})
|
|
1445
2141
|
});
|
|
1446
2142
|
for (const attempt of pending.values()) {
|
|
1447
|
-
if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent)
|
|
2143
|
+
if (attempt.claimed?.messageID === event.messageID && attempt.claimed.id === event.id && attempt.sessionID === event.sessionID && attempt.agent === event.agent) {
|
|
1448
2144
|
yield* recordState(ctx, attempt, "claimed");
|
|
2145
|
+
}
|
|
1449
2146
|
}
|
|
1450
|
-
if (parsed ===
|
|
2147
|
+
if (parsed === null || parsed.invocations.every((invocation) => invocation.isHelp)) {
|
|
1451
2148
|
return;
|
|
1452
|
-
if (ctx.location.workspaceID !== undefined)
|
|
1453
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
1454
|
-
message: "[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."
|
|
1455
|
-
}));
|
|
1456
|
-
const session = yield* ctx.session.get({ sessionID: event.sessionID });
|
|
1457
|
-
if (session.location.workspaceID !== ctx.location.workspaceID || parsed.invocations.some((invocation) => invocation.targetError !== undefined)) {
|
|
1458
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
1459
|
-
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."
|
|
1460
|
-
}));
|
|
1461
|
-
}
|
|
1462
|
-
const sessionDirectory = session.location.directory ?? ctx.location.directory;
|
|
1463
|
-
const rawWorkdir = parsed.rawInput["workdir"];
|
|
1464
|
-
const effectiveWorkdir = yield* Effect2.try(() => realpathSync2(isJSONString(rawWorkdir) ? resolve2(sessionDirectory, rawWorkdir) : sessionDirectory));
|
|
1465
|
-
const targetGitRoot = findGitRoot(effectiveWorkdir);
|
|
1466
|
-
const scope = scopeFor(ctx, event.sessionID, config, effectiveWorkdir);
|
|
1467
|
-
const baseline = yield* load(ctx, scope);
|
|
1468
|
-
const expectedDir = targetGitRoot ?? effectiveWorkdir;
|
|
1469
|
-
const baselineValid = baseline !== undefined && targetGitRoot !== undefined && baseline.directory === targetGitRoot && baseline.directory === expectedDir;
|
|
1470
|
-
if (!baselineValid || baseline === undefined) {
|
|
1471
|
-
const relWorkdir = relative2(sessionDirectory, expectedDir);
|
|
1472
|
-
const workdirHint = JSON.stringify(relWorkdir.length > 0 ? relWorkdir : ".");
|
|
1473
|
-
return yield* Effect2.fail(new Tool.Error({
|
|
1474
|
-
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.`
|
|
1475
|
-
}));
|
|
1476
2149
|
}
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
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;
|
|
1486
2191
|
});
|
|
1487
2192
|
}).pipe(Effect2.mapError((error) => error instanceof Tool.Error ? error : new Tool.Error({
|
|
1488
2193
|
message: error instanceof Error ? error.message : "[commit-guard] Git commit validation failed."
|
|
1489
2194
|
}))));
|
|
1490
|
-
yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* () {
|
|
1491
|
-
if (event.tool !== "shell")
|
|
2195
|
+
yield* ctx.tool.hook("execute.after", (event) => Effect2.gen(function* afterExecution() {
|
|
2196
|
+
if (event.tool !== "shell") {
|
|
1492
2197
|
return;
|
|
2198
|
+
}
|
|
1493
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);
|
|
1494
|
-
if (attempt === undefined)
|
|
2200
|
+
if (attempt === undefined) {
|
|
1495
2201
|
return;
|
|
2202
|
+
}
|
|
1496
2203
|
let published = false;
|
|
1497
2204
|
let captured;
|
|
1498
2205
|
let reason = "capture import or storage failed";
|
|
1499
|
-
yield* Effect2.gen(function* () {
|
|
2206
|
+
yield* Effect2.gen(function* publishCapture() {
|
|
1500
2207
|
reason = "shell result did not complete successfully";
|
|
1501
|
-
if (event.status !== "completed")
|
|
2208
|
+
if (event.status !== "completed") {
|
|
1502
2209
|
return;
|
|
2210
|
+
}
|
|
1503
2211
|
reason = "capture was superseded by a refresh";
|
|
1504
|
-
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter)
|
|
2212
|
+
if ((yield* counter(ctx, attempt.scope)) !== attempt.counter) {
|
|
1505
2213
|
return;
|
|
2214
|
+
}
|
|
1506
2215
|
const metadata = event.result.metadata;
|
|
1507
2216
|
reason = "shell result lacks verified foreground completion metadata";
|
|
1508
|
-
if (!isRecord(metadata))
|
|
2217
|
+
if (!isRecord(metadata)) {
|
|
1509
2218
|
return;
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {
|
|
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))) {
|
|
1513
2221
|
return;
|
|
1514
|
-
}
|
|
2222
|
+
}
|
|
2223
|
+
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => {});
|
|
1515
2224
|
reason = "capture session or workspace no longer matches";
|
|
1516
|
-
if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID)
|
|
2225
|
+
if (session === undefined || session.location.workspaceID !== ctx.location.workspaceID) {
|
|
1517
2226
|
return;
|
|
2227
|
+
}
|
|
1518
2228
|
reason = "private artifact is invalid or incomplete (END required)";
|
|
1519
|
-
const baseline = yield* Effect2.try({
|
|
1520
|
-
|
|
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) {
|
|
1521
2234
|
return;
|
|
2235
|
+
}
|
|
1522
2236
|
reason = "capture storage failed or its counter changed";
|
|
1523
2237
|
published = yield* publish(ctx, attempt, generation, baseline);
|
|
1524
2238
|
if (published) {
|
|
@@ -1526,37 +2240,48 @@ Add -s only when the returned policy or repository instructions require it.`,
|
|
|
1526
2240
|
failures.delete(attempt.scope);
|
|
1527
2241
|
yield* recordState(ctx, attempt, "published");
|
|
1528
2242
|
}
|
|
1529
|
-
}).pipe(Effect2.onExit(() => Effect2.gen(function* () {
|
|
1530
|
-
if (pending.get(attempt.scope) === attempt)
|
|
2243
|
+
}).pipe(Effect2.onExit(() => Effect2.gen(function* finalizeCapture() {
|
|
2244
|
+
if (pending.get(attempt.scope) === attempt) {
|
|
1531
2245
|
pending.delete(attempt.scope);
|
|
2246
|
+
}
|
|
1532
2247
|
if (!published) {
|
|
1533
2248
|
rememberFailure(attempt.scope, reason);
|
|
1534
2249
|
yield* recordState(ctx, attempt, "failed", reason).pipe(Effect2.catchCause(() => Effect2.void));
|
|
1535
2250
|
yield* invalidateOwned(ctx, attempt);
|
|
1536
2251
|
}
|
|
1537
|
-
}).pipe(Effect2.ensuring(Effect2.sync(() =>
|
|
2252
|
+
}).pipe(Effect2.ensuring(Effect2.sync(() => {
|
|
2253
|
+
cleanup(attempt);
|
|
2254
|
+
})))), Effect2.catchCause(() => Effect2.void));
|
|
1538
2255
|
const note = published && captured !== undefined ? baselineGuidance(captured, config) : `[commit-guard] This capture did not publish a usable baseline: ${reason.slice(0, 256)}.
|
|
1539
2256
|
` + `RECEIPT_OK alone does not authorize a commit.
|
|
1540
2257
|
` + "Call commit_context with the same workdir for status and next steps.";
|
|
1541
2258
|
if (event.status === "error") {
|
|
1542
|
-
event.error = new Tool.Error({
|
|
2259
|
+
event.error = new Tool.Error({
|
|
2260
|
+
error: event.error.error,
|
|
2261
|
+
metadata: event.error.metadata,
|
|
2262
|
+
message: `${event.error.message}
|
|
1543
2263
|
|
|
1544
|
-
${note}`
|
|
1545
|
-
|
|
2264
|
+
${note}`
|
|
2265
|
+
});
|
|
2266
|
+
} else {
|
|
1546
2267
|
event.result = appendCaptureNote(event.result, note);
|
|
2268
|
+
}
|
|
1547
2269
|
}));
|
|
1548
2270
|
})
|
|
1549
2271
|
});
|
|
1550
2272
|
var plugin_default = plugin;
|
|
1551
|
-
function captureInstructions(attempt, status) {
|
|
2273
|
+
var captureInstructions = function captureInstructions(attempt, status) {
|
|
1552
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:
|
|
1553
2275
|
${attempt.command}`;
|
|
1554
|
-
}
|
|
1555
|
-
function baselineGuidance(baseline, config) {
|
|
1556
|
-
if (baseline.gpgsign === "error" || baseline.signingkey === "error")
|
|
2276
|
+
};
|
|
2277
|
+
var baselineGuidance = function baselineGuidance(baseline, config) {
|
|
2278
|
+
if (baseline.gpgsign === "error" || baseline.signingkey === "error") {
|
|
1557
2279
|
return signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey");
|
|
1558
|
-
|
|
1559
|
-
|
|
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);
|
|
1560
2285
|
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
|
|
1561
2286
|
` : "";
|
|
1562
2287
|
const scopes = config.allowedScopes === undefined ? "No configured scope allowlist." : `Configured scope allowlist: ${config.allowedScopes.join(", ").slice(0, 512)}.`;
|
|
@@ -1568,21 +2293,31 @@ ${examples}Effective commit.gpgsign: ${baseline.gpgsign}. ${signoff}
|
|
|
1568
2293
|
` + `user.signingkey: ${baseline.signingkey === null ? "unset" : "configured"}. Signoff is not a cryptographic signature.
|
|
1569
2294
|
` + `A second commit_context call is optional.
|
|
1570
2295
|
` + "Set refresh:true after a branch switch, changed signing settings, or changed commit instructions.";
|
|
1571
|
-
}
|
|
1572
|
-
function appendCaptureNote(result, note) {
|
|
1573
|
-
const content =
|
|
1574
|
-
const
|
|
1575
|
-
const
|
|
1576
|
-
|
|
1577
|
-
|
|
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}
|
|
1578
2311
|
|
|
1579
|
-
${note}`
|
|
2312
|
+
${note}`
|
|
2313
|
+
}
|
|
2314
|
+
};
|
|
1580
2315
|
}
|
|
1581
2316
|
return annotated;
|
|
1582
|
-
}
|
|
1583
|
-
function signingError(setting) {
|
|
2317
|
+
};
|
|
2318
|
+
var signingError = function signingError(setting) {
|
|
1584
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.`;
|
|
1585
|
-
}
|
|
2320
|
+
};
|
|
1586
2321
|
export {
|
|
1587
2322
|
plugin_default as default
|
|
1588
2323
|
};
|