Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

devHome.ts

76 lines2.7 KB

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 = Effect.fn("devHome.resolveGitWorktreePath")(function* (
37 cwd: string,
38): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
39 const fileSystem = yield* FileSystem.FileSystem;
40 const path = yield* Path.Path;
41​
42 let directory = path.resolve(cwd);
43 for (;;) {
44 const gitPath = path.join(directory, ".git");
45 const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);
46 if (Option.isSome(info)) {
47 if (info.value.type !== "File") {
48 return undefined;
49 }
50 const contents = yield* fileSystem
51 .readFileString(gitPath)
52 .pipe(Effect.orElseSucceed(() => ""));
53 return pointsAtLinkedWorktree(contents, path) ? directory : undefined;
54 }
55 const parent = path.dirname(directory);
56 if (parent === directory) {
57 return undefined;
58 }
59 directory = parent;
60 }
61});
62​
63/**
64 * Deliberately does not require the directory to exist yet: falling back
65 * because it is missing would send callers at the shared home.
66 */
67export const resolveWorktreeT3Home = Effect.fn("devHome.resolveWorktreeT3Home")(function* (
68 cwd: string,
69): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
70 const worktreePath = yield* resolveGitWorktreePath(cwd);
71 if (worktreePath === undefined) {
72 return undefined;
73 }
74 const path = yield* Path.Path;
75 return path.join(worktreePath, ".t3");
76});