Compare commits

..
1 Commits
Author SHA1 Message Date
eb56b6666f Log text as plain text, and post buffered comments in the run step (#2122)
Text that the action logs, such as a prompt, a comment or a file name, could
contain workflow commands. Console output now shows them as plain text, and
git's output goes through console. The prompt input is no longer logged.

Buffered inline comments are posted at the end of the run step instead of in
a step of their own, so they aren't posted when a run is cancelled or times
out. The issue triage recipe passes only the issue's number.

Co-authored-by: Claude <[email protected]>
2026-11-23 15:51:21 -08:00
18 changed files with 366 additions and 62 deletions
-18
View File
@@ -447,24 +447,6 @@ runs:
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
- name: Post buffered inline comments
if: always() && inputs.classify_inline_comments != 'false'
shell: bash
env:
BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0"
GITHUB_TOKEN: ${{ steps.run.outputs.github_token || inputs.github_token || github.token }}
REPO_OWNER: ${{ github.event.repository.owner.login }}
REPO_NAME: ${{ github.event.repository.name }}
PR_NUMBER: ${{ github.event.pull_request.number || github.event.issue.number }}
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
- name: Revoke app token
if: always() && inputs.github_token == '' && steps.run.outputs.github_token != '' && steps.run.outputs.skipped_due_to_workflow_validation_mismatch != 'true'
shell: bash
+3 -2
View File
@@ -1,3 +1,4 @@
import * as core from "@actions/core";
import { spawnSync } from "child_process";
import { readdirSync, readFileSync } from "fs";
@@ -109,8 +110,8 @@ export function stopDescendants(): void {
signal(known, "SIGKILL");
const left = [...known].filter((pid) => cannotSignal.has(pid));
if (left.length > 0) {
console.log(
`::warning::Processes of another user could not be stopped: ${left.join(", ")}`,
core.warning(
`Processes of another user could not be stopped: ${left.join(", ")}`,
);
}
}
+2
View File
@@ -7,6 +7,7 @@ import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
import { validateEnvironmentVariables } from "./validate-env";
import { installPlugins } from "./install-plugins";
import { onCancel } from "./cancel";
import { escapeConsoleOutput } from "./log";
import { setExecutionFileOutputIfPresent } from "./execution-file";
import { setupWorkloadIdentity } from "./workload-identity";
import type { WorkloadIdentityHandle } from "./workload-identity";
@@ -95,5 +96,6 @@ async function run() {
}
if (import.meta.main) {
escapeConsoleOutput();
run();
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Changes what the runner would take for a workflow command, so that it's only shown.
* The runner reads `::name::` at the start of a line and `##[name]` anywhere in it.
*/
export function escapeWorkflowCommands(text: string): string {
return (
text
.replaceAll("##[", "##[\\")
// The runner skips spaces first. This skips all that isn't visible ASCII.
.replace(/^([^\x21-\x7e\r\n]*)::/gm, "$1\\::")
);
}
/**
* Keeps text that is logged, such as a comment or a file name, from running workflow
* commands. To run one, use @actions/core, which doesn't go through console.
*/
export function escapeConsoleOutput(): void {
for (const method of ["log", "info", "warn", "error", "debug"] as const) {
const write = console[method].bind(console);
console[method] = (...args: unknown[]) => {
const text = args.map((arg) =>
typeof arg === "string" ? arg : Bun.inspect(arg, { depth: 2 }),
);
write(escapeWorkflowCommands(text.join(" ")));
};
}
}
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bun
import { spawnSync } from "node:child_process";
import { describe, expect, test } from "bun:test";
import { escapeWorkflowCommands } from "../src/log";
describe("escapeWorkflowCommands", () => {
test.each([
["::warning::x", "\\::warning::x"],
["a\n::warning::x", "a\n\\::warning::x"],
["a\r::warning::x", "a\r\\::warning::x"],
["a\r\n \t::warning::x", "a\r\n \t\\::warning::x"],
[" \u0085 ::warning::x", " \u0085 \\::warning::x"],
["::warning file=a::x", "\\::warning file=a::x"],
["a ##[warning]x", "a ##[\\warning]x"],
["##[##[warning]x", "##[\\##[\\warning]x"],
["####[warning]x", "####[\\warning]x"],
])("escapes %j", (text, escaped) => {
expect(escapeWorkflowCommands(text)).toBe(escaped);
});
test.each(["std::string::npos", "## [x]", "a: b", "- see ::x", ""])(
"keeps %j",
(text) => {
expect(escapeWorkflowCommands(text)).toBe(text);
},
);
});
test("escapeConsoleOutput escapes what console writes, and not @actions/core", () => {
const { stdout, stderr } = spawnSync(
"bun",
[
"-e",
`import { escapeConsoleOutput } from "./src/log";
import * as core from "@actions/core";
escapeConsoleOutput();
console.log("a\\n::warning::b", { c: "##[warning]d" }, "100%s");
console.error("failed:", new Error("\\n::warning::e"));
try { await Bun.$\`git no-such-command\`.quiet(); } catch (e) { console.error(e); }
core.warning("f\\n::warning::g");`,
],
{ cwd: new URL("..", import.meta.url).pathname, encoding: "utf8" },
);
expect(stdout).toContain("a\n\\::warning::b");
expect(stdout).toContain("##[\\warning]d");
expect(stdout).toContain("100%s");
expect(stdout).toContain("\n::warning::f%0A::warning::g\n");
expect(stderr).toContain("\n\\::warning::e");
expect(stderr).toContain("no-such-command' is not a git command");
});
+2
View File
@@ -105,6 +105,8 @@ You can access any GitHub context variable using the standard GitHub Actions syn
- `${{ github.base_ref }}` - Base branch for PRs
- `${{ github.head_ref }}` - Head branch for PRs
Titles, descriptions, comments and branch names can come from people without write access. Prefer to pass only numbers, and let Claude read the rest with its tools, especially in a public repository.
## Advanced Configuration with claude_args
For more control over Claude's behavior, use the `claude_args` input to pass CLI arguments directly:
+1 -1
View File
@@ -145,7 +145,7 @@ Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` al
This has limits:
- It is not a sandbox. Code running on the runner, for example through an allowed `npm test`, can stop the action before it restores anything, or change the files later steps run, including the code of this and other actions. An allow rule for `Write` can reach those files too, so treat it like allowing code to run.
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, and the tracking comment isn't updated. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, the tracking comment isn't updated, and buffered inline comments aren't posted. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
- Submodule config, a repository checked out to a subdirectory, and an `include.path` target that does not exist yet are not restored.
- The git settings need git 2.31 or newer, and `safe.bareRepository` needs 2.38. On older versions they have no effect.
+3 -6
View File
@@ -409,11 +409,8 @@ jobs:
prompt: |
REPO: ${{ github.repository }}
ISSUE NUMBER: ${{ github.event.issue.number }}
TITLE: ${{ github.event.issue.title }}
BODY: ${{ github.event.issue.body }}
AUTHOR: ${{ github.event.issue.user.login }}
Analyze this new issue and:
Read this new issue with `./scripts/gh.sh issue view`, then:
1. Determine if it's a bug report, feature request, or question
2. Assess priority (critical, high, medium, low)
3. Suggest appropriate labels
@@ -437,7 +434,7 @@ jobs:
**Key Configuration:**
- Triggered on new issues
- Issue context in prompt
- Claude reads the issue itself. The prompt only has its number, because anyone who can open an issue controls its title and body
- Label management capabilities
- Requires `scripts/gh.sh` and `scripts/edit-issue-labels.sh` in your repo (see this repo's `scripts/` directory for examples)
@@ -590,7 +587,7 @@ prompt: |
### Common Tool Permissions
- **PR Comments**: `Bash(gh pr comment:*)`
- **Inline Comments**: `mcp__github_inline_comment__create_inline_comment` — pass `confirmed: true` to post immediately. When omitted, the comment is buffered and classified after the session ends (real review comments post, test/probe comments are filtered). This prevents subagent test comments from reaching PRs. To disable classification entirely, set `classify_inline_comments: 'false'` on the action.
- **Inline Comments**: `mcp__github_inline_comment__create_inline_comment` — pass `confirmed: true` to post immediately. When omitted, the comment is buffered and classified after the session ends (real review comments post, test/probe comments are filtered). If the run is cancelled, times out or crashes first, buffered comments are not posted. This prevents subagent test comments from reaching PRs. To disable classification entirely, set `classify_inline_comments: 'false'` on the action.
- **File Operations**: `Read,Write,Edit`
- **Git Operations**: `Bash(git:*)`
+9
View File
@@ -1,3 +1,12 @@
/** For an input that has no environment variable of its own. */
export function getActionInput(name: string): string | undefined {
try {
return JSON.parse(process.env.ALL_INPUTS ?? "{}")[name] || undefined;
} catch {
return undefined;
}
}
export function collectActionInputsPresence(): string {
const inputDefaults: Record<string, string> = {
trigger_phrase: "@claude",
@@ -1,4 +1,3 @@
#!/usr/bin/env bun
/**
* Reads buffered inline-comment calls from /tmp/inline-comments-buffer.jsonl,
* classifies each as "real review" vs "test/probe" using Haiku, and posts
@@ -9,9 +8,12 @@
* preserves backward compatibility — before this change, all unconfirmed
* calls posted immediately.
*/
import * as core from "@actions/core";
import { readFileSync } from "fs";
import { createOctokit } from "../github/api/client";
import { isEntityContext, type GitHubContext } from "../github/context";
import { redactSecrets } from "../github/utils/sanitizer";
import { getActionInput } from "./collect-inputs";
const BUFFER_PATH = "/tmp/inline-comments-buffer.jsonl";
@@ -44,10 +46,11 @@ Comments:
`;
async function classifyComments(bodies: string[]): Promise<boolean[] | null> {
const apiKey = process.env.ANTHROPIC_API_KEY;
// Not from the environment, where it can be a key for another ANTHROPIC_BASE_URL.
const apiKey = getActionInput("anthropic_api_key");
if (!apiKey) {
console.log(
"ANTHROPIC_API_KEY not set — skipping classification, posting all unconfirmed comments",
"anthropic_api_key not set — skipping classification, posting all unconfirmed comments",
);
return null;
}
@@ -144,10 +147,18 @@ async function postComment(
}
}
async function main() {
export async function postBufferedInlineComments({
context,
githubToken,
bufferPath = BUFFER_PATH,
}: {
context: GitHubContext;
githubToken: string;
bufferPath?: string;
}): Promise<void> {
let raw: string;
try {
raw = readFileSync(BUFFER_PATH, "utf8");
raw = readFileSync(bufferPath, "utf8");
} catch {
console.log("No buffered inline comments");
return;
@@ -165,17 +176,13 @@ async function main() {
console.log(`Found ${comments.length} buffered inline comment(s)`);
const githubToken = process.env.GITHUB_TOKEN;
const owner = process.env.REPO_OWNER;
const repo = process.env.REPO_NAME;
const prNumber = process.env.PR_NUMBER;
if (!githubToken || !owner || !repo || !prNumber) {
console.log(
"::warning::Missing GITHUB_TOKEN/REPO_OWNER/REPO_NAME/PR_NUMBER — cannot post buffered comments",
if (!isEntityContext(context) || !context.isPR) {
core.warning(
"The event is not for a pull request — cannot post buffered comments",
);
return;
}
const { owner, repo } = context.repository;
// Partition: confirmed=false are never posted; the rest are candidates
const neverPost = comments.filter((c) => c.confirmed === false);
@@ -199,11 +206,13 @@ async function main() {
verdicts === null ? [] : candidates.filter((_, i) => verdicts[i] === false);
if (filtered.length > 0) {
console.log(
`::warning::${filtered.length} buffered comment(s) classified as test/probe — NOT posted:`,
core.warning(
`${filtered.length} buffered comment(s) classified as test/probe — NOT posted:`,
);
for (const c of filtered) {
console.log(` [${c.path}:${c.line}] ${c.body.slice(0, 120)}`);
console.log(
` [${c.path}:${c.line}] ${redactSecrets(c.body).slice(0, 120)}`,
);
}
}
@@ -213,7 +222,7 @@ async function main() {
}
const octokit = createOctokit(githubToken).rest;
const pull_number = parseInt(prNumber, 10);
const pull_number = context.entityNumber;
const pr = await octokit.pulls.get({ owner, repo, pull_number });
const headSha = pr.data.head.sha;
@@ -227,8 +236,3 @@ async function main() {
}
console.log(`Posted ${posted}/${toPost.length}`);
}
main().catch((e) => {
console.error("post-buffered-inline-comments failed:", e);
process.exit(1);
});
+17 -1
View File
@@ -64,6 +64,7 @@ import {
import { validateBranchName } from "../github/operations/branch";
import type { BranchInfo } from "../github/operations/branch";
import { collectActionInputsPresence } from "./collect-inputs";
import { postBufferedInlineComments } from "./post-buffered-inline-comments";
import { updateCommentLink } from "./update-comment-link";
import { formatTurnsFromData } from "./format-turns";
import type { Turn } from "./format-turns";
@@ -76,6 +77,7 @@ import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code
import { installPlugins } from "../../base-action/src/install-plugins";
import { preparePrompt } from "../../base-action/src/prepare-prompt";
import { onCancel } from "../../base-action/src/cancel";
import { escapeConsoleOutput } from "../../base-action/src/log";
import { runClaude } from "../../base-action/src/run-claude";
import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk";
import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file";
@@ -206,6 +208,7 @@ async function run() {
let prepareCompleted = false;
// Set while a session could be running
let restoreSessionFiles: ReturnType<typeof snapshotSessionFiles> | undefined;
let hadSession = false;
let isFinishing = false;
// Revoking the app token depends on this output, and a session can write it.
@@ -300,7 +303,6 @@ async function run() {
: !!context.inputs?.prompt &&
!(isEntityContext(context) && isModeration(context));
console.log(`Mode: ${modeName}`);
console.log(`Context prompt: ${context.inputs?.prompt || "NO PROMPT"}`);
console.log(`Trigger result: ${containsTrigger}`);
if (!containsTrigger) {
@@ -481,6 +483,7 @@ async function run() {
);
let claudeResult: ClaudeRunResult;
hadSession = true;
try {
claudeResult = await runClaude(promptConfig.path, {
claudeArgs: prepareResult.claudeArgs,
@@ -574,9 +577,22 @@ async function run() {
// Set remaining action-level outputs
core.setOutput("branch_name", claudeBranch);
core.setOutput("github_token", githubToken);
// Last, because the step that revokes the app token needs the outputs. This isn't a
// step of its own, so that only the run step is given the API key.
if (hadSession && context?.inputs.classifyInlineComments && githubToken) {
try {
await postBufferedInlineComments({ context, githubToken });
} catch (error) {
core.setFailed(
`Posting buffered inline comments failed: ${redactSecrets(String(error))}`,
);
}
}
}
}
if (import.meta.main) {
escapeConsoleOutput();
run();
}
+2
View File
@@ -508,6 +508,8 @@ export async function fetchGitHubData({
// Use git hash-object to compute the SHA for the current file content
const sha = execFileSync("git", ["hash-object", file.path], {
encoding: "utf-8",
// Its errors name the file, so they are only logged below.
stdio: ["ignore", "pipe", "pipe"],
}).trim();
return {
...file,
+14 -4
View File
@@ -3,6 +3,16 @@ import { GITHUB_SERVER_URL } from "../api/config";
import { encodeBranchNameForUrl } from "./comments/common";
import { $ } from "bun";
/** Git's output can hold file names, so it's logged through console. */
async function git(...args: string[]): Promise<void> {
const result = await $`git ${args}`.quiet().nothrow();
const output = `${result.stdout}${result.stderr}`.trim();
if (output) console.log(output);
if (result.exitCode !== 0) {
throw new Error(`Command failed: git ${args.join(" ")}`);
}
}
async function pushLfsObjects(branch: string): Promise<void> {
let tracked: string;
try {
@@ -10,7 +20,7 @@ async function pushLfsObjects(branch: string): Promise<void> {
} catch {
return; // Git LFS isn't installed here
}
if (tracked.trim()) await $`git lfs push origin ${branch}`;
if (tracked.trim()) await git("lfs", "push", "origin", branch);
}
export async function checkAndCommitOrDeleteBranch(
@@ -102,18 +112,18 @@ export async function checkAndCommitOrDeleteBranch(
console.log("Found uncommitted changes, committing them...");
// Add all changes, minus anything restored from the base branch
await $`git add -A ${pathspecArgs}`;
await git("add", "-A", ...pathspecArgs);
// Commit with a descriptive message
const runId = process.env.GITHUB_RUN_ID || "unknown";
const commitMessage = `Auto-commit: Save uncommitted changes from Claude\n\nRun ID: ${runId}`;
await $`git commit -m ${commitMessage}`;
await git("commit", "-m", commitMessage);
// Hooks are off by now, and Git LFS uploads from a hook.
await pushLfsObjects(claudeBranch);
// Push the changes
await $`git push origin ${claudeBranch}`;
await git("push", "origin", claudeBranch);
console.log(
"✅ Successfully committed and pushed uncommitted changes",
+28 -5
View File
@@ -7,7 +7,10 @@
*/
import { $ } from "bun";
import { execFileSync } from "child_process";
import { execFileSync, spawnSync } from "child_process";
import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import type { ParsedGitHubContext } from "../context";
import { isPullRequestEvent } from "../context";
import { retryWithBackoff } from "../../utils/retry";
@@ -137,16 +140,36 @@ export function validateBranchName(branchName: string): void {
}
/**
* Executes a git command safely using execFileSync to avoid shell interpolation.
* Executes a git command safely using spawnSync to avoid shell interpolation.
*
* Security: execFileSync passes arguments directly to the git binary without
* Security: spawnSync passes arguments directly to the git binary without
* invoking a shell, preventing command injection attacks where malicious input
* could be interpreted as shell commands (e.g., branch names containing `;`, `|`, `&&`).
* Git's output can hold commit subjects and file names, so it's logged through console.
*
* @param args - Git command arguments (e.g., ["checkout", "branch-name"])
*/
function execGit(args: string[], env: NodeJS.ProcessEnv = process.env): void {
execFileSync("git", args, { stdio: "inherit", env });
export function execGit(
args: string[],
env: NodeJS.ProcessEnv = process.env,
): void {
// Not a pipe, which a process that a hook leaves running would keep open
const dir = mkdtempSync(join(tmpdir(), "claude-git-"));
const path = join(dir, "output");
const fd = openSync(path, "wx");
try {
const { error, status } = spawnSync("git", args, {
stdio: ["inherit", fd, fd],
env,
});
const output = readFileSync(path, "utf8").trim();
if (output) console.log(output);
if (error) throw error;
if (status !== 0) throw new Error(`Command failed: git ${args.join(" ")}`);
} finally {
closeSync(fd);
rmSync(dir, { recursive: true, force: true });
}
}
export type BranchInfo = {
+6 -1
View File
@@ -52,7 +52,12 @@ type TrackedPaths = { files: Set<string>; dirs: Set<string> };
// links into one are recorded as placeholders.
function listTrackedPaths(): TrackedPaths {
const gitPathList = (args: string[]) =>
execFileSync("git", args, { encoding: "utf8", maxBuffer: Infinity })
execFileSync("git", args, {
encoding: "utf8",
maxBuffer: Infinity,
// Git's warnings can name files.
stdio: ["ignore", "pipe", "pipe"],
})
.split("\0")
.filter(Boolean);
const modified = new Set(
+20 -2
View File
@@ -57,6 +57,24 @@ describe("action metadata", () => {
);
});
test("should not pass credentials from inputs to steps after the run step", () => {
const steps = readMetadata("action.yml").split(/^ - name: /m);
const later = steps.slice(
steps.findIndex((step) => step.startsWith("Run Claude Code Action")) + 1,
);
expect(later.length).toBeGreaterThan(0);
for (const step of later) {
const body = step.replace(/^ if: .+$/m, "");
expect(body).not.toMatch(
/inputs\.|env\.|ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN/,
);
if (body.includes("outputs.github_token")) {
expect(step).toContain("inputs.github_token == ''");
}
}
});
test("should keep restrict_untrusted_prs on by default and pass it to the run step", () => {
const metadata = readMetadata("action.yml");
@@ -85,7 +103,7 @@ describe("action metadata", () => {
.split("\n")
.filter((line) => line.includes("${GITHUB_ACTION_PATH}/src/"));
expect(commands).toHaveLength(3);
expect(commands).toHaveLength(2);
for (const command of commands) {
expect(command).toContain(
' --no-env-file --config="${GITHUB_ACTION_PATH}/bunfig.toml"' +
@@ -99,7 +117,7 @@ describe("action metadata", () => {
test("should turn off Bun's transpiler cache for the action's scripts", () => {
const steps = stepsRunningScripts(path);
expect(steps).toHaveLength(path === "action.yml" ? 3 : 1);
expect(steps).toHaveLength(path === "action.yml" ? 2 : 1);
for (const step of steps) {
expect(step).toMatch(
/^ env:\n(?: {8}.*\n|\n)*? {8}BUN_RUNTIME_TRANSPILER_CACHE_PATH: "0"$/m,
+59
View File
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
import { execFileSync } from "node:child_process";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execGit } from "../src/github/operations/branch";
const originalCwd = process.cwd();
let dir: string;
let logSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "exec-git-"));
process.chdir(dir);
const git = (...args: string[]) => execFileSync("git", args);
git("init", "-q", "-b", "main");
git("config", "user.email", "[email protected]");
git("config", "user.name", "Test");
git("commit", "-q", "--allow-empty", "-m", "base");
git("checkout", "-q", "--detach");
git("commit", "-q", "--allow-empty", "-m", "a subject");
logSpy = spyOn(console, "log").mockImplementation(() => {});
});
afterEach(() => {
logSpy.mockRestore();
process.chdir(originalCwd);
rmSync(dir, { recursive: true, force: true });
});
test("execGit logs git's output, which can hold a commit's subject, through console", () => {
execGit(["checkout", "main", "--"]);
expect(String(logSpy.mock.calls)).toContain("a subject");
});
test("execGit throws when git fails, and logs why", () => {
expect(() => execGit(["checkout", "no-such-branch", "--"])).toThrow(
"Command failed: git checkout no-such-branch --",
);
expect(String(logSpy.mock.calls)).toContain("no-such-branch");
});
test("execGit doesn't wait for a process that a hook leaves running", () => {
mkdirSync(join(dir, ".git/hooks"), { recursive: true });
const hook = join(dir, ".git/hooks/post-checkout");
writeFileSync(hook, "#!/bin/sh\nsleep 20 &\necho $! > pid\n", {
mode: 0o755,
});
const start = Date.now();
execGit(["checkout", "main", "--"]);
process.kill(Number(readFileSync(join(dir, "pid"), "utf8")));
expect(Date.now() - start).toBeLessThan(10_000);
});
@@ -0,0 +1,95 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { postBufferedInlineComments } from "../src/entrypoints/post-buffered-inline-comments";
import { createMockContext } from "./mockContext";
describe("postBufferedInlineComments", () => {
let requests: { url: string; body: any; key: string | null }[];
let spies: { mockRestore: () => void }[];
let verdicts: boolean[];
let dir: string;
let bufferPath: string;
const names = ["ALL_INPUTS", "ANTHROPIC_API_KEY"];
const savedEnv = names.map((name) => [name, process.env[name]] as const);
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "buffered-comments-"));
bufferPath = join(dir, "buffer.jsonl");
requests = [];
verdicts = [true, false];
process.env.ANTHROPIC_API_KEY = "key-from-environment";
const answer = async (input: any, init: any) => {
const url = String(input?.url ?? input);
const headers = new Headers(init?.headers);
const body = init?.body ? JSON.parse(init.body) : undefined;
requests.push({ url, body, key: headers.get("x-api-key") });
return Response.json(
url.includes("/v1/messages")
? { content: [{ type: "text", text: JSON.stringify(verdicts) }] }
: { id: 1, head: { sha: "head-sha" } },
);
};
spies = [
spyOn(globalThis, "fetch").mockImplementation(answer as any),
spyOn(console, "log").mockImplementation(() => {}),
spyOn(process.stdout, "write").mockImplementation(() => true),
];
writeFileSync(
bufferPath,
[
{ path: "a.ts", line: 1, body: "real" },
{ path: "b.ts", line: 2, body: "test" },
{ path: "c.ts", line: 3, body: "never", confirmed: false },
]
.map((comment) => JSON.stringify(comment) + "\n")
.join(""),
);
});
afterEach(() => {
spies.forEach((spy) => spy.mockRestore());
for (const [name, value] of savedEnv) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
rmSync(dir, { recursive: true, force: true });
});
const run = (isPR = true) =>
postBufferedInlineComments({
context: createMockContext({ isPR, entityNumber: 7 }),
bufferPath,
githubToken: "token",
});
const posted = () =>
requests
.filter(({ url }) => url.endsWith("/pulls/7/comments"))
.map(({ body }) => body.path);
test("classifies with the key from the input and posts the real ones", async () => {
process.env.ALL_INPUTS = JSON.stringify({ anthropic_api_key: "key" });
await run();
expect(
requests.filter(({ key }) => key).map(({ url, key }) => [url, key]),
).toEqual([["https://api.anthropic.com/v1/messages", "key"]]);
expect(posted()).toEqual(["a.ts"]);
});
test("posts nothing on an issue", async () => {
await run(false);
expect(requests).toEqual([]);
});
test.each([undefined, "{}", "not JSON"])(
"posts all candidates if the inputs are %j, without sending a key from the environment",
async (inputs) => {
delete process.env.ALL_INPUTS;
if (inputs) process.env.ALL_INPUTS = inputs;
await run();
expect(requests.filter(({ key }) => key)).toEqual([]);
expect(posted()).toEqual(["a.ts", "b.ts"]);
},
);
});