Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 171 additions & 1 deletion site/scripts/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
import { describe, expect, test } from "bun:test";
import { afterEach, describe, expect, test } from "bun:test";
import { execFile } from "node:child_process";
import {
mkdir,
mkdtemp,
readFile,
rm,
stat,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import {
buildCloneArgs,
buildGitEnvironment,
fetchSources,
isSource,
parsePins,
sparsePatterns,
Expand Down Expand Up @@ -88,3 +102,159 @@ describe("source fetch command construction", () => {
).toBe(true);
});
});

const REPO = "RigelBuild/tool";
const execFileAsync = promisify(execFile);
const cleanups: string[] = [];

afterEach(async () => {
await Promise.all(
cleanups
.splice(0)
.map((path) => rm(path, { recursive: true, force: true })),
);
});

interface Remote {
baseUrl: string;
first: string;
second: string;
side: string;
}

async function git(args: readonly string[], cwd: string): Promise<string> {
const { stdout } = await execFileAsync("git", [...args], {
cwd,
env: {
...buildGitEnvironment(),
GIT_AUTHOR_NAME: "Fetch Test",
GIT_AUTHOR_EMAIL: "fetch-test@example.invalid",
GIT_COMMITTER_NAME: "Fetch Test",
GIT_COMMITTER_EMAIL: "fetch-test@example.invalid",
},
encoding: "utf8",
});
return stdout.trim();
}

async function commitAll(cwd: string, message: string): Promise<void> {
await git(["add", "--all"], cwd);
await git(["commit", "--quiet", "-m", message], cwd);
}

// Builds RigelBuild/tool.git under a temp dir: main has two commits, and
// `side` branches off the first commit, so its SHA is not on main.
async function makeRemote(): Promise<Remote> {
const base = await mkdtemp(join(tmpdir(), "fetch-test-"));
cleanups.push(base);
const bare = join(base, "RigelBuild", "tool.git");
const scratch = join(base, "scratch");
await mkdir(join(base, "RigelBuild"), { recursive: true });
await git(["init", "--quiet", "--bare", bare], base);
await git(["symbolic-ref", "HEAD", "refs/heads/main"], bare);
// Without this the server drops --filter and the blob:none path is untested.
await git(["config", "uploadpack.allowFilter", "true"], bare);

await git(["init", "--quiet", scratch], base);
await git(["symbolic-ref", "HEAD", "refs/heads/main"], scratch);
await git(["remote", "add", "origin", bare], scratch);
await writeFile(join(scratch, "README.md"), "# one\n");
await writeFile(join(scratch, "docs-bundle.toml"), 'name = "tool"\n');
await commitAll(scratch, "first");
const first = await git(["rev-parse", "HEAD"], scratch);
await writeFile(join(scratch, "README.md"), "# two\n");
await commitAll(scratch, "second");
const second = await git(["rev-parse", "HEAD"], scratch);
await git(["checkout", "--quiet", "-b", "side", first], scratch);
await writeFile(join(scratch, "side.md"), "# side\n");
await commitAll(scratch, "side");
const side = await git(["rev-parse", "HEAD"], scratch);
await git(["push", "--quiet", "origin", "main", "side"], scratch);
// Trailing slash: fetch.ts appends `${repo}.git` directly to baseUrl.
return { baseUrl: `${pathToFileURL(base).href}/`, first, second, side };
}

async function fetchTool(
remote: Remote,
pins: ReadonlyMap<string, string>,
production: boolean,
): Promise<string> {
const workDir = await mkdtemp(join(tmpdir(), "fetch-work-"));
cleanups.push(workDir);
await fetchSources({
sources: [{ repo: REPO, mount: "tool", config: "default" }],
workDir,
pins,
production,
baseUrl: remote.baseUrl,
});
return workDir;
}

async function readFetched(workDir: string): Promise<unknown> {
return JSON.parse(await readFile(join(workDir, "fetched.json"), "utf8"));
}

