@robhowley/pi-structured-return 1.4.0 → 1.5.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.
Files changed (42) hide show
  1. package/README.md +79 -75
  2. package/extensions/structured-return/src/config/registry.test.ts +171 -0
  3. package/extensions/structured-return/src/config/registry.ts +91 -14
  4. package/extensions/structured-return/src/index.test.ts +54 -0
  5. package/extensions/structured-return/src/index.ts +20 -9
  6. package/extensions/structured-return/src/parsers/ava-text.test.ts +116 -0
  7. package/extensions/structured-return/src/parsers/ava-text.ts +161 -0
  8. package/extensions/structured-return/src/parsers/cargo-build.ts +2 -2
  9. package/extensions/structured-return/src/parsers/cargo-test.ts +2 -2
  10. package/extensions/structured-return/src/parsers/dbt-json.ts +2 -2
  11. package/extensions/structured-return/src/parsers/eslint-json.ts +2 -2
  12. package/extensions/structured-return/src/parsers/go-test-json.test.ts +119 -0
  13. package/extensions/structured-return/src/parsers/go-test-json.ts +137 -0
  14. package/extensions/structured-return/src/parsers/hadolint-json.test.ts +73 -0
  15. package/extensions/structured-return/src/parsers/hadolint-json.ts +55 -0
  16. package/extensions/structured-return/src/parsers/junit-xml.ts +2 -2
  17. package/extensions/structured-return/src/parsers/minitest-text.ts +2 -2
  18. package/extensions/structured-return/src/parsers/mocha-json.test.ts +108 -0
  19. package/extensions/structured-return/src/parsers/mocha-json.ts +77 -0
  20. package/extensions/structured-return/src/parsers/mypy-json.test.ts +101 -0
  21. package/extensions/structured-return/src/parsers/mypy-json.ts +80 -0
  22. package/extensions/structured-return/src/parsers/pylint-json.test.ts +120 -0
  23. package/extensions/structured-return/src/parsers/pylint-json.ts +64 -0
  24. package/extensions/structured-return/src/parsers/rspec-json.ts +2 -2
  25. package/extensions/structured-return/src/parsers/rubocop-json.test.ts +118 -0
  26. package/extensions/structured-return/src/parsers/rubocop-json.ts +65 -0
  27. package/extensions/structured-return/src/parsers/ruff-json.ts +2 -2
  28. package/extensions/structured-return/src/parsers/shellcheck-json.test.ts +110 -0
  29. package/extensions/structured-return/src/parsers/shellcheck-json.ts +61 -0
  30. package/extensions/structured-return/src/parsers/stylelint-json.test.ts +120 -0
  31. package/extensions/structured-return/src/parsers/stylelint-json.ts +68 -0
  32. package/extensions/structured-return/src/parsers/swiftc-text.test.ts +73 -0
  33. package/extensions/structured-return/src/parsers/swiftc-text.ts +47 -0
  34. package/extensions/structured-return/src/parsers/tail-fallback.ts +2 -2
  35. package/extensions/structured-return/src/parsers/tsc-text.test.ts +81 -0
  36. package/extensions/structured-return/src/parsers/tsc-text.ts +47 -0
  37. package/extensions/structured-return/src/parsers/unittest-text.test.ts +126 -0
  38. package/extensions/structured-return/src/parsers/unittest-text.ts +116 -0
  39. package/extensions/structured-return/src/parsers/utils.ts +43 -0
  40. package/extensions/structured-return/src/parsers/vitest-json.ts +2 -2
  41. package/package.json +1 -1
  42. package/skills/structured-return/SKILL.md +39 -0
