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 const repository = yield* driver.detectRepository(cwd);
89 if (!repository) {
90 return null;
91 }
92 return {
93 kind,
94 repository,
95 driver,
96 } satisfies VcsDriverHandle;
97 });
98
99 const detectResolvedKind = Effect.fn("VcsDriverRegistry.detectResolvedKind")(function* (input: {
100 readonly cwd: string;
101 readonly requestedKind: VcsDriverKind | "auto";
102 }) {
103 const requestedKind = input.requestedKind;
104
105 if (requestedKind !== "auto" && requestedKind !== "unknown") {
106 const driver = yield* get(requestedKind);
107 return yield* detectWithDriver(requestedKind, driver, input.cwd);
108 }
109
110 return yield* detectWithDriver("git", git, input.cwd);
111 });
112
113 // Symlinks can put cwd outside root; then inspect cwd alone.
114 const foldersBelowRoot = (cwd: string, rootPath: string) => {
115 const relative = path.relative(path.resolve(rootPath), path.resolve(cwd));
116 if (relative.startsWith("..") || path.isAbsolute(relative)) return [cwd];
117 return Array.from({ length: relative.split(path.sep).length }, (_, levelsUp) =>
118 path.resolve(cwd, ...Array<string>(levelsUp).fill("..")),
119 );
120 };
121
122 const readDiskState = (cwd: string, repository: VcsRepositoryIdentity) =>
123 Effect.all({
124 gitEntries: Effect.forEach(foldersBelowRoot(cwd, repository.rootPath), (folder) =>
125 fileSystem.exists(path.join(folder, ".git")),
126 ),
127 repositoryOnDisk: Effect.forEach(
128 repository.metadataPath === null
129 ? [cwd]
130 : [cwd, path.resolve(cwd, repository.metadataPath)],
131 (target) => fileSystem.exists(target),
132 ).pipe(Effect.map((results) => results.every(Boolean))),
133 }).pipe(Effect.orElseSucceed(() => null));
134
135 const detectionCache = yield* Cache.makeWith<
136 string,
137 { readonly handle: VcsDriverHandle; readonly gitEntries: ReadonlyArray<boolean> } | null,
138 VcsError
139 >(
140 (key) =>
141 Effect.gen(function* () {
142 const input = parseDetectionCacheKey(key);
143 const handle = yield* detectResolvedKind(input);
144 if (handle === null) return null;
145 const disk = yield* readDiskState(input.cwd, handle.repository);
146 return { handle, gitEntries: disk?.gitEntries ?? [] };
147 }),
148 {
149 capacity: DETECTION_CACHE_CAPACITY,
150 timeToLive: Exit.match({
151 onSuccess: (detected) => (detected === null ? Duration.zero : DETECTION_CACHE_TTL),
152 onFailure: () => Duration.zero,
153 }),
154 },
155 );
156
157 const detect: VcsDriverRegistry["Service"]["detect"] = Effect.fn("VcsDriverRegistry.detect")(
158 function* (input) {
159 const requestedKind = yield* projectConfig.resolveKind(input);
160 const key = detectionCacheKey({ cwd: input.cwd, requestedKind });
161 const cached = yield* Cache.get(detectionCache, key);
162 if (cached === null) return null;
163 const disk = yield* readDiskState(input.cwd, cached.handle.repository);
164 if (
165 disk?.repositoryOnDisk &&
166 disk.gitEntries.length === cached.gitEntries.length &&
167 disk.gitEntries.every((exists, index) => exists === cached.gitEntries[index])
168 ) {
169 return cached.handle;
170 }
171 yield* Cache.invalidate(detectionCache, key);
172 return (yield* Cache.get(detectionCache, key))?.handle ?? null;
173 },
174 );
175
176 const resolve: VcsDriverRegistry["Service"]["resolve"] = Effect.fn("VcsDriverRegistry.resolve")(
177 function* (input) {
178 const detected = yield* detect(input);
179 if (detected) {
180 return detected;
181 }
182
183 const requestedKind = input.requestedKind ?? "auto";
184 return yield* new VcsUnsupportedOperationError({
185 operation: "VcsDriverRegistry.resolve",
186 kind: requestedKind === "auto" ? "unknown" : requestedKind,
187 detail:
188 requestedKind === "auto"
189 ? `No supported VCS repository was detected at ${input.cwd}.`
190 : `No ${requestedKind} repository was detected at ${input.cwd}.`,
191 });
192 },
193 );
194
195 return VcsDriverRegistry.of({
196 get,
197 detect,
198 resolve,
199 });
200});
201
202export const layer = Layer.effect(VcsDriverRegistry, make).pipe(
203 Layer.provide(VcsProjectConfig.layer),
204);