opencode-commit-guard 1.1.2 → 1.2.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 +16 -5
- package/dist/index.js +1030 -209
- package/package.json +5 -4
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import { randomUUID as randomUUID2 } from "crypto";
|
|
|
4
4
|
import { existsSync as existsSync2, realpathSync as realpathSync2 } from "fs";
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { Plugin, Tool } from "@opencode/plugin/effect";
|
|
7
|
-
import { Cause, Effect as Effect2 } from "effect";
|
|
7
|
+
import { Cause, Clock, Effect as Effect2 } from "effect";
|
|
8
8
|
|
|
9
9
|
// src/capture.ts
|
|
10
10
|
import { createHash, randomUUID } from "crypto";
|
|
@@ -23,7 +23,6 @@ import {
|
|
|
23
23
|
} from "fs";
|
|
24
24
|
import { tmpdir } from "os";
|
|
25
25
|
import nodePath from "path";
|
|
26
|
-
import { gzipSync } from "zlib";
|
|
27
26
|
import { Effect, Semaphore } from "effect";
|
|
28
27
|
|
|
29
28
|
// src/types.ts
|
|
@@ -70,15 +69,17 @@ var isGitDirectory = (dir) => {
|
|
|
70
69
|
}
|
|
71
70
|
};
|
|
72
71
|
var findGitRoot = (startDir) => {
|
|
72
|
+
let found;
|
|
73
73
|
let current;
|
|
74
74
|
try {
|
|
75
75
|
current = realpathSync(startDir);
|
|
76
76
|
} catch {
|
|
77
|
-
return;
|
|
77
|
+
return found;
|
|
78
78
|
}
|
|
79
79
|
while (true) {
|
|
80
80
|
if (isGitDirectory(current)) {
|
|
81
|
-
|
|
81
|
+
found = current;
|
|
82
|
+
break;
|
|
82
83
|
}
|
|
83
84
|
const parent = dirname(current);
|
|
84
85
|
if (parent === current) {
|
|
@@ -86,7 +87,7 @@ var findGitRoot = (startDir) => {
|
|
|
86
87
|
}
|
|
87
88
|
current = parent;
|
|
88
89
|
}
|
|
89
|
-
return;
|
|
90
|
+
return found;
|
|
90
91
|
};
|
|
91
92
|
var findSubRepos = (dir, maxDepth = 2) => {
|
|
92
93
|
const repos = [];
|
|
@@ -94,23 +95,26 @@ var findSubRepos = (dir, maxDepth = 2) => {
|
|
|
94
95
|
if (currentDepth > maxDepth) {
|
|
95
96
|
return;
|
|
96
97
|
}
|
|
98
|
+
let entries = [];
|
|
97
99
|
try {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
100
|
+
entries = readdirSync(currentDir, { withFileTypes: true });
|
|
101
|
+
} catch {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
for (const entry of entries) {
|
|
105
|
+
if (!entry.isDirectory() && !entry.isSymbolicLink()) {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (entry.name.startsWith(".") || entry.name === "node_modules" || entry.name === "dist") {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const fullPath = join(currentDir, entry.name);
|
|
112
|
+
if (isGitDirectory(fullPath)) {
|
|
113
|
+
repos.push(fullPath);
|
|
114
|
+
} else if (currentDepth < maxDepth) {
|
|
115
|
+
search(fullPath, currentDepth + 1);
|
|
112
116
|
}
|
|
113
|
-
}
|
|
117
|
+
}
|
|
114
118
|
};
|
|
115
119
|
search(dir, 1);
|
|
116
120
|
return repos;
|
|
@@ -141,19 +145,20 @@ var resolveTargetWorkdir = (baseDir, requestedDir) => {
|
|
|
141
145
|
return { workdir: realpathSync(baseDir) };
|
|
142
146
|
}
|
|
143
147
|
const subRepos = findSubRepos(baseDir);
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
}
|
|
147
|
-
if (subRepos.length === 0) {
|
|
148
|
+
const [firstRepo] = subRepos;
|
|
149
|
+
if (firstRepo === undefined) {
|
|
148
150
|
return {
|
|
149
151
|
error: `No Git repository found in ${baseDir}. Specify the repository directory with the 'workdir' option, for example: commit_context({ workdir: "path/to/repo" }).`
|
|
150
152
|
};
|
|
151
153
|
}
|
|
154
|
+
if (subRepos.length === 1) {
|
|
155
|
+
return { workdir: realpathSync(firstRepo) };
|
|
156
|
+
}
|
|
152
157
|
const repoList = subRepos.map((repo) => relative(baseDir, repo)).join(", ");
|
|
153
158
|
return {
|
|
154
159
|
error: `The directory ${baseDir} is not a Git repository. Multiple Git repositories were found: ${repoList}.
|
|
155
160
|
Specify which repository to target with the 'workdir' option, for example:
|
|
156
|
-
commit_context({ workdir: "${relative(baseDir,
|
|
161
|
+
commit_context({ workdir: "${relative(baseDir, firstRepo)}" })`
|
|
157
162
|
};
|
|
158
163
|
};
|
|
159
164
|
var counterKey = (scope) => `counter/${scope}`;
|
|
@@ -243,9 +248,9 @@ var load = (ctx, scope) => storageLock.withPermits(1)(Effect.gen(function* readB
|
|
|
243
248
|
}));
|
|
244
249
|
return newest?.baseline;
|
|
245
250
|
}));
|
|
246
|
-
var captureCommand = (path, watchdogSeconds) => {
|
|
247
|
-
if (
|
|
248
|
-
return windowsCaptureCommand(path);
|
|
251
|
+
var captureCommand = (path, watchdogSeconds, platform) => {
|
|
252
|
+
if (platform === "win32") {
|
|
253
|
+
return windowsCaptureCommand(path, watchdogSeconds);
|
|
249
254
|
}
|
|
250
255
|
const quoted = `'${path.replaceAll("'", "'\\''")}'`;
|
|
251
256
|
const script = `set -euo pipefail
|
|
@@ -280,7 +285,8 @@ kill "$watchdog" 2>/dev/null
|
|
|
280
285
|
wait "$watchdog" 2>/dev/null
|
|
281
286
|
exit "$status"' bash '${script.replaceAll("'", "'\\''")}' ${quoted} 2>/dev/null`;
|
|
282
287
|
};
|
|
283
|
-
var windowsCaptureCommand = (path) => {
|
|
288
|
+
var windowsCaptureCommand = (path, watchdogSeconds) => {
|
|
289
|
+
const watchdogMs = Math.round(watchdogSeconds * 1000);
|
|
284
290
|
const script = `$ErrorActionPreference = 'Stop'
|
|
285
291
|
$clock = [Diagnostics.Stopwatch]::StartNew()
|
|
286
292
|
$lines = [Collections.Generic.List[string]]::new()
|
|
@@ -294,24 +300,26 @@ function gitResult([string]$arguments) {
|
|
|
294
300
|
$p = [Diagnostics.Process]::new()
|
|
295
301
|
$p.StartInfo = $info
|
|
296
302
|
$memory = [IO.MemoryStream]::new()
|
|
303
|
+
$started = $false
|
|
297
304
|
try {
|
|
298
|
-
|
|
305
|
+
$started = $p.Start()
|
|
306
|
+
if (!$started) { throw 'Git did not start' }
|
|
299
307
|
$p.BeginErrorReadLine()
|
|
300
308
|
$buffer = [byte[]]::new(4096)
|
|
301
309
|
while ($true) {
|
|
302
310
|
$task = $p.StandardOutput.BaseStream.ReadAsync($buffer, 0, $buffer.Length)
|
|
303
|
-
$remaining =
|
|
311
|
+
$remaining = ${watchdogMs} - [int]$clock.ElapsedMilliseconds
|
|
304
312
|
if ($remaining -le 0 -or !$task.Wait($remaining)) { throw 'Capture timed out' }
|
|
305
313
|
$count = $task.Result
|
|
306
314
|
if ($count -eq 0) { break }
|
|
307
315
|
if ($memory.Length + $count -gt ${maxBytes}) { throw 'Capture exceeds size limit' }
|
|
308
316
|
$memory.Write($buffer, 0, $count)
|
|
309
317
|
}
|
|
310
|
-
$remaining =
|
|
318
|
+
$remaining = ${watchdogMs} - [int]$clock.ElapsedMilliseconds
|
|
311
319
|
if ($remaining -le 0 -or !$p.WaitForExit($remaining)) { throw 'Capture timed out' }
|
|
312
320
|
return @{ Code = $p.ExitCode; Bytes = $memory.ToArray() }
|
|
313
321
|
} finally {
|
|
314
|
-
if ($
|
|
322
|
+
if ($started -and !$p.HasExited) { try { $p.Kill($true) } catch {} }
|
|
315
323
|
$p.Dispose()
|
|
316
324
|
$memory.Dispose()
|
|
317
325
|
}
|
|
@@ -344,34 +352,34 @@ try {
|
|
|
344
352
|
}
|
|
345
353
|
$lines.Add('END')
|
|
346
354
|
$bytes = [Text.Encoding]::UTF8.GetBytes(($lines -join "\`n") + "\`n")
|
|
347
|
-
if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge
|
|
355
|
+
if ($bytes.Length -gt ${maxBytes} -or $clock.ElapsedMilliseconds -ge ${watchdogMs}) { throw 'Capture exceeds limits' }
|
|
348
356
|
$path = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(path).toString("base64")}'))
|
|
349
357
|
$file = [IO.FileStream]::new($path, [IO.FileMode]::Truncate, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete)
|
|
350
358
|
try { $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() }
|
|
351
359
|
[Console]::Write("RECEIPT_OK\`n")
|
|
352
360
|
} catch { exit 1 }`;
|
|
353
|
-
|
|
354
|
-
const bootstrap = `$m = [IO.MemoryStream]::new([Convert]::FromBase64String('${compressed}')); $g = [IO.Compression.GZipStream]::new($m, [IO.Compression.CompressionMode]::Decompress); $r = [IO.StreamReader]::new($g, [Text.Encoding]::UTF8); try { Invoke-Expression $r.ReadToEnd() } finally { $r.Dispose(); $g.Dispose(); $m.Dispose() }`;
|
|
355
|
-
return `powershell -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(bootstrap, "utf16le").toString("base64")}`;
|
|
361
|
+
return `pwsh -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
|
|
356
362
|
};
|
|
357
|
-
var createPending = (scope, sessionID, agent, counterValue, workdir, watchdogSeconds = 15) => {
|
|
363
|
+
var createPending = (scope, sessionID, agent, counterValue, workdir, watchdogSeconds = 15, platform = process.platform, now = 0) => {
|
|
358
364
|
const directory = mkdtempSync(join(tmpdir(), "commit-context-"));
|
|
359
365
|
try {
|
|
360
366
|
const file = join(directory, randomUUID());
|
|
361
367
|
const fd = openSync(file, constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_RDWR, 384);
|
|
362
368
|
const stat = fstatSync(fd);
|
|
363
|
-
|
|
369
|
+
const attempt = {
|
|
364
370
|
scope,
|
|
365
371
|
sessionID,
|
|
366
372
|
agent,
|
|
367
373
|
counter: counterValue,
|
|
374
|
+
artifactPath: file,
|
|
368
375
|
directory,
|
|
369
376
|
workdir,
|
|
370
377
|
fd,
|
|
371
378
|
identity: { dev: stat.dev, ino: stat.ino, uid: stat.uid },
|
|
372
|
-
expires:
|
|
373
|
-
command: captureCommand(file, watchdogSeconds)
|
|
379
|
+
expires: now + captureTimeout,
|
|
380
|
+
command: captureCommand(file, watchdogSeconds, platform)
|
|
374
381
|
};
|
|
382
|
+
return attempt;
|
|
375
383
|
} catch (error) {
|
|
376
384
|
rmSync(directory, { recursive: true, force: true });
|
|
377
385
|
throw error;
|
|
@@ -391,9 +399,9 @@ var decode = (line) => {
|
|
|
391
399
|
}
|
|
392
400
|
return Buffer.from(line, "base64").toString("utf-8");
|
|
393
401
|
};
|
|
394
|
-
var readCaptureArtifact = (pending) => {
|
|
402
|
+
var readCaptureArtifact = (pending, platform = process.platform) => {
|
|
395
403
|
const stat = fstatSync(pending.fd);
|
|
396
|
-
if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid ||
|
|
404
|
+
if (!stat.isFile() || stat.dev !== pending.identity.dev || stat.ino !== pending.identity.ino || stat.uid !== pending.identity.uid || platform !== "win32" && (stat.mode & 511) !== 384 || stat.size > maxBytes || stat.size === 0) {
|
|
397
405
|
throw new Error("Invalid private capture artifact");
|
|
398
406
|
}
|
|
399
407
|
const bytes = Buffer.alloc(stat.size);
|
|
@@ -419,21 +427,21 @@ var decodeConfigField = (state, field) => {
|
|
|
419
427
|
};
|
|
420
428
|
var assertBaselineIdentity = (baseline, fields, rawLog) => {
|
|
421
429
|
const { directory, gitDir, commonDir, head, messages } = baseline;
|
|
422
|
-
if (!isAbsolute(directory) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || directory !== findGitRoot(baseline.workdir) || !["branch", "detached"].includes(fields[4]) || !["head", "unborn"].includes(fields[6]) || head !== null && !/^[a-f0-9]{40,64}$/u.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00"))) {
|
|
430
|
+
if (!isAbsolute(directory) || !isAbsolute(gitDir) || !isAbsolute(commonDir) || directory !== findGitRoot(baseline.workdir) || !["branch", "detached"].includes(fields[4] ?? "") || !["head", "unborn"].includes(fields[6] ?? "") || head !== null && !/^[a-f0-9]{40,64}$/u.test(head) || head === null && rawLog !== "" || head !== null && (messages.length === 0 || messages.length > 10 || !rawLog.endsWith("\x00\x00"))) {
|
|
423
431
|
throw new Error("Invalid Git baseline");
|
|
424
432
|
}
|
|
425
433
|
};
|
|
426
|
-
var importCapture = (pending) => {
|
|
427
|
-
const fields = readCaptureArtifact(pending);
|
|
428
|
-
const rawRoot = decode(fields[1]).trimEnd();
|
|
434
|
+
var importCapture = (pending, platform = process.platform) => {
|
|
435
|
+
const fields = readCaptureArtifact(pending, platform);
|
|
436
|
+
const rawRoot = decode(fields[1] ?? "").trimEnd();
|
|
429
437
|
const root = isAbsolute(rawRoot) ? realpathSync(resolve(rawRoot)) : rawRoot;
|
|
430
|
-
const gitDir = decode(fields[2]).trimEnd();
|
|
431
|
-
const commonDir = decode(fields[3]).trimEnd();
|
|
432
|
-
const branch = fields[4] === "branch" ? decode(fields[5]).trimEnd() : null;
|
|
433
|
-
const head = fields[6] === "head" ? decode(fields[7]).trim() : null;
|
|
434
|
-
const rawLog = decode(fields[8]);
|
|
438
|
+
const gitDir = decode(fields[2] ?? "").trimEnd();
|
|
439
|
+
const commonDir = decode(fields[3] ?? "").trimEnd();
|
|
440
|
+
const branch = fields[4] === "branch" ? decode(fields[5] ?? "").trimEnd() : null;
|
|
441
|
+
const head = fields[6] === "head" ? decode(fields[7] ?? "").trim() : null;
|
|
442
|
+
const rawLog = decode(fields[8] ?? "");
|
|
435
443
|
const messages = head === null ? [] : rawLog.split("\x00\x00").filter((message) => message.length > 0);
|
|
436
|
-
const value = decode(fields[10]).trim();
|
|
444
|
+
const value = decode(fields[10] ?? "").trim();
|
|
437
445
|
let gpgsign = fields[9] === "unset" ? "unset" : "error";
|
|
438
446
|
if (fields[9] === "set" && (value === "true" || value === "false")) {
|
|
439
447
|
gpgsign = value;
|
|
@@ -447,16 +455,16 @@ var importCapture = (pending) => {
|
|
|
447
455
|
head,
|
|
448
456
|
messages,
|
|
449
457
|
gpgsign,
|
|
450
|
-
signingkey: decodeConfigField(fields[11], fields[12])
|
|
458
|
+
signingkey: decodeConfigField(fields[11] ?? "", fields[12] ?? "")
|
|
451
459
|
};
|
|
452
460
|
assertBaselineIdentity(baseline, fields, rawLog);
|
|
453
461
|
return baseline;
|
|
454
462
|
};
|
|
455
|
-
var publish = (ctx, pending, generation, baseline) => storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
|
|
463
|
+
var publish = (ctx, pending, generation, baseline, now) => storageLock.withPermits(1)(Effect.gen(function* writeBaseline() {
|
|
456
464
|
if ((yield* counter(ctx, pending.scope)) !== pending.counter) {
|
|
457
465
|
return false;
|
|
458
466
|
}
|
|
459
|
-
const sequence = `${
|
|
467
|
+
const sequence = `${now.toString().padStart(15, "0")}-${randomUUID()}`;
|
|
460
468
|
const checksum = snapshotChecksum(pending.scope, pending.counter, generation, sequence, baseline);
|
|
461
469
|
yield* ctx.storage.set(prefix(pending.scope) + sequence, {
|
|
462
470
|
schema: version,
|
|
@@ -732,7 +740,7 @@ var scanDoubleQuote = (command, start, nesting) => {
|
|
|
732
740
|
while (i < command.length && command[i] !== '"') {
|
|
733
741
|
const character = command[i];
|
|
734
742
|
if (character === "\\" && i + 1 < command.length) {
|
|
735
|
-
const escaped = command[i + 1];
|
|
743
|
+
const escaped = command[i + 1] ?? "";
|
|
736
744
|
if (escaped !== `
|
|
737
745
|
`) {
|
|
738
746
|
content += ['"', "\\", "$", "`"].includes(escaped) ? escaped : `\\${escaped}`;
|
|
@@ -818,13 +826,14 @@ var trackSubstitutionWord = (command, state) => {
|
|
|
818
826
|
}
|
|
819
827
|
let word = "";
|
|
820
828
|
for (let end = state.i;end < command.length; end += 1) {
|
|
821
|
-
|
|
829
|
+
const ch = command[end] ?? "";
|
|
830
|
+
if (ch === "\\" && command[end + 1] === `
|
|
822
831
|
`) {
|
|
823
832
|
end += 1;
|
|
824
|
-
} else if (isWordSeparator(
|
|
833
|
+
} else if (isWordSeparator(ch)) {
|
|
825
834
|
break;
|
|
826
835
|
} else {
|
|
827
|
-
word +=
|
|
836
|
+
word += ch;
|
|
828
837
|
}
|
|
829
838
|
}
|
|
830
839
|
advanceCaseState(state.cases, state.depth, word);
|
|
@@ -885,7 +894,7 @@ var stepSubstitutionSyntax = (command, state, nesting) => {
|
|
|
885
894
|
};
|
|
886
895
|
var stepSubstitutionWord = (command, state, nesting) => {
|
|
887
896
|
const { i } = state;
|
|
888
|
-
const character = command[i];
|
|
897
|
+
const character = command[i] ?? "";
|
|
889
898
|
if (character === "#" && state.atWordStart) {
|
|
890
899
|
const end = command.indexOf(`
|
|
891
900
|
`, i);
|
|
@@ -896,7 +905,7 @@ var stepSubstitutionWord = (command, state, nesting) => {
|
|
|
896
905
|
trackSubstitutionWord(command, state);
|
|
897
906
|
}
|
|
898
907
|
const result = scanWordFragment(command, i, nesting + 1);
|
|
899
|
-
if (result ===
|
|
908
|
+
if (result === null) {
|
|
900
909
|
return false;
|
|
901
910
|
}
|
|
902
911
|
state.i = result.end;
|
|
@@ -953,7 +962,7 @@ var consumeCommandSubstitution = (command, start, nesting = 0) => {
|
|
|
953
962
|
if (stepSubstitutionSyntax(command, state, nesting) || stepSubstitutionWord(command, state, nesting)) {
|
|
954
963
|
continue;
|
|
955
964
|
}
|
|
956
|
-
const character = command[state.i];
|
|
965
|
+
const character = command[state.i] ?? "";
|
|
957
966
|
if (stepSubstitutionParenthesis(command, state)) {
|
|
958
967
|
continue;
|
|
959
968
|
}
|
|
@@ -995,6 +1004,9 @@ var heredocSubstitutions = (body) => {
|
|
|
995
1004
|
var isBraceCommandPosition = (tokens) => {
|
|
996
1005
|
for (let index = tokens.length - 1;index >= 0; index -= 1) {
|
|
997
1006
|
const token = tokens[index];
|
|
1007
|
+
if (token === undefined) {
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
998
1010
|
if (token.type === "operator") {
|
|
999
1011
|
break;
|
|
1000
1012
|
}
|
|
@@ -1027,8 +1039,11 @@ var scanWord = (command, start, nesting) => {
|
|
|
1027
1039
|
let expansion = false;
|
|
1028
1040
|
let unsupportedDelimiter;
|
|
1029
1041
|
let i = start;
|
|
1030
|
-
while (i < command.length
|
|
1031
|
-
const character = command[i];
|
|
1042
|
+
while (i < command.length) {
|
|
1043
|
+
const character = command[i] ?? "";
|
|
1044
|
+
if (isWordSeparator(character)) {
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
1032
1047
|
if (character === "\\" && command[i + 1] === `
|
|
1033
1048
|
`) {
|
|
1034
1049
|
i += 2;
|
|
@@ -1045,7 +1060,7 @@ var scanWord = (command, start, nesting) => {
|
|
|
1045
1060
|
unsupportedDelimiter = dollarQuote === "'" ? "ANSI-C quoted" : "locale-quoted";
|
|
1046
1061
|
}
|
|
1047
1062
|
const result = scanWordFragment(command, i, nesting);
|
|
1048
|
-
if (result !==
|
|
1063
|
+
if (result !== null) {
|
|
1049
1064
|
quoted ||= result.quoted === true;
|
|
1050
1065
|
if (result.bytes === undefined) {
|
|
1051
1066
|
content += result.content;
|
|
@@ -1094,17 +1109,18 @@ var scanWordFragment = (command, i, nesting) => {
|
|
|
1094
1109
|
substitutions: [result.content]
|
|
1095
1110
|
};
|
|
1096
1111
|
}
|
|
1097
|
-
return;
|
|
1112
|
+
return null;
|
|
1098
1113
|
};
|
|
1099
1114
|
var skipTrivia = (command, start) => {
|
|
1100
1115
|
let i = start;
|
|
1101
1116
|
while (i < command.length) {
|
|
1102
|
-
|
|
1117
|
+
const ch = command[i] ?? "";
|
|
1118
|
+
if (/[ \t\r]/u.test(ch)) {
|
|
1103
1119
|
i += 1;
|
|
1104
|
-
} else if (
|
|
1120
|
+
} else if (ch === "\\" && command[i + 1] === `
|
|
1105
1121
|
`) {
|
|
1106
1122
|
i += 2;
|
|
1107
|
-
} else if (
|
|
1123
|
+
} else if (ch === "#") {
|
|
1108
1124
|
const end = command.indexOf(`
|
|
1109
1125
|
`, i);
|
|
1110
1126
|
i = end === -1 ? command.length : end;
|
|
@@ -1117,7 +1133,8 @@ var skipTrivia = (command, start) => {
|
|
|
1117
1133
|
var readHeredocDelimiter = (command, start, nesting) => {
|
|
1118
1134
|
const stripTabs = command[start + 2] === "-";
|
|
1119
1135
|
const i = skipTrivia(command, start + (stripTabs ? 3 : 2));
|
|
1120
|
-
|
|
1136
|
+
const next = command[i];
|
|
1137
|
+
if (next === undefined || isWordSeparator(next) || /[<>]/u.test(next)) {
|
|
1121
1138
|
throw incompleteHeredoc();
|
|
1122
1139
|
}
|
|
1123
1140
|
const word = scanWord(command, i, nesting);
|
|
@@ -1127,7 +1144,7 @@ var readHeredocDelimiter = (command, start, nesting) => {
|
|
|
1127
1144
|
return {
|
|
1128
1145
|
delimiter: {
|
|
1129
1146
|
delimiter: word.content,
|
|
1130
|
-
quoted: word.quoted
|
|
1147
|
+
quoted: word.quoted,
|
|
1131
1148
|
stripTabs
|
|
1132
1149
|
},
|
|
1133
1150
|
end: word.end
|
|
@@ -1139,6 +1156,9 @@ var readOperator = (command, i, tokens) => {
|
|
|
1139
1156
|
return pair;
|
|
1140
1157
|
}
|
|
1141
1158
|
const character = command[i];
|
|
1159
|
+
if (character === undefined) {
|
|
1160
|
+
return null;
|
|
1161
|
+
}
|
|
1142
1162
|
if (`|;
|
|
1143
1163
|
()`.includes(character) || character === "&" && command[i + 1] !== ">") {
|
|
1144
1164
|
return character;
|
|
@@ -1149,11 +1169,12 @@ var readOperator = (command, i, tokens) => {
|
|
|
1149
1169
|
`) {
|
|
1150
1170
|
end += 2;
|
|
1151
1171
|
}
|
|
1152
|
-
|
|
1172
|
+
const following = command[end];
|
|
1173
|
+
if (following === undefined || isWordSeparator(following) || /[<>]/u.test(following)) {
|
|
1153
1174
|
return character;
|
|
1154
1175
|
}
|
|
1155
1176
|
}
|
|
1156
|
-
return;
|
|
1177
|
+
return null;
|
|
1157
1178
|
};
|
|
1158
1179
|
var tokenizeShell = (command) => {
|
|
1159
1180
|
const tokens = [];
|
|
@@ -1163,7 +1184,7 @@ var tokenizeShell = (command) => {
|
|
|
1163
1184
|
let i = 0;
|
|
1164
1185
|
while ((i = skipTrivia(command, i)) < command.length) {
|
|
1165
1186
|
const operator = readOperator(command, i, tokens);
|
|
1166
|
-
if (operator !==
|
|
1187
|
+
if (operator !== null) {
|
|
1167
1188
|
if (operator === "(") {
|
|
1168
1189
|
if (arithmeticDepth === undefined && command[i + 1] === "(" && isArithmeticCommandPosition(tokens)) {
|
|
1169
1190
|
arithmeticDepth = depth;
|
|
@@ -1182,11 +1203,14 @@ var tokenizeShell = (command) => {
|
|
|
1182
1203
|
for (const heredoc of heredocs) {
|
|
1183
1204
|
const body = consumeHeredoc(command, i, heredoc);
|
|
1184
1205
|
i = body.end;
|
|
1185
|
-
tokens[heredoc.index]
|
|
1186
|
-
|
|
1187
|
-
heredoc
|
|
1188
|
-
|
|
1189
|
-
|
|
1206
|
+
const target = tokens[heredoc.index];
|
|
1207
|
+
if (target !== undefined) {
|
|
1208
|
+
tokens[heredoc.index] = {
|
|
1209
|
+
...target,
|
|
1210
|
+
heredoc: { body: body.content, quoted: heredoc.quoted },
|
|
1211
|
+
substitutions: heredoc.quoted ? undefined : heredocSubstitutions(body.content)
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1190
1214
|
}
|
|
1191
1215
|
heredocs.length = 0;
|
|
1192
1216
|
}
|
|
@@ -1219,41 +1243,18 @@ var tokenizeShell = (command) => {
|
|
|
1219
1243
|
}
|
|
1220
1244
|
return tokens;
|
|
1221
1245
|
};
|
|
1222
|
-
var splitSimpleCommands = (tokens) => {
|
|
1223
|
-
const commands = [];
|
|
1224
|
-
let current = [];
|
|
1225
|
-
let precedingPipeline = false;
|
|
1226
|
-
for (const token of tokens) {
|
|
1227
|
-
if (token.type === "operator") {
|
|
1228
|
-
const isPipeline = token.value === "|" || token.value === "|&";
|
|
1229
|
-
const hasCommand = current.length > 0;
|
|
1230
|
-
if (hasCommand) {
|
|
1231
|
-
commands.push({
|
|
1232
|
-
tokens: current,
|
|
1233
|
-
pipeline: precedingPipeline || isPipeline
|
|
1234
|
-
});
|
|
1235
|
-
}
|
|
1236
|
-
current = [];
|
|
1237
|
-
if (hasCommand || token.value !== `
|
|
1238
|
-
`) {
|
|
1239
|
-
precedingPipeline = isPipeline;
|
|
1240
|
-
}
|
|
1241
|
-
} else {
|
|
1242
|
-
current.push(token);
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
if (current.length > 0) {
|
|
1246
|
-
commands.push({ tokens: current, pipeline: precedingPipeline });
|
|
1247
|
-
}
|
|
1248
|
-
return commands;
|
|
1249
|
-
};
|
|
1250
1246
|
var extractCommandWords = (tokens) => {
|
|
1251
1247
|
const words = [];
|
|
1252
1248
|
for (let i = 0;i < tokens.length; i += 1) {
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1249
|
+
const token = tokens[i];
|
|
1250
|
+
if (token === undefined) {
|
|
1251
|
+
continue;
|
|
1252
|
+
}
|
|
1253
|
+
if (token.type === "redirect") {
|
|
1254
|
+
const hasEmbeddedTarget = /[<>]&(?:\d+|-)$/u.test(token.value);
|
|
1255
|
+
i += !hasEmbeddedTarget && tokens[i + 1]?.type === "word" ? 1 : 0;
|
|
1256
|
+
} else if (token.type === "word") {
|
|
1257
|
+
words.push(token);
|
|
1257
1258
|
}
|
|
1258
1259
|
}
|
|
1259
1260
|
return words;
|
|
@@ -1263,6 +1264,9 @@ var skipWrapperOptions = (words, start, valued) => {
|
|
|
1263
1264
|
let index = start;
|
|
1264
1265
|
while (index < words.length) {
|
|
1265
1266
|
const argument = words[index];
|
|
1267
|
+
if (argument === undefined) {
|
|
1268
|
+
break;
|
|
1269
|
+
}
|
|
1266
1270
|
if (argument === "--") {
|
|
1267
1271
|
return index + 1;
|
|
1268
1272
|
}
|
|
@@ -1277,6 +1281,9 @@ var findCommandStart = (words) => {
|
|
|
1277
1281
|
let index = 0;
|
|
1278
1282
|
while (index < words.length) {
|
|
1279
1283
|
const word = words[index];
|
|
1284
|
+
if (word === undefined) {
|
|
1285
|
+
break;
|
|
1286
|
+
}
|
|
1280
1287
|
if (isAssignment(word) || commandPrefixes.has(word)) {
|
|
1281
1288
|
index += 1;
|
|
1282
1289
|
} else {
|
|
@@ -1294,6 +1301,9 @@ var consumeGitGlobalOptions = (words, start) => {
|
|
|
1294
1301
|
let targetError;
|
|
1295
1302
|
while (index < words.length) {
|
|
1296
1303
|
const token = words[index];
|
|
1304
|
+
if (token === undefined) {
|
|
1305
|
+
break;
|
|
1306
|
+
}
|
|
1297
1307
|
const argument = token.value;
|
|
1298
1308
|
if (token.expansion === true) {
|
|
1299
1309
|
throw inspectionError("Cannot inspect dynamic Git options or subcommands. Use literal command words.");
|
|
@@ -1307,7 +1317,7 @@ var consumeGitGlobalOptions = (words, start) => {
|
|
|
1307
1317
|
if (!argument.startsWith("-")) {
|
|
1308
1318
|
break;
|
|
1309
1319
|
}
|
|
1310
|
-
const option = /^-[Cc]/u.test(argument) ? argument.slice(0, 2) : argument.split("=")[0];
|
|
1320
|
+
const option = /^-[Cc]/u.test(argument) ? argument.slice(0, 2) : argument.split("=")[0] ?? "";
|
|
1311
1321
|
if (targetGlobalOptions.has(option)) {
|
|
1312
1322
|
targetError = "Git global directory or configuration flags can change the commit target or signing policy. Use a direct git commit in the captured workdir.";
|
|
1313
1323
|
}
|
|
@@ -1315,9 +1325,8 @@ var consumeGitGlobalOptions = (words, start) => {
|
|
|
1315
1325
|
}
|
|
1316
1326
|
return { index, targetError };
|
|
1317
1327
|
};
|
|
1318
|
-
var consumeShortCommitFlags = (words, start, result) => {
|
|
1328
|
+
var consumeShortCommitFlags = (words, start, argument, result) => {
|
|
1319
1329
|
let index = start;
|
|
1320
|
-
const argument = words[start].value;
|
|
1321
1330
|
for (let i = 1;i < argument.length; i += 1) {
|
|
1322
1331
|
const option = argument[i];
|
|
1323
1332
|
if (option === "s") {
|
|
@@ -1345,6 +1354,18 @@ var consumeShortCommitFlags = (words, start, result) => {
|
|
|
1345
1354
|
}
|
|
1346
1355
|
return index;
|
|
1347
1356
|
};
|
|
1357
|
+
var consumeMessageOrFileFlag = (words, index, argument, isMessage, result) => {
|
|
1358
|
+
const equals = argument.indexOf("=");
|
|
1359
|
+
const nextIndex = equals === -1 ? index + 1 : index;
|
|
1360
|
+
const input = equals === -1 ? words[nextIndex]?.value : argument.slice(equals + 1);
|
|
1361
|
+
if (isMessage) {
|
|
1362
|
+
result.messageExpansion ||= words[nextIndex]?.expansion === true;
|
|
1363
|
+
}
|
|
1364
|
+
if (input !== undefined) {
|
|
1365
|
+
(isMessage ? result.messages : result.filePaths).push(input);
|
|
1366
|
+
}
|
|
1367
|
+
return nextIndex;
|
|
1368
|
+
};
|
|
1348
1369
|
var parseCommitArguments = (words, start) => {
|
|
1349
1370
|
const result = {
|
|
1350
1371
|
messages: [],
|
|
@@ -1358,45 +1379,40 @@ var parseCommitArguments = (words, start) => {
|
|
|
1358
1379
|
hasTrailer: false
|
|
1359
1380
|
};
|
|
1360
1381
|
for (let index = start;index < words.length; index += 1) {
|
|
1361
|
-
const
|
|
1362
|
-
if (
|
|
1382
|
+
const token = words[index];
|
|
1383
|
+
if (token === undefined || token.value === "--") {
|
|
1363
1384
|
break;
|
|
1364
1385
|
}
|
|
1386
|
+
const argument = token.value;
|
|
1365
1387
|
const boolean = booleanCommitFlags.get(argument);
|
|
1366
1388
|
if (boolean !== undefined) {
|
|
1367
1389
|
Object.assign(result, { [boolean[0]]: boolean[1] });
|
|
1368
1390
|
continue;
|
|
1369
1391
|
}
|
|
1370
|
-
const [option] = argument.split("=");
|
|
1392
|
+
const [option = ""] = argument.split("=");
|
|
1371
1393
|
const isMessage = option === "--message" || argument === "-m";
|
|
1372
1394
|
const isFile = option === "--file" || argument === "-F";
|
|
1373
1395
|
if (isMessage || isFile) {
|
|
1374
|
-
|
|
1375
|
-
const input = equals === -1 ? words[index += 1]?.value : argument.slice(equals + 1);
|
|
1376
|
-
if (isMessage) {
|
|
1377
|
-
result.messageExpansion ||= words[index]?.expansion === true;
|
|
1378
|
-
}
|
|
1379
|
-
if (input !== undefined) {
|
|
1380
|
-
(isMessage ? result.messages : result.filePaths).push(input);
|
|
1381
|
-
}
|
|
1396
|
+
index = consumeMessageOrFileFlag(words, index, argument, isMessage, result);
|
|
1382
1397
|
} else if (commitLongOptionsWithArg.has(option)) {
|
|
1383
1398
|
result.isFixup ||= option === "--fixup";
|
|
1384
1399
|
result.hasTrailer ||= option === "--trailer";
|
|
1385
1400
|
index += argument.includes("=") ? 0 : 1;
|
|
1386
1401
|
} else if (/^-[^-]/u.test(argument)) {
|
|
1387
|
-
index = consumeShortCommitFlags(words, index, result);
|
|
1402
|
+
index = consumeShortCommitFlags(words, index, argument, result);
|
|
1388
1403
|
}
|
|
1389
1404
|
}
|
|
1390
1405
|
return result;
|
|
1391
1406
|
};
|
|
1392
|
-
var
|
|
1407
|
+
var isGitExecutable = (executable, mode) => mode === "pwsh" ? /^(?:.*[/\\])?git(?:\.exe)?$/iu.test(executable) : executable === "git" || executable.endsWith("/git");
|
|
1408
|
+
var extractInvocation = (words, start, mode) => {
|
|
1393
1409
|
const executable = words[start]?.value;
|
|
1394
|
-
if (executable === undefined || executable
|
|
1395
|
-
return;
|
|
1410
|
+
if (executable === undefined || !isGitExecutable(executable, mode)) {
|
|
1411
|
+
return null;
|
|
1396
1412
|
}
|
|
1397
1413
|
const global = consumeGitGlobalOptions(words, start + 1);
|
|
1398
1414
|
if (words[global.index]?.value !== "commit") {
|
|
1399
|
-
return;
|
|
1415
|
+
return null;
|
|
1400
1416
|
}
|
|
1401
1417
|
const wrapperChange = words.slice(0, start).some((word) => word.value === "env" || isAssignment(word.value));
|
|
1402
1418
|
return {
|
|
@@ -1408,7 +1424,7 @@ var consumeShellOptions = (words, start) => {
|
|
|
1408
1424
|
let index = start + 1;
|
|
1409
1425
|
let executeString = false;
|
|
1410
1426
|
while (index < words.length) {
|
|
1411
|
-
const option = words[index]
|
|
1427
|
+
const option = words[index]?.value ?? "";
|
|
1412
1428
|
if (option === "--") {
|
|
1413
1429
|
index += 1;
|
|
1414
1430
|
break;
|
|
@@ -1429,17 +1445,17 @@ var consumeShellOptions = (words, start) => {
|
|
|
1429
1445
|
};
|
|
1430
1446
|
var extractShellCBody = (words, start) => {
|
|
1431
1447
|
if (!/^(?:.*\/)?(?:bash|sh|zsh)$/u.test(words[start]?.value ?? "")) {
|
|
1432
|
-
return;
|
|
1448
|
+
return null;
|
|
1433
1449
|
}
|
|
1434
1450
|
const { index, executeString } = consumeShellOptions(words, start);
|
|
1435
1451
|
if (!executeString) {
|
|
1436
|
-
return;
|
|
1452
|
+
return null;
|
|
1437
1453
|
}
|
|
1438
1454
|
const body = words[index];
|
|
1439
1455
|
if (body === undefined || body.expansion === true) {
|
|
1440
1456
|
throw inspectionError("Cannot parse an expanded or missing shell -c body reliably. Use a literal shell body; if committing, run git commit directly.");
|
|
1441
1457
|
}
|
|
1442
|
-
if (/^(?:.*\/)?sh$/u.test(words[start]
|
|
1458
|
+
if (/^(?:.*\/)?sh$/u.test(words[start]?.value ?? "") && body.value.includes("$'")) {
|
|
1443
1459
|
throw inspectionError("Cannot parse $' quoting portably in sh -c. Use a literal bash -c or zsh -c body.");
|
|
1444
1460
|
}
|
|
1445
1461
|
return body.value;
|
|
@@ -1471,44 +1487,740 @@ var attachStdinHeredoc = (invocation, tokens, pipeline) => {
|
|
|
1471
1487
|
stdinMessage: stdinError === undefined ? heredoc?.heredoc?.body : undefined
|
|
1472
1488
|
};
|
|
1473
1489
|
};
|
|
1474
|
-
var
|
|
1490
|
+
var pwshBacktickEscapes = new Map(Object.entries({
|
|
1491
|
+
"0": "\x00",
|
|
1492
|
+
a: "\x07",
|
|
1493
|
+
b: "\b",
|
|
1494
|
+
e: "\x1B",
|
|
1495
|
+
f: "\f",
|
|
1496
|
+
n: `
|
|
1497
|
+
`,
|
|
1498
|
+
r: "\r",
|
|
1499
|
+
t: "\t",
|
|
1500
|
+
v: "\v"
|
|
1501
|
+
}));
|
|
1502
|
+
var pwshTargetMutators = new Set([
|
|
1503
|
+
"cd",
|
|
1504
|
+
"sl",
|
|
1505
|
+
"set-location",
|
|
1506
|
+
"push-location",
|
|
1507
|
+
"pushd",
|
|
1508
|
+
"pop-location",
|
|
1509
|
+
"popd",
|
|
1510
|
+
"set-variable",
|
|
1511
|
+
"sv",
|
|
1512
|
+
"iex",
|
|
1513
|
+
"invoke-expression",
|
|
1514
|
+
"."
|
|
1515
|
+
]);
|
|
1516
|
+
var isPwshSingleQuote = (character) => character === "'" || character >= "\u2018" && character <= "\u201B";
|
|
1517
|
+
var isPwshDoubleQuote = (character) => character === '"' || character >= "\u201C" && character <= "\u201E";
|
|
1518
|
+
var isPwshHorizontalSpace = (character) => character === " " || character === "\t" || character === "\x85" || character === "\xA0" || character === "\u2028" || character === "\u2029" || character === "\v" || character === "\f" || /^\p{Zs}$/u.test(character);
|
|
1519
|
+
var isPwshNewline = (character) => character === `
|
|
1520
|
+
` || character === "\r";
|
|
1521
|
+
var isPwshWordSeparator = (character) => isPwshHorizontalSpace(character) || isPwshNewline(character) || ";&|(){}".includes(character);
|
|
1522
|
+
var isPwshVariableStart = (command, index) => command[index] === "$" && /[\p{L}\p{N}_?^$:]/u.test(command[index + 1] ?? "");
|
|
1523
|
+
var decodePwshBacktick = (command, start) => {
|
|
1524
|
+
const next = command[start + 1];
|
|
1525
|
+
if (next === undefined) {
|
|
1526
|
+
return { content: "`", end: start + 1 };
|
|
1527
|
+
}
|
|
1528
|
+
if (next === "\r" && command[start + 2] === `
|
|
1529
|
+
`) {
|
|
1530
|
+
return { content: `
|
|
1531
|
+
`, end: start + 3 };
|
|
1532
|
+
}
|
|
1533
|
+
if (next === "u" && command[start + 2] === "{") {
|
|
1534
|
+
const close = command.indexOf("}", start + 3);
|
|
1535
|
+
const hex = close === -1 ? "" : command.slice(start + 3, close);
|
|
1536
|
+
if (close === -1 || !/^[0-9a-fA-F]{1,6}$/u.test(hex)) {
|
|
1537
|
+
throw inspectionError("Invalid PowerShell Unicode escape sequence. Use valid `u{hex} syntax.");
|
|
1538
|
+
}
|
|
1539
|
+
const code = Number.parseInt(hex, 16);
|
|
1540
|
+
if (code > 1114111 || code >= 55296 && code <= 57343) {
|
|
1541
|
+
throw inspectionError("Invalid PowerShell Unicode scalar value in `u{hex} escape.");
|
|
1542
|
+
}
|
|
1543
|
+
return { content: String.fromCodePoint(code), end: close + 1 };
|
|
1544
|
+
}
|
|
1545
|
+
const mapped = pwshBacktickEscapes.get(next);
|
|
1546
|
+
return { content: mapped ?? next, end: start + 2 };
|
|
1547
|
+
};
|
|
1548
|
+
var scanPwshSingleQuote = (command, start) => {
|
|
1549
|
+
let content = "";
|
|
1550
|
+
let i = start + 1;
|
|
1551
|
+
while (i < command.length) {
|
|
1552
|
+
const ch = command[i] ?? "";
|
|
1553
|
+
if (isPwshSingleQuote(ch)) {
|
|
1554
|
+
const next = command[i + 1] ?? "";
|
|
1555
|
+
if (isPwshSingleQuote(next)) {
|
|
1556
|
+
content += next;
|
|
1557
|
+
i += 2;
|
|
1558
|
+
continue;
|
|
1559
|
+
}
|
|
1560
|
+
return { content, end: i + 1 };
|
|
1561
|
+
}
|
|
1562
|
+
content += ch;
|
|
1563
|
+
i += 1;
|
|
1564
|
+
}
|
|
1565
|
+
throw inspectionError(`Unterminated PowerShell single quote starting at character ${start + 1}. Close the quote before running the command.`);
|
|
1566
|
+
};
|
|
1567
|
+
var scanPwshBracedVar = (command, start) => {
|
|
1568
|
+
for (let i = start + 2;i < command.length; i += 1) {
|
|
1569
|
+
if (command[i] === "`") {
|
|
1570
|
+
i += 1;
|
|
1571
|
+
} else if (command[i] === "}") {
|
|
1572
|
+
return i + 1;
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
throw inspectionError(`Unterminated PowerShell braced variable starting at character ${start + 1}.`);
|
|
1576
|
+
};
|
|
1577
|
+
var skipPwshBlockComment = (command, start) => {
|
|
1578
|
+
const end = command.indexOf("#>", start + 2);
|
|
1579
|
+
if (end === -1) {
|
|
1580
|
+
throw inspectionError(`Unterminated PowerShell block comment starting at character ${start + 1}. Close it with #>.`);
|
|
1581
|
+
}
|
|
1582
|
+
return end + 2;
|
|
1583
|
+
};
|
|
1584
|
+
var scanPwshExpandableText = (text, nesting) => {
|
|
1585
|
+
let content = "";
|
|
1586
|
+
let expansion = false;
|
|
1587
|
+
const substitutions = [];
|
|
1588
|
+
let i = 0;
|
|
1589
|
+
while (i < text.length) {
|
|
1590
|
+
const ch = text[i] ?? "";
|
|
1591
|
+
if (ch === "`") {
|
|
1592
|
+
const escaped = decodePwshBacktick(text, i);
|
|
1593
|
+
content += escaped.content;
|
|
1594
|
+
i = escaped.end;
|
|
1595
|
+
} else if (ch === "$" && text[i + 1] === "(") {
|
|
1596
|
+
const sub = consumePwshSubexpression(text, i, nesting);
|
|
1597
|
+
content += text.slice(i, sub.end);
|
|
1598
|
+
substitutions.push(sub.content);
|
|
1599
|
+
expansion = true;
|
|
1600
|
+
i = sub.end;
|
|
1601
|
+
} else if (ch === "$" && text[i + 1] === "{") {
|
|
1602
|
+
const end = scanPwshBracedVar(text, i);
|
|
1603
|
+
content += text.slice(i, end);
|
|
1604
|
+
expansion = true;
|
|
1605
|
+
i = end;
|
|
1606
|
+
} else {
|
|
1607
|
+
expansion ||= isPwshVariableStart(text, i);
|
|
1608
|
+
content += ch;
|
|
1609
|
+
i += 1;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
return { content, expansion, substitutions };
|
|
1613
|
+
};
|
|
1614
|
+
var scanPwshHereString = (command, start, nesting) => {
|
|
1615
|
+
const quote = command[start + 1] ?? "";
|
|
1616
|
+
const isSingle = isPwshSingleQuote(quote);
|
|
1617
|
+
let i = start + 2;
|
|
1618
|
+
while (i < command.length && (command[i] === " " || command[i] === "\t")) {
|
|
1619
|
+
i += 1;
|
|
1620
|
+
}
|
|
1621
|
+
if (command[i] === "\r" && command[i + 1] === `
|
|
1622
|
+
`) {
|
|
1623
|
+
i += 2;
|
|
1624
|
+
} else if (command[i] === `
|
|
1625
|
+
`) {
|
|
1626
|
+
i += 1;
|
|
1627
|
+
} else {
|
|
1628
|
+
throw inspectionError(`Invalid PowerShell here-string header at character ${start + 1}. Put a newline immediately after @${quote}.`);
|
|
1629
|
+
}
|
|
1630
|
+
const lines = [];
|
|
1631
|
+
while (i < command.length) {
|
|
1632
|
+
const lineEnd = command.indexOf(`
|
|
1633
|
+
`, i);
|
|
1634
|
+
const rawEnd = lineEnd === -1 ? command.length : lineEnd;
|
|
1635
|
+
const rawLine = command.slice(i, rawEnd);
|
|
1636
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
1637
|
+
const first = line[0] ?? "";
|
|
1638
|
+
if ((isSingle ? isPwshSingleQuote(first) : isPwshDoubleQuote(first)) && line[1] === "@") {
|
|
1639
|
+
const footerEnd = i + 2;
|
|
1640
|
+
const body = lines.join(`
|
|
1641
|
+
`);
|
|
1642
|
+
if (isSingle) {
|
|
1643
|
+
return {
|
|
1644
|
+
content: body,
|
|
1645
|
+
end: footerEnd,
|
|
1646
|
+
hereString: { body, quoted: true }
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
const expanded = scanPwshExpandableText(body, nesting);
|
|
1650
|
+
return {
|
|
1651
|
+
content: expanded.content,
|
|
1652
|
+
end: footerEnd,
|
|
1653
|
+
expansion: expanded.expansion,
|
|
1654
|
+
substitutions: expanded.substitutions,
|
|
1655
|
+
hereString: { body: expanded.content, quoted: false }
|
|
1656
|
+
};
|
|
1657
|
+
}
|
|
1658
|
+
lines.push(line);
|
|
1659
|
+
if (lineEnd === -1) {
|
|
1660
|
+
break;
|
|
1661
|
+
}
|
|
1662
|
+
i = lineEnd + 1;
|
|
1663
|
+
}
|
|
1664
|
+
throw inspectionError(`Unterminated PowerShell here-string starting at character ${start + 1}. Close it with ${isSingle ? "'@" : '"@'} at column 0.`);
|
|
1665
|
+
};
|
|
1666
|
+
var scanPwshDoubleQuote = (command, start, nesting) => {
|
|
1667
|
+
let content = "";
|
|
1668
|
+
let expansion = false;
|
|
1669
|
+
const substitutions = [];
|
|
1670
|
+
let i = start + 1;
|
|
1671
|
+
while (i < command.length) {
|
|
1672
|
+
const ch = command[i] ?? "";
|
|
1673
|
+
if (isPwshDoubleQuote(ch)) {
|
|
1674
|
+
const next = command[i + 1] ?? "";
|
|
1675
|
+
if (isPwshDoubleQuote(next)) {
|
|
1676
|
+
content += next;
|
|
1677
|
+
i += 2;
|
|
1678
|
+
continue;
|
|
1679
|
+
}
|
|
1680
|
+
return { content, end: i + 1, expansion, substitutions };
|
|
1681
|
+
}
|
|
1682
|
+
if (ch === "`") {
|
|
1683
|
+
const escaped = decodePwshBacktick(command, i);
|
|
1684
|
+
content += escaped.content;
|
|
1685
|
+
i = escaped.end;
|
|
1686
|
+
} else if (ch === "$" && command[i + 1] === "(") {
|
|
1687
|
+
const sub = consumePwshSubexpression(command, i, nesting);
|
|
1688
|
+
content += command.slice(i, sub.end);
|
|
1689
|
+
substitutions.push(sub.content);
|
|
1690
|
+
expansion = true;
|
|
1691
|
+
i = sub.end;
|
|
1692
|
+
} else if (ch === "$" && command[i + 1] === "{") {
|
|
1693
|
+
const end = scanPwshBracedVar(command, i);
|
|
1694
|
+
content += command.slice(i, end);
|
|
1695
|
+
expansion = true;
|
|
1696
|
+
i = end;
|
|
1697
|
+
} else {
|
|
1698
|
+
expansion ||= isPwshVariableStart(command, i);
|
|
1699
|
+
content += ch;
|
|
1700
|
+
i += 1;
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
throw inspectionError(`Unterminated PowerShell double quote starting at character ${start + 1}. Close the quote before running the command.`);
|
|
1704
|
+
};
|
|
1705
|
+
var stepPwshSubexpression = (command, i, atWordStart, nesting) => {
|
|
1706
|
+
const ch = command[i] ?? "";
|
|
1707
|
+
if (ch === "<" && command[i + 1] === "#") {
|
|
1708
|
+
return skipPwshBlockComment(command, i);
|
|
1709
|
+
}
|
|
1710
|
+
if (ch === "#" && atWordStart) {
|
|
1711
|
+
let end = i + 1;
|
|
1712
|
+
while (end < command.length && !isPwshNewline(command[end] ?? "")) {
|
|
1713
|
+
end += 1;
|
|
1714
|
+
}
|
|
1715
|
+
return end;
|
|
1716
|
+
}
|
|
1717
|
+
if (ch === "@" && (isPwshSingleQuote(command[i + 1] ?? "") || isPwshDoubleQuote(command[i + 1] ?? ""))) {
|
|
1718
|
+
return scanPwshHereString(command, i, nesting + 1).end;
|
|
1719
|
+
}
|
|
1720
|
+
if (isPwshSingleQuote(ch)) {
|
|
1721
|
+
return scanPwshSingleQuote(command, i).end;
|
|
1722
|
+
}
|
|
1723
|
+
if (isPwshDoubleQuote(ch)) {
|
|
1724
|
+
return scanPwshDoubleQuote(command, i, nesting + 1).end;
|
|
1725
|
+
}
|
|
1726
|
+
if (ch === "`") {
|
|
1727
|
+
return decodePwshBacktick(command, i).end;
|
|
1728
|
+
}
|
|
1729
|
+
return null;
|
|
1730
|
+
};
|
|
1731
|
+
var consumePwshSubexpression = (command, start, nesting = 0) => {
|
|
1732
|
+
if (nesting > 12) {
|
|
1733
|
+
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
1734
|
+
}
|
|
1735
|
+
let depth = 1;
|
|
1736
|
+
let i = start + 2;
|
|
1737
|
+
let atWordStart = true;
|
|
1738
|
+
while (i < command.length) {
|
|
1739
|
+
const stepped = stepPwshSubexpression(command, i, atWordStart, nesting);
|
|
1740
|
+
if (stepped !== null) {
|
|
1741
|
+
i = stepped;
|
|
1742
|
+
atWordStart = false;
|
|
1743
|
+
continue;
|
|
1744
|
+
}
|
|
1745
|
+
const ch = command[i] ?? "";
|
|
1746
|
+
if (ch === "(") {
|
|
1747
|
+
depth += 1;
|
|
1748
|
+
} else if (ch === ")") {
|
|
1749
|
+
depth -= 1;
|
|
1750
|
+
if (depth === 0) {
|
|
1751
|
+
return { content: command.slice(start + 2, i), end: i + 1 };
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
atWordStart = isPwshWordSeparator(ch);
|
|
1755
|
+
i += 1;
|
|
1756
|
+
}
|
|
1757
|
+
throw inspectionError(`Unterminated PowerShell subexpression starting at character ${start + 1}. Close it with ).`);
|
|
1758
|
+
};
|
|
1759
|
+
var skipPwshTrivia = (command, start) => {
|
|
1760
|
+
let i = start;
|
|
1761
|
+
while (i < command.length) {
|
|
1762
|
+
const ch = command[i] ?? "";
|
|
1763
|
+
if (isPwshHorizontalSpace(ch)) {
|
|
1764
|
+
i += 1;
|
|
1765
|
+
} else if (ch === "`" && command[i + 1] === "\r" && command[i + 2] === `
|
|
1766
|
+
`) {
|
|
1767
|
+
i += 3;
|
|
1768
|
+
} else if (ch === "`" && isPwshNewline(command[i + 1] ?? "")) {
|
|
1769
|
+
i += 2;
|
|
1770
|
+
} else if (ch === "<" && command[i + 1] === "#") {
|
|
1771
|
+
i = skipPwshBlockComment(command, i);
|
|
1772
|
+
} else if (ch === "#") {
|
|
1773
|
+
i += 1;
|
|
1774
|
+
while (i < command.length && !isPwshNewline(command[i] ?? "")) {
|
|
1775
|
+
i += 1;
|
|
1776
|
+
}
|
|
1777
|
+
} else {
|
|
1778
|
+
break;
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
return i;
|
|
1782
|
+
};
|
|
1783
|
+
var findStopParsingEnd = (command, start) => {
|
|
1784
|
+
let inQuote = false;
|
|
1785
|
+
for (let i = start;i < command.length; i += 1) {
|
|
1786
|
+
const ch = command[i] ?? "";
|
|
1787
|
+
if (isPwshNewline(ch)) {
|
|
1788
|
+
return i;
|
|
1789
|
+
}
|
|
1790
|
+
if (isPwshDoubleQuote(ch)) {
|
|
1791
|
+
inQuote = !inQuote;
|
|
1792
|
+
} else if (!inQuote && (ch === "|" || command.slice(i, i + 2) === "&&" || command.slice(i, i + 2) === "||")) {
|
|
1793
|
+
return i;
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
return command.length;
|
|
1797
|
+
};
|
|
1798
|
+
var scanPwshStopParsing = (command, start) => {
|
|
1799
|
+
const end = findStopParsingEnd(command, start);
|
|
1800
|
+
let contentStart = start;
|
|
1801
|
+
while (contentStart < end && isPwshHorizontalSpace(command[contentStart] ?? "")) {
|
|
1802
|
+
contentStart += 1;
|
|
1803
|
+
}
|
|
1804
|
+
const raw = command.slice(contentStart, end);
|
|
1805
|
+
if (/%[^%\r\n]+%/u.test(raw)) {
|
|
1806
|
+
throw inspectionError("Cannot inspect PowerShell stop-parsing (--%) with %VAR% expansion. Supply literal arguments.");
|
|
1807
|
+
}
|
|
1808
|
+
if (/["\u201C-\u201E]/u.test(raw)) {
|
|
1809
|
+
throw inspectionError("Cannot inspect quoted arguments after PowerShell stop-parsing (--%). Supply literal arguments without --%.");
|
|
1810
|
+
}
|
|
1811
|
+
for (const ch of raw) {
|
|
1812
|
+
if (ch !== " " && isPwshHorizontalSpace(ch)) {
|
|
1813
|
+
throw inspectionError("Cannot inspect non-space whitespace after PowerShell stop-parsing (--%). Supply literal arguments without --%.");
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
const tokens = [];
|
|
1817
|
+
for (const part of raw.split(" ")) {
|
|
1818
|
+
if (part.length > 0) {
|
|
1819
|
+
tokens.push({ type: "word", value: part });
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
return { tokens, end };
|
|
1823
|
+
};
|
|
1824
|
+
var scanPwshWordFragment = (command, i, nesting) => {
|
|
1825
|
+
const ch = command[i] ?? "";
|
|
1826
|
+
if (isPwshSingleQuote(ch)) {
|
|
1827
|
+
return scanPwshSingleQuote(command, i);
|
|
1828
|
+
}
|
|
1829
|
+
if (isPwshDoubleQuote(ch)) {
|
|
1830
|
+
return scanPwshDoubleQuote(command, i, nesting);
|
|
1831
|
+
}
|
|
1832
|
+
if ((ch === "$" || ch === "@") && command[i + 1] === "(") {
|
|
1833
|
+
const sub = consumePwshSubexpression(command, i, nesting);
|
|
1834
|
+
return {
|
|
1835
|
+
content: command.slice(i, sub.end),
|
|
1836
|
+
end: sub.end,
|
|
1837
|
+
expansion: true,
|
|
1838
|
+
substitutions: [sub.content]
|
|
1839
|
+
};
|
|
1840
|
+
}
|
|
1841
|
+
if (ch === "$" && command[i + 1] === "{") {
|
|
1842
|
+
const end = scanPwshBracedVar(command, i);
|
|
1843
|
+
return { content: command.slice(i, end), end, expansion: true };
|
|
1844
|
+
}
|
|
1845
|
+
if (ch === "`") {
|
|
1846
|
+
return decodePwshBacktick(command, i);
|
|
1847
|
+
}
|
|
1848
|
+
return null;
|
|
1849
|
+
};
|
|
1850
|
+
var scanPwshWord = (command, start, nesting) => {
|
|
1851
|
+
const first = command[start] ?? "";
|
|
1852
|
+
const second = command[start + 1] ?? "";
|
|
1853
|
+
if (first === "@" && (isPwshSingleQuote(second) || isPwshDoubleQuote(second))) {
|
|
1854
|
+
return scanPwshHereString(command, start, nesting);
|
|
1855
|
+
}
|
|
1856
|
+
if (first === "@" && /^[\p{L}\p{N}_]/u.test(second)) {
|
|
1857
|
+
throw inspectionError("Cannot inspect PowerShell splatting (@var) reliably. Supply literal arguments.");
|
|
1858
|
+
}
|
|
1859
|
+
let content = "";
|
|
1860
|
+
let expansion = false;
|
|
1861
|
+
const substitutions = [];
|
|
1862
|
+
let i = start;
|
|
1863
|
+
while (i < command.length) {
|
|
1864
|
+
const ch = command[i] ?? "";
|
|
1865
|
+
if (isPwshWordSeparator(ch) || ch === ">" || ch === "<" && command[i + 1] === "#") {
|
|
1866
|
+
break;
|
|
1867
|
+
}
|
|
1868
|
+
const fragment = scanPwshWordFragment(command, i, nesting);
|
|
1869
|
+
if (fragment !== null) {
|
|
1870
|
+
content += fragment.content;
|
|
1871
|
+
expansion ||= fragment.expansion === true;
|
|
1872
|
+
substitutions.push(...fragment.substitutions ?? []);
|
|
1873
|
+
i = fragment.end;
|
|
1874
|
+
continue;
|
|
1875
|
+
}
|
|
1876
|
+
expansion ||= isPwshVariableStart(command, i);
|
|
1877
|
+
content += ch;
|
|
1878
|
+
i += 1;
|
|
1879
|
+
}
|
|
1880
|
+
return { content, end: i, expansion, substitutions };
|
|
1881
|
+
};
|
|
1882
|
+
var readPwshPunctuation = (command, i, tokens) => {
|
|
1883
|
+
const pair = command.slice(i, i + 2);
|
|
1884
|
+
if (pair === "&&" || pair === "||") {
|
|
1885
|
+
tokens.push({ type: "operator", value: pair });
|
|
1886
|
+
return i + 2;
|
|
1887
|
+
}
|
|
1888
|
+
const ch = command[i] ?? "";
|
|
1889
|
+
if (isPwshNewline(ch)) {
|
|
1890
|
+
tokens.push({ type: "operator", value: `
|
|
1891
|
+
` });
|
|
1892
|
+
return i + (ch === "\r" && command[i + 1] === `
|
|
1893
|
+
` ? 2 : 1);
|
|
1894
|
+
}
|
|
1895
|
+
if (ch === "(") {
|
|
1896
|
+
const sub = consumePwshSubexpression(command, i - 1, 0);
|
|
1897
|
+
tokens.push({
|
|
1898
|
+
type: "word",
|
|
1899
|
+
value: command.slice(i, sub.end),
|
|
1900
|
+
expansion: true,
|
|
1901
|
+
grouped: true,
|
|
1902
|
+
substitutions: [sub.content]
|
|
1903
|
+
});
|
|
1904
|
+
return sub.end;
|
|
1905
|
+
}
|
|
1906
|
+
if (ch === ")") {
|
|
1907
|
+
throw inspectionError(`Unexpected closing parenthesis at character ${i + 1}.`);
|
|
1908
|
+
}
|
|
1909
|
+
if ("|;{}".includes(ch)) {
|
|
1910
|
+
tokens.push({ type: "operator", value: ch });
|
|
1911
|
+
return i + 1;
|
|
1912
|
+
}
|
|
1913
|
+
if (ch === "&") {
|
|
1914
|
+
const atStart = tokens.length === 0 || tokens.at(-1)?.type === "operator";
|
|
1915
|
+
tokens.push({ type: atStart ? "word" : "operator", value: "&" });
|
|
1916
|
+
return i + 1;
|
|
1917
|
+
}
|
|
1918
|
+
return null;
|
|
1919
|
+
};
|
|
1920
|
+
var tokenizePwsh = (command) => {
|
|
1921
|
+
const tokens = [];
|
|
1922
|
+
let i = 0;
|
|
1923
|
+
while ((i = skipPwshTrivia(command, i)) < command.length) {
|
|
1924
|
+
const next = readPwshPunctuation(command, i, tokens);
|
|
1925
|
+
if (next !== null) {
|
|
1926
|
+
i = next;
|
|
1927
|
+
continue;
|
|
1928
|
+
}
|
|
1929
|
+
const ch = command[i] ?? "";
|
|
1930
|
+
const redirect = /^(?:[1-6*])?(?:>>|>&1|>)/u.exec(command.slice(i))?.[0];
|
|
1931
|
+
if (redirect !== undefined) {
|
|
1932
|
+
tokens.push({ type: "redirect", value: redirect });
|
|
1933
|
+
i += redirect.length;
|
|
1934
|
+
continue;
|
|
1935
|
+
}
|
|
1936
|
+
if (command.slice(i, i + 3) === "--%" && (i + 3 >= command.length || isPwshWordSeparator(command[i + 3] ?? ""))) {
|
|
1937
|
+
const stopped = scanPwshStopParsing(command, i + 3);
|
|
1938
|
+
tokens.push(...stopped.tokens);
|
|
1939
|
+
i = stopped.end;
|
|
1940
|
+
continue;
|
|
1941
|
+
}
|
|
1942
|
+
const word = scanPwshWord(command, i, 0);
|
|
1943
|
+
if (word.end <= i) {
|
|
1944
|
+
throw inspectionError(`Unexpected PowerShell token "${ch}" at character ${i + 1}.`);
|
|
1945
|
+
}
|
|
1946
|
+
tokens.push({
|
|
1947
|
+
type: "word",
|
|
1948
|
+
value: word.content,
|
|
1949
|
+
substitutions: word.substitutions,
|
|
1950
|
+
expansion: word.expansion,
|
|
1951
|
+
hereString: word.hereString
|
|
1952
|
+
});
|
|
1953
|
+
i = word.end;
|
|
1954
|
+
}
|
|
1955
|
+
return tokens;
|
|
1956
|
+
};
|
|
1957
|
+
var decodePwshEncodedCommand = (encoded) => {
|
|
1958
|
+
if (encoded.length === 0 || encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded)) {
|
|
1959
|
+
throw inspectionError("Cannot decode invalid pwsh -EncodedCommand base64 payload.");
|
|
1960
|
+
}
|
|
1961
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
1962
|
+
if (bytes.length % 2 !== 0) {
|
|
1963
|
+
throw inspectionError("Cannot decode pwsh -EncodedCommand payload with odd UTF-16LE byte length.");
|
|
1964
|
+
}
|
|
1965
|
+
return bytes.toString("utf16le");
|
|
1966
|
+
};
|
|
1967
|
+
var pwshSwitchTable = [
|
|
1968
|
+
["version", "boolean", "v"],
|
|
1969
|
+
["help", "boolean", "h"],
|
|
1970
|
+
["login", "boolean", "l"],
|
|
1971
|
+
["noexit", "unsupported", "noe"],
|
|
1972
|
+
["noprofile", "boolean", "nop"],
|
|
1973
|
+
["nologo", "boolean", "nol"],
|
|
1974
|
+
["noninteractive", "boolean", "noni"],
|
|
1975
|
+
["sshservermode", "boolean", "sshs"],
|
|
1976
|
+
["noprofileloadtime", "boolean", "noprofileloadtime"],
|
|
1977
|
+
["interactive", "boolean", "i"],
|
|
1978
|
+
["configurationfile", "value", "configurationfile"],
|
|
1979
|
+
["configurationname", "value", "config"],
|
|
1980
|
+
["custompipename", "value", "cus"],
|
|
1981
|
+
["commandwithargs", "commandWithArgs", "commandwithargs"],
|
|
1982
|
+
["command", "command", "c"],
|
|
1983
|
+
["windowstyle", "value", "w"],
|
|
1984
|
+
["file", "unsupported", "f"],
|
|
1985
|
+
["outputformat", "value", "o"],
|
|
1986
|
+
["inputformat", "value", "inp"],
|
|
1987
|
+
["executionpolicy", "value", "ex"],
|
|
1988
|
+
["encodedcommand", "encodedCommand", "e"],
|
|
1989
|
+
["encodedarguments", "unsupported", "encodeda"],
|
|
1990
|
+
["settingsfile", "value", "settings"],
|
|
1991
|
+
["sta", "boolean", "sta"],
|
|
1992
|
+
["mta", "boolean", "mta"],
|
|
1993
|
+
["workingdirectory", "workingDirectory", "wo"]
|
|
1994
|
+
];
|
|
1995
|
+
var pwshSwitchAliases = new Map([
|
|
1996
|
+
["?", "boolean"],
|
|
1997
|
+
["ec", "encodedCommand"],
|
|
1998
|
+
["cwa", "commandWithArgs"],
|
|
1999
|
+
["wd", "workingDirectory"],
|
|
2000
|
+
["ea", "unsupported"],
|
|
2001
|
+
["if", "value"],
|
|
2002
|
+
["of", "value"],
|
|
2003
|
+
["ep", "value"]
|
|
2004
|
+
]);
|
|
2005
|
+
var classifyPwshSwitch = (raw) => {
|
|
2006
|
+
const normalized = raw.replace(/^[/\-\u2013-\u2015]+/u, "").toLowerCase();
|
|
2007
|
+
if (normalized.length === 0) {
|
|
2008
|
+
return null;
|
|
2009
|
+
}
|
|
2010
|
+
const alias = pwshSwitchAliases.get(normalized);
|
|
2011
|
+
if (alias !== undefined) {
|
|
2012
|
+
return alias;
|
|
2013
|
+
}
|
|
2014
|
+
const matched = pwshSwitchTable.find(([full, , minPrefix]) => full.startsWith(normalized) && normalized.length >= minPrefix.length);
|
|
2015
|
+
return matched?.[1] ?? null;
|
|
2016
|
+
};
|
|
2017
|
+
var isPwshSwitchToken = (raw) => raw.length > 1 && /^[/\-\u2013-\u2015]/u.test(raw);
|
|
2018
|
+
var readPwshCommandArgs = (words, index, kind) => {
|
|
2019
|
+
const target = words[index];
|
|
2020
|
+
if (target === undefined || target.expansion === true) {
|
|
2021
|
+
throw inspectionError("Cannot parse an expanded or missing pwsh command body reliably. Use a literal command.");
|
|
2022
|
+
}
|
|
2023
|
+
if (kind === "encodedCommand") {
|
|
2024
|
+
return decodePwshEncodedCommand(target.value);
|
|
2025
|
+
}
|
|
2026
|
+
if (target.value === "-") {
|
|
2027
|
+
throw inspectionError("Cannot inspect pwsh reading commands from standard input (-). Supply a literal command.");
|
|
2028
|
+
}
|
|
2029
|
+
if (kind === "commandWithArgs") {
|
|
2030
|
+
return target.value;
|
|
2031
|
+
}
|
|
2032
|
+
const remaining = words.slice(index);
|
|
2033
|
+
if (remaining.some((word) => word.expansion === true)) {
|
|
2034
|
+
throw inspectionError("Cannot parse an expanded pwsh -Command body reliably. Use a literal command.");
|
|
2035
|
+
}
|
|
2036
|
+
return remaining.map((word) => word.value).join(" ");
|
|
2037
|
+
};
|
|
2038
|
+
var extractPwshBody = (words, start) => {
|
|
2039
|
+
if (!/^(?:.*[/\\])?pwsh(?:\.exe)?$/iu.test(words[start]?.value ?? "")) {
|
|
2040
|
+
return null;
|
|
2041
|
+
}
|
|
2042
|
+
let index = start + 1;
|
|
2043
|
+
let workingDirectoryChanged = false;
|
|
2044
|
+
let encodedBody;
|
|
2045
|
+
let infoFlag = false;
|
|
2046
|
+
while (index < words.length) {
|
|
2047
|
+
const token = words[index];
|
|
2048
|
+
if (token === undefined) {
|
|
2049
|
+
break;
|
|
2050
|
+
}
|
|
2051
|
+
if (token.expansion === true) {
|
|
2052
|
+
throw inspectionError("Cannot inspect dynamic pwsh arguments reliably. Use literal arguments.");
|
|
2053
|
+
}
|
|
2054
|
+
if (!isPwshSwitchToken(token.value)) {
|
|
2055
|
+
throw inspectionError("Cannot inspect positional pwsh script files reliably. Pass a literal -Command or run git commit directly.");
|
|
2056
|
+
}
|
|
2057
|
+
const kind = classifyPwshSwitch(token.value);
|
|
2058
|
+
if (kind === null || kind === "unsupported") {
|
|
2059
|
+
throw inspectionError(`Cannot inspect unsupported pwsh switch "${token.value}" reliably. Use literal -Command or run git commit directly.`);
|
|
2060
|
+
}
|
|
2061
|
+
const normalized = token.value.replace(/^[/\-\u2013-\u2015]+/u, "").toLowerCase();
|
|
2062
|
+
if (kind === "boolean") {
|
|
2063
|
+
infoFlag ||= normalized === "?" || "help".startsWith(normalized) || "version".startsWith(normalized);
|
|
2064
|
+
index += 1;
|
|
2065
|
+
} else if (kind === "value" || kind === "workingDirectory") {
|
|
2066
|
+
workingDirectoryChanged ||= kind === "workingDirectory";
|
|
2067
|
+
index += 2;
|
|
2068
|
+
} else if (kind === "encodedCommand") {
|
|
2069
|
+
encodedBody = readPwshCommandArgs(words, index + 1, kind);
|
|
2070
|
+
index += 2;
|
|
2071
|
+
} else {
|
|
2072
|
+
return {
|
|
2073
|
+
body: readPwshCommandArgs(words, index + 1, kind),
|
|
2074
|
+
workingDirectoryChanged
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
if (encodedBody !== undefined) {
|
|
2079
|
+
return { body: encodedBody, workingDirectoryChanged };
|
|
2080
|
+
}
|
|
2081
|
+
if (infoFlag) {
|
|
2082
|
+
return null;
|
|
2083
|
+
}
|
|
2084
|
+
throw inspectionError("Cannot inspect bare pwsh invocation without -Command or -EncodedCommand. Supply a literal command.");
|
|
2085
|
+
};
|
|
2086
|
+
var splitPipelines = (tokens, mode) => {
|
|
2087
|
+
const result = [];
|
|
2088
|
+
let stages = [];
|
|
2089
|
+
let current = [];
|
|
2090
|
+
const flush = () => {
|
|
2091
|
+
if (current.length > 0) {
|
|
2092
|
+
stages.push(current);
|
|
2093
|
+
current = [];
|
|
2094
|
+
}
|
|
2095
|
+
if (stages.length === 0) {
|
|
2096
|
+
return;
|
|
2097
|
+
}
|
|
2098
|
+
const isPipeline = stages.length > 1;
|
|
2099
|
+
const [firstStage] = stages;
|
|
2100
|
+
const pipedHereString = mode === "pwsh" && stages.length === 2 && firstStage?.length === 1 && firstStage[0]?.type === "word" && firstStage[0].hereString?.quoted === true ? firstStage[0].hereString.body : undefined;
|
|
2101
|
+
for (let stageIndex = 0;stageIndex < stages.length; stageIndex += 1) {
|
|
2102
|
+
const stageTokens = stages[stageIndex];
|
|
2103
|
+
if (stageTokens !== undefined) {
|
|
2104
|
+
result.push({
|
|
2105
|
+
tokens: stageTokens,
|
|
2106
|
+
pipeline: isPipeline,
|
|
2107
|
+
pipedHereString: stageIndex === 1 ? pipedHereString : undefined
|
|
2108
|
+
});
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
stages = [];
|
|
2112
|
+
};
|
|
2113
|
+
for (const token of tokens) {
|
|
2114
|
+
if (token.type === "operator") {
|
|
2115
|
+
if (token.value === "|" || token.value === "|&") {
|
|
2116
|
+
if (current.length > 0) {
|
|
2117
|
+
stages.push(current);
|
|
2118
|
+
current = [];
|
|
2119
|
+
}
|
|
2120
|
+
} else if (token.value !== `
|
|
2121
|
+
` || current.length > 0 || stages.length === 0) {
|
|
2122
|
+
flush();
|
|
2123
|
+
}
|
|
2124
|
+
} else {
|
|
2125
|
+
current.push(token);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
flush();
|
|
2129
|
+
return result;
|
|
2130
|
+
};
|
|
2131
|
+
var attachPwshStdin = (invocation, stage) => {
|
|
2132
|
+
if (!invocation.filePaths.includes("-")) {
|
|
2133
|
+
return invocation;
|
|
2134
|
+
}
|
|
2135
|
+
if (stage.pipedHereString !== undefined) {
|
|
2136
|
+
return {
|
|
2137
|
+
...invocation,
|
|
2138
|
+
stdinMessage: stage.pipedHereString
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
return {
|
|
2142
|
+
...invocation,
|
|
2143
|
+
stdinError: "In PowerShell, pipe a single literal here-string (@'...'@ | git commit -F -) or pass -m directly."
|
|
2144
|
+
};
|
|
2145
|
+
};
|
|
2146
|
+
var resolveCommandStart = (words, values, mode) => {
|
|
2147
|
+
if (mode === "posix") {
|
|
2148
|
+
return findCommandStart(values);
|
|
2149
|
+
}
|
|
2150
|
+
if (words[0]?.value === "&") {
|
|
2151
|
+
if (words[1] === undefined || words[1].expansion === true) {
|
|
2152
|
+
throw inspectionError("Cannot inspect a dynamic PowerShell call operator (& $cmd). Use literal command words.");
|
|
2153
|
+
}
|
|
2154
|
+
return 1;
|
|
2155
|
+
}
|
|
2156
|
+
return 0;
|
|
2157
|
+
};
|
|
2158
|
+
var isTargetMutatorCommand = (values, start, mode) => {
|
|
2159
|
+
const commandName = values[start] ?? "";
|
|
2160
|
+
if (mode === "pwsh") {
|
|
2161
|
+
return pwshTargetMutators.has(commandName.toLowerCase()) || /^\$\{?env:/iu.test(values[0] ?? "");
|
|
2162
|
+
}
|
|
2163
|
+
return targetMutators.has(commandName) || values.length > 0 && values.every(isAssignment);
|
|
2164
|
+
};
|
|
2165
|
+
var assertLiteralCommandName = (firstWord, mode) => {
|
|
2166
|
+
if (firstWord?.expansion !== true) {
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
2169
|
+
if (mode === "pwsh" && (firstWord.hereString !== undefined || firstWord.grouped === true || /^\$\{?env:/iu.test(firstWord.value))) {
|
|
2170
|
+
return;
|
|
2171
|
+
}
|
|
2172
|
+
throw inspectionError("Cannot inspect a dynamic command name. Use literal command words.");
|
|
2173
|
+
};
|
|
2174
|
+
var collectStageSubstitutions = (tokens, mode, changedDirectory, depth, invocations) => {
|
|
2175
|
+
let mutated = changedDirectory;
|
|
2176
|
+
for (const token of tokens) {
|
|
2177
|
+
for (const substitution of token.substitutions ?? []) {
|
|
2178
|
+
const subResult = extractGitCommitsInternal(substitution, mode, mutated, depth + 1);
|
|
2179
|
+
invocations.push(...subResult.invocations);
|
|
2180
|
+
if (mode === "pwsh" && subResult.changedDirectory) {
|
|
2181
|
+
mutated = true;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
return mutated;
|
|
2186
|
+
};
|
|
2187
|
+
var extractGitCommitsInternal = (command, mode, inheritedDirectoryChange, depth) => {
|
|
1475
2188
|
if (depth > 12 || command.length > 262144) {
|
|
1476
2189
|
throw inspectionError("Shell parsing limit exceeded. Simplify the unsupported syntax.");
|
|
1477
2190
|
}
|
|
1478
|
-
const tokens = tokenizeShell(command);
|
|
2191
|
+
const tokens = mode === "pwsh" ? tokenizePwsh(command) : tokenizeShell(command);
|
|
1479
2192
|
const invocations = [];
|
|
1480
2193
|
let changedDirectory = inheritedDirectoryChange;
|
|
1481
|
-
for (const
|
|
1482
|
-
|
|
2194
|
+
for (const stage of splitPipelines(tokens, mode)) {
|
|
2195
|
+
changedDirectory = collectStageSubstitutions(stage.tokens, mode, changedDirectory, depth, invocations);
|
|
2196
|
+
const words = extractCommandWords(stage.tokens);
|
|
1483
2197
|
const values = words.map((token) => token.value);
|
|
1484
|
-
const start =
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
const
|
|
1489
|
-
const
|
|
1490
|
-
if (
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
2198
|
+
const start = resolveCommandStart(words, values, mode);
|
|
2199
|
+
assertLiteralCommandName(words[start], mode);
|
|
2200
|
+
const invocation = extractInvocation(words, start, mode);
|
|
2201
|
+
const posixBody = extractShellCBody(words, start);
|
|
2202
|
+
const pwshBody = extractPwshBody(words, start);
|
|
2203
|
+
const wrapperChange = mode === "posix" && values.slice(0, start).some((word) => word === "env" || isAssignment(word));
|
|
2204
|
+
if (posixBody !== null) {
|
|
2205
|
+
invocations.push(...extractGitCommitsInternal(posixBody, "posix", changedDirectory || wrapperChange, depth + 1).invocations);
|
|
2206
|
+
}
|
|
2207
|
+
if (pwshBody !== null) {
|
|
2208
|
+
invocations.push(...extractGitCommitsInternal(pwshBody.body, "pwsh", changedDirectory || wrapperChange || pwshBody.workingDirectoryChanged, depth + 1).invocations);
|
|
2209
|
+
}
|
|
2210
|
+
if (isTargetMutatorCommand(values, start, mode)) {
|
|
1495
2211
|
changedDirectory = true;
|
|
1496
2212
|
}
|
|
1497
|
-
if (invocation !==
|
|
2213
|
+
if (invocation !== null) {
|
|
1498
2214
|
const target = changedDirectory ? {
|
|
1499
2215
|
...invocation,
|
|
1500
2216
|
targetError: "A preceding directory or environment change makes the commit target ambiguous. Run git commit in a separate shell call with the captured workdir."
|
|
1501
2217
|
} : invocation;
|
|
1502
|
-
invocations.push(attachStdinHeredoc(target,
|
|
2218
|
+
invocations.push(mode === "pwsh" ? attachPwshStdin(target, stage) : attachStdinHeredoc(target, stage.tokens, stage.pipeline));
|
|
1503
2219
|
}
|
|
1504
2220
|
}
|
|
1505
|
-
|
|
1506
|
-
for (const substitution of token.substitutions ?? []) {
|
|
1507
|
-
invocations.push(...extractGitCommits(substitution, changedDirectory, depth + 1));
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
return invocations;
|
|
2221
|
+
return { invocations, changedDirectory };
|
|
1511
2222
|
};
|
|
2223
|
+
var extractGitCommits = (command, options) => extractGitCommitsInternal(command, options?.shell ?? "posix", false, 0).invocations;
|
|
1512
2224
|
|
|
1513
2225
|
// src/validator.ts
|
|
1514
2226
|
var signoffPattern = /^\s*[sS][iI][gG][nN][eE][dD]-[oO][fF][fF]-[bB][yY]:\s+[^<>\r\n]+\s+<[^<>\r\n@]+@[^<>\r\n@]+>\s*$/u;
|
|
@@ -1517,7 +2229,7 @@ var subjectScopeViolation = (subject, effective) => {
|
|
|
1517
2229
|
return 'Subject line is empty. The commit message must begin with "<scope>: <subject>".';
|
|
1518
2230
|
}
|
|
1519
2231
|
if (scopePattern.test(effective)) {
|
|
1520
|
-
return;
|
|
2232
|
+
return null;
|
|
1521
2233
|
}
|
|
1522
2234
|
if (/^:\s*/u.test(effective)) {
|
|
1523
2235
|
return `Missing scope before colon in subject line "${subject}". Expected format: "<scope>: <subject>".`;
|
|
@@ -1530,58 +2242,60 @@ var subjectScopeViolation = (subject, effective) => {
|
|
|
1530
2242
|
}
|
|
1531
2243
|
return `Missing scope in subject line "${subject}". First line must follow "<scope>: <subject>" format.`;
|
|
1532
2244
|
};
|
|
1533
|
-
var resolveMessages = (invocation, violations) => {
|
|
2245
|
+
var resolveMessages = (invocation, violations, shellMode) => {
|
|
1534
2246
|
if (invocation.messageExpansion === true) {
|
|
1535
2247
|
violations.push("Cannot validate a message containing shell expansion. Supply the final message literally.");
|
|
1536
|
-
return;
|
|
2248
|
+
return null;
|
|
1537
2249
|
}
|
|
1538
2250
|
if (invocation.hasTrailer === true) {
|
|
1539
2251
|
violations.push("Cannot validate --trailer. Put the trailer in the literal message body or use -s.");
|
|
1540
|
-
return;
|
|
2252
|
+
return null;
|
|
1541
2253
|
}
|
|
1542
2254
|
const filePath = invocation.filePaths.at(-1);
|
|
1543
2255
|
if (filePath === undefined) {
|
|
1544
2256
|
return invocation.messages;
|
|
1545
2257
|
}
|
|
2258
|
+
const inlineHint = shellMode === "pwsh" ? "Use an inline single-quoted -m message or a single literal here-string pipeline (@'...'@ | git commit -F -)." : "Use an inline $'...' message or one quoted stdin heredoc.";
|
|
1546
2259
|
if (filePath !== "-" || invocation.filePaths.length !== 1) {
|
|
1547
|
-
violations.push(
|
|
1548
|
-
return;
|
|
2260
|
+
violations.push(`Cannot validate a commit message from -F/--file before permission approval. ${inlineHint}`);
|
|
2261
|
+
return null;
|
|
1549
2262
|
}
|
|
1550
2263
|
if (invocation.stdinError !== undefined || invocation.stdinMessage === undefined || invocation.messages.length > 0) {
|
|
1551
|
-
violations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."}
|
|
1552
|
-
return;
|
|
2264
|
+
violations.push(`${invocation.stdinError ?? "Cannot combine -F - with -m or unsupported stdin input."} ${inlineHint}`);
|
|
2265
|
+
return null;
|
|
1553
2266
|
}
|
|
1554
2267
|
return [invocation.stdinMessage];
|
|
1555
2268
|
};
|
|
1556
2269
|
var checkAllowedScope = (subject, effective, allowed) => {
|
|
1557
2270
|
const rawScope = scopePattern.exec(effective)?.[1];
|
|
1558
2271
|
if (rawScope === undefined || allowed.length === 0) {
|
|
1559
|
-
return;
|
|
2272
|
+
return null;
|
|
1560
2273
|
}
|
|
1561
2274
|
const conventional = /^(?<type>[^(]+)\((?<scope>[^)]+)\)$/u.exec(rawScope);
|
|
1562
2275
|
if ([rawScope, conventional?.[1], conventional?.[2]].some((scope) => scope !== undefined && allowed.includes(scope))) {
|
|
1563
|
-
return;
|
|
2276
|
+
return null;
|
|
1564
2277
|
}
|
|
1565
2278
|
const detail = effective === subject ? "" : ` Subject line: "${subject}".`;
|
|
1566
2279
|
return `Scope "${rawScope}" is not in the allowed scopes list. Allowed scopes: ${allowed.join(", ")}.${detail}`;
|
|
1567
2280
|
};
|
|
1568
|
-
var checkLineLength = (lines, max) => {
|
|
2281
|
+
var checkLineLength = (lines, max, shellMode) => {
|
|
1569
2282
|
if (max <= 0) {
|
|
1570
|
-
return;
|
|
2283
|
+
return null;
|
|
1571
2284
|
}
|
|
1572
2285
|
const overlong = lines.flatMap((line, index) => line.length > max ? [` - Line ${index + 1} (${line.length} chars, max ${max}): "${line}"`] : []);
|
|
1573
|
-
|
|
2286
|
+
const wrapHint = shellMode === "pwsh" ? "Wrap with real newlines inside a literal @'...'@ here-string or PowerShell `n escapes inside double quotes." : `Wrap with real newlines inside $'...'; "\\n" inside double quotes stays literal.`;
|
|
2287
|
+
return overlong.length === 0 ? null : `Commit message exceeds maximum line length of ${max} characters:
|
|
1574
2288
|
${overlong.join(`
|
|
1575
2289
|
`)}
|
|
1576
|
-
Each -m becomes one paragraph line.
|
|
2290
|
+
Each -m becomes one paragraph line. ${wrapHint}`;
|
|
1577
2291
|
};
|
|
1578
|
-
var validateInvocation = (invocation, config) => {
|
|
2292
|
+
var validateInvocation = (invocation, config, shellMode) => {
|
|
1579
2293
|
const violations = [];
|
|
1580
2294
|
if (invocation.isHelp) {
|
|
1581
2295
|
return violations;
|
|
1582
2296
|
}
|
|
1583
|
-
const messages = resolveMessages(invocation, violations);
|
|
1584
|
-
if (messages ===
|
|
2297
|
+
const messages = resolveMessages(invocation, violations, shellMode);
|
|
2298
|
+
if (messages === null) {
|
|
1585
2299
|
return violations;
|
|
1586
2300
|
}
|
|
1587
2301
|
if (messages.length === 0) {
|
|
@@ -1597,10 +2311,10 @@ var validateInvocation = (invocation, config) => {
|
|
|
1597
2311
|
const effective = subject.replace(/^(?:(?:fixup|squash)!\s+)+/u, "");
|
|
1598
2312
|
const checks = [
|
|
1599
2313
|
checkAllowedScope(subject, effective, config.allowedScopes ?? []),
|
|
1600
|
-
config.requireScope ? subjectScopeViolation(subject, effective) :
|
|
1601
|
-
checkLineLength(lines, config.maxLineLength)
|
|
2314
|
+
config.requireScope ? subjectScopeViolation(subject, effective) : null,
|
|
2315
|
+
checkLineLength(lines, config.maxLineLength, shellMode)
|
|
1602
2316
|
];
|
|
1603
|
-
violations.push(...checks.filter((violation) => violation !==
|
|
2317
|
+
violations.push(...checks.filter((violation) => violation !== null));
|
|
1604
2318
|
const subjectIndex = lines.findIndex((line) => line.trim().length > 0);
|
|
1605
2319
|
const hasTrailer = subjectIndex !== -1 && lines.slice(subjectIndex + 1).some((line) => signoffPattern.test(line));
|
|
1606
2320
|
if (config.enforceSignoff && !invocation.hasSignoffFlag && !hasTrailer) {
|
|
@@ -1608,8 +2322,8 @@ var validateInvocation = (invocation, config) => {
|
|
|
1608
2322
|
}
|
|
1609
2323
|
return violations;
|
|
1610
2324
|
};
|
|
1611
|
-
var validateGitCommits = (invocations, config, _originalCommand) => {
|
|
1612
|
-
const violations = invocations.flatMap((invocation) => validateInvocation(invocation, config));
|
|
2325
|
+
var validateGitCommits = (invocations, config, _originalCommand, shellMode = "posix") => {
|
|
2326
|
+
const violations = invocations.flatMap((invocation) => validateInvocation(invocation, config, shellMode));
|
|
1613
2327
|
if (violations.length === 0) {
|
|
1614
2328
|
return;
|
|
1615
2329
|
}
|
|
@@ -1618,6 +2332,13 @@ var validateGitCommits = (invocations, config, _originalCommand) => {
|
|
|
1618
2332
|
`);
|
|
1619
2333
|
const scope = config.allowedScopes?.[0] ?? "scope";
|
|
1620
2334
|
const policy = config.enforceSignoff ? "required: captured commit.gpgsign=true. Keep -s." : "not required: captured commit.gpgsign=false|unset.";
|
|
2335
|
+
const signoff = config.enforceSignoff ? " -s" : "";
|
|
2336
|
+
const example = shellMode === "pwsh" ? ` @'
|
|
2337
|
+
${scope}: Subject
|
|
2338
|
+
|
|
2339
|
+
Body line one.
|
|
2340
|
+
Body line two.
|
|
2341
|
+
'@ | git commit${signoff} -F -` : ` git commit${signoff} -m $'${scope}: Subject\\n\\nBody line one.\\nBody line two.'`;
|
|
1621
2342
|
throw new Error(`[commit-guard] Git commit rejected: commit message format rules violated.
|
|
1622
2343
|
|
|
1623
2344
|
Violations:
|
|
@@ -1625,7 +2346,7 @@ ${details}
|
|
|
1625
2346
|
|
|
1626
2347
|
Signoff ${policy}
|
|
1627
2348
|
Example:
|
|
1628
|
-
|
|
2349
|
+
${example}`);
|
|
1629
2350
|
};
|
|
1630
2351
|
|
|
1631
2352
|
// src/plugin.ts
|
|
@@ -1633,12 +2354,13 @@ var { relative: relative2, resolve: resolve2 } = path;
|
|
|
1633
2354
|
var publicationGuidance = 'Commit after the shell result reports "Frozen commit baseline"; otherwise call commit_context again with the same workdir before committing.';
|
|
1634
2355
|
var receiptGuidance = "RECEIPT_OK confirms only that the artifact was written, not that the baseline was published.";
|
|
1635
2356
|
var toToolError = (cause) => {
|
|
1636
|
-
|
|
1637
|
-
|
|
2357
|
+
let current = cause;
|
|
2358
|
+
while (Cause.isUnknownError(current)) {
|
|
2359
|
+
current = current.cause;
|
|
1638
2360
|
}
|
|
1639
|
-
return
|
|
1640
|
-
message:
|
|
1641
|
-
error:
|
|
2361
|
+
return current instanceof Tool.Error ? current : new Tool.Error({
|
|
2362
|
+
message: current instanceof Error ? current.message : "[commit-guard] Git commit validation failed.",
|
|
2363
|
+
error: current
|
|
1642
2364
|
});
|
|
1643
2365
|
};
|
|
1644
2366
|
var signingError = (setting) => `[commit-guard] Git could not read ${setting} as valid. Repeating the capture will not fix it. Inspect with git config --show-origin --get-all ${setting}; fix the value without changing the intended signing policy, then call commit_context with refresh:true.`;
|
|
@@ -1648,7 +2370,7 @@ var baselineGuidance = (baseline, config) => {
|
|
|
1648
2370
|
}
|
|
1649
2371
|
const observed = [
|
|
1650
2372
|
...new Set(baseline.messages.map((message) => scopePattern.exec(message.split(`
|
|
1651
|
-
`)[0])?.[1]).filter((scope) => scope !== undefined && scope.length <= 40))
|
|
2373
|
+
`)[0] ?? "")?.[1]).filter((scope) => scope !== undefined && scope.length <= 40))
|
|
1652
2374
|
].slice(0, 3);
|
|
1653
2375
|
const examples = observed.length > 0 ? `Observed scope examples (not an allowlist): ${observed.join(", ")}.
|
|
1654
2376
|
` : "";
|
|
@@ -1664,10 +2386,24 @@ Set refresh:true after a branch switch, changed signing settings, or changed com
|
|
|
1664
2386
|
};
|
|
1665
2387
|
var captureInstructions = (attempt, status) => `${status}Run this shell command immediately, unchanged, in the foreground with workdir ${attempt.workdir} (do not run it in the background). ` + `Do not wrap it or chain another command onto it. ${publicationGuidance} ${receiptGuidance}
|
|
1666
2388
|
${attempt.command}`;
|
|
2389
|
+
var rememberExpired = (state, command) => {
|
|
2390
|
+
const trimmed = command.trim();
|
|
2391
|
+
state.recentExpired.delete(trimmed);
|
|
2392
|
+
state.recentExpired.add(trimmed);
|
|
2393
|
+
if (state.recentExpired.size > 64) {
|
|
2394
|
+
const oldest = state.recentExpired.values().next().value;
|
|
2395
|
+
if (oldest !== undefined) {
|
|
2396
|
+
state.recentExpired.delete(oldest);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
};
|
|
2400
|
+
var expiredCaptureError = () => new Error("[commit-guard] This commit_context capture command expired after 20 seconds before it was claimed. Call commit_context right before committing and run the returned command immediately, unchanged, in the foreground.");
|
|
1667
2401
|
var sweep = (state) => Effect2.gen(function* sweepPending() {
|
|
2402
|
+
const now = yield* state.clock.currentTimeMillis;
|
|
1668
2403
|
for (const attempt of [...state.pending.values()].slice(0, 32)) {
|
|
1669
2404
|
state.pending.delete(attempt.scope);
|
|
1670
|
-
if (attempt.claimed === undefined &&
|
|
2405
|
+
if (attempt.claimed === undefined && now >= attempt.expires) {
|
|
2406
|
+
rememberExpired(state, attempt.command);
|
|
1671
2407
|
cleanup(attempt);
|
|
1672
2408
|
yield* recordState(state.ctx, attempt, "expired");
|
|
1673
2409
|
yield* invalidateOwned(state.ctx, attempt);
|
|
@@ -1701,16 +2437,23 @@ var validateFields = (input, fields, booleans) => {
|
|
|
1701
2437
|
};
|
|
1702
2438
|
var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.gen(function* prepare() {
|
|
1703
2439
|
const { ctx, pending, config } = state;
|
|
2440
|
+
const now = yield* state.clock.currentTimeMillis;
|
|
1704
2441
|
const previous = pending.get(scope);
|
|
1705
2442
|
if (previous !== undefined) {
|
|
1706
|
-
if (request.refresh !== true) {
|
|
2443
|
+
if (request.refresh !== true && previous.claimed !== undefined) {
|
|
2444
|
+
return {
|
|
2445
|
+
content: `Capture claimed; permission approval or execution is pending. Wait for its foreground shell result. ${publicationGuidance} ${receiptGuidance}`
|
|
2446
|
+
};
|
|
2447
|
+
}
|
|
2448
|
+
if (request.refresh !== true && previous.workdir === workdir) {
|
|
2449
|
+
previous.expires = now + captureTimeout;
|
|
1707
2450
|
return {
|
|
1708
|
-
content:
|
|
2451
|
+
content: captureInstructions(previous, "Capture still pending and unclaimed. ")
|
|
1709
2452
|
};
|
|
1710
2453
|
}
|
|
1711
2454
|
pending.delete(scope);
|
|
1712
2455
|
cleanup(previous);
|
|
1713
|
-
yield* recordState(ctx, previous, "failed", "capture replaced by refresh");
|
|
2456
|
+
yield* recordState(ctx, previous, "failed", request.refresh === true ? "capture replaced by refresh" : "capture replaced by workdir change");
|
|
1714
2457
|
yield* invalidateOwned(ctx, previous);
|
|
1715
2458
|
}
|
|
1716
2459
|
if (request.refresh !== true) {
|
|
@@ -1720,7 +2463,7 @@ var prepareCapture = (state, toolContext, request, workdir, scope) => Effect2.ge
|
|
|
1720
2463
|
}
|
|
1721
2464
|
}
|
|
1722
2465
|
const count = yield* invalidate(ctx, scope);
|
|
1723
|
-
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, workdir));
|
|
2466
|
+
const attempt = yield* Effect2.sync(() => createPending(scope, toolContext.sessionID, toolContext.agent, count, workdir, 15, process.platform, now));
|
|
1724
2467
|
pending.set(scope, attempt);
|
|
1725
2468
|
const status = state.failures.get(scope) ?? (yield* captureStatus(ctx, scope));
|
|
1726
2469
|
yield* recordState(ctx, attempt, "prepared");
|
|
@@ -1771,23 +2514,68 @@ var runCommitContext = (state, input, toolContext) => Effect2.gen(function* cont
|
|
|
1771
2514
|
state.preparing.delete(scope);
|
|
1772
2515
|
})));
|
|
1773
2516
|
}).pipe(Effect2.mapError(toToolError));
|
|
2517
|
+
var claimMismatchReason = (event, input, attempt, sessionDirectory) => {
|
|
2518
|
+
if (event.tool !== "shell") {
|
|
2519
|
+
return `tool "${event.tool}" is not "shell"`;
|
|
2520
|
+
}
|
|
2521
|
+
if (event.sessionID !== attempt.sessionID || event.agent !== attempt.agent) {
|
|
2522
|
+
return "session or agent does not match the original commit_context call";
|
|
2523
|
+
}
|
|
2524
|
+
if (input.background === true) {
|
|
2525
|
+
return "background: true is not allowed; run the capture in the foreground";
|
|
2526
|
+
}
|
|
2527
|
+
if (attempt.claimed !== undefined) {
|
|
2528
|
+
return "capture was already claimed";
|
|
2529
|
+
}
|
|
2530
|
+
let resolvedWorkdir;
|
|
2531
|
+
try {
|
|
2532
|
+
resolvedWorkdir = resolveCanonicalWorkdir(sessionDirectory, input.workdir);
|
|
2533
|
+
} catch {
|
|
2534
|
+
return `shell workdir is inaccessible; expected ${attempt.workdir}`;
|
|
2535
|
+
}
|
|
2536
|
+
if (resolvedWorkdir !== attempt.workdir) {
|
|
2537
|
+
return `resolved workdir ${resolvedWorkdir} does not match expected workdir ${attempt.workdir}`;
|
|
2538
|
+
}
|
|
2539
|
+
return null;
|
|
2540
|
+
};
|
|
1774
2541
|
var claimCapture = (state, event, input, attempt) => Effect2.gen(function* claim() {
|
|
2542
|
+
const now = yield* state.clock.currentTimeMillis;
|
|
2543
|
+
if (attempt.claimed === undefined && now >= attempt.expires) {
|
|
2544
|
+
state.pending.delete(attempt.scope);
|
|
2545
|
+
rememberExpired(state, attempt.command);
|
|
2546
|
+
cleanup(attempt);
|
|
2547
|
+
yield* recordState(state.ctx, attempt, "expired");
|
|
2548
|
+
yield* invalidateOwned(state.ctx, attempt);
|
|
2549
|
+
yield* Effect2.fail(expiredCaptureError());
|
|
2550
|
+
return;
|
|
2551
|
+
}
|
|
1775
2552
|
const session = yield* state.ctx.session.get({
|
|
1776
2553
|
sessionID: event.sessionID
|
|
1777
2554
|
});
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
2555
|
+
const sessionDirectory = session.location.directory ?? state.ctx.location.directory;
|
|
2556
|
+
const nowAfterSession = yield* state.clock.currentTimeMillis;
|
|
2557
|
+
if (state.pending.get(attempt.scope) !== attempt) {
|
|
2558
|
+
yield* Effect2.fail(new Error("[commit-guard] Capture is no longer active. Call commit_context with refresh: true."));
|
|
2559
|
+
return;
|
|
2560
|
+
}
|
|
2561
|
+
if (attempt.claimed === undefined && nowAfterSession >= attempt.expires) {
|
|
2562
|
+
state.pending.delete(attempt.scope);
|
|
2563
|
+
rememberExpired(state, attempt.command);
|
|
2564
|
+
cleanup(attempt);
|
|
2565
|
+
yield* recordState(state.ctx, attempt, "expired");
|
|
2566
|
+
yield* invalidateOwned(state.ctx, attempt);
|
|
2567
|
+
yield* Effect2.fail(expiredCaptureError());
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
const reason = claimMismatchReason(event, input, attempt, sessionDirectory);
|
|
2571
|
+
if (reason !== null) {
|
|
2572
|
+
yield* Effect2.fail(new Error(`[commit-guard] Capture must use its exact foreground shell command in the original session and workdir (${reason}). Call commit_context with refresh: true.`));
|
|
2573
|
+
return;
|
|
2574
|
+
}
|
|
2575
|
+
attempt.claimed = { messageID: event.messageID, id: event.id };
|
|
1788
2576
|
yield* recordState(state.ctx, attempt, "claimed");
|
|
1789
2577
|
});
|
|
1790
|
-
var verifyBaselineAndValidate = (state, event, input, command, invocations) => Effect2.gen(function* validate() {
|
|
2578
|
+
var verifyBaselineAndValidate = (state, event, input, command, shellMode, invocations) => Effect2.gen(function* validate() {
|
|
1791
2579
|
const { ctx, config } = state;
|
|
1792
2580
|
if (ctx.location.workspaceID !== undefined) {
|
|
1793
2581
|
return yield* Effect2.fail(new Error("[commit-guard] Remote workspace commits cannot use local commit context. Capture from a verified local checkout."));
|
|
@@ -1809,10 +2597,22 @@ var verifyBaselineAndValidate = (state, event, input, command, invocations) => E
|
|
|
1809
2597
|
return yield* Effect2.fail(new Error(signingError(baseline.gpgsign === "error" ? "commit.gpgsign" : "user.signingkey")));
|
|
1810
2598
|
}
|
|
1811
2599
|
yield* Effect2.try(() => {
|
|
1812
|
-
validateGitCommits(invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, command);
|
|
2600
|
+
validateGitCommits(invocations, { ...config, enforceSignoff: baseline.gpgsign === "true" }, command, shellMode);
|
|
1813
2601
|
});
|
|
1814
2602
|
return yield* Effect2.void;
|
|
1815
2603
|
});
|
|
2604
|
+
var isPwshTool = (state, event) => Effect2.gen(function* detectPwsh() {
|
|
2605
|
+
const description = event.info?.description;
|
|
2606
|
+
if (isJSONString(description)) {
|
|
2607
|
+
return /using pwsh\./iu.test(description);
|
|
2608
|
+
}
|
|
2609
|
+
const tools = yield* state.ctx.tool.list().pipe(Effect2.orElseSucceed(() => []));
|
|
2610
|
+
const shellTool = tools.find((item) => item.id === event.tool) ?? tools.find((item) => item.id === "shell");
|
|
2611
|
+
if (shellTool !== undefined && isJSONString(shellTool.description)) {
|
|
2612
|
+
return /using pwsh\./iu.test(shellTool.description);
|
|
2613
|
+
}
|
|
2614
|
+
return process.platform === "win32";
|
|
2615
|
+
});
|
|
1816
2616
|
var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
|
|
1817
2617
|
yield* sweep(state);
|
|
1818
2618
|
if (event.tool !== "shell" && event.tool !== "bash") {
|
|
@@ -1829,12 +2629,28 @@ var handleBeforeExecute = (state, event) => Effect2.gen(function* before() {
|
|
|
1829
2629
|
yield* claimCapture(state, event, input, attempt);
|
|
1830
2630
|
return;
|
|
1831
2631
|
}
|
|
1832
|
-
const
|
|
2632
|
+
const trimmed = command.trim();
|
|
2633
|
+
const modified = [...state.pending.values()].find((item) => {
|
|
2634
|
+
const encoded = /-EncodedCommand (?<payload>[A-Za-z0-9+/=]+)$/u.exec(item.command)?.groups?.payload;
|
|
2635
|
+
return item.command.trim() === trimmed || command.includes(item.command) || command.includes(item.artifactPath) || encoded !== undefined && command.includes(encoded);
|
|
2636
|
+
});
|
|
2637
|
+
if (modified !== undefined) {
|
|
2638
|
+
yield* Effect2.fail(new Error("[commit-guard] Capture command was modified, wrapped, or chained. Run the exact command returned by commit_context unchanged in the foreground, or call commit_context({ refresh: true })."));
|
|
2639
|
+
return;
|
|
2640
|
+
}
|
|
2641
|
+
if (state.recentExpired.has(trimmed) || [...state.recentExpired].some((expired) => command.includes(expired))) {
|
|
2642
|
+
yield* Effect2.fail(expiredCaptureError());
|
|
2643
|
+
return;
|
|
2644
|
+
}
|
|
2645
|
+
const shellMode = (yield* isPwshTool(state, event)) ? "pwsh" : "posix";
|
|
2646
|
+
const invocations = yield* Effect2.try(() => extractGitCommits(command, { shell: shellMode }));
|
|
1833
2647
|
if (invocations.length > 0 && !invocations.every((invocation) => invocation.isHelp)) {
|
|
1834
|
-
yield* verifyBaselineAndValidate(state, event, input, command, invocations);
|
|
2648
|
+
yield* verifyBaselineAndValidate(state, event, input, command, shellMode, invocations);
|
|
1835
2649
|
}
|
|
1836
2650
|
}).pipe(Effect2.mapError(toToolError));
|
|
1837
|
-
var
|
|
2651
|
+
var allowedMetadataKeys = new Set(["status", "exit", "truncated", "timeout"]);
|
|
2652
|
+
var unexpectedMetadataKeys = (metadata) => Object.keys(metadata).filter((key) => !allowedMetadataKeys.has(key));
|
|
2653
|
+
var isVerifiedShellMetadata = (metadata) => isRecord(metadata) && metadata.status === "completed" && metadata.exit === 0 && metadata.truncated === false && (metadata.timeout === undefined || metadata.timeout === false) && unexpectedMetadataKeys(metadata).length === 0;
|
|
1838
2654
|
var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* publishAttempt() {
|
|
1839
2655
|
const { ctx } = state;
|
|
1840
2656
|
if (!isRecord(event.input) || event.input.command !== attempt.command) {
|
|
@@ -1847,7 +2663,8 @@ var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* pu
|
|
|
1847
2663
|
return "capture was superseded by a refresh";
|
|
1848
2664
|
}
|
|
1849
2665
|
if (!isVerifiedShellMetadata(event.result.metadata)) {
|
|
1850
|
-
|
|
2666
|
+
const unexpected = isRecord(event.result.metadata) ? unexpectedMetadataKeys(event.result.metadata) : [];
|
|
2667
|
+
return unexpected.length > 0 ? `shell result lacks verified foreground completion metadata (unexpected keys: ${unexpected.join(", ")})` : "shell result lacks verified foreground completion metadata";
|
|
1851
2668
|
}
|
|
1852
2669
|
const session = yield* Effect2.orElseSucceed(ctx.session.get({ sessionID: event.sessionID }), () => null);
|
|
1853
2670
|
if (session === null || session.location.workspaceID !== ctx.location.workspaceID) {
|
|
@@ -1857,7 +2674,8 @@ var publishCapturedAttempt = (state, event, attempt) => Effect2.gen(function* pu
|
|
|
1857
2674
|
if (baseline === null || baseline.workdir !== attempt.workdir || ctx.location.workspaceID !== undefined) {
|
|
1858
2675
|
return "private artifact is invalid or incomplete (END required)";
|
|
1859
2676
|
}
|
|
1860
|
-
|
|
2677
|
+
const now = yield* state.clock.currentTimeMillis;
|
|
2678
|
+
if (!(yield* publish(ctx, attempt, state.generation, baseline, now).pipe(Effect2.catchCause(() => Effect2.succeed(false))))) {
|
|
1861
2679
|
return "capture storage failed or its counter changed";
|
|
1862
2680
|
}
|
|
1863
2681
|
state.failures.delete(attempt.scope);
|
|
@@ -1936,11 +2754,14 @@ var plugin = Plugin.define({
|
|
|
1936
2754
|
id: "opencode-commit-guard",
|
|
1937
2755
|
effect: (ctx) => Effect2.gen(function* setup() {
|
|
1938
2756
|
const config = yield* Effect2.sync(() => parseConfig(ctx.options));
|
|
2757
|
+
const clock = yield* Clock.Clock;
|
|
1939
2758
|
const state = {
|
|
1940
2759
|
ctx,
|
|
2760
|
+
clock,
|
|
1941
2761
|
config,
|
|
1942
2762
|
generation: randomUUID2(),
|
|
1943
2763
|
pending: new Map,
|
|
2764
|
+
recentExpired: new Set,
|
|
1944
2765
|
preparing: new Set,
|
|
1945
2766
|
lastSessionWorkdir: new Map,
|
|
1946
2767
|
failures: new Map
|