mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-17 04:09:36 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1f58ad5e6 | ||
|
|
fe99289f39 | ||
|
|
514ab7e6d3 | ||
|
|
bcbcedd16c | ||
|
|
9fa68854da | ||
|
|
f3b070c881 | ||
|
|
4d75e5f390 |
@@ -1,4 +1,7 @@
|
||||
.DS_Store
|
||||
node_modules
|
||||
scripts/.push-branch
|
||||
scripts/.no-hooks
|
||||
scripts/.git-repo
|
||||
|
||||
**/.claude/settings.local.json
|
||||
|
||||
+6
-7
@@ -281,13 +281,12 @@ runs:
|
||||
id: run
|
||||
shell: bash
|
||||
run: |
|
||||
# Do NOT pass --tsconfig-override here. It triggers a Bun runtime bug
|
||||
# ("Internal error: directory mismatch for directory .../tsconfig.json")
|
||||
# that aborts the run with exit code 1. Bun already auto-discovers the
|
||||
# action's own tsconfig.json by walking up from the entry file, so the
|
||||
# override is redundant. See oven-sh/bun#25730.
|
||||
# Keep these options wherever the action runs its own scripts, so that Bun
|
||||
# takes its settings from the action's directory. Bun before 1.4.3 logs
|
||||
# "directory mismatch" for --tsconfig-override (oven-sh/bun#25730).
|
||||
bun --no-env-file \
|
||||
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
|
||||
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
|
||||
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
|
||||
env:
|
||||
# Prepare inputs
|
||||
@@ -428,9 +427,9 @@ runs:
|
||||
run: |
|
||||
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
|
||||
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
|
||||
# No --tsconfig-override: see the "Run Claude Code Action" step above.
|
||||
"$BUN_BIN" --no-env-file \
|
||||
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
|
||||
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
|
||||
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
|
||||
|
||||
- name: Post buffered inline comments
|
||||
@@ -445,9 +444,9 @@ runs:
|
||||
run: |
|
||||
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
|
||||
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
|
||||
# No --tsconfig-override: see the "Run Claude Code Action" step above.
|
||||
"$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
|
||||
|
||||
@@ -147,7 +147,7 @@ runs:
|
||||
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
|
||||
run: |
|
||||
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
|
||||
CLAUDE_CODE_VERSION="2.1.323"
|
||||
CLAUDE_CODE_VERSION="2.1.325"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
|
||||
+10
-10
@@ -6,7 +6,7 @@
|
||||
"name": "@anthropic-ai/claude-code-base-action",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.323",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
|
||||
"shell-quote": "^1.8.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -27,23 +27,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]3", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.323", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.323", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.323", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.323" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-GXIczMzzceNWB+bIImK59hWOQoBWZtSw+AESPc/qbAWmmHM8Wrqb5KvTwWZ07CmjyC/KcPC47nOLxxyHlWqKPA=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]5", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.325" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-MhSm2Fhk3DA/hhjdCKXDZWlnykpPWJjX42SogllAHMplY9ZKT+Ltb8QPtQxpe225Imfs4A8IKaNE4biivA+fHg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-hWkXHsSMIv+78duw3mDi0bndCpWquGuMrCX6C7G9LzEtpcd+ZvzI5ZE4E6SwqX1bSy8rxhEg+hVJSTk4ABoxpA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0u8bTug2zH+zWE8CMiFrm/ldmH20uA9B/zhXpI7ATHFJnpPMdwTqE56CFM0m3LOwnNum0jpRn7XV1dn6Pf2pqA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "x64" }, "sha512-JHtMk+FBRQPvH046dUIda6s6bza8CRQkaAdy96JwV1zqgi3mtlAg5yXFxPA/QNoiHz5Ul225wCZr9lR7gbwkMg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]5", "", { "os": "darwin", "cpu": "x64" }, "sha512-HD3YRFyM5H5QH2usS/WD6gobk3BEp2jq9dKyrkhAVdQIqFMlrcSrRhGA0i3R1IOLxtPAYkmDGepZ62k1kMOW9Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-ONhCJapk9UxpaZ3HY1GTZezMoiQ6Ab7fIubS+dJeXIyj8aQjGQALHQoEl9D1Hrr+q5ppZPOAt0hg69x8aGbTBA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-28oVrCEN6M6MJP8Od4SK/scal1QdLbn5Sci+qL8j55l6csHtPeUYF9zdjWLniFKph43pejfZf5te/Vf/bwehkw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-N+ZTBRQj8Ew3/eLCZE7JADceyN6Yi1CncJAdzknF5RL9dckIujv4B7C9neBNOXdo+bGFEysjPcUbVsaRkPguKQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-72y6QNRZC4eMCxne/wNsuwNHsViSkgFKlYMCUVXxmiR9gpIMd3rf++oJMIsSuEAQqzqT7jwCrdtibv6R4bx5PA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9M0rnLcCa9sJdZoRCPbjyMOv3raoJm39u348t2ozCgE35Y9e/jGgxy+rG2jfRTaCBILDDrR57ClRQVRlpNeLpQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-wXEWbDmNYiorY5EKASYjvQct8zHShUPmAS9N/IAsgPA/cx2vsOFqPQw8jRQKeaW6AmFgx7k/Wf7THalNXbMEkQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-QMaFszyJraPnZyJTy6K9vr1wVA/4MIjWSFcaByGv/x3Hk/F7smsMnqpuATO6M6bRsev+IVPj0p6rsdpYAdt1yA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-BHewYUTd7mDLR5iHTVt6Q28gJKLC5C24b1H3NM0qGt9dxnjVUh1Lza52GzHY2Rb9hAPQymLSXWuVh1OFoFQatA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "arm64" }, "sha512-FS+eYSMU/x8Hmy98zypoOw9/+jMgtGmBEyYmE+jJUCdb3a4k1pwcx08XGici/hnBR3xiKK65ifxwVg2oNyZocQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]5", "", { "os": "win32", "cpu": "arm64" }, "sha512-NH3I2o105oKK8lfJ5RlzCp+YTZn3qncwQ1xSzQ4jqn7LUddThIidpFU7B+TKQxh1X9eayAp7EtrBQ36mXflQwQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "x64" }, "sha512-mW2h1o0Kt92AKZBr05AwE3izJTAYpWNUurOppPdzH/hditbT1zwc0tAJ3p+G+XMkqUWenJNbpunVG0utfQ2hmA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]5", "", { "os": "win32", "cpu": "x64" }, "sha512-pjqVL++V/2oMJ6u1HdB608bcTUvzts1e8hX93Q8khasy2JB+R823bnvpQapcOurOWB3+v1X2JXIjXyWcGPJCQQ=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.323",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
|
||||
"shell-quote": "^1.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -24,7 +24,7 @@ const ACCUMULATING_FLAGS = new Set([
|
||||
]);
|
||||
|
||||
// Delimiter used to join accumulated flag values
|
||||
const ACCUMULATE_DELIMITER = "\x00";
|
||||
export const ACCUMULATE_DELIMITER = "\x00";
|
||||
|
||||
// shell-quote treats ()|&;<> as control operators and splits adjacent text
|
||||
// around them into separate tokens (returned as `{op}` objects, which we then
|
||||
@@ -275,8 +275,11 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
|
||||
const directDisallowedTools = options.disallowedTools
|
||||
? options.disallowedTools.split(",").map((t) => t.trim())
|
||||
: [];
|
||||
// Not deduplicated: a rule can hold a comma, so these can be pieces of rules, and the
|
||||
// SDK joins them again. Dropping a repeated piece would break a rule and the ones after it.
|
||||
const mergedDisallowedTools = [
|
||||
...new Set([...extraArgsDisallowedTools, ...directDisallowedTools]),
|
||||
...extraArgsDisallowedTools,
|
||||
...directDisallowedTools,
|
||||
];
|
||||
delete extraArgs["disallowedTools"];
|
||||
delete extraArgs["disallowed-tools"];
|
||||
|
||||
@@ -269,6 +269,17 @@ describe("parseSdkOptions", () => {
|
||||
expect(result.sdkOptions.extraArgs?.["disallowedTools"]).toBeUndefined();
|
||||
});
|
||||
|
||||
test("keeps rules that share text after a comma", () => {
|
||||
const result = parseSdkOptions({
|
||||
claudeArgs: `--disallowedTools 'Bash(/x.sh {a,b}/*)' --disallowedTools 'Bash(git add {a,b}/*)'`,
|
||||
disallowedTools: "Bash(bun:*)",
|
||||
});
|
||||
|
||||
expect(result.sdkOptions.disallowedTools?.join(",")).toBe(
|
||||
"Bash(/x.sh {a,b}/*),Bash(git add {a,b}/*),Bash(bun:*)",
|
||||
);
|
||||
});
|
||||
|
||||
test("should merge disallowedTools from both sources", () => {
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: '--disallowedTools "Bash"',
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.323",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
@@ -37,23 +37,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]3", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.323", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.323", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.323", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.323", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.323" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-GXIczMzzceNWB+bIImK59hWOQoBWZtSw+AESPc/qbAWmmHM8Wrqb5KvTwWZ07CmjyC/KcPC47nOLxxyHlWqKPA=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]5", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.325", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.325", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.325" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-MhSm2Fhk3DA/hhjdCKXDZWlnykpPWJjX42SogllAHMplY9ZKT+Ltb8QPtQxpe225Imfs4A8IKaNE4biivA+fHg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-hWkXHsSMIv+78duw3mDi0bndCpWquGuMrCX6C7G9LzEtpcd+ZvzI5ZE4E6SwqX1bSy8rxhEg+hVJSTk4ABoxpA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-0u8bTug2zH+zWE8CMiFrm/ldmH20uA9B/zhXpI7ATHFJnpPMdwTqE56CFM0m3LOwnNum0jpRn7XV1dn6Pf2pqA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "x64" }, "sha512-JHtMk+FBRQPvH046dUIda6s6bza8CRQkaAdy96JwV1zqgi3mtlAg5yXFxPA/QNoiHz5Ul225wCZr9lR7gbwkMg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]5", "", { "os": "darwin", "cpu": "x64" }, "sha512-HD3YRFyM5H5QH2usS/WD6gobk3BEp2jq9dKyrkhAVdQIqFMlrcSrRhGA0i3R1IOLxtPAYkmDGepZ62k1kMOW9Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-ONhCJapk9UxpaZ3HY1GTZezMoiQ6Ab7fIubS+dJeXIyj8aQjGQALHQoEl9D1Hrr+q5ppZPOAt0hg69x8aGbTBA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-28oVrCEN6M6MJP8Od4SK/scal1QdLbn5Sci+qL8j55l6csHtPeUYF9zdjWLniFKph43pejfZf5te/Vf/bwehkw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-N+ZTBRQj8Ew3/eLCZE7JADceyN6Yi1CncJAdzknF5RL9dckIujv4B7C9neBNOXdo+bGFEysjPcUbVsaRkPguKQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-72y6QNRZC4eMCxne/wNsuwNHsViSkgFKlYMCUVXxmiR9gpIMd3rf++oJMIsSuEAQqzqT7jwCrdtibv6R4bx5PA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9M0rnLcCa9sJdZoRCPbjyMOv3raoJm39u348t2ozCgE35Y9e/jGgxy+rG2jfRTaCBILDDrR57ClRQVRlpNeLpQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-wXEWbDmNYiorY5EKASYjvQct8zHShUPmAS9N/IAsgPA/cx2vsOFqPQw8jRQKeaW6AmFgx7k/Wf7THalNXbMEkQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-QMaFszyJraPnZyJTy6K9vr1wVA/4MIjWSFcaByGv/x3Hk/F7smsMnqpuATO6M6bRsev+IVPj0p6rsdpYAdt1yA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]5", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-BHewYUTd7mDLR5iHTVt6Q28gJKLC5C24b1H3NM0qGt9dxnjVUh1Lza52GzHY2Rb9hAPQymLSXWuVh1OFoFQatA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "arm64" }, "sha512-FS+eYSMU/x8Hmy98zypoOw9/+jMgtGmBEyYmE+jJUCdb3a4k1pwcx08XGici/hnBR3xiKK65ifxwVg2oNyZocQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]5", "", { "os": "win32", "cpu": "arm64" }, "sha512-NH3I2o105oKK8lfJ5RlzCp+YTZn3qncwQ1xSzQ4jqn7LUddThIidpFU7B+TKQxh1X9eayAp7EtrBQ36mXflQwQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "x64" }, "sha512-mW2h1o0Kt92AKZBr05AwE3izJTAYpWNUurOppPdzH/hditbT1zwc0tAJ3p+G+XMkqUWenJNbpunVG0utfQ2hmA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]5", "", { "os": "win32", "cpu": "x64" }, "sha512-pjqVL++V/2oMJ6u1HdB608bcTUvzts1e8hX93Q8khasy2JB+R823bnvpQapcOurOWB3+v1X2JXIjXyWcGPJCQQ=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
|
||||
|
||||
|
||||
+13
-7
@@ -57,11 +57,15 @@ This is general guidance for these event types — see [GitHub's documentation](
|
||||
|
||||
### Which files come from the base branch on pull requests
|
||||
|
||||
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
|
||||
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
|
||||
|
||||
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
|
||||
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head, apart from the files described below. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
|
||||
|
||||
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config.
|
||||
On pull requests from authors without write access, the action also replaces what npm and Bun read from the repository root with the base branch's version, wherever the two differ: `.npmrc`, `bunfig.toml` and tracked files in `node_modules/`. In a `package.json` whose `name`, `bin`, `directories.bin` or `workspaces` change the commands it provides, only `name`, `bin`, `directories` and `workspaces` are replaced, or the whole file if it can't be understood, including in other directories if the base branch uses workspaces. The pull request's versions are kept under `.claude-pr/` for reading, except for `node_modules/`. Claude can't edit `.npmrc`, `bunfig.toml`, `node_modules/` or, where one was replaced, `package.json` on these pull requests, in any directory. Its Bash commands start in the repository root there, because a hook runs in the session's current directory and only the root's files are replaced. The replaced files stay in the working tree for later steps in the job, and if Claude stages everything, its commit can include them, as with the paths above. `restrict_untrusted_prs: false` turns this off.
|
||||
|
||||
This doesn't cover other package managers, the `.env` files and `tsconfig.json` that Bun loads, other files that a hook's own command reads, or a git command that resets the working tree during the session, so keep hooks self-contained as described above. Files that git doesn't track, such as packages an earlier step installed, stay as they are. A file that is the same link on both branches is left as a link.
|
||||
|
||||
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config on pull requests from authors with write access.
|
||||
|
||||
### Running code from pull requests
|
||||
|
||||
@@ -88,20 +92,22 @@ Job logs, and job and step names, are text the pull request controls. To turn of
|
||||
|
||||
Bots often open pull requests from branches in your own repository. Runs there usually need no approval and can get secrets, so these steps don't protect you in that case.
|
||||
|
||||
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
|
||||
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied, tool config comes from the base branch as described [above](#which-files-come-from-the-base-branch-on-pull-requests), and a `cd` no longer carries over to the next Bash command. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
|
||||
|
||||
### What a session can leave behind
|
||||
|
||||
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on.
|
||||
|
||||
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is cancelled before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
|
||||
Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` always work on the repository the action checked out, and take only a short list of flags, so `git add -f` is refused. They ignore settings from the environment: `GIT_SSH_COMMAND`, `GIT_ASKPASS`, `GIT_CONFIG_*`, any other `GIT_*` variable except the author and committer ones, `XDG_CONFIG_HOME`, and a `HOME` changed during the session. A workflow that relies on one of those, such as pushing over SSH with `GIT_SSH_COMMAND`, can allow its own command in `claude_args`, such as `Bash(git push:*)`, which gives up these protections for that workflow.
|
||||
|
||||
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.
|
||||
- A run that is cancelled or times out during the session does not restore anything, and later `always()` and post steps still run.
|
||||
- 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. On older versions they have no effect.
|
||||
- The git settings need git 2.31 or newer, and `safe.bareRepository` needs 2.38. On older versions they have no effect.
|
||||
|
||||
### `claude-code-action` vs `claude-code-base-action`
|
||||
|
||||
@@ -111,7 +117,7 @@ This has limits:
|
||||
|
||||
In its default configuration, **Claude does not create pull requests automatically** when responding to `@claude` mentions. Instead:
|
||||
|
||||
- Claude commits code changes to a new branch, or to the pull request's branch, through wrapper scripts in the action. A deny rule for `git commit` or `git push` in `claude_args` also covers those scripts. A deny rule in a settings file doesn't, so pass it in `claude_args`
|
||||
- Claude commits code changes to a new branch, or to the pull request's branch, through wrapper scripts in the action. A deny rule for `git add`, `git rm`, `git commit` or `git push` in `claude_args` also covers those scripts, including a narrower rule such as `git add -A:*`. A deny rule in a settings file doesn't, so pass it in `claude_args`
|
||||
- Claude's push command can't update any other branch. For a pull request from a fork, its branch is `pr-N` in your repository, and the fork's branch is not updated
|
||||
- Branch protection on your default branch is still worth having: a workflow can allow other push commands, and a pull request opened from the default branch has that branch as its own
|
||||
- Claude provides a **link to the GitHub PR creation page** in its response
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.323",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.325",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Wrapper around `git add` that only stages files. Without it, an allow rule for
|
||||
# `git add` also permits flags that open an editor or read a file of paths.
|
||||
#
|
||||
# Usage:
|
||||
# git-add.sh [-A] [-u] [-v] [--chmod=+x|--chmod=-x] [--] <paths>
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
|
||||
|
||||
paths_only=false
|
||||
for arg in "$@"; do
|
||||
if [[ "$paths_only" == true ]]; then
|
||||
continue
|
||||
fi
|
||||
case "$arg" in
|
||||
-A | --all | -u | --update | -v | --verbose | --chmod=+x | --chmod=-x) ;;
|
||||
--) paths_only=true ;;
|
||||
-*)
|
||||
echo "Error: only -A, -u, -v, --chmod and file paths are allowed (got: $arg)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
exec git "${git_args[@]}" add "$@"
|
||||
@@ -8,6 +8,8 @@ set -euo pipefail
|
||||
# Usage:
|
||||
# git-commit.sh -m "<message>" [-m "<message>"] [-a] [--allow-empty] [-- <paths>]
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
|
||||
|
||||
has_message=false
|
||||
expect_message=false
|
||||
paths_only=false
|
||||
@@ -50,4 +52,4 @@ if [[ "$has_message" != true ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exec git commit "$@"
|
||||
exec git "${git_args[@]}" commit "$@"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Sourced by the git wrappers. Clears settings in the environment that change what
|
||||
# git runs, and sets the arguments every wrapper passes to git. Files beside this
|
||||
# script, written by the action, record the session's repository and hook setting.
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
while IFS= read -r name; do
|
||||
case "$name" in
|
||||
GIT_AUTHOR_* | GIT_COMMITTER_*) ;;
|
||||
GIT_*) unset "$name" ;;
|
||||
esac
|
||||
done < <(compgen -e)
|
||||
unset XDG_CONFIG_HOME EDITOR VISUAL PAGER SSH_ASKPASS
|
||||
|
||||
git_args=(-c core.fsmonitor=false -c safe.bareRepository=explicit)
|
||||
if [[ -e "$script_dir/.no-hooks" ]]; then
|
||||
git_args+=(-c core.hooksPath=/dev/null)
|
||||
fi
|
||||
if [[ -e "$script_dir/.git-repo" ]]; then
|
||||
{ IFS= read -r git_dir; IFS= read -r work_tree; IFS= read -r home || true; } <"$script_dir/.git-repo"
|
||||
git_args+=("--git-dir=$git_dir" "--work-tree=$work_tree")
|
||||
if [[ -n "$home" ]]; then
|
||||
export HOME="$home"
|
||||
fi
|
||||
fi
|
||||
+8
-3
@@ -2,8 +2,9 @@
|
||||
set -euo pipefail
|
||||
|
||||
# Wrapper around `git push` that only allows `origin <ref>` with no flags, and only
|
||||
# updates the branch this session was set up on (CLAUDE_PUSH_BRANCH). That stops a
|
||||
# prompt-injected session from updating main or anyone else's branch.
|
||||
# updates the branch this session was set up on. That stops a prompt-injected session
|
||||
# from updating main or anyone else's branch. Tag mode records the branch in a file
|
||||
# beside this script. Elsewhere, set CLAUDE_PUSH_BRANCH.
|
||||
# Defends against --receive-pack / --exec RCE and arbitrary-remote exfiltration
|
||||
# (H1 #3556799). `git push:*` in allowedTools permits `git push --receive-pack='sh -c ...' ext::sh`
|
||||
# which runs arbitrary shell on the Actions runner. This wrapper closes that.
|
||||
@@ -30,6 +31,10 @@ if [[ "$1" != "origin" ]]; then
|
||||
fi
|
||||
|
||||
BRANCH="${CLAUDE_PUSH_BRANCH:-}"
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
|
||||
if [[ -e "$script_dir/.push-branch" ]]; then
|
||||
BRANCH="$(<"$script_dir/.push-branch")"
|
||||
fi
|
||||
if [[ -z "$BRANCH" ]]; then
|
||||
echo "Error: CLAUDE_PUSH_BRANCH is not set, so there is no branch to push to" >&2
|
||||
exit 1
|
||||
@@ -45,4 +50,4 @@ case "$2" in
|
||||
esac
|
||||
|
||||
# The full refspec fixes the target, whatever HEAD points at, and can't be forced.
|
||||
exec git push origin "$SOURCE:refs/heads/$BRANCH"
|
||||
exec git "${git_args[@]}" push origin "$SOURCE:refs/heads/$BRANCH"
|
||||
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Wrapper around `git rm` that only takes basic flags and file paths.
|
||||
#
|
||||
# Usage:
|
||||
# git-rm.sh [-r] [-f] [--cached] [-q] [--] <paths>
|
||||
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/git-env.sh"
|
||||
|
||||
paths_only=false
|
||||
for arg in "$@"; do
|
||||
if [[ "$paths_only" == true ]]; then
|
||||
continue
|
||||
fi
|
||||
case "$arg" in
|
||||
-r | -f | -rf | -fr | --force | --cached | -q | --quiet) ;;
|
||||
--) paths_only=true ;;
|
||||
-*)
|
||||
echo "Error: only -r, -f, --cached, -q and file paths are allowed (got: $arg)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
exec git "${git_args[@]}" rm "$@"
|
||||
@@ -24,6 +24,8 @@ import { GITHUB_SERVER_URL } from "../github/api/config";
|
||||
import { extractUserRequest } from "../utils/extract-user-request";
|
||||
export type { CommonFields, PreparedContext } from "./types";
|
||||
|
||||
const GIT_ADD_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-add.sh`;
|
||||
const GIT_RM_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-rm.sh`;
|
||||
const GIT_PUSH_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-push.sh`;
|
||||
const GIT_COMMIT_WRAPPER = `${process.env.GITHUB_ACTION_PATH}/scripts/git-commit.sh`;
|
||||
|
||||
@@ -55,10 +57,10 @@ export function buildAllowedToolsString(
|
||||
} else {
|
||||
// When not using commit signing, add specific Bash git commands
|
||||
baseTools.push(
|
||||
"Bash(git add:*)",
|
||||
`Bash(${GIT_ADD_WRAPPER}:*)`,
|
||||
`Bash(${GIT_COMMIT_WRAPPER}:*)`,
|
||||
`Bash(${GIT_PUSH_WRAPPER}:*)`,
|
||||
"Bash(git rm:*)",
|
||||
`Bash(${GIT_RM_WRAPPER}:*)`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -436,7 +438,7 @@ function getCommitInstructions(
|
||||
if (eventData.isPR && !eventData.claudeBranch) {
|
||||
return `
|
||||
- Use git commands via the Bash tool to commit and push your changes:
|
||||
- Stage files: Bash(git add <files>)
|
||||
- Stage files: Bash(${GIT_ADD_WRAPPER} <files>)
|
||||
- Commit with a descriptive message: Bash(${GIT_COMMIT_WRAPPER} -m "<message>")
|
||||
${
|
||||
coAuthorLine
|
||||
@@ -450,7 +452,7 @@ function getCommitInstructions(
|
||||
return `
|
||||
- You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch.
|
||||
- Use git commands via the Bash tool to commit and push your changes:
|
||||
- Stage files: Bash(git add <files>)
|
||||
- Stage files: Bash(${GIT_ADD_WRAPPER} <files>)
|
||||
- Commit with a descriptive message: Bash(${GIT_COMMIT_WRAPPER} -m "<message>")
|
||||
${
|
||||
coAuthorLine
|
||||
@@ -830,10 +832,10 @@ ${
|
||||
- mcp__github_file_ops__commit_files: {"files": ["path/to/file1.js", "path/to/file2.py"], "message": "feat: add new feature"}
|
||||
- mcp__github_file_ops__delete_files: {"paths": ["path/to/old.js"], "message": "chore: remove deprecated file"}`
|
||||
: `- Use git commands via the Bash tool for version control (remember that you have access to these git commands):
|
||||
- Stage files: Bash(git add <files>)
|
||||
- Stage files: Bash(${GIT_ADD_WRAPPER} <files>)
|
||||
- Commit changes: Bash(${GIT_COMMIT_WRAPPER} -m "<message>")
|
||||
- Push to remote: Bash(${GIT_PUSH_WRAPPER} origin HEAD)
|
||||
- Delete files: Bash(git rm <files>) followed by commit and push
|
||||
- Delete files: Bash(${GIT_RM_WRAPPER} <files>) followed by commit and push
|
||||
- Check status: Bash(git status)
|
||||
- View diff: Bash(git diff)${eventData.isPR && eventData.baseBranch ? `\n - IMPORTANT: For PR diffs, use: Bash(git diff origin/${eventData.baseBranch}...HEAD)` : ""}`
|
||||
}
|
||||
|
||||
+39
-8
@@ -33,10 +33,16 @@ import { prepareTagMode } from "../modes/tag";
|
||||
import { prepareAgentMode } from "../modes/agent";
|
||||
import { checkContainsTrigger } from "../github/validation/trigger";
|
||||
import {
|
||||
clearSessionState,
|
||||
disableGitPrograms,
|
||||
prepareGitForSession,
|
||||
snapshotSessionFiles,
|
||||
} from "../github/operations/session-guard";
|
||||
import { restoreConfigFromBase } from "../github/operations/restore-config";
|
||||
import {
|
||||
restoreToolConfigFromBase,
|
||||
toolConfigDenyRules,
|
||||
} from "../github/operations/tool-config";
|
||||
import { validateBranchName } from "../github/operations/branch";
|
||||
import { collectActionInputsPresence } from "./collect-inputs";
|
||||
import { updateCommentLink } from "./update-comment-link";
|
||||
@@ -85,7 +91,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.323";
|
||||
const claudeCodeVersion = "2.1.325";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
@@ -249,7 +255,9 @@ async function run() {
|
||||
const untrustedPrDisallowedTools = isEntityContext(context)
|
||||
? await getUntrustedPrDisallowedTools(octokit.rest, context)
|
||||
: [];
|
||||
disableGitPrograms({ hooks: untrustedPrDisallowedTools.length > 0 });
|
||||
const hooksOff = untrustedPrDisallowedTools.length > 0;
|
||||
disableGitPrograms({ hooks: hooksOff });
|
||||
clearSessionState();
|
||||
|
||||
console.log(
|
||||
`Preparing with mode: ${modeName} for event: ${context.eventName}`,
|
||||
@@ -279,6 +287,13 @@ async function run() {
|
||||
|
||||
validateEnvironmentVariables();
|
||||
|
||||
// Tag mode sets claudeBranch only when it branched from the base instead of
|
||||
// checking out the PR's head, as for a closed or merged PR.
|
||||
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
|
||||
const isUntrustedCheckout =
|
||||
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
|
||||
let restoredToolConfig: string[] = [];
|
||||
|
||||
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
|
||||
// Restore them from the base branch before the CLI reads them.
|
||||
//
|
||||
@@ -300,6 +315,11 @@ async function run() {
|
||||
}
|
||||
if (restoreBase) {
|
||||
restoredConfigPaths = restoreConfigFromBase(restoreBase);
|
||||
// Before plugins are installed, which can already start package managers here.
|
||||
if (isUntrustedCheckout) {
|
||||
restoredToolConfig = restoreToolConfigFromBase(restoreBase);
|
||||
restoredConfigPaths.push(...restoredToolConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,14 +339,24 @@ async function run() {
|
||||
promptFile,
|
||||
});
|
||||
|
||||
// Tag mode sets claudeBranch only when it branched from the base instead of
|
||||
// checking out the PR's head, as for a closed or merged PR. The deny rules are
|
||||
// passed separately because text added to claudeArgs can be lost: a comment at
|
||||
// Passed separately because text added to claudeArgs can be lost: a comment at
|
||||
// the end of the user's claude_args would swallow it.
|
||||
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
|
||||
const disallowedTools = checkedOutPrHead ? untrustedPrDisallowedTools : [];
|
||||
const disallowedTools = isUntrustedCheckout
|
||||
? [
|
||||
...untrustedPrDisallowedTools,
|
||||
...toolConfigDenyRules(restoredToolConfig),
|
||||
]
|
||||
: [];
|
||||
|
||||
const restoreSessionFiles = snapshotSessionFiles();
|
||||
// A hook runs in the session's current directory, and only the repository root's tool
|
||||
// config comes from the base branch. This keeps Bash from moving the session.
|
||||
if (isUntrustedCheckout) {
|
||||
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
|
||||
}
|
||||
|
||||
const restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: hooksOff }),
|
||||
);
|
||||
|
||||
let claudeResult: ClaudeRunResult;
|
||||
try {
|
||||
@@ -374,6 +404,7 @@ async function run() {
|
||||
core.setFailed(`Action failed with error: ${redactSecrets(errorMessage)}`);
|
||||
} finally {
|
||||
// Phase 4: Cleanup (always runs)
|
||||
clearSessionState();
|
||||
|
||||
// Stop refreshing the workload identity token file and delete the token
|
||||
// material so it doesn't outlive this step
|
||||
|
||||
@@ -31,6 +31,7 @@ export const SENSITIVE_PATHS = [
|
||||
".ripgreprc",
|
||||
"CLAUDE.md",
|
||||
"CLAUDE.local.md",
|
||||
"AGENTS.md",
|
||||
".husky",
|
||||
];
|
||||
|
||||
@@ -206,7 +207,7 @@ function snapshotSensitivePath(
|
||||
}
|
||||
}
|
||||
|
||||
function ensureClaudePrExcludedFromGit(): void {
|
||||
export function ensureClaudePrExcludedFromGit(): void {
|
||||
const excludePath = execFileSync(
|
||||
"git",
|
||||
["rev-parse", "--git-path", "info/exclude"],
|
||||
@@ -258,7 +259,8 @@ function ensureClaudePrExcludedFromGit(): void {
|
||||
* extends to the runtime itself: `bunx <tool>` runs the tool under `node` when
|
||||
* `node` is on PATH, but on a Bun-only runner Bun executes the script and reads
|
||||
* `bunfig.toml` (e.g. `preload`) from the checkout, so `bunfig.toml` and
|
||||
* `.npmrc` there are PR-controlled runtime config too.
|
||||
* `.npmrc` there are PR-controlled runtime config too. On PRs from authors without
|
||||
* write access, restoreToolConfigFromBase replaces those.
|
||||
*
|
||||
* @param baseBranch - PR base branch name. Must be pre-validated (branch.ts
|
||||
* calls validateBranchName on it before returning).
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
constants,
|
||||
fstatSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
@@ -13,7 +14,7 @@ import {
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { homedir } from "os";
|
||||
import { isAbsolute, join, resolve } from "path";
|
||||
import { dirname, isAbsolute, join, resolve } from "path";
|
||||
|
||||
type TrackedFile = { label: string; path: string };
|
||||
|
||||
@@ -30,6 +31,23 @@ type FileSnapshot = TrackedFile & {
|
||||
|
||||
const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
const SESSION_STATE_FILES = [".push-branch", ".no-hooks", ".git-repo"];
|
||||
|
||||
// How many GIT_CONFIG_* entries were there before disableGitPrograms added any.
|
||||
let entriesBeforeAction: number | undefined;
|
||||
|
||||
const codeOf = (error: unknown): string =>
|
||||
(error as { code?: string }).code ?? "unknown error";
|
||||
|
||||
function gitProgramSettings({ hooks }: { hooks: boolean }): [string, string][] {
|
||||
return hooks
|
||||
? [
|
||||
["core.fsmonitor", "false"],
|
||||
["core.hooksPath", "/dev/null"],
|
||||
]
|
||||
: [["core.fsmonitor", "false"]];
|
||||
}
|
||||
|
||||
function resolveGitPath(file: string): string | null {
|
||||
try {
|
||||
const path = execFileSync("git", ["rev-parse", "--git-path", file], {
|
||||
@@ -83,6 +101,7 @@ function filesLaterStepsTrust(): TrackedFile[] {
|
||||
[".git/config", resolveGitPath("config")],
|
||||
[".git/config.worktree", resolveGitPath("config.worktree")],
|
||||
["~/.gitconfig", join(home, ".gitconfig")],
|
||||
["GIT_CONFIG_GLOBAL", process.env.GIT_CONFIG_GLOBAL],
|
||||
[
|
||||
"git config in XDG_CONFIG_HOME",
|
||||
join(process.env.XDG_CONFIG_HOME || join(home, ".config"), "git/config"),
|
||||
@@ -171,14 +190,20 @@ function restorePath(before: FileSnapshot): string {
|
||||
* sandbox: code running as the runner's user can stop the action before it
|
||||
* restores anything.
|
||||
*/
|
||||
export function snapshotSessionFiles(): () => void {
|
||||
const snapshots = filesLaterStepsTrust().map(readSnapshot);
|
||||
export function snapshotSessionFiles(beforeSession?: () => void): () => void {
|
||||
const files = filesLaterStepsTrust();
|
||||
const snapshots = files.map(readSnapshot);
|
||||
// What the action changes for the session goes back too, without a warning.
|
||||
beforeSession?.();
|
||||
const atStart = files.map(readSnapshot);
|
||||
|
||||
return () => {
|
||||
const restored: string[] = [];
|
||||
for (const before of snapshots) {
|
||||
for (const [index, before] of snapshots.entries()) {
|
||||
try {
|
||||
if (isUnchanged(before, readSnapshot(before))) continue;
|
||||
const now = readSnapshot(before);
|
||||
if (isUnchanged(before, now)) continue;
|
||||
const changedBySession = !isUnchanged(atStart[index]!, now);
|
||||
if (before.state === "opaque") {
|
||||
core.warning(
|
||||
`Could not restore ${before.label} after the session: it was not a regular file before`,
|
||||
@@ -190,12 +215,11 @@ export function snapshotSessionFiles(): () => void {
|
||||
if (before.state === "file") {
|
||||
writeFileSync(path, before.content!, { mode: before.mode });
|
||||
}
|
||||
restored.push(before.label);
|
||||
if (changedBySession) restored.push(before.label);
|
||||
} catch (error) {
|
||||
// The label is fixed text, and the error code carries no file content.
|
||||
const { code } = error as { code?: string };
|
||||
core.warning(
|
||||
`Could not restore ${before.label} after the session (${code ?? "unknown error"})`,
|
||||
`Could not restore ${before.label} after the session (${codeOf(error)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -213,10 +237,8 @@ export function snapshotSessionFiles(): () => void {
|
||||
* kept. It is not written to GITHUB_ENV, so later steps are unaffected.
|
||||
*/
|
||||
export function disableGitPrograms({ hooks }: { hooks: boolean }): void {
|
||||
const settings: [string, string][] = [["core.fsmonitor", "false"]];
|
||||
if (hooks) settings.push(["core.hooksPath", "/dev/null"]);
|
||||
|
||||
let count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "", 10) || 0;
|
||||
entriesBeforeAction ??= count;
|
||||
const current = new Map<string, string | undefined>();
|
||||
for (let i = 0; i < count; i++) {
|
||||
current.set(
|
||||
@@ -224,7 +246,7 @@ export function disableGitPrograms({ hooks }: { hooks: boolean }): void {
|
||||
process.env[`GIT_CONFIG_VALUE_${i}`],
|
||||
);
|
||||
}
|
||||
for (const [key, value] of settings) {
|
||||
for (const [key, value] of gitProgramSettings({ hooks })) {
|
||||
if (current.get(key) === value) continue;
|
||||
process.env[`GIT_CONFIG_KEY_${count}`] = key;
|
||||
process.env[`GIT_CONFIG_VALUE_${count}`] = value;
|
||||
@@ -232,3 +254,96 @@ export function disableGitPrograms({ hooks }: { hooks: boolean }): void {
|
||||
}
|
||||
process.env.GIT_CONFIG_COUNT = String(count);
|
||||
}
|
||||
|
||||
const sessionFile = (name: string): string | undefined =>
|
||||
process.env.GITHUB_ACTION_PATH
|
||||
? join(process.env.GITHUB_ACTION_PATH, "scripts", name)
|
||||
: undefined;
|
||||
|
||||
function writeSessionFile(name: string, content: string): void {
|
||||
const path = sessionFile(name);
|
||||
if (!path) return;
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
rmSync(path, { force: true, recursive: true });
|
||||
writeFileSync(path, content, { mode: 0o444 });
|
||||
}
|
||||
|
||||
/** Records the only branch the push wrapper may update. */
|
||||
export function pinPushBranch(branch: string): void {
|
||||
try {
|
||||
writeSessionFile(".push-branch", branch);
|
||||
} catch (error) {
|
||||
// With no file and no variable, the wrapper refuses to push.
|
||||
core.warning(`Could not record the session's branch (${codeOf(error)})`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes what the wrappers read, so another step in this job can't inherit it. */
|
||||
export function clearSessionState(): void {
|
||||
for (const name of SESSION_STATE_FILES) {
|
||||
const path = sessionFile(name);
|
||||
if (!path) continue;
|
||||
try {
|
||||
rmSync(path, { force: true, recursive: true });
|
||||
} catch (error) {
|
||||
core.warning(`Could not remove ${name} (${codeOf(error)})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const gitOutput = (...args: string[]): string | null => {
|
||||
try {
|
||||
return execFileSync("git", args, {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
env: { ...process.env },
|
||||
}).trim();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Moves the settings from disableGitPrograms out of the environment for the session.
|
||||
* Repository config and the wrappers keep them in force instead, and
|
||||
* snapshotSessionFiles puts the config back afterwards. Elsewhere the concern is a
|
||||
* repository git finds in a plain folder, with its own config. Git only reads
|
||||
* safe.bareRepository from global config or the command line.
|
||||
*/
|
||||
export function prepareGitForSession({ hooks }: { hooks: boolean }): void {
|
||||
const count = Number.parseInt(process.env.GIT_CONFIG_COUNT ?? "", 10) || 0;
|
||||
const before = entriesBeforeAction ?? count;
|
||||
for (let i = before; i < count; i++) {
|
||||
delete process.env[`GIT_CONFIG_KEY_${i}`];
|
||||
delete process.env[`GIT_CONFIG_VALUE_${i}`];
|
||||
}
|
||||
if (before > 0) process.env.GIT_CONFIG_COUNT = String(before);
|
||||
else delete process.env.GIT_CONFIG_COUNT;
|
||||
entriesBeforeAction = undefined;
|
||||
|
||||
const setConfig = (scope: string, entries: [string, string][]): void => {
|
||||
for (const [key, value] of entries) {
|
||||
if (gitOutput("config", scope, "--replace-all", key, value) === null) {
|
||||
core.warning(`Could not set ${key} for the session`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Before the global setting, which stops git from finding a bare repository here.
|
||||
const gitDir = gitOutput("rev-parse", "--absolute-git-dir");
|
||||
const workTree = gitDir && gitOutput("rev-parse", "--show-toplevel");
|
||||
if (gitDir) setConfig("--local", gitProgramSettings({ hooks }));
|
||||
setConfig("--global", [["safe.bareRepository", "explicit"]]);
|
||||
|
||||
try {
|
||||
if (hooks) writeSessionFile(".no-hooks", "");
|
||||
if (gitDir && workTree) {
|
||||
const home = process.env.HOME || homedir();
|
||||
writeSessionFile(".git-repo", `${gitDir}\n${workTree}\n${home}\n`);
|
||||
}
|
||||
} catch (error) {
|
||||
core.warning(
|
||||
`Could not record git settings for the wrappers (${codeOf(error)})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,422 @@
|
||||
import * as core from "@actions/core";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmdirSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { dirname } from "path";
|
||||
import {
|
||||
ensureClaudePrExcludedFromGit,
|
||||
SENSITIVE_PATHS,
|
||||
} from "./restore-config";
|
||||
|
||||
// What npm and Bun read from the repository root to decide which program to run and
|
||||
// where to download it from. Config from the base branch can start them, for example
|
||||
// in a hook or an MCP server. node_modules counts because its .bin comes first on PATH,
|
||||
// and package.json because npx looks for commands there first.
|
||||
const TOOL_CONFIG = [".npmrc", "bunfig.toml", "node_modules"];
|
||||
const PACKAGE_JSON = "package.json";
|
||||
|
||||
// The fields that provide commands. A bin that is a string is named after the package,
|
||||
// and npx looks in workspaces too.
|
||||
const COMMAND_FIELDS = ["name", "bin", "directories", "workspaces"];
|
||||
const NO_COMMANDS = "none";
|
||||
const ENCODING = "working-tree-encoding";
|
||||
|
||||
const MAX_OUTPUT_BYTES = 1024 ** 3;
|
||||
const MAX_PACKAGE_JSON_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
type Entry = { mode: string; oid: string };
|
||||
type Replacement = { path: string; entry: Entry; content?: Buffer };
|
||||
|
||||
// File names can be any bytes. Latin-1 keeps each one intact.
|
||||
const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
|
||||
const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
|
||||
const isLink = (entry: Entry): boolean => entry.mode === "120000";
|
||||
const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
|
||||
|
||||
// No file name or content, which the pull request controls, reaches the log.
|
||||
function warn(what: string, error: unknown): void {
|
||||
const { code, status } = error as { code?: string; status?: number };
|
||||
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
|
||||
}
|
||||
|
||||
function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
return execFileSync("git", args, {
|
||||
stdio: ["pipe", "pipe", "ignore"],
|
||||
input,
|
||||
env: { ...process.env },
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
});
|
||||
}
|
||||
|
||||
// A parent that is a file or a looping link means there is nothing there.
|
||||
function onDisk(path: string) {
|
||||
try {
|
||||
return lstatSync(fsPath(path));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// File systems can ignore case, and some the way a character is encoded.
|
||||
const fold = (path: string): string =>
|
||||
fsPath(path).toString().normalize("NFKC").toLowerCase();
|
||||
|
||||
/**
|
||||
* Whether a path is in a directory that comes from the base branch already. The index
|
||||
* has the pull request's version of it, so nothing there may be rebuilt from that.
|
||||
*/
|
||||
function isRestored(path: string, topLevel: Set<string>): boolean {
|
||||
const [dir] = path.split("/") as [string];
|
||||
return SENSITIVE_PATHS.some(
|
||||
(restored) =>
|
||||
dir === restored ||
|
||||
// Another spelling is a directory of its own only if the file system lists it.
|
||||
(fold(dir) === fold(restored) && !topLevel.has(dir)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Which tool config a path belongs to. */
|
||||
function rootName(path: string): string | undefined {
|
||||
const folded = fold(path);
|
||||
// A directory with one of these names is in the file's place, whatever it holds.
|
||||
const name = TOOL_CONFIG.find(
|
||||
(name) => folded === name || folded.startsWith(`${name}/`),
|
||||
);
|
||||
if (name) return name;
|
||||
return folded === PACKAGE_JSON || folded.endsWith(`/${PACKAGE_JSON}`)
|
||||
? PACKAGE_JSON
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Whether no parent of a path is a link, which could lead out of the checkout. */
|
||||
function hasRealParents(path: string): boolean {
|
||||
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
|
||||
if (onDisk(dir)?.isSymbolicLink()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function remove(path: string): void {
|
||||
rmSync(fsPath(path), { recursive: true, force: true });
|
||||
// An empty directory would stand in the way of a file of that name.
|
||||
try {
|
||||
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
|
||||
rmdirSync(fsPath(dir));
|
||||
}
|
||||
} catch {
|
||||
// It isn't empty.
|
||||
}
|
||||
}
|
||||
|
||||
// Each entry is "<mode> <other fields>\t<path>", relative to the working directory.
|
||||
function parseEntries(listing: Buffer, oidField: number): Map<string, Entry> {
|
||||
const entries = new Map<string, Entry>();
|
||||
const topLevel = new Set(
|
||||
readdirSync(".", { encoding: "buffer" }).map((name) =>
|
||||
name.toString("latin1"),
|
||||
),
|
||||
);
|
||||
for (const line of listing.toString("latin1").split("\0")) {
|
||||
const [info, path] = line.split(/\t(.*)/s);
|
||||
if (!info || !path || !rootName(path) || isRestored(path, topLevel)) {
|
||||
continue;
|
||||
}
|
||||
const fields = info.split(" ");
|
||||
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
const pullRequestEntries = (): Map<string, Entry> =>
|
||||
parseEntries(git(["ls-files", "--stage", "-z"]), 1);
|
||||
|
||||
// A checkout with a narrow refspec has no remote-tracking branch, only FETCH_HEAD.
|
||||
function baseEntries(baseBranch: string): Map<string, Entry> {
|
||||
let ref = `refs/remotes/origin/${baseBranch}`;
|
||||
try {
|
||||
git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
|
||||
} catch {
|
||||
ref = "FETCH_HEAD";
|
||||
}
|
||||
return parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
|
||||
}
|
||||
|
||||
/** The stored content of each entry, which no .gitattributes has been applied to. */
|
||||
function readBlobs(entries: Entry[]): Map<string, Buffer> {
|
||||
const blobs = new Map<string, Buffer>();
|
||||
const oids = [...new Set(entries.map(({ oid }) => oid))];
|
||||
if (oids.length === 0) return blobs;
|
||||
const output = git(["cat-file", "--batch"], `${oids.join("\n")}\n`);
|
||||
// "<oid> <type> <size>\n<content>\n", or "<oid> missing\n"
|
||||
for (let at = 0; at < output.length; ) {
|
||||
const end = output.indexOf("\n", at);
|
||||
const [oid, , size] = output.toString("latin1", at, end).split(" ");
|
||||
at = end + 1;
|
||||
if (size === undefined) continue;
|
||||
blobs.set(oid!, output.subarray(at, at + Number(size)));
|
||||
at += Number(size) + 1;
|
||||
}
|
||||
return blobs;
|
||||
}
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
/** Parses a package.json, or returns undefined if it can't be understood. */
|
||||
function parsePackageJson(size: number, read: () => Buffer): Json | undefined {
|
||||
if (size > MAX_PACKAGE_JSON_BYTES) return undefined;
|
||||
// trimStart also drops a byte order mark.
|
||||
const json = JSON.parse(read().toString().trimStart());
|
||||
return json && typeof json === "object" ? json : undefined;
|
||||
}
|
||||
|
||||
/** The package.json that git stores. */
|
||||
function readPackageJson(entry: Entry): Json | undefined {
|
||||
if (!isFile(entry)) return undefined;
|
||||
try {
|
||||
const size = Number(git(["cat-file", "-s", entry.oid]).toString());
|
||||
return parsePackageJson(size, () => git(["cat-file", "blob", entry.oid]));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The package.json on disk, which .gitattributes can make differ from what git stores. */
|
||||
function readPackageJsonOnDisk(path: string): Json | undefined {
|
||||
try {
|
||||
const { size } = lstatSync(fsPath(path));
|
||||
return parsePackageJson(size, () => readFileSync(fsPath(path)));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** The commands a package.json provides, or undefined if that can't be told. */
|
||||
function commands(json: Json | undefined): string | undefined {
|
||||
if (!json) return undefined;
|
||||
// Other directories, such as the one for tests, provide no commands.
|
||||
const directories = (json.directories as Json | null | undefined)?.bin;
|
||||
if (!json.bin && !directories && !json.workspaces) return NO_COMMANDS;
|
||||
const provided: Json = { ...json, directories };
|
||||
return JSON.stringify(COMMAND_FIELDS.map((field) => provided[field] ?? null));
|
||||
}
|
||||
|
||||
/**
|
||||
* The attributes that make git write each file differently from what it stores. The
|
||||
* pull request controls .gitattributes.
|
||||
*/
|
||||
function conversions(paths: string[]): Map<string, Set<string>> {
|
||||
const found = new Map<string, Set<string>>();
|
||||
if (paths.length === 0) return found;
|
||||
// Checkout uses the index's .gitattributes, and the one on disk can be converted too.
|
||||
// If the index has none, it uses the one on disk.
|
||||
for (const source of [["--cached"], []]) {
|
||||
const fields = git(
|
||||
["check-attr", ...source, "-z", "--stdin", ENCODING, "ident", "filter"],
|
||||
Buffer.from(paths.map((path) => `${path}\0`).join(""), "latin1"),
|
||||
)
|
||||
.toString("latin1")
|
||||
.split("\0");
|
||||
// "<path> <attribute> <value>", each ended by a NUL
|
||||
for (let i = 0; i + 2 < fields.length; i += 3) {
|
||||
const [path, attribute, value] = fields.slice(i) as [
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
];
|
||||
if (value === "unspecified" || value === "unset") continue;
|
||||
// Git takes this as no conversion.
|
||||
if (attribute === ENCODING && /^utf-?8$/i.test(value)) continue;
|
||||
found.set(path, (found.get(path) ?? new Set()).add(attribute));
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function differs(
|
||||
path: string,
|
||||
converted: Set<string> | undefined,
|
||||
pr?: Entry,
|
||||
base?: Entry,
|
||||
): boolean {
|
||||
const isSame = pr?.oid === base?.oid && pr?.mode === base?.mode;
|
||||
// Even an unchanged file can then be one that npm or Bun can't read.
|
||||
if (converted?.has(ENCODING)) return true;
|
||||
if (rootName(path) !== PACKAGE_JSON) return !isSame;
|
||||
if (!pr || isSame) return false;
|
||||
const provided = [commands(readPackageJson(pr))];
|
||||
// npm reads what is on disk, unless an earlier step removed it.
|
||||
if (converted && hasRealParents(path) && onDisk(path)?.isFile()) {
|
||||
provided.push(commands(readPackageJsonOnDisk(path)));
|
||||
}
|
||||
// Only one that provides commands matters, so most pull requests keep their own.
|
||||
const allowed = [
|
||||
NO_COMMANDS,
|
||||
base ? commands(readPackageJson(base)) : NO_COMMANDS,
|
||||
];
|
||||
return provided.some((value) => !value || !allowed.includes(value));
|
||||
}
|
||||
|
||||
/** The pull request's package.json with the base branch's commands. */
|
||||
function withBaseCommands(
|
||||
pr: Entry,
|
||||
base: Entry | undefined,
|
||||
): Buffer | undefined {
|
||||
const json = readPackageJson(pr);
|
||||
const baseJson = base ? readPackageJson(base) : {};
|
||||
if (!json || !baseJson) return undefined;
|
||||
for (const field of COMMAND_FIELDS) {
|
||||
// Without a bin, a new package's name provides no command.
|
||||
if (field === "name" && !base) continue;
|
||||
if (baseJson[field] === undefined) delete json[field];
|
||||
else json[field] = baseJson[field];
|
||||
}
|
||||
return Buffer.from(`${JSON.stringify(json, null, 2)}\n`);
|
||||
}
|
||||
|
||||
/** Keeps the pull request's version readable, as for the other restored config. */
|
||||
function snapshotForReview(path: string, entry: Entry): void {
|
||||
if (!isFile(entry) || rootName(path) === "node_modules") return;
|
||||
try {
|
||||
const content = git(["cat-file", "blob", entry.oid]);
|
||||
const copy = fsPath(`.claude-pr/${path}`);
|
||||
mkdirSync(fsPath(`.claude-pr/${dirname(path)}`), { recursive: true });
|
||||
writeFileSync(copy, content);
|
||||
ensureClaudePrExcludedFromGit();
|
||||
} catch (error) {
|
||||
warn("Could not keep a copy of tool config for review", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the pull request's tool config with the base branch's wherever they differ.
|
||||
* Like restoreConfigFromBase, which must run first because it fetches the base branch,
|
||||
* it changes the working tree and not the index. Only tracked files are replaced, so
|
||||
* what an earlier step created stays. In a package.json only the commands are replaced.
|
||||
*
|
||||
* @returns The names that were replaced, from a fixed list. Callers that stage files
|
||||
* must exclude them.
|
||||
* @throws If the base branch's version can't be put in place. The message holds no
|
||||
* file name, because the pull request controls those.
|
||||
*/
|
||||
export function restoreToolConfigFromBase(baseBranch: string): string[] {
|
||||
try {
|
||||
return restoreToolConfig(baseBranch);
|
||||
} catch (error) {
|
||||
warn("Could not replace tool config", error);
|
||||
throw new Error(
|
||||
"Could not use the base branch's version of the files that npm and Bun read",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function restoreToolConfig(baseBranch: string): string[] {
|
||||
const pr = pullRequestEntries();
|
||||
const base = baseEntries(baseBranch);
|
||||
const all = [...new Set([...pr.keys(), ...base.keys()])];
|
||||
// npx reads the packages in subdirectories only through the root's workspaces, and
|
||||
// a pull request's own are replaced below.
|
||||
const rootJson = base.get(PACKAGE_JSON);
|
||||
const hasWorkspaces =
|
||||
rootJson !== undefined &&
|
||||
readPackageJson(rootJson)?.workspaces !== undefined;
|
||||
const matters = (path: string): boolean =>
|
||||
hasWorkspaces || rootName(path) !== PACKAGE_JSON || !path.includes("/");
|
||||
|
||||
const converted = conversions(
|
||||
[...pr].flatMap(([path, entry]) =>
|
||||
isFile(entry) && matters(path) && rootName(path) !== "node_modules"
|
||||
? [path]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
// Names that differ only in case can be the same file.
|
||||
const differing = new Set(
|
||||
all
|
||||
.filter(
|
||||
(path) =>
|
||||
matters(path) &&
|
||||
differs(path, converted.get(path), pr.get(path), base.get(path)),
|
||||
)
|
||||
.map(fold),
|
||||
);
|
||||
const candidates = all.filter((path) => differing.has(fold(path)));
|
||||
|
||||
// A directory where the pull request has a file or link came from an earlier step.
|
||||
const replaced = candidates.filter((path) => {
|
||||
const entry = pr.get(path);
|
||||
const stats = entry && onDisk(path);
|
||||
return (
|
||||
stats &&
|
||||
(!stats.isDirectory() || isSubmodule(entry)) &&
|
||||
hasRealParents(path)
|
||||
);
|
||||
});
|
||||
// All of these go before anything is written.
|
||||
for (const path of replaced) {
|
||||
snapshotForReview(path, pr.get(path)!);
|
||||
remove(path);
|
||||
}
|
||||
|
||||
const removed = new Set(replaced);
|
||||
const toWrite = candidates.flatMap((path): Replacement[] => {
|
||||
const entry = base.get(path);
|
||||
const prEntry = pr.get(path);
|
||||
// One that the pull request has but is not on disk was left out or deleted by the
|
||||
// workflow. One that only the base has matters unless it's a package.json.
|
||||
const wanted = prEntry
|
||||
? removed.has(path)
|
||||
: rootName(path) !== PACKAGE_JSON;
|
||||
if (!wanted || onDisk(path)) return [];
|
||||
const content =
|
||||
prEntry && rootName(path) === PACKAGE_JSON
|
||||
? withBaseCommands(prEntry, entry)
|
||||
: undefined;
|
||||
if (content) return [{ path, entry: prEntry!, content }];
|
||||
return entry && !isSubmodule(entry) ? [{ path, entry, content }] : [];
|
||||
});
|
||||
const blobs = readBlobs(
|
||||
toWrite.flatMap(({ entry, content }) => (content ? [] : [entry])),
|
||||
);
|
||||
const written: string[] = [];
|
||||
for (const { path, entry, content = blobs.get(entry.oid) } of toWrite) {
|
||||
if (!hasRealParents(path)) continue;
|
||||
if (!content) throw new Error("missing object");
|
||||
mkdirSync(fsPath(dirname(path)), { recursive: true });
|
||||
if (isLink(entry)) symlinkSync(content, fsPath(path));
|
||||
else {
|
||||
const mode = entry.mode === "100755" ? 0o755 : 0o644;
|
||||
writeFileSync(fsPath(path), content, { mode, flag: "wx" });
|
||||
}
|
||||
written.push(path);
|
||||
}
|
||||
|
||||
const names = [
|
||||
...new Set([...replaced, ...written].map((path) => rootName(path)!)),
|
||||
];
|
||||
if (names.length > 0) {
|
||||
core.warning(
|
||||
`The pull request and its base branch differ in what npm and Bun read (${names.join(", ")}), so the base branch's version is used and Claude can't edit it. See docs/security.md.`,
|
||||
);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rules that stop a session from editing tool config, for a pull request whose author
|
||||
* doesn't have write access. Other package.json edits are ordinary work. The rules
|
||||
* cover subdirectories too, because a hook runs in the session's current directory.
|
||||
*/
|
||||
export const toolConfigDenyRules = (replaced: string[]): string[] => [
|
||||
...TOOL_CONFIG.map((name) =>
|
||||
name === "node_modules" ? "Edit(./node_modules/**)" : `Edit(./${name})`,
|
||||
),
|
||||
...(replaced.includes(PACKAGE_JSON) ? ["Edit(package.json)"] : []),
|
||||
];
|
||||
@@ -26,6 +26,7 @@ function bunServerArgs(scriptPath: string): string[] {
|
||||
return [
|
||||
"--no-env-file",
|
||||
`--config=${actionPath}/bunfig.toml`,
|
||||
`--tsconfig-override=${actionPath}/tsconfig.json`,
|
||||
"run",
|
||||
`${actionPath}/${scriptPath}`,
|
||||
];
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { parse as parseShellArgs } from "shell-quote";
|
||||
import {
|
||||
ACCUMULATE_DELIMITER,
|
||||
escapeShellMeta,
|
||||
parseClaudeArgsToExtraArgs,
|
||||
unescapeShellMeta,
|
||||
@@ -99,9 +100,38 @@ export function parseDeniedBashPatterns(claudeArgs: string): string[] {
|
||||
: [];
|
||||
},
|
||||
);
|
||||
return values.flatMap((value) =>
|
||||
[...value.matchAll(/Bash\(([^)]*)\)/g)].map((match) => match[1]!),
|
||||
);
|
||||
const patterns = values.flatMap((value) => [
|
||||
// Whole rules, whose own text can hold parentheses: Bash(git add "app/(auth)/*").
|
||||
...value
|
||||
.split(ACCUMULATE_DELIMITER)
|
||||
.flatMap((part) => part.match(RULE) ?? [])
|
||||
.flatMap((rule) => rule.trim().match(/^Bash\((.*)\)$/)?.[1] ?? []),
|
||||
// Also whatever looks like a rule, so that one the CLI can't read still denies.
|
||||
...[...value.matchAll(/Bash\(([^)]*)\)/g)].map((match) => match[1]!),
|
||||
]);
|
||||
return [...new Set(patterns)];
|
||||
}
|
||||
|
||||
/**
|
||||
* One rule in a list. Like the CLI, it ends at a comma or space outside parentheses,
|
||||
* where any `)` ends the parentheses.
|
||||
*/
|
||||
const RULE = /(?:\([^)]*\)?|[^ ,(])+/g;
|
||||
|
||||
/**
|
||||
* The deny rules a wrapper needs so a workflow's rules for the command it runs still
|
||||
* apply: all of it for a rule that covers every use, otherwise each narrower form, so
|
||||
* `git add -A:*` becomes `<wrapper> -A:*`.
|
||||
*/
|
||||
export function wrapperDenyRules(
|
||||
patterns: string[],
|
||||
command: string,
|
||||
wrapper: string,
|
||||
): string[] {
|
||||
if (deniesCommand(patterns, command)) return [`Bash(${wrapper}:*)`];
|
||||
return patterns
|
||||
.filter((pattern) => pattern.startsWith(`${command} `))
|
||||
.map((pattern) => `Bash(${wrapper}${pattern.slice(command.length)})`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -115,6 +145,6 @@ export function deniesCommand(patterns: string[], command: string): boolean {
|
||||
const source = pattern.endsWith(":*")
|
||||
? `${toRegex(pattern.slice(0, -2))}( .*)?`
|
||||
: toRegex(pattern);
|
||||
return new RegExp(`^${source}$`, "s").test(`${command} x`);
|
||||
return new RegExp(`^${source}$`, "s").test(`${command} \0`);
|
||||
});
|
||||
}
|
||||
|
||||
+20
-14
@@ -1,5 +1,6 @@
|
||||
import { checkHumanActor } from "../../github/validation/actor";
|
||||
import { defaultsToAutoMode } from "../permission-mode";
|
||||
import { pinPushBranch } from "../../github/operations/session-guard";
|
||||
import { createInitialComment } from "../../github/operations/comments/create-initial";
|
||||
import { setupBranch } from "../../github/operations/branch";
|
||||
import {
|
||||
@@ -24,9 +25,9 @@ import { updateClaudeComment } from "../../github/operations/comments/update-cla
|
||||
import type { GitHubContext } from "../../github/context";
|
||||
import type { Octokits } from "../../github/api/client";
|
||||
import {
|
||||
deniesCommand,
|
||||
parseAllowedTools,
|
||||
parseDeniedBashPatterns,
|
||||
wrapperDenyRules,
|
||||
} from "../agent/parse-tools";
|
||||
|
||||
/**
|
||||
@@ -160,8 +161,10 @@ export async function prepareTagMode({
|
||||
|
||||
const sessionBranch = branchInfo.claudeBranch || branchInfo.currentBranch;
|
||||
// scripts/git-push.sh refuses to update any other branch.
|
||||
process.env.CLAUDE_PUSH_BRANCH = sessionBranch;
|
||||
pinPushBranch(sessionBranch);
|
||||
|
||||
const gitAddWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-add.sh`;
|
||||
const gitRmWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-rm.sh`;
|
||||
const gitPushWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-push.sh`;
|
||||
const gitCommitWrapper = `${process.env.GITHUB_ACTION_PATH}/scripts/git-commit.sh`;
|
||||
|
||||
@@ -185,10 +188,10 @@ export async function prepareTagMode({
|
||||
// SSH signing still uses git CLI, just with signing enabled
|
||||
if (!useApiCommitSigning) {
|
||||
tagModeTools.push(
|
||||
"Bash(git add:*)",
|
||||
`Bash(${gitAddWrapper}:*)`,
|
||||
`Bash(${gitCommitWrapper}:*)`,
|
||||
`Bash(${gitPushWrapper}:*)`,
|
||||
"Bash(git rm:*)",
|
||||
`Bash(${gitRmWrapper}:*)`,
|
||||
);
|
||||
} else {
|
||||
// When using API commit signing, use MCP file ops tools
|
||||
@@ -226,19 +229,22 @@ export async function prepareTagMode({
|
||||
const permissionMode = defaultsToAutoMode() ? "auto" : "acceptEdits";
|
||||
claudeArgs += ` --permission-mode ${permissionMode} --allowedTools "${tagModeTools.join(",")}"`;
|
||||
|
||||
// Deny rules match the command's text, so a workflow's deny of `git commit` or
|
||||
// `git push` wouldn't match the wrappers that run them. Deny the wrappers too.
|
||||
// Deny rules match the command's text, so a workflow's deny of a git command
|
||||
// wouldn't match the wrapper that runs it. Deny the wrappers too.
|
||||
const userDeniedTools = parseDeniedBashPatterns(userClaudeArgs);
|
||||
const deniedWrappers = [
|
||||
...(deniesCommand(userDeniedTools, "git commit")
|
||||
? [`Bash(${gitCommitWrapper}:*)`]
|
||||
: []),
|
||||
...(deniesCommand(userDeniedTools, "git push")
|
||||
? [`Bash(${gitPushWrapper}:*)`]
|
||||
: []),
|
||||
const wrappers: [string, string][] = [
|
||||
["git commit", gitCommitWrapper],
|
||||
["git push", gitPushWrapper],
|
||||
["git add", gitAddWrapper],
|
||||
["git rm", gitRmWrapper],
|
||||
];
|
||||
const deniedWrappers = wrappers.flatMap(([command, wrapper]) =>
|
||||
wrapperDenyRules(userDeniedTools, command, wrapper),
|
||||
);
|
||||
if (deniedWrappers.length > 0) {
|
||||
claudeArgs += ` --disallowedTools "${deniedWrappers.join(",")}"`;
|
||||
// A narrower rule can hold quotes or a $, and this string gets parsed again.
|
||||
const rules = deniedWrappers.join(",").replace(/'/g, "'\\''");
|
||||
claudeArgs += ` --disallowedTools '${rules}'`;
|
||||
}
|
||||
|
||||
// Append user's claude_args (which may have more --mcp-config flags, or another
|
||||
|
||||
@@ -27,6 +27,25 @@ describe("action metadata", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should start each of the action's scripts with the same Bun options", () => {
|
||||
const commands = readFileSync(
|
||||
new URL("../action.yml", import.meta.url),
|
||||
"utf8",
|
||||
)
|
||||
.replace(/\\\n\s*/g, "")
|
||||
.split("\n")
|
||||
.filter((line) => line.includes("${GITHUB_ACTION_PATH}/src/"));
|
||||
|
||||
expect(commands).toHaveLength(3);
|
||||
for (const command of commands) {
|
||||
expect(command).toContain(
|
||||
' --no-env-file --config="${GITHUB_ACTION_PATH}/bunfig.toml"' +
|
||||
' --tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json"' +
|
||||
" run ${GITHUB_ACTION_PATH}/src/entrypoints/",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("should not put step outputs into shell scripts", () => {
|
||||
// A session can write step outputs, so an expression in a script could run
|
||||
// its commands. Scripts have to read these values from the environment.
|
||||
|
||||
@@ -790,7 +790,7 @@ describe("generatePrompt", () => {
|
||||
|
||||
// Should have git command instructions
|
||||
expect(prompt).toContain("Use git commands via the Bash tool");
|
||||
expect(prompt).toContain("git add");
|
||||
expect(prompt).toContain("scripts/git-add.sh");
|
||||
expect(prompt).toContain("scripts/git-commit.sh -m");
|
||||
expect(prompt).toContain("scripts/git-push.sh origin");
|
||||
|
||||
@@ -1083,7 +1083,7 @@ describe("buildAllowedToolsString", () => {
|
||||
expect(result).toContain("Read");
|
||||
|
||||
// Default is no commit signing, so should have specific Bash git commands
|
||||
expect(result).toContain("Bash(git add:*)");
|
||||
expect(result).toContain("scripts/git-add.sh:*)");
|
||||
expect(result).toContain("scripts/git-commit.sh:*)");
|
||||
expect(result).not.toContain("Bash(git commit:*)");
|
||||
expect(result).toContain("scripts/git-push.sh:*)");
|
||||
@@ -1106,7 +1106,7 @@ describe("buildAllowedToolsString", () => {
|
||||
expect(result).not.toContain("Write");
|
||||
|
||||
// Should have specific Bash git commands for non-signing mode
|
||||
expect(result).toContain("Bash(git add:*)");
|
||||
expect(result).toContain("scripts/git-add.sh:*)");
|
||||
expect(result).toContain("scripts/git-commit.sh:*)");
|
||||
expect(result).toContain("mcp__github_comment__update_claude_comment");
|
||||
|
||||
@@ -1199,10 +1199,10 @@ describe("buildAllowedToolsString", () => {
|
||||
expect(result).not.toContain("Write");
|
||||
|
||||
// Specific Bash git commands should be included
|
||||
expect(result).toContain("Bash(git add:*)");
|
||||
expect(result).toContain("scripts/git-add.sh:*)");
|
||||
expect(result).toContain("scripts/git-commit.sh:*)");
|
||||
expect(result).toContain("scripts/git-push.sh:*)");
|
||||
expect(result).toContain("Bash(git rm:*)");
|
||||
expect(result).toContain("scripts/git-rm.sh:*)");
|
||||
|
||||
// Comment tool from minimal server should be included
|
||||
expect(result).toContain("mcp__github_comment__update_claude_comment");
|
||||
@@ -1218,7 +1218,7 @@ describe("buildAllowedToolsString", () => {
|
||||
|
||||
// Base tools should be present
|
||||
expect(result).toContain("Read");
|
||||
expect(result).toContain("Bash(git add:*)");
|
||||
expect(result).toContain("scripts/git-add.sh:*)");
|
||||
|
||||
// Custom tools should be included
|
||||
expect(result).toContain("CustomTool1");
|
||||
|
||||
+246
-1
@@ -1,15 +1,28 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { spawnSync } from "child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
|
||||
import {
|
||||
chmodSync,
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { join, resolve } from "path";
|
||||
|
||||
const SCRIPTS = resolve(import.meta.dir, "../scripts");
|
||||
|
||||
// The wrappers clear GIT_CONFIG_GLOBAL, so a developer's own config needs HOME moved.
|
||||
let testHome = tmpdir();
|
||||
|
||||
// git exports these into hooks, such as a pre-commit hook running this suite.
|
||||
const env = () => {
|
||||
const copy = {
|
||||
...process.env,
|
||||
HOME: testHome,
|
||||
GIT_AUTHOR_NAME: "t",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "t",
|
||||
@@ -45,6 +58,7 @@ describe("git wrappers", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "git-wrappers-"));
|
||||
testHome = dir;
|
||||
repo = join(dir, "repo");
|
||||
remote = join(dir, "remote.git");
|
||||
spawnSync("git", ["init", "-q", "--bare", "-b", "main", remote], {
|
||||
@@ -137,6 +151,214 @@ describe("git wrappers", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("git-add.sh and git-rm.sh", () => {
|
||||
const add = (...args: string[]) =>
|
||||
run(join(SCRIPTS, "git-add.sh"), ...args);
|
||||
const rm = (...args: string[]) => run(join(SCRIPTS, "git-rm.sh"), ...args);
|
||||
|
||||
test("git-add.sh stages files", () => {
|
||||
writeFileSync(join(repo, "a.txt"), "a");
|
||||
expect(add("a.txt").status).toBe(0);
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("a.txt");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["-e"],
|
||||
["--edit"],
|
||||
["-p"],
|
||||
["-i"],
|
||||
["-f"],
|
||||
["--force"],
|
||||
["--pathspec-from-file=.git/config"],
|
||||
])("git-add.sh rejects %s", (flag) => {
|
||||
const result = add(flag, ".");
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain("are allowed");
|
||||
});
|
||||
|
||||
test("git-add.sh takes a path that looks like a flag after --", () => {
|
||||
writeFileSync(join(repo, "-e"), "a");
|
||||
expect(add("--", "-e").status).toBe(0);
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("-e");
|
||||
});
|
||||
|
||||
test("git-add.sh records the executable bit", () => {
|
||||
writeFileSync(join(repo, "run.sh"), "#!/bin/sh\n");
|
||||
run(join(SCRIPTS, "git-add.sh"), "--chmod=+x", "run.sh");
|
||||
expect(git("ls-files", "--stage", "run.sh")).toStartWith("100755");
|
||||
});
|
||||
|
||||
test("git-rm.sh removes files and rejects other flags", () => {
|
||||
writeFileSync(join(repo, "a.txt"), "a");
|
||||
git("add", "a.txt");
|
||||
git("commit", "-q", "-m", "add");
|
||||
expect(rm("--pathspec-from-file=.git/config").status).toBe(1);
|
||||
expect(rm("a.txt").status).toBe(0);
|
||||
expect(existsSync(join(repo, "a.txt"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settings the wrappers ignore", () => {
|
||||
const withMarker = () => {
|
||||
const marker = join(dir, "marker");
|
||||
const program = join(dir, "program.sh");
|
||||
writeFileSync(program, `#!/bin/sh\necho ran >> "${marker}"\n`);
|
||||
chmodSync(program, 0o755);
|
||||
return { marker, program };
|
||||
};
|
||||
const inEnv = (
|
||||
script: string,
|
||||
args: string[],
|
||||
extra: Record<string, string>,
|
||||
) =>
|
||||
spawnSync(join(SCRIPTS, script), args, {
|
||||
cwd: repo,
|
||||
env: { ...env(), ...extra },
|
||||
encoding: "utf8",
|
||||
});
|
||||
|
||||
test.each([
|
||||
["git-add.sh", ["."]],
|
||||
["git-commit.sh", ["--allow-empty", "-m", "x"]],
|
||||
])("%s ignores program settings in GIT_CONFIG_*", (script, args) => {
|
||||
const { marker, program } = withMarker();
|
||||
writeFileSync(join(repo, "a.txt"), "a");
|
||||
const result = inEnv(script, args, {
|
||||
GIT_CONFIG_COUNT: "1",
|
||||
GIT_CONFIG_KEY_0: "core.fsmonitor",
|
||||
GIT_CONFIG_VALUE_0: program,
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
test("git-add.sh ignores XDG_CONFIG_HOME", () => {
|
||||
const { marker, program } = withMarker();
|
||||
mkdirSync(join(dir, "xdg/git"), { recursive: true });
|
||||
writeFileSync(
|
||||
join(dir, "xdg/git/config"),
|
||||
`[core]\n\tfsmonitor = ${program}\n`,
|
||||
);
|
||||
writeFileSync(join(repo, "a.txt"), "a");
|
||||
const result = inEnv("git-add.sh", ["a.txt"], {
|
||||
XDG_CONFIG_HOME: join(dir, "xdg"),
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
|
||||
// What the action writes beside the scripts, in a copy of them.
|
||||
const copyScripts = (state: Record<string, string>) => {
|
||||
const scripts = join(dir, "scripts");
|
||||
mkdirSync(scripts, { recursive: true });
|
||||
for (const name of ["git-add.sh", "git-commit.sh", "git-env.sh"]) {
|
||||
copyFileSync(join(SCRIPTS, name), join(scripts, name));
|
||||
}
|
||||
for (const [name, content] of Object.entries(state)) {
|
||||
writeFileSync(join(scripts, name), content);
|
||||
}
|
||||
return scripts;
|
||||
};
|
||||
|
||||
test("hooks stay on unless the action turned them off", () => {
|
||||
const { marker, program } = withMarker();
|
||||
mkdirSync(join(repo, "hooks"));
|
||||
copyFileSync(program, join(repo, "hooks/pre-commit"));
|
||||
git("config", "core.hooksPath", "hooks");
|
||||
const commitWith = (scripts: string) =>
|
||||
spawnSync(
|
||||
join(scripts, "git-commit.sh"),
|
||||
["--allow-empty", "-m", "x"],
|
||||
{ cwd: repo, env: env(), encoding: "utf8" },
|
||||
);
|
||||
|
||||
expect(commitWith(copyScripts({ ".no-hooks": "" })).status).toBe(0);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
|
||||
rmSync(join(dir, "scripts/.no-hooks"));
|
||||
expect(commitWith(join(dir, "scripts")).status).toBe(0);
|
||||
expect(existsSync(marker)).toBe(true);
|
||||
});
|
||||
|
||||
test("the wrappers use the recorded home", () => {
|
||||
const { marker, program } = withMarker();
|
||||
const fakeHome = join(dir, "fake-home");
|
||||
mkdirSync(fakeHome);
|
||||
writeFileSync(join(fakeHome, "attributes"), "a.txt filter=x\n");
|
||||
writeFileSync(
|
||||
join(fakeHome, ".gitconfig"),
|
||||
`[core]\n\tattributesFile = ${join(fakeHome, "attributes")}\n[filter "x"]\n\tclean = ${program}\n`,
|
||||
);
|
||||
writeFileSync(join(repo, "a.txt"), "a");
|
||||
const gitDir = join(repo, ".git");
|
||||
const scripts = copyScripts({
|
||||
".git-repo": `${gitDir}\n${repo}\n${testHome}\n`,
|
||||
});
|
||||
const run = (path: string) =>
|
||||
spawnSync(join(path, "git-add.sh"), ["a.txt"], {
|
||||
cwd: repo,
|
||||
env: { ...env(), HOME: fakeHome },
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(run(scripts).status).toBe(0);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
// Without the recorded home, that config is read, so the check above means something.
|
||||
run(SCRIPTS);
|
||||
expect(existsSync(marker)).toBe(true);
|
||||
});
|
||||
|
||||
describe("a folder shaped like a repository", () => {
|
||||
const makeFolder = () => {
|
||||
const { marker, program } = withMarker();
|
||||
const evil = join(repo, "evil");
|
||||
mkdirSync(join(evil, "objects"), { recursive: true });
|
||||
mkdirSync(join(evil, "refs"));
|
||||
writeFileSync(join(evil, "HEAD"), "ref: refs/heads/main\n");
|
||||
writeFileSync(join(dir, "attributes"), "* filter=x\n");
|
||||
writeFileSync(
|
||||
join(evil, "config"),
|
||||
`[core]\n\tbare = false\n\tworktree = ..\n\tattributesFile = ${join(dir, "attributes")}\n[filter "x"]\n\tclean = ${program}\n`,
|
||||
);
|
||||
writeFileSync(join(repo, "a.txt"), "a");
|
||||
return { marker, evil };
|
||||
};
|
||||
|
||||
test("the wrappers stay on the recorded repository", () => {
|
||||
const { marker, evil } = makeFolder();
|
||||
const gitDir = join(repo, ".git");
|
||||
const scripts = copyScripts({ ".git-repo": `${gitDir}\n${repo}\n` });
|
||||
const result = spawnSync(join(scripts, "git-add.sh"), ["../a.txt"], {
|
||||
cwd: evil,
|
||||
env: env(),
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("a.txt");
|
||||
});
|
||||
|
||||
test("with nothing recorded, git refuses the folder", () => {
|
||||
const { marker, evil } = makeFolder();
|
||||
const result = spawnSync(join(SCRIPTS, "git-add.sh"), ["../a.txt"], {
|
||||
cwd: evil,
|
||||
env: env(),
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(result.status).not.toBe(0);
|
||||
expect(existsSync(marker)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test("git-commit.sh ignores GIT_DIR", () => {
|
||||
const before = git("rev-parse", "HEAD");
|
||||
const result = inEnv("git-commit.sh", ["--allow-empty", "-m", "x"], {
|
||||
GIT_DIR: join(dir, "elsewhere"),
|
||||
});
|
||||
expect(result.status).toBe(0);
|
||||
expect(git("rev-parse", "HEAD")).not.toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("git-push.sh", () => {
|
||||
const SESSION_BRANCH = "claude/issue-1";
|
||||
|
||||
@@ -154,6 +376,29 @@ describe("git wrappers", () => {
|
||||
encoding: "utf8",
|
||||
});
|
||||
};
|
||||
test("the recorded branch wins over CLAUDE_PUSH_BRANCH", () => {
|
||||
const scripts = join(dir, "scripts");
|
||||
mkdirSync(scripts);
|
||||
for (const name of ["git-push.sh", "git-env.sh"]) {
|
||||
copyFileSync(join(SCRIPTS, name), join(scripts, name));
|
||||
}
|
||||
writeFileSync(join(scripts, ".push-branch"), SESSION_BRANCH);
|
||||
git("commit", "-q", "--allow-empty", "-m", "second");
|
||||
const before = remoteHead();
|
||||
const result = spawnSync(
|
||||
join(scripts, "git-push.sh"),
|
||||
["origin", "HEAD"],
|
||||
{
|
||||
cwd: repo,
|
||||
env: { ...env(), CLAUDE_PUSH_BRANCH: "main" },
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
expect(result.status).toBe(0);
|
||||
expect(remoteHead()).toBe(before);
|
||||
expect(remoteBranch(SESSION_BRANCH)).toBe(git("rev-parse", "HEAD"));
|
||||
});
|
||||
|
||||
const remoteBranch = (branch: string) =>
|
||||
spawnSync(
|
||||
"git",
|
||||
|
||||
@@ -246,6 +246,7 @@ describe("prepareMcpConfig", () => {
|
||||
expect(parsed.mcpServers[name].args).toEqual([
|
||||
"--no-env-file",
|
||||
"--config=/test/action/path/bunfig.toml",
|
||||
"--tsconfig-override=/test/action/path/tsconfig.json",
|
||||
"run",
|
||||
`/test/action/path/${script}`,
|
||||
]);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, test, expect } from "bun:test";
|
||||
import {
|
||||
deniesCommand,
|
||||
wrapperDenyRules,
|
||||
parseAllowedTools,
|
||||
parseDeniedBashPatterns,
|
||||
} from "../../src/modes/agent/parse-tools";
|
||||
@@ -23,6 +24,22 @@ describe("parseDeniedBashPatterns", () => {
|
||||
expected as string[],
|
||||
);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[`'Bash(git add "app/(auth)/*")'`, `git add "app/(auth)/*"`],
|
||||
[`'Bash(a:*) Bash(git add "(x)/*"),Bash(b:*)'`, `git add "(x)/*"`],
|
||||
[`'Bash(git add {a,b}/*)'`, "git add {a,b}/*"],
|
||||
[`"Read(x(" "Bash(a b:*)"`, "a b:*"],
|
||||
[`"Bash(a:*)\nBash(b c:*)"`, "b c:*"],
|
||||
[`"Bash(a:*),\nBash(git add \\"(x)/*\\")"`, `git add "(x)/*"`],
|
||||
[`"Bash(git add {a" "b}/*)"`, "git add {a\0b}/*"],
|
||||
[`"Bash(a:*);Read(x)"`, "a:*"],
|
||||
[`"Bash(a:*))"`, "a:*"],
|
||||
])("finds the rule in %s", (rules, expected) => {
|
||||
expect(parseDeniedBashPatterns(`--disallowedTools ${rules}`)).toContain(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deniesCommand", () => {
|
||||
@@ -42,6 +59,8 @@ describe("deniesCommand", () => {
|
||||
|
||||
test.each([
|
||||
"git commit --amend:*",
|
||||
"git commit x:*",
|
||||
"git commit x*",
|
||||
"git committed:*",
|
||||
"git commit",
|
||||
"git push:*",
|
||||
@@ -53,6 +72,27 @@ describe("deniesCommand", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("wrapperDenyRules", () => {
|
||||
const rules = (...patterns: string[]) =>
|
||||
wrapperDenyRules(patterns, "git add", "/a/git-add.sh");
|
||||
|
||||
test("denies the whole wrapper for a rule that covers every use", () => {
|
||||
expect(rules("git add:*")).toEqual(["Bash(/a/git-add.sh:*)"]);
|
||||
expect(rules("git:*", "git add -A:*")).toEqual(["Bash(/a/git-add.sh:*)"]);
|
||||
});
|
||||
|
||||
test("keeps the arguments of a narrower rule", () => {
|
||||
expect(rules("git add -A:*", "git add .")).toEqual([
|
||||
"Bash(/a/git-add.sh -A:*)",
|
||||
"Bash(/a/git-add.sh .)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("ignores rules for other commands", () => {
|
||||
expect(rules("git push:*", "git addendum:*", "")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAllowedTools", () => {
|
||||
test("keeps unquoted Bash rules whole", () => {
|
||||
expect(parseAllowedTools("--allowedTools Bash(gh:*),Read")).toEqual([
|
||||
|
||||
+46
-10
@@ -1,3 +1,4 @@
|
||||
import { parseDeniedBashPatterns } from "../../src/modes/agent/parse-tools";
|
||||
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
|
||||
import { prepareTagMode } from "../../src/modes/tag";
|
||||
import { mockIssueCommentContext } from "../mockContext";
|
||||
@@ -8,6 +9,10 @@ import * as branch from "../../src/github/operations/branch";
|
||||
import * as createPrompt from "../../src/create-prompt";
|
||||
import * as mcp from "../../src/mcp/install-mcp-server";
|
||||
import * as gitConfig from "../../src/github/operations/git-config";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
import * as sessionGuard from "../../src/github/operations/session-guard";
|
||||
|
||||
describe("Tag Mode", () => {
|
||||
test("prepareTagMode is exported as a function", () => {
|
||||
@@ -77,15 +82,21 @@ describe("Tag Mode", () => {
|
||||
});
|
||||
|
||||
describe("push branch", () => {
|
||||
const saved = process.env.CLAUDE_PUSH_BRANCH;
|
||||
const savedPath = process.env.GITHUB_ACTION_PATH;
|
||||
let actionPath: string;
|
||||
|
||||
const pinned = () =>
|
||||
readFileSync(join(actionPath, "scripts/.push-branch"), "utf8");
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.CLAUDE_PUSH_BRANCH;
|
||||
actionPath = mkdtempSync(join(tmpdir(), "tag-action-"));
|
||||
process.env.GITHUB_ACTION_PATH = actionPath;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.CLAUDE_PUSH_BRANCH;
|
||||
else process.env.CLAUDE_PUSH_BRANCH = saved;
|
||||
rmSync(actionPath, { recursive: true, force: true });
|
||||
if (savedPath === undefined) delete process.env.GITHUB_ACTION_PATH;
|
||||
else process.env.GITHUB_ACTION_PATH = savedPath;
|
||||
});
|
||||
|
||||
test("pins the push wrapper to a new claude branch", async () => {
|
||||
@@ -94,7 +105,8 @@ describe("Tag Mode", () => {
|
||||
octokit: {} as any,
|
||||
githubToken: "test-token",
|
||||
});
|
||||
expect(process.env.CLAUDE_PUSH_BRANCH).toBe("claude/test");
|
||||
expect(pinned()).toBe("claude/test");
|
||||
expect(process.env.CLAUDE_PUSH_BRANCH).toBeUndefined();
|
||||
});
|
||||
|
||||
test("pins the push wrapper to the branch of an open PR", async () => {
|
||||
@@ -109,7 +121,7 @@ describe("Tag Mode", () => {
|
||||
octokit: {} as any,
|
||||
githubToken: "test-token",
|
||||
});
|
||||
expect(process.env.CLAUDE_PUSH_BRANCH).toBe("feature");
|
||||
expect(pinned()).toBe("feature");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -119,6 +131,9 @@ describe("Tag Mode", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.GITHUB_ACTION_PATH = "/action";
|
||||
spies.push(
|
||||
spyOn(sessionGuard, "pinPushBranch").mockImplementation(() => {}),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -138,11 +153,20 @@ describe("Tag Mode", () => {
|
||||
return claudeArgs;
|
||||
};
|
||||
|
||||
test.each([
|
||||
["git add", "git-add.sh"],
|
||||
["git rm", "git-rm.sh"],
|
||||
])("a deny of %s also denies its wrapper", async (command, wrapper) => {
|
||||
expect(
|
||||
await prepare(`--disallowedTools "Bash(${command}:*)"`),
|
||||
).toContain(`--disallowedTools 'Bash(/action/scripts/${wrapper}:*)'`);
|
||||
});
|
||||
|
||||
test("a deny of git commit also denies the commit wrapper", async () => {
|
||||
expect(
|
||||
await prepare(`--disallowedTools "Bash(git commit:*)"`),
|
||||
).toContain(
|
||||
`--disallowedTools "Bash(/action/scripts/git-commit.sh:*)"`,
|
||||
`--disallowedTools 'Bash(/action/scripts/git-commit.sh:*)'`,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -152,19 +176,31 @@ describe("Tag Mode", () => {
|
||||
`--disallowedTools "Bash(git comm*)"`,
|
||||
])("carries over %s", async (args) => {
|
||||
expect(await prepare(args)).toContain(
|
||||
`--disallowedTools "Bash(/action/scripts/git-commit.sh:*)`,
|
||||
`--disallowedTools 'Bash(/action/scripts/git-commit.sh:*)`,
|
||||
);
|
||||
});
|
||||
|
||||
test("a deny of git push also denies the push wrapper", async () => {
|
||||
expect(await prepare(`--disallowedTools "Bash(git push:*)"`)).toContain(
|
||||
`--disallowedTools "Bash(/action/scripts/git-push.sh:*)"`,
|
||||
`--disallowedTools 'Bash(/action/scripts/git-push.sh:*)'`,
|
||||
);
|
||||
});
|
||||
|
||||
test("adds no deny rule of its own otherwise", async () => {
|
||||
const args = await prepare(`--disallowedTools "Bash(git add -A:*)"`);
|
||||
expect(args).toContain(
|
||||
`--disallowedTools 'Bash(/action/scripts/git-add.sh -A:*)'`,
|
||||
);
|
||||
for (const rest of [`"a b"`, "it's", "$HOME/x", `"(a)/x"`]) {
|
||||
const denied = await prepare(
|
||||
`--disallowedTools 'Bash(git add ${rest.replace(/'/g, "'\\''")}:*)'`,
|
||||
);
|
||||
expect(parseDeniedBashPatterns(denied)).toContain(
|
||||
`/action/scripts/git-add.sh ${rest}:*`,
|
||||
);
|
||||
}
|
||||
expect(await prepare(`--disallowedTools "WebFetch"`)).not.toContain(
|
||||
`--disallowedTools "Bash(`,
|
||||
`--disallowedTools 'Bash(`,
|
||||
);
|
||||
expect(await prepare("")).not.toContain("--disallowedTools");
|
||||
});
|
||||
|
||||
@@ -148,6 +148,35 @@ describe("restoreConfigFromBase", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("removes an AGENTS.md that only the PR has", () => {
|
||||
writeRepoFile("AGENTS.md", "pr agent instructions\n");
|
||||
git(["add", "AGENTS.md"]);
|
||||
git(["commit", "-m", "pr adds agents file"]);
|
||||
|
||||
const restored = restoreConfigFromBase("main");
|
||||
|
||||
expect(restored).toContain("AGENTS.md");
|
||||
expect(existsRepoFile("AGENTS.md")).toBe(false);
|
||||
expect(readRepoFile(".claude-pr/AGENTS.md")).toBe(
|
||||
"pr agent instructions\n",
|
||||
);
|
||||
});
|
||||
|
||||
test("uses the base branch's AGENTS.md, also through a CLAUDE.md link", () => {
|
||||
setupSymlinkedMainBranch();
|
||||
writeRepoFile("AGENTS.md", "pr agent instructions\n");
|
||||
git(["commit", "-am", "pr edits agents file"]);
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile("AGENTS.md")).toBe("shared agent instructions\n");
|
||||
expect(readRepoFile("CLAUDE.md")).toBe("shared agent instructions\n");
|
||||
expect(readRepoFile(".claude-pr/AGENTS.md")).toBe(
|
||||
"pr agent instructions\n",
|
||||
);
|
||||
expect(git(["diff", "--cached", "--name-only"])).toBe("");
|
||||
});
|
||||
|
||||
test("records dangling links as placeholders, including top-level ones", () => {
|
||||
setupSymlinkedMainBranch();
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
@@ -15,15 +16,20 @@ import {
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
import {
|
||||
clearSessionState,
|
||||
disableGitPrograms,
|
||||
pinPushBranch,
|
||||
prepareGitForSession,
|
||||
snapshotSessionFiles,
|
||||
} from "../src/github/operations/session-guard";
|
||||
|
||||
const KEYS = [
|
||||
"GITHUB_ACTION_PATH",
|
||||
"GITHUB_ENV",
|
||||
"GITHUB_PATH",
|
||||
"HOME",
|
||||
"XDG_CONFIG_HOME",
|
||||
"GIT_CONFIG_GLOBAL",
|
||||
"GIT_CONFIG_COUNT",
|
||||
"GIT_CONFIG_KEY_0",
|
||||
"GIT_CONFIG_VALUE_0",
|
||||
@@ -198,6 +204,164 @@ describe("session guard", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("git settings during the session", () => {
|
||||
const local = (key: string) => {
|
||||
try {
|
||||
return git("config", "--local", key).trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
git("init", "-q", join(dir, "repo"));
|
||||
process.chdir(join(dir, "repo"));
|
||||
});
|
||||
|
||||
test("moves the action's settings from the environment to the repository", () => {
|
||||
disableGitPrograms({ hooks: true });
|
||||
expect(process.env.GIT_CONFIG_COUNT).toBe("2");
|
||||
const restore = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: true }),
|
||||
);
|
||||
expect(process.env.GIT_CONFIG_COUNT).toBeUndefined();
|
||||
expect(process.env.GIT_CONFIG_KEY_0).toBeUndefined();
|
||||
expect(process.env.GIT_CONFIG_VALUE_1).toBeUndefined();
|
||||
expect(local("core.fsmonitor")).toBe("false");
|
||||
expect(local("core.hooksPath")).toBe("/dev/null");
|
||||
|
||||
restore();
|
||||
expect(local("core.fsmonitor")).toBe("");
|
||||
expect(local("core.hooksPath")).toBe("");
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
|
||||
const globalConfig = (key: string) => {
|
||||
try {
|
||||
return git("config", "--global", "--get", key).trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
test("refuses repositories in plain folders, and puts that back", () => {
|
||||
const restore = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: true }),
|
||||
);
|
||||
expect(globalConfig("safe.bareRepository")).toBe("explicit");
|
||||
expect(globalConfig("core.hooksPath")).toBe("");
|
||||
|
||||
restore();
|
||||
expect(globalConfig("safe.bareRepository")).toBe("");
|
||||
expect(warnings()).toEqual([]);
|
||||
});
|
||||
|
||||
test("restores a global config file named by GIT_CONFIG_GLOBAL", () => {
|
||||
process.env.GIT_CONFIG_GLOBAL = join(dir, "global-config");
|
||||
const restore = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: false }),
|
||||
);
|
||||
expect(readFileSync(process.env.GIT_CONFIG_GLOBAL, "utf8")).toContain(
|
||||
"explicit",
|
||||
);
|
||||
restore();
|
||||
expect(existsSync(process.env.GIT_CONFIG_GLOBAL)).toBe(false);
|
||||
});
|
||||
|
||||
test("outside a repository, still refuses them and records the hook setting", () => {
|
||||
process.env.GITHUB_ACTION_PATH = dir;
|
||||
const outside = join(dir, "outside");
|
||||
mkdirSync(outside);
|
||||
process.chdir(outside);
|
||||
prepareGitForSession({ hooks: true });
|
||||
expect(globalConfig("safe.bareRepository")).toBe("explicit");
|
||||
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(true);
|
||||
expect(existsSync(join(dir, "scripts/.git-repo"))).toBe(false);
|
||||
});
|
||||
|
||||
test("sets repository config in a bare working directory", () => {
|
||||
const bare = join(dir, "bare.git");
|
||||
git("init", "-q", "--bare", bare);
|
||||
process.chdir(bare);
|
||||
prepareGitForSession({ hooks: false });
|
||||
expect(warnings()).toEqual([]);
|
||||
expect(readFileSync(join(bare, "config"), "utf8")).toContain("fsmonitor");
|
||||
});
|
||||
|
||||
test("keeps a workflow's own entries in the environment", () => {
|
||||
process.env.GIT_CONFIG_COUNT = "1";
|
||||
process.env.GIT_CONFIG_KEY_0 = "user.name";
|
||||
process.env.GIT_CONFIG_VALUE_0 = "someone";
|
||||
disableGitPrograms({ hooks: false });
|
||||
prepareGitForSession({ hooks: false });
|
||||
expect(process.env.GIT_CONFIG_COUNT).toBe("1");
|
||||
expect(process.env.GIT_CONFIG_VALUE_0).toBe("someone");
|
||||
expect(process.env.GIT_CONFIG_KEY_1).toBeUndefined();
|
||||
});
|
||||
|
||||
test("leaves hooks on unless asked", () => {
|
||||
disableGitPrograms({ hooks: false });
|
||||
prepareGitForSession({ hooks: false });
|
||||
expect(local("core.hooksPath")).toBe("");
|
||||
expect(local("core.fsmonitor")).toBe("false");
|
||||
});
|
||||
|
||||
test("a session's own change is still reported", () => {
|
||||
const restore = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: false }),
|
||||
);
|
||||
git("config", "--local", "core.fsmonitor", "evil");
|
||||
restore();
|
||||
expect(local("core.fsmonitor")).toBe("");
|
||||
expect(warnings().join(" ")).toContain("restored");
|
||||
});
|
||||
|
||||
test("records and clears what the wrappers read", () => {
|
||||
process.env.GITHUB_ACTION_PATH = dir;
|
||||
pinPushBranch("claude/x");
|
||||
prepareGitForSession({ hooks: true });
|
||||
expect(readFileSync(join(dir, "scripts/.push-branch"), "utf8")).toBe(
|
||||
"claude/x",
|
||||
);
|
||||
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(true);
|
||||
pinPushBranch("claude/y");
|
||||
expect(readFileSync(join(dir, "scripts/.push-branch"), "utf8")).toBe(
|
||||
"claude/y",
|
||||
);
|
||||
const repoFile = join(dir, "scripts/.git-repo");
|
||||
const repoRoot = realpathSync(join(dir, "repo"));
|
||||
expect(readFileSync(repoFile, "utf8")).toBe(
|
||||
`${repoRoot}/.git\n${repoRoot}\n${process.env.HOME}\n`,
|
||||
);
|
||||
clearSessionState();
|
||||
expect(existsSync(join(dir, "scripts/.push-branch"))).toBe(false);
|
||||
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(false);
|
||||
expect(existsSync(repoFile)).toBe(false);
|
||||
});
|
||||
|
||||
test("clearing also removes a directory left in a file's place", () => {
|
||||
process.env.GITHUB_ACTION_PATH = dir;
|
||||
mkdirSync(join(dir, "scripts/.no-hooks"), { recursive: true });
|
||||
expect(() => clearSessionState()).not.toThrow();
|
||||
expect(existsSync(join(dir, "scripts/.no-hooks"))).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves a workflow's entries alone if nothing was added", () => {
|
||||
process.env.GIT_CONFIG_COUNT = "1";
|
||||
process.env.GIT_CONFIG_KEY_0 = "user.name";
|
||||
process.env.GIT_CONFIG_VALUE_0 = "someone";
|
||||
prepareGitForSession({ hooks: false });
|
||||
expect(process.env.GIT_CONFIG_COUNT).toBe("1");
|
||||
expect(process.env.GIT_CONFIG_VALUE_0).toBe("someone");
|
||||
});
|
||||
|
||||
test("warns if it can't set the repository's config", () => {
|
||||
writeFileSync(join(dir, "repo/.git/config.lock"), "");
|
||||
prepareGitForSession({ hooks: false });
|
||||
expect(warnings().join(" ")).toContain("Could not set core.fsmonitor");
|
||||
});
|
||||
});
|
||||
|
||||
test("replaces a directory a session put in a file's place", () => {
|
||||
const path = process.env.GITHUB_ENV!;
|
||||
const restore = snapshotSessionFiles();
|
||||
|
||||
@@ -0,0 +1,698 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { dirname, join } from "path";
|
||||
import {
|
||||
toolConfigDenyRules,
|
||||
restoreToolConfigFromBase,
|
||||
} from "../src/github/operations/tool-config";
|
||||
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
|
||||
|
||||
describe("restoreToolConfigFromBase", () => {
|
||||
let originalCwd: string;
|
||||
let tempDir: string;
|
||||
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
|
||||
const write = (path: string, content: string, executable = false) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, content);
|
||||
if (executable) chmodSync(path, 0o755);
|
||||
};
|
||||
const read = (path: string) => readFileSync(path, "utf8");
|
||||
const commit = (message: string) => {
|
||||
git("add", "-A", "-f");
|
||||
git("commit", "-qm", message);
|
||||
};
|
||||
|
||||
// Commits the base branch, pushes it and starts the pull request's branch from it.
|
||||
const startPr = () => {
|
||||
commit("base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", "pr");
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
tempDir = mkdtempSync(join(tmpdir(), "tool-config-"));
|
||||
const remote = join(tempDir, "origin.git");
|
||||
const repo = join(tempDir, "repo");
|
||||
execFileSync("git", ["init", "-q", "--bare", remote]);
|
||||
execFileSync("git", ["init", "-q", "-b", "main", repo]);
|
||||
process.chdir(repo);
|
||||
git("config", "user.email", "[email protected]");
|
||||
git("config", "user.name", "Test User");
|
||||
git("remote", "add", "origin", remote);
|
||||
write("src/index.ts", "base\n");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("does nothing when the pull request has the same tool config", () => {
|
||||
write(".npmrc", "base\n");
|
||||
write("package.json", '{"name":"x","bin":"cli.js"}');
|
||||
startPr();
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(git("status", "--porcelain")).toBe("");
|
||||
expect(existsSync(".claude-pr")).toBe(false);
|
||||
});
|
||||
|
||||
test("uses the base version of a changed file, and removes an added one", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
write("bunfig.toml", "pr\n");
|
||||
write("node_modules/.bin/node", "#!/bin/sh\n", true);
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main").sort()).toEqual([
|
||||
".npmrc",
|
||||
"bunfig.toml",
|
||||
"node_modules",
|
||||
]);
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
expect(existsSync("bunfig.toml")).toBe(false);
|
||||
expect(existsSync("node_modules")).toBe(false);
|
||||
expect(read(".claude-pr/.npmrc")).toBe("pr\n");
|
||||
// Nothing is staged, so the pull request's versions are still what git has.
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("");
|
||||
});
|
||||
|
||||
test("brings back a file the pull request deleted", () => {
|
||||
write(".npmrc", "base\n");
|
||||
write("node_modules/.bin/tool", "base\n", true);
|
||||
startPr();
|
||||
rmSync(".npmrc");
|
||||
rmSync("node_modules", { recursive: true });
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
expect(read("node_modules/.bin/tool")).toBe("base\n");
|
||||
expect(lstatSync("node_modules/.bin/tool").mode & 0o111).not.toBe(0);
|
||||
});
|
||||
|
||||
test("leaves untracked files that an earlier step created", () => {
|
||||
write("bunfig.toml", "base\n");
|
||||
startPr();
|
||||
rmSync("bunfig.toml");
|
||||
write(".npmrc.example", "pr\n");
|
||||
commit("pr");
|
||||
write("bunfig.toml", "from a step\n");
|
||||
write(".npmrc", "from a step\n");
|
||||
write("node_modules/.bin/tool", "installed\n", true);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("bunfig.toml")).toBe("from a step\n");
|
||||
expect(read(".npmrc")).toBe("from a step\n");
|
||||
expect(read("node_modules/.bin/tool")).toBe("installed\n");
|
||||
});
|
||||
|
||||
test("keeps a step's change to a file the pull request leaves alone", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
write(".npmrc", "base\nfrom a step\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read(".npmrc")).toBe("base\nfrom a step\n");
|
||||
});
|
||||
|
||||
test("keeps a file deleted by an earlier step deleted", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
rmSync(".npmrc");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(existsSync(".npmrc")).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves a directory an earlier step put in a tracked link's place", () => {
|
||||
startPr();
|
||||
symlinkSync("elsewhere", "node_modules");
|
||||
commit("pr");
|
||||
rmSync("node_modules");
|
||||
write("node_modules/tool/a", "installed\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("node_modules/tool/a")).toBe("installed\n");
|
||||
});
|
||||
|
||||
test("leaves files that a sparse checkout leaves out", () => {
|
||||
write("node_modules/tool/a", "base\n");
|
||||
startPr();
|
||||
write("node_modules/tool/a", "pr\n");
|
||||
commit("pr");
|
||||
git("sparse-checkout", "set", "src");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(existsSync("node_modules/tool/a")).toBe(false);
|
||||
});
|
||||
|
||||
test("replaces links without following them", () => {
|
||||
write("node_modules/.bin/tool", "base\n", true);
|
||||
startPr();
|
||||
const outside = join(tempDir, "outside");
|
||||
write(join(outside, ".bin/tool"), "outside\n");
|
||||
rmSync("node_modules", { recursive: true });
|
||||
symlinkSync(outside, "node_modules");
|
||||
symlinkSync(join(outside, ".bin/tool"), ".npmrc");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(lstatSync("node_modules").isDirectory()).toBe(true);
|
||||
expect(read("node_modules/.bin/tool")).toBe("base\n");
|
||||
expect(existsSync(".npmrc")).toBe(false);
|
||||
expect(read(join(outside, ".bin/tool"))).toBe("outside\n");
|
||||
});
|
||||
|
||||
test("writes and removes nothing through a link an earlier step added", () => {
|
||||
write("node_modules/a/b", "base\n");
|
||||
write("node_modules/c/d", "base\n");
|
||||
startPr();
|
||||
write("node_modules/a/b", "pr\n");
|
||||
rmSync("node_modules/c", { recursive: true });
|
||||
commit("pr");
|
||||
const outside = join(tempDir, "outside");
|
||||
write(join(outside, "a/b"), "outside\n");
|
||||
rmSync("node_modules", { recursive: true });
|
||||
symlinkSync(outside, "node_modules");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read(join(outside, "a/b"))).toBe("outside\n");
|
||||
expect(existsSync(join(outside, "c"))).toBe(false);
|
||||
});
|
||||
|
||||
test("brings back a link the base branch has", () => {
|
||||
write("node_modules/tool/cli.js", "base\n");
|
||||
mkdirSync("node_modules/.bin");
|
||||
symlinkSync("../tool/cli.js", "node_modules/.bin/tool");
|
||||
startPr();
|
||||
rmSync("node_modules/.bin/tool");
|
||||
write("node_modules/.bin/tool", "pr\n", true);
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(readlinkSync("node_modules/.bin/tool")).toBe("../tool/cli.js");
|
||||
});
|
||||
|
||||
test("replaces a directory the pull request puts in a file's place", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
rmSync(".npmrc");
|
||||
write(".npmrc/keep", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("replaces a directory that holds a package.json too", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
rmSync(".npmrc");
|
||||
write(".npmrc/package.json", "{}");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("rewrites an unchanged file that .gitattributes re-encodes", () => {
|
||||
write(".npmrc", "ignore-scripts=true\n");
|
||||
startPr();
|
||||
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
|
||||
git("add", ".gitattributes");
|
||||
git("commit", "-qm", "pr");
|
||||
expect(git("rev-parse", "HEAD:.npmrc")).toBe(
|
||||
git("rev-parse", "main:.npmrc"),
|
||||
);
|
||||
rmSync(".npmrc");
|
||||
git("checkout", "--", ".npmrc");
|
||||
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
|
||||
|
||||
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
|
||||
});
|
||||
|
||||
test("sees re-encoding when .gitattributes is re-encoded too", () => {
|
||||
write(".npmrc", "ignore-scripts=true\n");
|
||||
startPr();
|
||||
const encoding = "working-tree-encoding=UTF-16LE-BOM";
|
||||
write(".gitattributes", `.npmrc ${encoding}\n.gitattributes ${encoding}\n`);
|
||||
const oid = git("hash-object", "-w", "--no-filters", ".gitattributes");
|
||||
git("update-index", "--add", "--cacheinfo", `100644,${oid},.gitattributes`);
|
||||
git("commit", "-qm", "pr");
|
||||
rmSync(".npmrc");
|
||||
rmSync(".gitattributes");
|
||||
git("checkout", "--", ".");
|
||||
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
|
||||
expect(read(".gitattributes")).not.toContain(encoding);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
|
||||
|
||||
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
|
||||
});
|
||||
|
||||
test("sees re-encoding by a .gitattributes that is only on disk", () => {
|
||||
write(".npmrc", "ignore-scripts=true\n");
|
||||
startPr();
|
||||
write("f.txt", "pr\n");
|
||||
commit("pr");
|
||||
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
|
||||
rmSync(".npmrc");
|
||||
git("checkout", "--", ".npmrc");
|
||||
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
|
||||
|
||||
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
|
||||
});
|
||||
|
||||
test("matches names without regard to case", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write("BUNFIG.toml", "pr\n");
|
||||
write("Node_Modules/.bin/node", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(existsSync("BUNFIG.toml")).toBe(false);
|
||||
expect(existsSync("Node_Modules/.bin/node")).toBe(false);
|
||||
});
|
||||
|
||||
test("writes the base version as it is, whatever .gitattributes says", () => {
|
||||
write(".npmrc", "ignore-scripts=true\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
|
||||
});
|
||||
|
||||
test("keeps binary and empty content intact", () => {
|
||||
const content = Buffer.from([0, 10, 255, 10, 13, 0]);
|
||||
mkdirSync("node_modules");
|
||||
writeFileSync("node_modules/a", content);
|
||||
writeFileSync("node_modules/b", "");
|
||||
writeFileSync("node_modules/c", "no newline");
|
||||
startPr();
|
||||
for (const name of ["a", "b", "c"]) write(`node_modules/${name}`, "pr");
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(readFileSync("node_modules/a").equals(content)).toBe(true);
|
||||
expect(read("node_modules/b")).toBe("");
|
||||
expect(read("node_modules/c")).toBe("no newline");
|
||||
});
|
||||
|
||||
test("reports names from a fixed list, not the pull request's file names", () => {
|
||||
startPr();
|
||||
write("node_modules/a\n::stop-commands::x", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
const names = restoreToolConfigFromBase("main");
|
||||
|
||||
expect(names).toEqual(["node_modules"]);
|
||||
expect(existsSync("node_modules")).toBe(false);
|
||||
});
|
||||
|
||||
test("handles names that are not valid UTF-8", () => {
|
||||
startPr();
|
||||
const name = Buffer.from([...Buffer.from("node_modules/"), 0xff]);
|
||||
mkdirSync("node_modules");
|
||||
try {
|
||||
writeFileSync(name, "pr\n");
|
||||
} catch {
|
||||
return; // This file system refuses such names.
|
||||
}
|
||||
commit("pr");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(existsSync(name)).toBe(false);
|
||||
});
|
||||
|
||||
test("is not misled by a local branch with the base's name", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
git("branch", "origin/main");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("works in a checkout with no remote-tracking branch for the base", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
git("fetch", "-q", "origin", "main");
|
||||
git("update-ref", "-d", "refs/remotes/origin/main");
|
||||
|
||||
restoreToolConfigFromBase("main");
|
||||
|
||||
expect(read(".npmrc")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("stops edits to tool config, and to package.json only if replaced", () => {
|
||||
const rules = [
|
||||
"Edit(./.npmrc)",
|
||||
"Edit(./bunfig.toml)",
|
||||
"Edit(./node_modules/**)",
|
||||
];
|
||||
expect(toolConfigDenyRules([])).toEqual(rules);
|
||||
expect(toolConfigDenyRules(["package.json"])).toEqual([
|
||||
...rules,
|
||||
"Edit(package.json)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("matches names a file system can treat as the same", () => {
|
||||
startPr();
|
||||
write("node_module\u017F/.bin/node", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["node_modules"]);
|
||||
});
|
||||
|
||||
test("fails without naming a file if the base version can't be read", () => {
|
||||
write(".npmrc", "base\n");
|
||||
startPr();
|
||||
write(".npmrc", "pr\n");
|
||||
commit("pr");
|
||||
const oid = git("rev-parse", "main:.npmrc");
|
||||
rmSync(join(".git/objects", oid.slice(0, 2), oid.slice(2)));
|
||||
|
||||
expect(() => restoreToolConfigFromBase("main")).toThrow(
|
||||
/^Could not use the base branch's version/,
|
||||
);
|
||||
expect(existsSync(".npmrc")).toBe(false);
|
||||
});
|
||||
|
||||
describe("package.json", () => {
|
||||
const baseJson = { name: "x", bin: { x: "x.js" }, version: "1.0.0" };
|
||||
const start = (pr: unknown) => {
|
||||
write("package.json", JSON.stringify(baseJson));
|
||||
startPr();
|
||||
write("package.json", typeof pr === "string" ? pr : JSON.stringify(pr));
|
||||
commit("pr");
|
||||
};
|
||||
|
||||
test("keeps the pull request's version when only other fields change", () => {
|
||||
const pr = { ...baseJson, version: "2.0.0", dependencies: { a: "1" } };
|
||||
start(pr);
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
expect(JSON.parse(read("package.json"))).toEqual(pr);
|
||||
});
|
||||
|
||||
test("keeps the pull request's version when it removes the commands", () => {
|
||||
start({ name: "x" });
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["bin", { bin: { "tool@latest": "a.js" } }],
|
||||
["directories", { directories: { bin: "bin" } }],
|
||||
["name", { name: "tool" }],
|
||||
["workspaces", { workspaces: ["pkgs/*"] }],
|
||||
])("uses only the base's commands when %s changes", (_, change) => {
|
||||
const pr = { ...baseJson, ...change, dependencies: { a: "1" } };
|
||||
start(pr);
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
expect(JSON.parse(read("package.json"))).toEqual({
|
||||
...baseJson,
|
||||
dependencies: { a: "1" },
|
||||
});
|
||||
expect(JSON.parse(read(".claude-pr/package.json"))).toEqual(pr);
|
||||
});
|
||||
|
||||
describe("that .gitattributes converts", () => {
|
||||
const commitRaw = (attributes: string, stored: string) => {
|
||||
write(".gitattributes", `package.json ${attributes}\n`);
|
||||
write("package.json", stored);
|
||||
const oid = git("hash-object", "-w", "--no-filters", "package.json");
|
||||
git("add", ".gitattributes");
|
||||
git("update-index", "--cacheinfo", `100644,${oid},package.json`);
|
||||
git("commit", "-qm", "pr");
|
||||
rmSync("package.json");
|
||||
git("checkout", "--", "package.json");
|
||||
};
|
||||
const startFromBase = () => {
|
||||
write("package.json", JSON.stringify(baseJson));
|
||||
startPr();
|
||||
};
|
||||
|
||||
test("replaces commands that are only on disk", () => {
|
||||
startFromBase();
|
||||
commitRaw(
|
||||
"ident",
|
||||
'{"name":"x","a":"$Id:","b":{"c":"$","bin":{"x":"pr.js"},"d":"$Id:"},"e":"$"}',
|
||||
);
|
||||
expect(JSON.parse(read("package.json")).bin).toEqual({ x: "pr.js" });
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
|
||||
expect(JSON.parse(read("package.json")).bin).toEqual(baseJson.bin);
|
||||
});
|
||||
|
||||
test("replaces one that can't be understood", () => {
|
||||
startFromBase();
|
||||
commitRaw(
|
||||
"working-tree-encoding=UTF-16LE-BOM",
|
||||
JSON.stringify(baseJson),
|
||||
);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
|
||||
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
|
||||
});
|
||||
|
||||
test("replaces commands that aren't on disk", () => {
|
||||
startFromBase();
|
||||
commitRaw(
|
||||
"ident",
|
||||
'{"name":"x","a":"$Id: ","bin":{"x":"pr.js"},"b":" $"}',
|
||||
);
|
||||
expect(JSON.parse(read("package.json")).bin).toBeUndefined();
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
});
|
||||
|
||||
test("keeps a step's change to one that the pull request leaves alone", () => {
|
||||
write(".gitattributes", "* ident\n");
|
||||
startFromBase();
|
||||
write("f.txt", "pr\n");
|
||||
commit("pr");
|
||||
const changed = JSON.stringify({ ...baseJson, name: "@scope/x" });
|
||||
write("package.json", changed);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("package.json")).toBe(changed);
|
||||
});
|
||||
|
||||
test("keeps one whose encoding is no conversion", () => {
|
||||
startFromBase();
|
||||
const pr = JSON.stringify({ ...baseJson, version: "2.0.0" });
|
||||
commitRaw("working-tree-encoding=UTF-8", pr);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps what a step changed in one that is not converted", () => {
|
||||
startFromBase();
|
||||
write(
|
||||
"package.json",
|
||||
JSON.stringify({ ...baseJson, version: "2.0.0" }),
|
||||
);
|
||||
commit("pr");
|
||||
const changed = JSON.stringify({ ...baseJson, name: "@scope/x" });
|
||||
write("package.json", changed);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("package.json")).toBe(changed);
|
||||
});
|
||||
|
||||
test("keeps one with the same commands", () => {
|
||||
startFromBase();
|
||||
const pr = JSON.stringify({ ...baseJson, version: "2.0.0" });
|
||||
commitRaw("ident", pr);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("package.json")).toBe(pr);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps a new name if directories holds no commands", () => {
|
||||
const directories = { test: "test" };
|
||||
write("package.json", JSON.stringify({ name: "x", directories }));
|
||||
startPr();
|
||||
const pr = JSON.stringify({ name: "y", directories: { test: "t" } });
|
||||
write("package.json", pr);
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read("package.json")).toBe(pr);
|
||||
});
|
||||
|
||||
test.each([[null], ["bin"], [["bin"]], [1]])(
|
||||
"copes with directories being %p",
|
||||
(directories) => {
|
||||
start({ name: "y", directories });
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
test("uses the base version when it can't be understood", () => {
|
||||
start("{");
|
||||
restoreToolConfigFromBase("main");
|
||||
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
|
||||
});
|
||||
|
||||
test("understands a byte order mark", () => {
|
||||
start(`\uFEFF${JSON.stringify({ ...baseJson, version: "2.0.0" })}`);
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
});
|
||||
|
||||
test("looks in subdirectories only if the base branch has workspaces", () => {
|
||||
const tool = JSON.stringify({ name: "tool", bin: "x.js", version: "1" });
|
||||
startPr();
|
||||
write("pkgs/p/package.json", tool);
|
||||
commit("pr");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
git("checkout", "-q", "main");
|
||||
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
|
||||
commit("base 2");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-q", "-b", "pr2");
|
||||
write("pkgs/p/package.json", tool);
|
||||
commit("pr2");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
expect(JSON.parse(read("pkgs/p/package.json"))).toEqual({
|
||||
name: "tool",
|
||||
version: "1",
|
||||
});
|
||||
expect(JSON.parse(read(".claude-pr/pkgs/p/package.json")).name).toBe(
|
||||
"tool",
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves what the base branch's .claude and .husky hold", () => {
|
||||
const base = '{"name":"hooks","bin":"a.js","scripts":{"check":"base"}}';
|
||||
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
|
||||
write(".claude/hooks/package.json", base);
|
||||
write(".husky/package.json", base);
|
||||
startPr();
|
||||
for (const dir of [".claude/hooks", ".husky"]) {
|
||||
write(`${dir}/package.json`, '{"bin":"b.js","scripts":{"check":"pr"}}');
|
||||
}
|
||||
commit("pr");
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
expect(read(".claude/hooks/package.json")).toBe(base);
|
||||
expect(read(".husky/package.json")).toBe(base);
|
||||
});
|
||||
|
||||
test("counts another spelling of a restored directory only if it is that one", () => {
|
||||
const tool = '{"name":"tool","bin":"x.js"}';
|
||||
write("package.json", '{"name":"x","workspaces":["*"]}');
|
||||
write(".husky/package.json", tool);
|
||||
startPr();
|
||||
write(".Husky/package.json", tool);
|
||||
write("claude.md/package.json", tool);
|
||||
commit("pr");
|
||||
restoreConfigFromBase("main");
|
||||
const ownDirectories = readdirSync(".").filter((name) =>
|
||||
[".Husky", "claude.md"].includes(name),
|
||||
);
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(
|
||||
ownDirectories.length > 0 ? ["package.json"] : [],
|
||||
);
|
||||
|
||||
expect(read(".husky/package.json")).toBe(tool);
|
||||
for (const dir of ownDirectories) {
|
||||
expect(JSON.parse(read(`${dir}/package.json`))).toEqual({
|
||||
name: "tool",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("reports a restored directory's other spelling that it removes", () => {
|
||||
write("package.json", '{"name":"x","workspaces":["*"]}');
|
||||
startPr();
|
||||
write("claude.md/package.json", "{");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
|
||||
expect(existsSync("claude.md")).toBe(false);
|
||||
});
|
||||
|
||||
test("takes the commands out of a new package.json", () => {
|
||||
startPr();
|
||||
write("package.json", '{"name":"x"}');
|
||||
commit("pr");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual([]);
|
||||
|
||||
write("package.json", '{"name":"x","version":"1","bin":{"t":"a.js"}}');
|
||||
commit("pr 2");
|
||||
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
|
||||
expect(JSON.parse(read("package.json"))).toEqual({
|
||||
name: "x",
|
||||
version: "1",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user