@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 95 lines 4.01 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5
6 import * as ProcessRunner from "../processRunner.ts";
7 import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts";
8
9 const parseGitfileTarget = (contents: string): string | undefined => {
10 const firstLine = contents.split(/\r?\n/u, 1)[0] ?? "";
11 if (!firstLine.startsWith("gitdir:")) return undefined;
12 const target = firstLine.slice("gitdir:".length).trim();
13 return target === "" ? undefined : target;
14 };
15
16 const splitNul = (stdout: string) => stdout.split("\0").filter((entry) => entry !== "");
17
18 /**
19 * Whether a folder only holds a repository's metadata and worktrees: its `.git` file points at
20 * metadata inside it, a linked worktree lives inside it, and either the repository is bare or it
21 * has commits but no index. A checkout whose tracked files are all deleted keeps its index, and a
22 * fresh one has no commit. Anything this cannot establish answers false.
23 */
24 export const makeIsWorktreeContainer = Effect.gen(function* () {
25 const fileSystem = yield* FileSystem.FileSystem;
26 const path = yield* Path.Path;
27 const processRunner = yield* ProcessRunner.ProcessRunner;
28 const platform = yield* HostProcess.Platform;
29 const env = {
30 ...unsetInheritedRepositoryEnv(process.env, platform),
31 ...explicitBareRepositoryEnv(process.env, platform),
32 };
33
34 const realPath = (target: string) => fileSystem.realPath(target).pipe(Effect.option);
35 const isInside = (parent: string, child: string) => {
36 const relative = path.relative(parent, child);
37 return (
38 relative !== "" &&
39 relative !== ".." &&
40 !relative.startsWith(`..${path.sep}`) &&
41 !path.isAbsolute(relative)
42 );
43 };
44
45 return Effect.fn("ProjectService.isWorktreeContainer")(function* (workspaceRoot: string) {
46 // A `.git` directory is an ordinary checkout, so only a gitfile costs any Git process.
47 const gitfileTarget = yield* fileSystem.readFileString(path.join(workspaceRoot, ".git")).pipe(
48 Effect.map(parseGitfileTarget),
49 Effect.orElseSucceed(() => undefined),
50 );
51 if (gitfileTarget === undefined) return false;
52 const root = yield* realPath(workspaceRoot);
53 const gitDir = yield* realPath(path.resolve(workspaceRoot, gitfileTarget));
54 if (root._tag === "None" || gitDir._tag === "None") return false;
55 if (!isInside(root.value, gitDir.value)) return false;
56
57 const git = (args: ReadonlyArray<string>) =>
58 processRunner
59 .run({
60 command: "git",
61 args: ["-C", workspaceRoot, ...args],
62 env,
63 timeoutBehavior: "timedOutResult",
64 })
65 .pipe(
66 Effect.map((result) => (result.code === 0 && !result.timedOut ? result.stdout : null)),
67 Effect.orElseSucceed(() => null),
68 );
69
70 // Initializing Git in a bare container clears core.bare, so it is refused while still bare.
71 const isBare = yield* git(["rev-parse", "--is-bare-repository"]);
72 if (isBare === null) return false;
73 if (isBare.trim() !== "true") {
74 const hasCommit = yield* git(["rev-parse", "--quiet", "--verify", "HEAD^{commit}"]);
75 if (hasCommit === null) return false;
76 const hasIndex = yield* fileSystem
77 .exists(path.join(gitDir.value, "index"))
78 .pipe(Effect.orElseSucceed(() => true));
79 if (hasIndex) return false;
80 }
81
82 const worktrees = yield* git(["worktree", "list", "--porcelain", "-z"]);
83 if (worktrees === null) return false;
84 // The first entry is the main worktree, which Git reports as the metadata directory here.
85 const linkedWorktreePaths = splitNul(worktrees)
86 .filter((field) => field.startsWith("worktree "))
87 .slice(1)
88 .map((field) => field.slice("worktree ".length));
89 for (const worktreePath of linkedWorktreePaths) {
90 const worktree = yield* realPath(worktreePath);
91 if (worktree._tag === "Some" && isInside(root.value, worktree.value)) return true;
92 }
93 return false;
94 });
95 });