@@ -0,0 +1,116 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { describe, it, expect } from "vitest";
5
+ import parser from "./ava-text";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(stderr: string, cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ava-test-"));
10
+ const stderrPath = path.join(dir, "stderr");
11
+ const stdoutPath = path.join(dir, "stdout");
12
+ const logPath = path.join(dir, "log");
13
+ fs.writeFileSync(stderrPath, stderr);
14
+ fs.writeFileSync(stdoutPath, "");
15
+ fs.writeFileSync(logPath, stderr);
16
+ return {
17
+ command: "npx ava test_math.js --no-color",
18
+ argv: ["npx", "ava", "test_math.js", "--no-color"],
19
+ cwd,
20
+ artifactPaths: [],
21
+ stdoutPath,
22
+ stderrPath,
23
+ logPath,
24
+ };
25
+ }
26
+
27
+ const FAILURE_OUTPUT = `
28
+ ✔ adds two numbers correctly
29
+ ✘ [fail]: multiplies two numbers correctly
30
+ ✘ [fail]: does not divide by zero Error thrown in test
31
+ ─
32
+
33
+ multiplies two numbers correctly
34
+
35
+ test_math.js:8
36
+
37
+ 7: test('multiplies two numbers correctly', t => {
38
+ 8: t.is(3 * 4, 99);
39
+ 9: });
40
+
41
+ Difference (- actual, + expected):
42
+
43
+ - 12
44
+ + 99
45
+
46
+
47
+
48
+ does not divide by zero
49
+
50
+ Error thrown in test:
51
+
52
+ TypeError {
53
+ message: 'Cannot read properties of null (reading \\'value\\')',
54
+ }
55
+
56
+ TypeError: Cannot read properties of null (reading 'value')
57
+ at /project/benchmarks/test-runners/ava/test_math.js:12:29
58
+ at Test.callFn (file:///project/node_modules/ava/lib/test.js:525:26)
59
+ at Test.run (file:///project/node_modules/ava/lib/test.js:534:33)
60
+
61
+ ─
62
+
63
+ 2 tests failed
64
+ 1 test passed
65
+ `;
66
+
67
+ const SUCCESS_OUTPUT = `
68
+ ✔ adds two numbers correctly
69
+ ─
70
+
71
+ 1 test passed
72
+ `;
73
+
74
+ describe("ava-text parser", () => {
75
+ it("parses assertion failure with expected/actual and file:line", async () => {
76
+ const result = await parser.parse(makeCtx(FAILURE_OUTPUT));
77
+ expect(result.status).toBe("fail");
78
+ expect(result.summary).toBe("2 failed, 1 passed");
79
+ expect(result.failures).toHaveLength(2);
80
+
81
+ const assertion = result.failures![0];
82
+ expect(assertion.id).toBe("multiplies two numbers correctly");
83
+ expect(assertion.file).toBe("test_math.js");
84
+ expect(assertion.line).toBe(8);
85
+ expect(assertion.message).toBe("expected 99, got 12");
86
+ });
87
+
88
+ it("parses runtime error with message and file:line from stack", async () => {
89
+ const result = await parser.parse(makeCtx(FAILURE_OUTPUT));
90
+ const runtime = result.failures![1];
91
+ expect(runtime.id).toBe("does not divide by zero");
92
+ expect(runtime.file).toBe("benchmarks/test-runners/ava/test_math.js");
93
+ expect(runtime.line).toBe(12);
94
+ expect(runtime.message).toBe("Cannot read properties of null (reading \\'value\\')");
95
+ });
96
+
97
+ it("all passing → status pass", async () => {
98
+ const result = await parser.parse(makeCtx(SUCCESS_OUTPUT));
99
+ expect(result.status).toBe("pass");
100
+ expect(result.summary).toBe("1 passed");
101
+ expect(result.failures).toHaveLength(0);
102
+ });
103
+
104
+ it("empty stderr → status error", async () => {
105
+ const result = await parser.parse(makeCtx(""));
106
+ expect(result.status).toBe("error");
107
+ });
108
+
109
+ it("file paths are relative to cwd", async () => {
110
+ const result = await parser.parse(makeCtx(FAILURE_OUTPUT));
111
+ const runtime = result.failures![1];
112
+ // absolute /project/benchmarks/... becomes relative to /project
113
+ expect(runtime.file).not.toMatch(/^\//);
114
+ expect(runtime.file).toBe("benchmarks/test-runners/ava/test_math.js");
115
+ });
116
+ });
@@ -0,0 +1,161 @@
1
+ import path from "node:path";
2
+ import type { ParserModule, ParsedFailure } from "../types";
3
+ import { extractJsStackLocation, safeReadFile } from "./utils";
4
+
5
+ /**
6
+ * Parses AVA's default text output (--no-color).
7
+ * Reads stderrPath — AVA writes all output (results + diagnostics) to stderr.
8
+ */
9
+
10
+ // Summary line: "2 tests failed" or "3 tests passed"
11
+ const SUMMARY_RE = /(\d+) tests? (passed|failed)/g;
12
+
13
+ // Failure header in the results area: "✘ [fail]: <name>"
14
+ const FAIL_MARKER_RE = /^\s*✘\s+\[fail\]:\s+(.+?)(?:\s+Error thrown in test)?$/;
15
+
16
+ const parser: ParserModule = {
17
+ id: "ava-text",
18
+ async parse(ctx) {
19
+ const stderr = safeReadFile(ctx.stderrPath);
20
+ if (!stderr.trim()) {
21
+ return { tool: "ava", status: "error", summary: "no output", logPath: ctx.logPath };
22
+ }
23
+
24
+ // Extract pass/fail counts from summary lines at the end
25
+ let passed = 0;
26
+ let failed = 0;
27
+ let m: RegExpExecArray | null;
28
+ while ((m = SUMMARY_RE.exec(stderr)) !== null) {
29
+ const count = parseInt(m[1], 10);
30
+ if (m[2] === "passed") passed = count;
31
+ else failed = count;
32
+ }
33
+
34
+ if (passed === 0 && failed === 0) {
35
+ return { tool: "ava", status: "error", summary: "could not parse ava output", logPath: ctx.logPath };
36
+ }
37
+
38
+ const failures = parseFailureBlocks(stderr, ctx.cwd);
39
+
40
+ return {
41
+ tool: "ava",
42
+ status: failed > 0 ? "fail" : "pass",
43
+ summary: failed > 0 ? `${failed} failed, ${passed} passed` : `${passed} passed`,
44
+ failures,
45
+ logPath: ctx.logPath,
46
+ };
47
+ },
48
+ };
49
+
50
+ export default parser;
51
+
52
+ /**
53
+ * AVA's failure detail section lives between the first and last ─ separators.
54
+ * Each failure block starts with the test name (matching a name from the ✘ lines),
55
+ * followed by either a file:line (assertion) or "Error thrown in test:" (runtime).
56
+ *
57
+ * Strategy: collect failed test names from ✘ lines, then split the detail section
58
+ * by those names to get per-failure blocks.
59
+ */
60
+ function parseFailureBlocks(output: string, cwd: string): ParsedFailure[] {
61
+ const lines = output.split("\n");
62
+
63
+ // Collect failed test names from ✘ markers
64
+ const failedNames: string[] = [];
65
+ for (const line of lines) {
66
+ const fm = FAIL_MARKER_RE.exec(line);
67
+ if (fm) failedNames.push(fm[1]);
68
+ }
69
+
70
+ if (failedNames.length === 0) return [];
71
+
72
+ // Find the detail section between first and last ─ separators
73
+ const sepIndices: number[] = [];
74
+ for (let i = 0; i < lines.length; i++) {
75
+ if (lines[i].match(/^\s*─\s*$/)) sepIndices.push(i);
76
+ }
77
+ if (sepIndices.length < 2) return [];
78
+
79
+ const detailStart = sepIndices[0] + 1;
80
+ const detailEnd = sepIndices[sepIndices.length - 1];
81
+ const detailLines = lines.slice(detailStart, detailEnd);
82
+
83
+ // Split detail lines into blocks by test name
84
+ const blocks: Array<{ name: string; lines: string[] }> = [];
85
+ let currentBlock: { name: string; lines: string[] } | null = null;
86
+
87
+ for (const line of detailLines) {
88
+ const trimmed = line.trim();
89
+ if (failedNames.includes(trimmed)) {
90
+ if (currentBlock) blocks.push(currentBlock);
91
+ currentBlock = { name: trimmed, lines: [] };
92
+ } else if (currentBlock) {
93
+ currentBlock.lines.push(line);
94
+ }
95
+ }
96
+ if (currentBlock) blocks.push(currentBlock);
97
+
98
+ // Parse each block
99
+ return blocks.map((block) => parseBlock(block.name, block.lines, cwd));
100
+ }
101
+
102
+ function parseBlock(name: string, lines: string[], cwd: string): ParsedFailure {
103
+ // Determine type by looking for "Error thrown in test:"
104
+ const isRuntimeError = lines.some((l) => l.trim() === "Error thrown in test:");
105
+
106
+ if (isRuntimeError) {
107
+ return parseRuntimeError(name, lines, cwd);
108
+ }
109
+ return parseAssertionFailure(name, lines, cwd);
110
+ }
111
+
112
+ function parseAssertionFailure(name: string, lines: string[], cwd: string): ParsedFailure {
113
+ let file: string | undefined;
114
+ let line: number | undefined;
115
+ let actual: string | undefined;
116
+ let expected: string | undefined;
117
+
118
+ for (const l of lines) {
119
+ const trimmed = l.trim();
120
+
121
+ // file:line (standalone, e.g. "test_math.js:8")
122
+ if (!file) {
123
+ const flm = trimmed.match(/^(.+\.[a-z]{1,4}):(\d+)$/);
124
+ if (flm) {
125
+ file = path.relative(cwd, path.resolve(cwd, flm[1]));
126
+ line = parseInt(flm[2], 10);
127
+ continue;
128
+ }
129
+ }
130
+
131
+ // Diff values: "- 12" (actual), "+ 99" (expected)
132
+ if (trimmed.startsWith("- ") && actual === undefined) {
133
+ actual = trimmed.slice(2);
134
+ } else if (trimmed.startsWith("+ ") && expected === undefined) {
135
+ expected = trimmed.slice(2);
136
+ }
137
+ }
138
+
139
+ const message = actual !== undefined && expected !== undefined ? `expected ${expected}, got ${actual}` : undefined;
140
+
141
+ return { id: name, file, line, message };
142
+ }
143
+
144
+ function parseRuntimeError(name: string, lines: string[], cwd: string): ParsedFailure {
145
+ let message: string | undefined;
146
+
147
+ for (const l of lines) {
148
+ const trimmed = l.trim();
149
+ // Extract message from "message: '...'" inside the error object
150
+ if (!message) {
151
+ const msgMatch = trimmed.match(/^message:\s*'(.+)',?$/);
152
+ if (msgMatch) message = msgMatch[1];
153
+ }
154
+ }
155
+
156
+ // Extract file:line from the first user stack frame
157
+ const loc = extractJsStackLocation(lines.join("\n"));
158
+ const file = loc.file ? path.relative(cwd, path.resolve(cwd, loc.file)) : undefined;
159
+
160
+ return { id: name, file, line: loc.line, message };
161
+ }
@@ -1,6 +1,6 @@
1
- import fs from "node:fs";
2
1
  import path from "node:path";
3
2
  import type { ParserModule, ParsedFailure } from "../types";
3
+ import { safeReadFile } from "./utils";
4
4
 
5
5
  interface CargoSpan {
6
6
  file_name: string;
@@ -29,7 +29,7 @@ const parser: ParserModule = {
29
29
  id: "cargo-build",
30
30
  async parse(ctx) {
31
31
  // --message-format=json writes NDJSON to stdout; one JSON object per line
32
- const stdout = fs.readFileSync(ctx.stdoutPath, "utf8");
32
+ const stdout = safeReadFile(ctx.stdoutPath);
33
33
  const failures: ParsedFailure[] = [];
34
34
 
35
35
  for (const line of stdout.split("\n")) {
@@ -1,6 +1,6 @@
1
- import fs from "node:fs";
2
1
  import path from "node:path";
3
2
  import type { ParserModule, ParsedFailure } from "../types";
3
+ import { safeReadFile } from "./utils";
4
4
 
5
5
  // Rust 1.73+: thread 'name' (optional-id) panicked at file:line:col:
6
6
  // message on following line(s)
@@ -21,7 +21,7 @@ const parser: ParserModule = {
21
21
  async parse(ctx) {
22
22
  // Use combined log — test binary output goes to stdout, cargo progress to stderr;
23
23
  // reading both ensures we catch everything regardless of buffering order.
24
- const log = fs.readFileSync(ctx.logPath, "utf8");
24
+ const log = safeReadFile(ctx.logPath);
25
25
  const lines = log.split("\n").map((l) => l.trim());
26
26
 
27
27
  // If compilation failed there will be no "test result:" line
@@ -1,5 +1,5 @@
1
- import fs from "node:fs";
2
1
  import type { ParserModule, ParsedFailure } from "../types";
2
+ import { safeReadFile } from "./utils";
3
3
 
4
4
  interface DbtEvent {
5
5
  data: Record<string, unknown>;
@@ -29,7 +29,7 @@ const parser: ParserModule = {
29
29
  id: "dbt-json",
30
30
  async parse(ctx) {
31
31
  // dbt --log-format json writes JSONL to stdout
32
- const raw = fs.readFileSync(ctx.stdoutPath, "utf8");
32
+ const raw = safeReadFile(ctx.stdoutPath);
33
33
  const events: DbtEvent[] = [];
34
34
  for (const line of raw.split("\n")) {
35
35
  if (!line.trim().startsWith("{")) continue;
@@ -1,11 +1,11 @@
1
- import fs from "node:fs";
2
1
  import path from "node:path";
3
2
  import type { ParserModule } from "../types";
3
+ import { safeReadFile } from "./utils";
4
4
 
5
5
  const parser: ParserModule = {
6
6
  id: "eslint-json",
7
7
  async parse(ctx) {
8
- const stdout = fs.readFileSync(ctx.stdoutPath, "utf8").trim();
8
+ const stdout = safeReadFile(ctx.stdoutPath).trim();
9
9
  const files = stdout ? JSON.parse(stdout) : [];
10
10
  const failures = [] as Array<{ id: string; file?: string; line?: number; message?: string; rule?: string }>;
11
11
  for (const file of Array.isArray(files) ? files : []) {
@@ -0,0 +1,119 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { describe, it, expect } from "vitest";
5
+ import parser from "./go-test-json";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(stdout: string, cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "gotest-test-"));
10
+ const stdoutPath = path.join(dir, "stdout");
11
+ fs.writeFileSync(stdoutPath, stdout);
12
+ return {
13
+ command: "go test -json ./...",
14
+ argv: ["go", "test", "-json", "./..."],
15
+ cwd,
16
+ artifactPaths: [],
17
+ stdoutPath,
18
+ stderrPath: path.join(dir, "stderr"),
19
+ logPath: path.join(dir, "log"),
20
+ };
21
+ }
22
+
23
+ function ndjson(...events: object[]): string {
24
+ return events.map((e) => JSON.stringify(e)).join("\n");
25
+ }
26
+
27
+ describe("go-test-json parser", () => {
28
+ it("assertion failure → file:line and message from t.Errorf output", async () => {
29
+ const stdout = ndjson(
30
+ { Action: "run", Package: "math-test", Test: "TestAdd" },
31
+ { Action: "output", Package: "math-test", Test: "TestAdd", Output: "=== RUN TestAdd\n" },
32
+ { Action: "output", Package: "math-test", Test: "TestAdd", Output: "--- PASS: TestAdd (0.00s)\n" },
33
+ { Action: "pass", Package: "math-test", Test: "TestAdd" },
34
+ { Action: "run", Package: "math-test", Test: "TestMultiply" },
35
+ { Action: "output", Package: "math-test", Test: "TestMultiply", Output: "=== RUN TestMultiply\n" },
36
+ {
37
+ Action: "output",
38
+ Package: "math-test",
39
+ Test: "TestMultiply",
40
+ Output: " math_test.go:14: expected 99, got 12\n",
41
+ },
42
+ { Action: "output", Package: "math-test", Test: "TestMultiply", Output: "--- FAIL: TestMultiply (0.00s)\n" },
43
+ { Action: "fail", Package: "math-test", Test: "TestMultiply" },
44
+ { Action: "fail", Package: "math-test", Elapsed: 0.1 }
45
+ );
46
+ const result = await parser.parse(makeCtx(stdout));
47
+ expect(result.status).toBe("fail");
48
+ expect(result.summary).toBe("1 failed, 1 passed");
49
+ expect(result.failures).toHaveLength(1);
50
+ expect(result.failures![0]).toMatchObject({
51
+ file: "math_test.go",
52
+ line: 14,
53
+ message: "expected 99, got 12",
54
+ });
55
+ });
56
+
57
+ it("panic → message and user-code file:line from stack trace", async () => {
58
+ const stdout = ndjson(
59
+ { Action: "run", Package: "math-test", Test: "TestDoesNotPanic" },
60
+ { Action: "output", Package: "math-test", Test: "TestDoesNotPanic", Output: "=== RUN TestDoesNotPanic\n" },
61
+ {
62
+ Action: "output",
63
+ Package: "math-test",
64
+ Test: "TestDoesNotPanic",
65
+ Output: "--- FAIL: TestDoesNotPanic (0.00s)\n",
66
+ },
67
+ {
68
+ Action: "output",
69
+ Package: "math-test",
70
+ Test: "TestDoesNotPanic",
71
+ Output: "panic: runtime error: invalid memory address or nil pointer dereference [recovered, repanicked]\n",
72
+ },
73
+ { Action: "output", Package: "math-test", Test: "TestDoesNotPanic", Output: "goroutine 23 [running]:\n" },
74
+ {
75
+ Action: "output",
76
+ Package: "math-test",
77
+ Test: "TestDoesNotPanic",
78
+ Output: "testing.tRunner.func1.2({0x1003f2be0, 0x10043cec0})\n",
79
+ },
80
+ {
81
+ Action: "output",
82
+ Package: "math-test",
83
+ Test: "TestDoesNotPanic",
84
+ Output: "\t/usr/local/go/src/testing/testing.go:1974 +0x1a0\n",
85
+ },
86
+ {
87
+ Action: "output",
88
+ Package: "math-test",
89
+ Test: "TestDoesNotPanic",
90
+ Output: "math-test.TestDoesNotPanic(0x123)\n",
91
+ },
92
+ { Action: "output", Package: "math-test", Test: "TestDoesNotPanic", Output: "\t/project/math_test.go:20 +0x4\n" },
93
+ { Action: "fail", Package: "math-test", Test: "TestDoesNotPanic" },
94
+ { Action: "fail", Package: "math-test", Elapsed: 0.1 }
95
+ );
96
+ const result = await parser.parse(makeCtx(stdout, "/project"));
97
+ expect(result.failures).toHaveLength(1);
98
+ expect(result.failures![0].message).toBe("runtime error: invalid memory address or nil pointer dereference");
99
+ expect(result.failures![0].file).toBe("math_test.go");
100
+ expect(result.failures![0].line).toBe(20);
101
+ });
102
+
103
+ it("all passing → status pass", async () => {
104
+ const stdout = ndjson(
105
+ { Action: "run", Package: "math-test", Test: "TestAdd" },
106
+ { Action: "pass", Package: "math-test", Test: "TestAdd" },
107
+ { Action: "pass", Package: "math-test", Elapsed: 0.1 }
108
+ );
109
+ const result = await parser.parse(makeCtx(stdout));
110
+ expect(result.status).toBe("pass");
111
+ expect(result.summary).toBe("1 passed");
112
+ expect(result.failures).toHaveLength(0);
113
+ });
114
+
115
+ it("empty stdout → status error", async () => {
116
+ const result = await parser.parse(makeCtx(""));
117
+ expect(result.status).toBe("error");
118
+ });
119
+ });
@@ -0,0 +1,137 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import type { ParserModule, ParsedFailure } from "../types";
4
+
5
+ interface GoTestEvent {
6
+ Action: string;
7
+ Package?: string;
8
+ Test?: string;
9
+ Output?: string;
10
+ Elapsed?: number;
11
+ }
12
+
13
+ /** Extract file:line and message from a Go t.Error/t.Errorf output line. */
14
+ function parseTestOutput(output: string): { file?: string; line?: number; message?: string } | undefined {
15
+ // Format: " file.go:line: message"
16
+ const m = output.match(/^\s+(\S+\.go):(\d+):\s+(.+)/);
17
+ if (m) return { file: m[1], line: Number(m[2]), message: m[3].trim() };
18
+ return undefined;
19
+ }
20
+
21
+ /** Extract panic message and user-code file:line from a stack trace. */
22
+ function parsePanic(
23
+ outputs: string[],
24
+ testName: string
25
+ ): { message?: string; file?: string; line?: number } | undefined {
26
+ const panicLine = outputs.find((o) => o.trim().startsWith("panic:"));
27
+ if (!panicLine) return undefined;
28
+ const message = panicLine
29
+ .trim()
30
+ .replace(/^panic:\s*/, "")
31
+ .replace(/\s*\[.*\]$/, "")
32
+ .trim();
33
+
34
+ // Find the user code frame: "module.TestName(..." followed by "\tfile.go:line"
35
+ for (let i = 0; i < outputs.length - 1; i++) {
36
+ if (outputs[i].includes(`.${testName}(`)) {
37
+ const m = outputs[i + 1].match(/\t([^\t]+\.go):(\d+)/);
38
+ if (m) return { message, file: m[1], line: Number(m[2]) };
39
+ }
40
+ }
41
+ return { message };
42
+ }
43
+
44
+ const parser: ParserModule = {
45
+ id: "go-test-json",
46
+ async parse(ctx) {
47
+ const stdout = fs.readFileSync(ctx.stdoutPath, "utf8").trim();
48
+ if (!stdout) {
49
+ return { tool: "go test", status: "error", summary: "no output", logPath: ctx.logPath };
50
+ }
51
+
52
+ const events: GoTestEvent[] = [];
53
+ for (const line of stdout.split("\n")) {
54
+ if (!line.trim()) continue;
55
+ try {
56
+ events.push(JSON.parse(line) as GoTestEvent);
57
+ } catch {
58
+ // skip non-JSON lines
59
+ }
60
+ }
61
+
62
+ // Collect outputs per test
63
+ const testOutputs = new Map<string, string[]>();
64
+ let passed = 0;
65
+ let failed = 0;
66
+
67
+ for (const e of events) {
68
+ if (!e.Test) continue;
69
+ if (e.Action === "output") {
70
+ const outputs = testOutputs.get(e.Test) ?? [];
71
+ outputs.push(e.Output ?? "");
72
+ testOutputs.set(e.Test, outputs);
73
+ } else if (e.Action === "pass") {
74
+ passed++;
75
+ } else if (e.Action === "fail") {
76
+ failed++;
77
+ }
78
+ }
79
+
80
+ const failures: ParsedFailure[] = [];
81
+ for (const e of events) {
82
+ if (e.Action !== "fail" || !e.Test) continue;
83
+ const outputs = testOutputs.get(e.Test) ?? [];
84
+
85
+ // Try parsing as a t.Error/t.Errorf output first
86
+ let found = false;
87
+ for (const o of outputs) {
88
+ const parsed = parseTestOutput(o);
89
+ if (parsed) {
90
+ const relFile = parsed.file
91
+ ? path.isAbsolute(parsed.file)
92
+ ? path.relative(ctx.cwd, parsed.file)
93
+ : parsed.file
94
+ : undefined;
95
+ failures.push({
96
+ id: e.Test,
97
+ file: relFile,
98
+ line: parsed.line,
99
+ message: parsed.message,
100
+ });
101
+ found = true;
102
+ break;
103
+ }
104
+ }
105
+
106
+ if (!found) {
107
+ // Try parsing as a panic
108
+ const panic = parsePanic(outputs, e.Test);
109
+ if (panic) {
110
+ const relFile = panic.file
111
+ ? path.isAbsolute(panic.file)
112
+ ? path.relative(ctx.cwd, panic.file)
113
+ : panic.file
114
+ : undefined;
115
+ failures.push({
116
+ id: e.Test,
117
+ file: relFile,
118
+ line: panic.line,
119
+ message: panic.message ?? "panic",
120
+ });
121
+ } else {
122
+ failures.push({ id: e.Test, message: "test failed" });
123
+ }
124
+ }
125
+ }
126
+
127
+ return {
128
+ tool: "go test",
129
+ status: failed > 0 ? "fail" : "pass",
130
+ summary: failed > 0 ? `${failed} failed, ${passed} passed` : `${passed} passed`,
131
+ failures,
132
+ logPath: ctx.logPath,
133
+ };
134
+ },
135
+ };
136
+
137
+ export default parser;
@@ -0,0 +1,73 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { describe, it, expect } from "vitest";
5
+ import parser from "./hadolint-json";
6
+ import type { RunContext } from "../types";
7
+
8
+ function makeCtx(stdout: string, cwd = "/project"): RunContext {
9
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hadolint-test-"));
10
+ const stdoutPath = path.join(dir, "stdout");
11
+ fs.writeFileSync(stdoutPath, stdout);
12
+ return {
13
+ command: "hadolint Dockerfile --format json",
14
+ argv: ["hadolint", "Dockerfile", "--format", "json"],
15
+ cwd,
16
+ artifactPaths: [],
17
+ stdoutPath,
18
+ stderrPath: path.join(dir, "stderr"),
19
+ logPath: path.join(dir, "log"),
20
+ };
21
+ }
22
+
23
+ describe("hadolint-json parser", () => {
24
+ it("multiple errors → correct file, line, message, rule", async () => {
25
+ const stdout = JSON.stringify([
26
+ {
27
+ code: "DL3007",
28
+ column: 1,
29
+ file: "Dockerfile",
30
+ level: "warning",
31
+ line: 1,
32
+ message: "Using latest is prone to errors.",
33
+ },
34
+ {
35
+ code: "DL3008",
36
+ column: 1,
37
+ file: "Dockerfile",
38
+ level: "warning",
39
+ line: 2,
40
+ message: "Pin versions in apt get install.",
41
+ },
42
+ ]);
43
+ const result = await parser.parse(makeCtx(stdout));
44
+ expect(result.status).toBe("fail");
45
+ expect(result.summary).toBe("2 lint errors");
46
+ expect(result.failures![0]).toMatchObject({
47
+ file: "Dockerfile",
48
+ line: 1,
49
+ message: "Using latest is prone to errors.",
50
+ rule: "DL3007",
51
+ });
52
+ expect(result.failures![1]).toMatchObject({ rule: "DL3008" });
53
+ });
54
+
55
+ it("empty array → status pass", async () => {
56
+ const result = await parser.parse(makeCtx("[]"));
57
+ expect(result.status).toBe("pass");
58
+ expect(result.failures).toHaveLength(0);
59
+ });
60
+
61
+ it("empty stdout → status pass", async () => {
62
+ const result = await parser.parse(makeCtx(""));
63
+ expect(result.status).toBe("pass");
64
+ });
65
+
66
+ it("absolute paths → relativized", async () => {
67
+ const stdout = JSON.stringify([
68
+ { code: "DL3003", column: 1, file: "/project/Dockerfile", level: "warning", line: 3, message: "Use WORKDIR" },
69
+ ]);
70
+ const result = await parser.parse(makeCtx(stdout, "/project"));
71
+ expect(result.failures![0].file).toBe("Dockerfile");
72
+ });
73
+ });