Open History to see the last commit
1/**
2 * A linked git worktree gets its own (gitignored) `.t3`: feature work in a
3 * throwaway branch must not share a database with the real app, and an ambient
4 * `T3CODE_HOME` counts as an explicit base dir — flipping the state directory
5 * from `<base>/dev` to `<base>/userdata`, the live production database.
6 */
7
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12
13/**
14 * The common dir is not necessarily named `.git`: a worktree of a bare repo
15 * points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be
16 * anything. So match on the `worktrees/<name>` tail, which git always uses,
17 * rather than on the name of the directory containing it.
18 */
19const pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {
20 const gitdir = gitFileContents
21 .split(/\r?\n/)
22 .map((line) => line.trim())
23 .find((line) => line.startsWith("gitdir:"))
24 ?.slice("gitdir:".length)
25 .trim();
26 if (gitdir === undefined || gitdir.length === 0) {
27 return false;
28 }
29 const segments = path
30 .normalize(gitdir.replaceAll("\\", "/"))
31 .split(/[/\\]/)
32 .filter((segment) => segment.length > 0);
33 return segments.length >= 3 && segments.at(-2) === "worktrees";
34};
35
36export const resolveGitWorktreePath = (
37 cwd: string,
38): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
39 Effect.gen(function* () {
40 const fileSystem = yield* FileSystem.FileSystem;
41 const path = yield* Path.Path;
42
43 let directory = path.resolve(cwd);
44 for (;;) {
45 const gitPath = path.join(directory, ".git");
46 const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
47 if (Option.isSome(info)) {
48 if (info.value.type !== "File") {
49 return undefined;
50 }
51 const contents = yield* fileSystem
52 .readFileString(gitPath)
53 .pipe(Effect.orElseSucceed(() => ""));
54 return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
55 }
56 const parent = path.dirname(directory);
57 if (parent === directory) {
58 return undefined;
59 }
60 directory = parent;
61 }
62 });
63
64/**
65 * Deliberately does not require the directory to exist yet: falling back
66 * because it is missing would send callers at the shared home.
67 */
68export const resolveWorktreeT3Home = (
69 cwd: string,
70): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>
71 Effect.gen(function* () {
72 const worktreePath = yield* resolveGitWorktreePath(cwd);
73 if (worktreePath === undefined) {
74 return undefined;
75 }
76 const path = yield* Path.Path;
77 return path.join(worktreePath, ".t3");
78 });