2246 lines · 86.3 KB · TypeScript
RawDownload
import { existsSync } from "node:fs";import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices";import { it } from "@effect/vitest";import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";import { describe, expect, vi } from "vitest"; import { GitCoreLive, makeGitCore } from "./GitCore.ts";import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";import { GitCommandError } from "@t3tools/contracts";import { type ProcessRunResult, runProcess } from "../../processRunner.ts";import { ServerConfig } from "../../config.ts"; // ── Helpers ── const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-core-test-" });const GitCoreTestLayer = GitCoreLive.pipe(  Layer.provide(ServerConfigLayer),  Layer.provide(NodeServices.layer),);const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer); function makeTmpDir(  prefix = "git-test-",): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {  return Effect.gen(function* () {    const fileSystem = yield* FileSystem.FileSystem;    return yield* fileSystem.makeTempDirectoryScoped({ prefix });  });} function writeTextFile(  filePath: string,  contents: string,): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {  return Effect.gen(function* () {    const fileSystem = yield* FileSystem.FileSystem;    yield* fileSystem.writeFileString(filePath, contents);  });} /** Run a raw git command for test setup (not under test). */function git(  cwd: string,  args: ReadonlyArray<string>,  env?: NodeJS.ProcessEnv,): Effect.Effect<string, GitCommandError, GitCore> {  return Effect.gen(function* () {    const gitCore = yield* GitCore;    const result = yield* gitCore.execute({      operation: "GitCore.test.git",      cwd,      args,      ...(env ? { env } : {}),      timeoutMs: 10_000,    });    return result.stdout.trim();  });} function configureRemote(  cwd: string,  remoteName: string,  remotePath: string,  fetchNamespace: string,): Effect.Effect<string, GitCommandError, GitCore> {  return Effect.gen(function* () {    yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]);    return yield* git(cwd, [      "config",      "--replace-all",      `remote.${remoteName}.fetch`,      `+refs/heads/*:refs/remotes/${fetchNamespace}/*`,    ]);  });} function runShellCommand(input: {  command: string;  cwd: string;  timeoutMs?: number;  maxOutputBytes?: number;}): Effect.Effect<ProcessRunResult, Error> {  return Effect.promise(() => {    const shellPath =      process.platform === "win32"        ? (process.env.ComSpec ?? "cmd.exe")        : (process.env.SHELL ?? "/bin/sh");     const args =      process.platform === "win32" ? ["/d", "/s", "/c", input.command] : ["-lc", input.command];     return runProcess(shellPath, args, {      cwd: input.cwd,      timeoutMs: input.timeoutMs ?? 30_000,      allowNonZeroExit: true,      maxBufferBytes: input.maxOutputBytes ?? 1_000_000,      outputMode: "truncate",    });  });} const makeIsolatedGitCore = (executeOverride: GitCoreShape["execute"]) =>  makeGitCore({ executeOverride }).pipe(    Effect.provide(Layer.provideMerge(ServerConfigLayer, NodeServices.layer)),  ); /** Create a repo with an initial commit so branches work. */function initRepoWithCommit(  cwd: string,): Effect.Effect<  { initialBranch: string },  GitCommandError | PlatformError.PlatformError,  GitCore | FileSystem.FileSystem> {  return Effect.gen(function* () {    const core = yield* GitCore;    yield* core.initRepo({ cwd });    yield* git(cwd, ["config", "user.email", "test@test.com"]);    yield* git(cwd, ["config", "user.name", "Test"]);    yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");    yield* git(cwd, ["add", "."]);    yield* git(cwd, ["commit", "-m", "initial commit"]);    const initialBranch = yield* git(cwd, ["branch", "--show-current"]);    return { initialBranch };  });} function commitWithDate(  cwd: string,  fileName: string,  fileContents: string,  dateIsoString: string,  message: string,): Effect.Effect<  void,  GitCommandError | PlatformError.PlatformError,  GitCore | FileSystem.FileSystem> {  return Effect.gen(function* () {    yield* writeTextFile(path.join(cwd, fileName), fileContents);    yield* git(cwd, ["add", fileName]);    yield* git(cwd, ["commit", "-m", message], {      ...process.env,      GIT_AUTHOR_DATE: dateIsoString,      GIT_COMMITTER_DATE: dateIsoString,    });  });} function buildLargeText(lineCount = 20_000): string {  return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)    .join("\n")    .concat("\n");} function splitNullSeparatedPaths(input: string): string[] {  return input    .split("\0")    .map((value) => value.trim())    .filter((value) => value.length > 0);} // ── Tests ── it.layer(TestLayer)("git integration", (it) => {  describe("shell process execution", () => {    it.effect("caps captured output when maxOutputBytes is exceeded", () =>      Effect.gen(function* () {        const result = yield* runShellCommand({          command: `node -e "process.stdout.write('x'.repeat(2000))"`,          cwd: process.cwd(),          timeoutMs: 10_000,          maxOutputBytes: 128,        });         expect(result.code).toBe(0);        expect(result.stdout.length).toBeLessThanOrEqual(128);        expect(result.stdoutTruncated || result.stderrTruncated).toBe(true);      }),    );  });   // ── initGitRepo ──   describe("initGitRepo", () => {    it.effect("creates a valid git repo", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        yield* (yield* GitCore).initRepo({ cwd: tmp });        expect(existsSync(path.join(tmp, ".git"))).toBe(true);      }),    );     it.effect("listGitBranches reports isRepo: true after init + commit", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        yield* initRepoWithCommit(tmp);        const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        expect(result.isRepo).toBe(true);        expect(result.hasOriginRemote).toBe(false);        expect(result.branches.length).toBeGreaterThanOrEqual(1);      }),    );  });   describe("workspace helpers", () => {    it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () =>      Effect.gen(function* () {        const cwd = "/virtual/repo";        const relativePaths = Array.from({ length: 340 }, (_, index) => {          const prefix = index % 3 === 0 ? "ignored" : "kept";          return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`;        });        const expectedPaths = relativePaths.filter(          (relativePath) => !relativePath.startsWith("ignored/"),        );         const seenChunks: string[][] = [];        const core = yield* makeIsolatedGitCore((input) => {          if (            input.args.join(" ") !==            "-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"          ) {            return Effect.fail(              new GitCommandError({                operation: input.operation,                command: `git ${input.args.join(" ")}`,                cwd: input.cwd,                detail: "unexpected git command in chunking test",              }),            );          }           const chunkPaths = splitNullSeparatedPaths(input.stdin ?? "");          seenChunks.push(chunkPaths);          const ignoredPaths = chunkPaths.filter((relativePath) =>            relativePath.startsWith("ignored/"),          );           return Effect.succeed({            code: ignoredPaths.length > 0 ? 0 : 1,            stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "",            stderr: "",            stdoutTruncated: false,            stderrTruncated: false,          });        });         const result = yield* core.filterIgnoredPaths(cwd, relativePaths);         expect(seenChunks.length).toBeGreaterThan(1);        expect(seenChunks.flat()).toEqual(relativePaths);        expect(result).toEqual(expectedPaths);      }),    );     it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>      Effect.gen(function* () {        const core = yield* makeIsolatedGitCore((input) => {          expect(input.args).toEqual([            "-c",            "core.fsmonitor=false",            "-c",            "core.untrackedCache=false",            "ls-files",            "--cached",            "--others",            "--exclude-standard",            "-z",          ]);          return Effect.succeed({            code: 0,            stdout: "src/index.ts\0README.md\0",            stderr: "",            stdoutTruncated: false,            stderrTruncated: false,          });        });         const result = yield* core.listWorkspaceFiles("/virtual/repo");        expect(result.paths).toEqual(["src/index.ts", "README.md"]);        expect(result.truncated).toBe(false);      }),    );  });   // ── listGitBranches ──   describe("listGitBranches", () => {    it.effect("returns isRepo: false for non-git directory", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        expect(result.isRepo).toBe(false);        expect(result.hasOriginRemote).toBe(false);        expect(result.branches).toEqual([]);      }),    );     it.effect("returns the current branch with current: true", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        yield* initRepoWithCommit(tmp);        const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        const current = result.branches.find((b) => b.current);        expect(current).toBeDefined();        expect(current!.current).toBe(true);      }),    );     it.effect("does not include detached HEAD pseudo-refs as branches", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        yield* initRepoWithCommit(tmp);        yield* git(tmp, ["checkout", "--detach", "HEAD"]);         const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        expect(result.branches.some((branch) => branch.name.startsWith("("))).toBe(false);        expect(result.branches.some((branch) => branch.current)).toBe(false);      }),    );     it.effect("keeps current branch first and sorts the remaining branches by recency", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        yield* initRepoWithCommit(tmp);        const initialBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(          (branch) => branch.current,        )!.name;         yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "older-branch" });        yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" });        yield* commitWithDate(          tmp,          "older.txt",          "older branch change\n",          "Thu, 1 Jan 2037 00:00:00 +0000",          "older branch change",        );         yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: initialBranch });        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" });        yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" });        yield* commitWithDate(          tmp,          "newer.txt",          "newer branch change\n",          "Fri, 1 Jan 2038 00:00:00 +0000",          "newer branch change",        );         // Switch away to show current branch is pinned, then remaining branches are recency-sorted.        yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "older-branch" });         const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        expect(result.branches[0]!.name).toBe("older-branch");        expect(result.branches[1]!.name).toBe("newer-branch");      }),    );     it.effect("keeps default branch right after current branch", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        const remote = yield* makeTmpDir();        yield* initRepoWithCommit(tmp);        const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: tmp })).branches.find(          (branch) => branch.current,        )!.name;         yield* git(remote, ["init", "--bare"]);        yield* git(tmp, ["remote", "add", "origin", remote]);        yield* git(tmp, ["push", "-u", "origin", defaultBranch]);        yield* git(tmp, ["remote", "set-head", "origin", defaultBranch]);         yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "current-branch" });        yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" });        yield* commitWithDate(          tmp,          "current.txt",          "current change\n",          "Thu, 1 Jan 2037 00:00:00 +0000",          "current change",        );         yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: defaultBranch });        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "newer-branch" });        yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "newer-branch" });        yield* commitWithDate(          tmp,          "newer.txt",          "newer change\n",          "Fri, 1 Jan 2038 00:00:00 +0000",          "newer change",        );         yield* (yield* GitCore).checkoutBranch({ cwd: tmp, branch: "current-branch" });         const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        expect(result.branches[0]!.name).toBe("current-branch");        expect(result.branches[1]!.name).toBe(defaultBranch);        expect(result.branches[2]!.name).toBe("newer-branch");      }),    );     it.effect("lists multiple branches after creating them", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        yield* initRepoWithCommit(tmp);        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });         const result = yield* (yield* GitCore).listBranches({ cwd: tmp });        const names = result.branches.map((b) => b.name);        expect(names).toContain("feature-a");        expect(names).toContain("feature-b");      }),    );     it.effect("paginates branch results and returns paging metadata", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        const { initialBranch } = yield* initRepoWithCommit(tmp);        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });        yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" });         const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 });        expect(firstPage.totalCount).toBe(4);        expect(firstPage.nextCursor).toBe(2);        expect(firstPage.branches.map((branch) => branch.name)).toEqual([          initialBranch,          "feature-a",        ]);         const secondPage = yield* (yield* GitCore).listBranches({          cwd: tmp,          cursor: firstPage.nextCursor ?? 0,          limit: 2,        });        expect(secondPage.totalCount).toBe(4);        expect(secondPage.nextCursor).toBeNull();        expect(secondPage.branches.map((branch) => branch.name)).toEqual([          "feature-b",          "feature-c",        ]);      }),    );     it.effect("parses separate branch names when column.ui is always enabled", () =>      Effect.gen(function* () {        const tmp = yield* makeTmpDir();        const { initialBranch } = yield* initRepoWithCommit(tmp);        const createdBranchNames = [          "go-bin",          "copilot/rewrite-cli-in-go",          "copilot/rewrite-cli-in-rust",        ] as const;        for (const branchName of createdBranchNames) {          yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName });        }        yield* git(tmp, ["config", "column.ui", "always"]);         const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], {          ...process.env,          COLUMNS: "120",        });        expect(          rawBranchOutput            .split("\n")            .some(              (line) =>                createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2,            ),        ).toBe(true);         const realGitCore = yield* GitCore;        const core = yield* makeIsolatedGitCore((input) =>          realGitCore.execute(            input.args[0] === "branch"              ? {                  ...input,                  env: { ...input.env, COLUMNS: "120" },                }              : input,          ),        );         const result = yield* core.listBranches({ cwd: tmp });        const localBranchNames = result.branches          .filter((branch) => !branch.isRemote)          .map((branch) => branch.name);         expect(localBranchNames).toHaveLength(4);        expect(localBranchNames).toEqual(          expect.arrayContaining([initialBranch, ...createdBranchNames]),        );        expect(          localBranchNames.some(

Lines 1–500 of 2246.