mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-12-02 01:59:59 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
438d3dcef2 | ||
|
|
f6e1ffc452 |
+1
-1
@@ -57,7 +57,7 @@ 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`, `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.
|
||||
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. The restored files are written with the base branch's `.gitattributes`. The run stops if one of that branch's filters, other than Git LFS, changes a restored file (for example by decrypting it) and the pull request's `.gitattributes` gives the file another filter or none, because a commit could then store it unfiltered. The restored files are removed first. To go on, use the same filter for the file in the pull request, for example by updating it.
|
||||
|
||||
On a pull request whose author does not have write access, everything this section takes from the base branch comes from your default branch instead, even if the pull request targets another branch such as a release branch. To use a different branch for pull requests that don't target the default branch, set the `base_branch` input to a fixed branch name, never to a value from the pull request. On pull request and review events, the default branch is used if the input equals the pull request's head branch name. Changes to these files are left out when Claude commits with its commit command. A bot's pull request from a branch in your repository still uses its base, unless that is a `pr-N` branch or a comment in the pull request's conversation started the run and the pull request is closed or the workflow has a `prompt` without `track_progress`. `restrict_untrusted_prs: false` turns this off.
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import * as core from "@actions/core";
|
||||
import { execFileSync } from "child_process";
|
||||
import { randomUUID } from "crypto";
|
||||
import {
|
||||
appendFileSync,
|
||||
copyFileSync,
|
||||
cpSync,
|
||||
existsSync,
|
||||
lstatSync,
|
||||
@@ -9,10 +11,12 @@ import {
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
realpathSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { dirname, join, posix, relative, sep } from "path";
|
||||
import { fetchDepthArgs } from "./fetch-depth";
|
||||
|
||||
@@ -296,6 +300,246 @@ export function fetchBranch(branch: string): void {
|
||||
fetchRef(`+refs/heads/${branch}:refs/remotes/origin/${branch}`, 1);
|
||||
}
|
||||
|
||||
// A .gitattributes that a sparse checkout leaves out stays marked as left out while
|
||||
// useAttributesFrom has one on disk.
|
||||
const KEEP_SPARSE = ["-c", "sparse.expectFilesOutsideOfPatterns=true"];
|
||||
|
||||
// File names can be any bytes. Latin-1 keeps each one intact.
|
||||
function gitBytes(
|
||||
args: string[],
|
||||
input = "",
|
||||
env: Record<string, string> = {},
|
||||
): Buffer {
|
||||
return execFileSync("git", [...KEEP_SPARSE, ...args], {
|
||||
input: Buffer.from(input, "latin1"),
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
maxBuffer: Infinity,
|
||||
env: { ...process.env, ...env },
|
||||
});
|
||||
}
|
||||
|
||||
const listSensitive = (args: string[]): string[] =>
|
||||
gitBytes([...args, "-z", "--", ...SENSITIVE_PATHS])
|
||||
.toString("latin1")
|
||||
.split("\0")
|
||||
.filter(Boolean);
|
||||
|
||||
const isAttributesFile = (path: string): boolean =>
|
||||
path.endsWith("/.gitattributes");
|
||||
|
||||
/** The filter that git applies to each file. */
|
||||
function filtersOf(
|
||||
paths: string[],
|
||||
env?: Record<string, string>,
|
||||
): Map<string, string> {
|
||||
if (paths.length === 0) return new Map();
|
||||
const fields = gitBytes(
|
||||
["check-attr", "-z", "--stdin", "filter"],
|
||||
paths.map((path) => `${path}\0`).join(""),
|
||||
env,
|
||||
)
|
||||
.toString("latin1")
|
||||
.split("\0");
|
||||
// "<path> filter <value>", each ended by a NUL
|
||||
return new Map(
|
||||
paths.map((_, i) => [fields[i * 3]!, fields[i * 3 + 2]!] as const),
|
||||
);
|
||||
}
|
||||
|
||||
// Git LFS keeps large files elsewhere, so what it writes isn't secret.
|
||||
const NOT_SECRET = ["unspecified", "unset", "set", "lfs"];
|
||||
|
||||
/** Whether git runs a program that can change files as it writes them. */
|
||||
function changesFiles(filter: string): boolean {
|
||||
const name = Buffer.from(filter, "latin1").toString();
|
||||
return ["smudge", "process"].some((key) => {
|
||||
try {
|
||||
const command = gitBytes(["config", "--get", `filter.${name}.${key}`]);
|
||||
return !["", "cat"].includes(command.toString().trim());
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The filters after `git add -A`, which drops each .gitattributes that is only in the
|
||||
* index, but not those that a sparse checkout leaves out.
|
||||
*/
|
||||
function filtersAfterAdd(paths: string[]): Map<string, string> | undefined {
|
||||
const dropped = gitBytes([
|
||||
"ls-files",
|
||||
"--deleted",
|
||||
"-z",
|
||||
"--",
|
||||
":(top,glob)**/.gitattributes",
|
||||
]).toString("latin1");
|
||||
if (!dropped) return undefined;
|
||||
const index = gitBytes(["rev-parse", "--git-path", "index"])
|
||||
.toString()
|
||||
.replace(/\r?\n$/, "");
|
||||
const copy = join(tmpdir(), `index-${randomUUID()}`);
|
||||
try {
|
||||
copyFileSync(index, copy);
|
||||
const env = { GIT_INDEX_FILE: copy };
|
||||
gitBytes(["update-index", "--force-remove", "-z", "--stdin"], dropped, env);
|
||||
return filtersOf(paths, env);
|
||||
} finally {
|
||||
rmSync(copy, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws if the base branch's filter changed a restored file, as one that decrypts
|
||||
* does, and git could now store that file without the filter.
|
||||
*/
|
||||
function checkFilters(
|
||||
ref: string,
|
||||
baseBranch: string,
|
||||
written: Map<string, string>,
|
||||
): void {
|
||||
const paths = [...written.keys()];
|
||||
const current = filtersOf(paths);
|
||||
const states = [current, filtersAfterAdd(paths) ?? current];
|
||||
const unfiltered = new Set(
|
||||
paths.filter((path) => {
|
||||
const filter = written.get(path)!;
|
||||
return (
|
||||
!NOT_SECRET.includes(filter) &&
|
||||
states.some((state) => state.get(path) !== filter) &&
|
||||
changesFiles(filter)
|
||||
);
|
||||
}),
|
||||
);
|
||||
if (unfiltered.size === 0) return;
|
||||
|
||||
for (const entry of listSensitive(["ls-tree", "-r", ref])) {
|
||||
const [info = "", name = ""] = entry.split(/\t(.*)/s);
|
||||
const [mode = "", , oid = ""] = info.split(" ");
|
||||
const path = Buffer.from(name, "latin1");
|
||||
if (
|
||||
unfiltered.has(name) &&
|
||||
mode.startsWith("100") &&
|
||||
lstatSync(path, { throwIfNoEntry: false })?.isFile() &&
|
||||
!readFileSync(path).equals(gitBytes(["cat-file", "blob", oid]))
|
||||
) {
|
||||
throw new Error(
|
||||
`The pull request's .gitattributes has other filters for Claude's config than ${baseBranch}, so a commit could store that config unfiltered. Use the same filters for these files as ${baseBranch}, for example by updating the pull request.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type BaseAttributes = {
|
||||
/** Index entries that were removed, for the caller's `git reset` to bring back. */
|
||||
removed: string[];
|
||||
putBack: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Makes `git checkout <ref> -- <path>` write the sensitive paths, which must be gone
|
||||
* from disk, with the .gitattributes files of `ref` and not the checked-out commit's.
|
||||
* That command reads each one from disk, or from the index if it isn't on disk.
|
||||
* If this throws, the run stops, because without the config it would go on without
|
||||
* its hooks and deny rules.
|
||||
*/
|
||||
function useAttributesFrom(ref: string): BaseAttributes {
|
||||
// The files above the sensitive paths, from the working directory up to the root of
|
||||
// the repository, where they differ.
|
||||
const prefix = gitBytes(["rev-parse", "--show-prefix"])
|
||||
.toString()
|
||||
.replace(/\r?\n$/, "");
|
||||
const depth = prefix.split("/").length - 1;
|
||||
const files = Array.from({ length: depth + 1 }, (_, up) => {
|
||||
const path = `${"../".repeat(up)}.gitattributes`;
|
||||
const inRepo = posix.join(prefix, path);
|
||||
const [mode = "", , oid] = gitBytes([
|
||||
"ls-tree",
|
||||
"--full-tree",
|
||||
ref,
|
||||
"--",
|
||||
inRepo,
|
||||
])
|
||||
.toString()
|
||||
.split(/\s/);
|
||||
// Git ignores one that is a link. An empty file keeps git from using the index's.
|
||||
const content =
|
||||
oid && mode.startsWith("100")
|
||||
? gitBytes(["cat-file", "blob", oid])
|
||||
: Buffer.alloc(0);
|
||||
const stats = lstatSync(path, { throwIfNoEntry: false });
|
||||
const isSame = stats
|
||||
? stats.isFile() && readFileSync(path).equals(content)
|
||||
: !oid && gitBytes(["ls-files", "--", path]).length === 0;
|
||||
return { path, content, isSame, backup: `${path}-${randomUUID()}` };
|
||||
}).filter(({ isSame }) => !isSame);
|
||||
|
||||
// Below them, checkout uses the files of `ref`, but it keeps index entries that `ref`
|
||||
// doesn't have.
|
||||
const inRef = new Set(listSensitive(["ls-tree", "-r", "--name-only", ref]));
|
||||
const removed = listSensitive(["ls-files"]).filter(
|
||||
(path) => isAttributesFile(path) && !inRef.has(path),
|
||||
);
|
||||
|
||||
const replaced: typeof files = [];
|
||||
const putBack = () => {
|
||||
const errors: unknown[] = [];
|
||||
for (const { path, backup } of replaced) {
|
||||
try {
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
if (lstatSync(backup, { throwIfNoEntry: false })) {
|
||||
renameSync(backup, path);
|
||||
}
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) throw errors[0];
|
||||
};
|
||||
try {
|
||||
for (const file of files) {
|
||||
if (lstatSync(file.path, { throwIfNoEntry: false })) {
|
||||
renameSync(file.path, file.backup);
|
||||
}
|
||||
replaced.push(file);
|
||||
writeFileSync(file.path, file.content, { flag: "wx" });
|
||||
}
|
||||
if (removed.length > 0) {
|
||||
gitBytes(
|
||||
["update-index", "--force-remove", "-z", "--stdin"],
|
||||
removed.map((path) => `${path}\0`).join(""),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
putBack();
|
||||
} catch {
|
||||
// The first error says why.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return { removed, putBack };
|
||||
}
|
||||
|
||||
/**
|
||||
* `git checkout <ref> -- <path>` stages the restored files. Unstage so the revert
|
||||
* doesn't silently leak into commits the CLI makes later. This also brings back the
|
||||
* index entries that useAttributesFrom removed.
|
||||
*/
|
||||
function unstageSensitivePaths(hasRemovedEntries: boolean): void {
|
||||
try {
|
||||
execFileSync("git", ["reset", "--", ...SENSITIVE_PATHS], {
|
||||
stdio: "pipe",
|
||||
});
|
||||
} catch {
|
||||
// Nothing was staged, or paths don't exist on HEAD — either is fine. But a
|
||||
// commit would delete the PR's files whose entries were removed.
|
||||
if (hasRemovedEntries) {
|
||||
throw new Error("Could not put the pull request's index entries back");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores security-sensitive config paths from the PR base branch, or from the
|
||||
* branch that chooseConfigBranch picks in its place.
|
||||
@@ -377,26 +621,39 @@ export function restoreConfigFromBase(baseBranch: string): string[] {
|
||||
|
||||
fetchBranch(baseBranch);
|
||||
|
||||
for (const p of SENSITIVE_PATHS) {
|
||||
try {
|
||||
execFileSync(
|
||||
"git",
|
||||
["checkout", `refs/remotes/origin/${baseBranch}`, "--", p],
|
||||
{ stdio: "pipe" },
|
||||
);
|
||||
} catch {
|
||||
// Path doesn't exist on base — it stays deleted.
|
||||
}
|
||||
}
|
||||
|
||||
// `git checkout <ref> -- <path>` stages the restored files. Unstage so the
|
||||
// revert doesn't silently leak into commits the CLI makes later.
|
||||
const ref = `refs/remotes/origin/${baseBranch}`;
|
||||
const { removed, putBack } = useAttributesFrom(ref);
|
||||
try {
|
||||
execFileSync("git", ["reset", "--", ...SENSITIVE_PATHS], {
|
||||
stdio: "pipe",
|
||||
});
|
||||
} catch {
|
||||
// Nothing was staged, or paths don't exist on HEAD — either is fine.
|
||||
let written: Map<string, string>;
|
||||
try {
|
||||
for (const p of SENSITIVE_PATHS) {
|
||||
try {
|
||||
execFileSync("git", [...KEEP_SPARSE, "checkout", ref, "--", p], {
|
||||
stdio: "pipe",
|
||||
});
|
||||
} catch {
|
||||
// Path doesn't exist on base — it stays deleted.
|
||||
}
|
||||
}
|
||||
written = filtersOf(listSensitive(["ls-tree", "-r", "--name-only", ref]));
|
||||
} finally {
|
||||
try {
|
||||
putBack();
|
||||
} finally {
|
||||
unstageSensitivePaths(removed.length > 0);
|
||||
}
|
||||
}
|
||||
checkFilters(ref, baseBranch, written);
|
||||
} catch (error) {
|
||||
// The run stops, but a later step could still commit what a filter decrypted.
|
||||
for (const p of SENSITIVE_PATHS) {
|
||||
try {
|
||||
rmSync(p, { recursive: true, force: true });
|
||||
} catch {
|
||||
core.warning(`Could not remove ${p} after the restore failed`);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Every sensitive path is reported, not just the ones that changed: the
|
||||
|
||||
@@ -487,6 +487,283 @@ describe("restoreConfigFromBase", () => {
|
||||
).toEqual([".claude/settings.json", "CLAUDE.md"]);
|
||||
});
|
||||
|
||||
describe("with .gitattributes", () => {
|
||||
const HOOK = ".claude/hooks/check.sh";
|
||||
const SCRIPT = "#!/bin/sh\n# $Id$\nexit 2\n";
|
||||
|
||||
// Commits files to main, and starts a new branch for a pull request there.
|
||||
function setupBase(files: Record<string, string>): void {
|
||||
git(["checkout", "main"]);
|
||||
for (const [path, contents] of Object.entries(files)) {
|
||||
writeRepoFile(path, contents);
|
||||
}
|
||||
git(["add", "--", ...Object.keys(files)]);
|
||||
git(["update-index", "--chmod=+x", HOOK]);
|
||||
git(["commit", "-m", "base files"]);
|
||||
git(["push", "origin", "main"]);
|
||||
git(["checkout", "-f", "-B", "pr"]);
|
||||
}
|
||||
|
||||
function commitAttributes(path: string, contents: string): void {
|
||||
writeRepoFile(path, contents);
|
||||
git(["add", "--", path]);
|
||||
git(["commit", "-m", "pr attributes"]);
|
||||
}
|
||||
|
||||
function expectBaseFiles(): void {
|
||||
expect(readRepoFile(HOOK)).toBe(SCRIPT);
|
||||
expect(lstatRepoFile(HOOK).mode & 0o111).not.toBe(0);
|
||||
expect(readRepoFile(".claude/settings.json")).toBe(
|
||||
`${JSON.stringify({ source: "base" })}\n`,
|
||||
);
|
||||
expect(readRepoFile("CLAUDE.md")).toBe("base claude instructions\n");
|
||||
expect(git(["diff", "--cached", "--name-only"])).toBe("");
|
||||
expect(
|
||||
readdirSync(repoDir).filter((name) =>
|
||||
name.startsWith(".gitattributes-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
}
|
||||
|
||||
test.each([
|
||||
[".gitattributes", "* text eol=crlf\n"],
|
||||
[".gitattributes", ".claude/** working-tree-encoding=UTF-16\n"],
|
||||
[".gitattributes", "* ident\n"],
|
||||
[".claude/hooks/.gitattributes", "*.sh text eol=crlf\n"],
|
||||
])("ignores the PR's %s: %j", (path, attributes) => {
|
||||
setupBase({ [HOOK]: SCRIPT });
|
||||
commitAttributes(path, attributes);
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expectBaseFiles();
|
||||
// The PR's own file is as it was, apart from restored directories.
|
||||
expect(git(["show", `:${path}`])).toBe(attributes);
|
||||
expect(existsRepoFile(path)).toBe(!path.startsWith(".claude/"));
|
||||
});
|
||||
|
||||
test("ignores attributes that are only in the index or on disk", () => {
|
||||
setupBase({ [HOOK]: SCRIPT });
|
||||
commitAttributes(".gitattributes", "* text eol=crlf\n");
|
||||
rmSync(join(repoDir, ".gitattributes"));
|
||||
restoreConfigFromBase("main");
|
||||
expectBaseFiles();
|
||||
|
||||
git(["rm", "--cached", ".gitattributes"]);
|
||||
git(["commit", "-m", "remove attributes"]);
|
||||
writeRepoFile(".gitattributes", "* text eol=crlf\n");
|
||||
restoreConfigFromBase("main");
|
||||
expectBaseFiles();
|
||||
});
|
||||
|
||||
test("uses the base branch's attributes and filters", () => {
|
||||
git(["config", "filter.upper.smudge", "tr a-z A-Z"]);
|
||||
setupBase({
|
||||
[HOOK]: SCRIPT,
|
||||
".gitattributes": "CLAUDE.md filter=upper\n",
|
||||
});
|
||||
commitAttributes(
|
||||
".gitattributes",
|
||||
"CLAUDE.md filter=upper text eol=crlf\n",
|
||||
);
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile("CLAUDE.md")).toBe("BASE CLAUDE INSTRUCTIONS\n");
|
||||
expect(readRepoFile(HOOK)).toBe(SCRIPT);
|
||||
});
|
||||
|
||||
test("works in a subdirectory of the repository", () => {
|
||||
setupBase({ [HOOK]: SCRIPT, [`app/${HOOK}`]: SCRIPT });
|
||||
commitAttributes(".gitattributes", "* text eol=crlf\n");
|
||||
process.chdir(join(repoDir, "app"));
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile(`app/${HOOK}`)).toBe(SCRIPT);
|
||||
expect(readRepoFile(".gitattributes")).toBe("* text eol=crlf\n");
|
||||
expect(existsRepoFile("app/.gitattributes")).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps a .gitattributes that a sparse checkout leaves out", () => {
|
||||
setupBase({ [HOOK]: SCRIPT });
|
||||
commitAttributes(".gitattributes", "* text eol=crlf\n");
|
||||
git(["sparse-checkout", "set", "--no-cone", "/.claude/", "/CLAUDE.md"]);
|
||||
expect(git(["ls-files", "-t", ".gitattributes"])).toStartWith("S ");
|
||||
git(["checkout", "--", "."]);
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile(HOOK)).toBe(SCRIPT);
|
||||
expect(existsRepoFile(".gitattributes")).toBe(false);
|
||||
expect(git(["ls-files", "-t", ".gitattributes"])).toStartWith("S ");
|
||||
});
|
||||
|
||||
describe("when a filter changes the base branch's config", () => {
|
||||
const SECRET = ".claude/é secret.md";
|
||||
|
||||
beforeEach(() => {
|
||||
git(["config", "filter.rot.smudge", "tr n-za-m a-z"]);
|
||||
git(["config", "filter.rot.clean", "tr a-z n-za-m"]);
|
||||
});
|
||||
|
||||
function setupFilter(filter = "rot"): void {
|
||||
setupBase({
|
||||
[HOOK]: SCRIPT,
|
||||
".gitattributes": `.claude/*.md filter=${filter}\n`,
|
||||
[SECRET]: "plain text\n",
|
||||
});
|
||||
}
|
||||
|
||||
test.each([
|
||||
[".gitattributes", "# none\n"],
|
||||
[".gitattributes", ".claude/*.md filter=other\n"],
|
||||
[".claude/.gitattributes", "*.md -filter\n"],
|
||||
])("stops if the PR drops it in %s: %j", (path, attributes) => {
|
||||
setupFilter();
|
||||
commitAttributes(path, attributes);
|
||||
|
||||
expect(() => restoreConfigFromBase("main")).toThrow(
|
||||
"Use the same filters for these files as main",
|
||||
);
|
||||
|
||||
expect(existsRepoFile(SECRET)).toBe(false);
|
||||
expect(git(["diff", "--cached", "--name-only"])).toBe("");
|
||||
expect(git(["show", `:${path}`])).toBe(attributes);
|
||||
});
|
||||
|
||||
test("stops if the PR has the filter only in a file that is removed", () => {
|
||||
setupFilter();
|
||||
writeRepoFile(".gitattributes", "# none\n");
|
||||
writeRepoFile(".claude/.gitattributes", "*.md filter=rot\n");
|
||||
git(["add", ".gitattributes", ".claude/.gitattributes"]);
|
||||
git(["commit", "-m", "pr moves the filter"]);
|
||||
|
||||
expect(() => restoreConfigFromBase("main")).toThrow(
|
||||
"Use the same filters for these files as main",
|
||||
);
|
||||
|
||||
expect(existsRepoFile(SECRET)).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves nothing behind if another step fails", () => {
|
||||
setupFilter();
|
||||
writeRepoFile("CLAUDE.md", "pr\n");
|
||||
git(["commit", "-am", "pr changes CLAUDE.md"]);
|
||||
commitAttributes(".claude/hooks/.gitattributes", "*.sh -text\n");
|
||||
commitAttributes(".gitattributes", "CLAUDE.md filter=strict\n");
|
||||
// This accepts only the PR's version, so git reset fails on the restored one.
|
||||
git(["config", "filter.strict.clean", "grep pr"]);
|
||||
git(["config", "filter.strict.required", "true"]);
|
||||
|
||||
expect(() => restoreConfigFromBase("main")).toThrow(
|
||||
"Could not put the pull request's index entries back",
|
||||
);
|
||||
|
||||
expect(existsRepoFile(SECRET)).toBe(false);
|
||||
});
|
||||
|
||||
test("goes on if a sparse checkout leaves out the same attributes", () => {
|
||||
setupFilter();
|
||||
git(["sparse-checkout", "set", "--no-cone", "/.claude/", "/src/"]);
|
||||
expect(git(["ls-files", "-t", ".gitattributes"])).toStartWith("S ");
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
git(["add", "-A"]);
|
||||
|
||||
expect(readRepoFile(SECRET)).toBe("plain text\n");
|
||||
expect(git(["show", `:${SECRET}`])).toBe("cynva grkg\n");
|
||||
});
|
||||
|
||||
test("goes on if the filter doesn't change files", () => {
|
||||
git(["config", "filter.same.smudge", "cat"]);
|
||||
setupFilter("same text eol=crlf");
|
||||
commitAttributes(".gitattributes", "*.md text eol=crlf\n");
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile(SECRET)).toBe("plain text\r\n");
|
||||
});
|
||||
|
||||
test("goes on if only line endings differ", () => {
|
||||
setupFilter("missing text eol=crlf");
|
||||
commitAttributes(".gitattributes", "*.md text eol=crlf\n");
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile(SECRET)).toBe("plain text\r\n");
|
||||
});
|
||||
|
||||
test("commits it filtered if the PR keeps the filter", () => {
|
||||
setupFilter();
|
||||
commitAttributes(
|
||||
".gitattributes",
|
||||
"*.png binary\n.claude/*.md filter=rot\n",
|
||||
);
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
expect(readRepoFile(SECRET)).toBe("plain text\n");
|
||||
git(["add", "-A"]);
|
||||
|
||||
expect(git(["diff", "--cached", "--name-only"])).toBe("");
|
||||
expect(git(["show", `:${SECRET}`])).toBe("cynva grkg\n");
|
||||
});
|
||||
|
||||
test("goes on if the filter isn't configured or the PR adds one", () => {
|
||||
setupFilter("missing");
|
||||
commitAttributes(".gitattributes", "CLAUDE.md filter=rot\n");
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile(SECRET)).toBe("plain text\n");
|
||||
expect(readRepoFile("CLAUDE.md")).toBe("base claude instructions\n");
|
||||
});
|
||||
});
|
||||
|
||||
test("stops if it can't put the PR's index entries back", () => {
|
||||
setupBase({
|
||||
[HOOK]: SCRIPT,
|
||||
".gitattributes": "CLAUDE.md filter=strict\n",
|
||||
});
|
||||
commitAttributes(".claude/hooks/.gitattributes", "*.sh text eol=crlf\n");
|
||||
writeRepoFile("CLAUDE.md", "pr\n");
|
||||
git(["commit", "-am", "pr changes CLAUDE.md"]);
|
||||
// This accepts only the PR's version, so git reset fails on the restored one.
|
||||
git(["config", "filter.strict.smudge", "cat"]);
|
||||
git(["config", "filter.strict.clean", "grep pr"]);
|
||||
git(["config", "filter.strict.required", "true"]);
|
||||
|
||||
expect(() => restoreConfigFromBase("main")).toThrow(
|
||||
"Could not put the pull request's index entries back",
|
||||
);
|
||||
});
|
||||
|
||||
test("works in a subdirectory that starts with a dash", () => {
|
||||
setupBase({ [HOOK]: SCRIPT, [`-app/${HOOK}`]: SCRIPT });
|
||||
commitAttributes(".gitattributes", "* text eol=crlf\n");
|
||||
process.chdir(join(repoDir, "-app"));
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(readRepoFile(`-app/${HOOK}`)).toBe(SCRIPT);
|
||||
});
|
||||
|
||||
test("puts a link back and doesn't write through it", () => {
|
||||
setupBase({ [HOOK]: SCRIPT, ".gitattributes": "*.png binary\n" });
|
||||
const target = writeOutsideFile("attributes", "* text eol=crlf\n");
|
||||
rmSync(join(repoDir, ".gitattributes"));
|
||||
symlinkRepoFile(".gitattributes", target);
|
||||
git(["add", ".gitattributes"]);
|
||||
git(["commit", "-m", "pr link"]);
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expectBaseFiles();
|
||||
expect(lstatRepoFile(".gitattributes").isSymbolicLink()).toBe(true);
|
||||
expect(readFileSync(target, "utf8")).toBe("* text eol=crlf\n");
|
||||
});
|
||||
});
|
||||
|
||||
function git(args: string[]): string {
|
||||
return execFileSync("git", args, {
|
||||
cwd: repoDir,
|
||||
|
||||
Reference in New Issue
Block a user