describe("source fetch against a local bare repo", () => {
test("checks out the pinned SHA instead of the branch head", async () => {
const remote = await makeRemote();
const workDir = await fetchTool(
remote,
new Map([[REPO, remote.first]]),
false,
);
expect(
await readFile(join(workDir, "sources", "tool", "README.md"), "utf8"),
).toBe("# one\n");
expect(await readFetched(workDir)).toEqual([
expect.objectContaining({ repo: REPO, sha: remote.first }),
]);
});

test("production rejects a pin that is not an ancestor of main", async () => {
const remote = await makeRemote();
const ancestor = await fetchTool(
remote,
new Map([[REPO, remote.first]]),
true,
);
expect(await readFetched(ancestor)).toEqual([
expect.objectContaining({ sha: remote.first }),
]);

// runGit labels failures with args[0], which is "-C" for this call.
await expect(
fetchTool(remote, new Map([[REPO, remote.side]]), true),
).rejects.toThrow("git -C failed (1)");

// Control: the same side-branch SHA is accepted when production is off.
const dev = await fetchTool(remote, new Map([[REPO, remote.side]]), false);
expect(await readFetched(dev)).toEqual([
expect.objectContaining({ sha: remote.side }),
]);
});

test("removes .git from the fetched tree", async () => {
const remote = await makeRemote();
const workDir = await fetchTool(remote, new Map<string, string>(), false);
const root = join(workDir, "sources", "tool");
expect(await readFile(join(root, "README.md"), "utf8")).toBe("# two\n");
await expect(stat(join(root, ".git"))).rejects.toMatchObject({
code: "ENOENT",
});
});

test("writes fetched.json with repo, sha, and root per source", async () => {
const remote = await makeRemote();
const workDir = await fetchTool(remote, new Map<string, string>(), false);
expect(await readFetched(workDir)).toEqual([
{
repo: REPO,
mount: "tool",
config: "default",
root: join(workDir, "sources", "tool"),
sha: remote.second,
},
]);
});
});
11 changes: 9 additions & 2 deletions site/scripts/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ interface FetchOptions {
workDir: string;
pins: ReadonlyMap<string, string>;
production: boolean;
/** Clone URL prefix ending in "/". Defaults to GitHub. */
baseUrl?: string;
}

const REPO_PATTERN = /^RigelBuild\/[A-Za-z0-9_-][A-Za-z0-9_.-]*$/;
const GITHUB_BASE_URL = "https://github.com/";

const IMAGE_EXTENSIONS = [
"png",
Expand Down Expand Up @@ -70,6 +73,7 @@ export function buildCloneArgs(
repo: string,
destination: string,
pin?: string,
baseUrl = GITHUB_BASE_URL,
): string[] {
const args = [
"-c",
Expand All @@ -81,7 +85,7 @@ export function buildCloneArgs(
"--sparse",
];
if (pin === undefined) args.push("--depth", "1");
args.push(`https://github.com/${repo}.git`, destination);
args.push(`${baseUrl}${repo}.git`, destination);
return args;
}

Expand Down Expand Up @@ -143,12 +147,13 @@ async function fetchSource(
workDir: string,
pin: string | undefined,
production: boolean,
baseUrl: string,
env: NodeJS.ProcessEnv,
): Promise<FetchedSource> {
const root = join(workDir, "sources", basename(source.repo));
await rm(root, { recursive: true, force: true });
await mkdir(join(workDir, "sources"), { recursive: true });
await runGit(buildCloneArgs(source.repo, root, pin), workDir, env);
await runGit(buildCloneArgs(source.repo, root, pin, baseUrl), workDir, env);
await runGit(
["-C", root, "sparse-checkout", "set", "--no-cone", ...sparsePatterns()],
workDir,
Expand Down Expand Up @@ -198,6 +203,7 @@ export async function fetchSources(options: FetchOptions): Promise<void> {
const fetchedPath = join(options.workDir, "fetched.json");
await rm(fetchedPath, { force: true });
const env = buildGitEnvironment();
const baseUrl = options.baseUrl ?? GITHUB_BASE_URL;
for (const repo of options.pins.keys()) {
if (!options.sources.some((source) => source.repo === repo))
throw new Error(`pin does not match a configured source: ${repo}`);
Expand All @@ -210,6 +216,7 @@ export async function fetchSources(options: FetchOptions): Promise<void> {
options.workDir,
options.pins.get(source.repo),
options.production,
baseUrl,
env,
),
);
Expand Down
Loading