Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9
10import type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from "@t3tools/contracts";
11import { VcsUnsupportedOperationError } from "@t3tools/contracts";
12import * as GitVcsDriver from "./GitVcsDriver.ts";
13import * as VcsProjectConfig from "./VcsProjectConfig.ts";
14import * as VcsDriver from "./VcsDriver.ts";
15
16const DETECTION_CACHE_CAPACITY = 2_048;
17// Detection costs three git processes per cwd; cached hits still stat disk, so TTL bounds only undetectable changes.
18const DETECTION_CACHE_TTL = Duration.minutes(5);
19
20export interface VcsDriverResolveInput {
21 readonly cwd: string;
22 readonly requestedKind?: VcsDriverKind | "auto";
23}
24
25export interface VcsDriverHandle {
26 readonly kind: VcsDriverKind;
27 readonly repository: VcsRepositoryIdentity;
28 readonly driver: VcsDriver.VcsDriver["Service"];
29}
30
31export class VcsDriverRegistry extends Context.Service<
32 VcsDriverRegistry,
33 {
34 readonly get: (kind: VcsDriverKind) => Effect.Effect<VcsDriver.VcsDriver["Service"], VcsError>;
35 readonly detect: (
36 input: VcsDriverResolveInput,
37 ) => Effect.Effect<VcsDriverHandle | null, VcsError>;
38 readonly resolve: (input: VcsDriverResolveInput) => Effect.Effect<VcsDriverHandle, VcsError>;
39 }
40>()("t3/vcs/VcsDriverRegistry") {}
41
42function detectionCacheKey(input: {
43 readonly cwd: string;
44 readonly requestedKind: VcsDriverKind | "auto";
45}): string {
46 return `${input.requestedKind}\0${input.cwd}`;
47}
48
49function parseDetectionCacheKey(key: string): {
50 readonly cwd: string;
51 readonly requestedKind: VcsDriverKind | "auto";
52} {
53 const separatorIndex = key.indexOf("\0");
54 return {
55 requestedKind: key.slice(0, separatorIndex) as VcsDriverKind | "auto",
56 cwd: key.slice(separatorIndex + 1),
57 };
58}
59
60export const make = Effect.gen(function* () {
61 const fileSystem = yield* FileSystem.FileSystem;
62 const path = yield* Path.Path;
63 const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
64 const git = yield* GitVcsDriver.makeVcsDriver;
65 const drivers: Partial<Record<VcsDriverKind, VcsDriver.VcsDriver["Service"]>> = {
66 git,
67 };
68
69 const get: VcsDriverRegistry["Service"]["get"] = (kind) => {
70 const driver = drivers[kind];
71 if (!driver) {
72 return Effect.fail(
73 new VcsUnsupportedOperationError({
74 operation: "VcsDriverRegistry.get",
75 kind,
76 detail: `No ${kind} VCS driver is registered.`,
77 }),
78 );
79 }
80 return Effect.succeed(driver);
81 };
82
83 const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
84 kind: VcsDriverKind,
85 driver: VcsDriver.VcsDriver["Service"],
86 cwd: string,
87 ) {
88 // Status, review and source control show a repository Git cannot read as none at all.
89 // Checkpoints need the failure, so CheckpointStore asks the driver directly.
90 const repository = yield* driver.detectRepository(cwd).pipe(
91 Effect.catchTags({
92 VcsProcessExitError: (error) =>
93 error.operation === GitVcsDriver.WORK_TREE_PROBE_OPERATION
94 ? Effect.succeed(null)
95 : Effect.fail(error),
96 }),
97 );
98 if (!repository) {
99 return null;
100 }
101 return {
102 kind,
103 repository,
104 driver,
105 } satisfies VcsDriverHandle;
106 });
107
108 const detectResolvedKind = Effect.fn("VcsDriverRegistry.detectResolvedKind")(function* (input: {
109 readonly cwd: string;
110 readonly requestedKind: VcsDriverKind | "auto";
111 }) {
112 const requestedKind = input.requestedKind;
113
114 if (requestedKind !== "auto" && requestedKind !== "unknown") {
115 const driver = yield* get(requestedKind);
116 return yield* detectWithDriver(requestedKind, driver, input.cwd);
117 }
118
119 return yield* detectWithDriver("git", git, input.cwd);
120 });
121
122 // Symlinks can put cwd outside root; then inspect cwd alone.
123 const foldersBelowRoot = (cwd: string, rootPath: string) => {
124 const relative = path.relative(path.resolve(rootPath), path.resolve(cwd));
125 if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
126 return [cwd];
127 }
128 return Array.from({ length: relative.split(path.sep).length }, (_, levelsUp) =>
129 path.resolve(cwd, ...Array<string>(levelsUp).fill("..")),
130 );
131 };
132
133 const readDiskState = (cwd: string, repository: VcsRepositoryIdentity) =>
134 Effect.all({
135 gitEntries: Effect.forEach(foldersBelowRoot(cwd, repository.rootPath), (folder) =>
136 fileSystem.exists(path.join(folder, ".git")),
137 ),
138 repositoryOnDisk: Effect.forEach(
139 repository.metadataPath === null
140 ? [cwd]
141 : [cwd, path.resolve(cwd, repository.metadataPath)],
142 (target) => fileSystem.exists(target),
143 ).pipe(Effect.map((results) => results.every(Boolean))),
144 }).pipe(Effect.orElseSucceed(() => null));
145
146 const detectionCache = yield* Cache.makeWith<
147 string,
148 { readonly handle: VcsDriverHandle; readonly gitEntries: ReadonlyArray<boolean> } | null,
149 VcsError
150 >(
151 (key) =>
152 Effect.gen(function* () {
153 const input = parseDetectionCacheKey(key);
154 const handle = yield* detectResolvedKind(input);
155 if (handle === null) return null;
156 const disk = yield* readDiskState(input.cwd, handle.repository);
157 return { handle, gitEntries: disk?.gitEntries ?? [] };
158 }),
159 {
160 capacity: DETECTION_CACHE_CAPACITY,
161 timeToLive: Exit.match({
162 onSuccess: (detected) => (detected === null ? Duration.zero : DETECTION_CACHE_TTL),
163 onFailure: () => Duration.zero,
164 }),
165 },
166 );
167
168 const detect: VcsDriverRegistry["Service"]["detect"] = Effect.fn("VcsDriverRegistry.detect")(
169 function* (input) {
170 const requestedKind = yield* projectConfig.resolveKind(input);
171 const key = detectionCacheKey({ cwd: input.cwd, requestedKind });
172 const cached = yield* Cache.get(detectionCache, key);
173 if (cached === null) return null;
174 const disk = yield* readDiskState(input.cwd, cached.handle.repository);
175 if (
176 disk?.repositoryOnDisk &&
177 disk.gitEntries.length === cached.gitEntries.length &&
178 disk.gitEntries.every((exists, index) => exists === cached.gitEntries[index])
179 ) {
180 return cached.handle;
181 }
182 yield* Cache.invalidate(detectionCache, key);
183 return (yield* Cache.get(detectionCache, key))?.handle ?? null;
184 },
185 );
186
187 const resolve: VcsDriverRegistry["Service"]["resolve"] = Effect.fn("VcsDriverRegistry.resolve")(
188 function* (input) {
189 const detected = yield* detect(input);
190 if (detected) {
191 return detected;
192 }
193
194 const requestedKind = input.requestedKind ?? "auto";
195 return yield* new VcsUnsupportedOperationError({
196 operation: "VcsDriverRegistry.resolve",
197 kind: requestedKind === "auto" ? "unknown" : requestedKind,
198 detail:
199 requestedKind === "auto"
200 ? `No supported VCS repository was detected at ${input.cwd}.`
201 : `No ${requestedKind} repository was detected at ${input.cwd}.`,
202 });
203 },
204 );
205
206 return VcsDriverRegistry.of({
207 get,
208 detect,
209 resolve,
210 });
211});
212
213export const layer = Layer.effect(VcsDriverRegistry, make).pipe(
214 Layer.provide(VcsProjectConfig.layer),
215);