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

VcsDriverRegistry.ts

210 lines7.0 KB

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";
24​
25export interface VcsDriverHandle {
26 readonly kind: VcsDriverKind;
27 readonly repository: VcsRepositoryIdentity;
28 readonly driver: VcsDriver.VcsDriver["Service"];
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}`;
48​
49function parseDetectionCacheKey(key: string): {
50 readonly cwd: string;
51 readonly requestedKind: VcsDriverKind | "auto";
52} {
53 const separatorIndex = key.indexOf("\0");
54 if (separatorIndex === -1) {
55 return {
56 cwd: key,
57 requestedKind: "auto",
58 };
59 }
60 return {
61 requestedKind: key.slice(0, separatorIndex) as VcsDriverKind | "auto",
62 cwd: key.slice(separatorIndex + 1),
63 };
65​
66export const make = Effect.gen(function* () {
67 const fileSystem = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;
70 const git = yield* GitVcsDriver.makeVcsDriver;
71 const drivers: Partial<Record<VcsDriverKind, VcsDriver.VcsDriver["Service"]>> = {
72 git,
73 };
74​
75 const get: VcsDriverRegistry["Service"]["get"] = (kind) => {
76 const driver = drivers[kind];
77 if (!driver) {
78 return Effect.fail(
79 new VcsUnsupportedOperationError({
80 operation: "VcsDriverRegistry.get",
81 kind,
82 detail: `No ${kind} VCS driver is registered.`,
83 }),
84 );
85 }
86 return Effect.succeed(driver);
87 };
88​
89 const detectWithDriver = Effect.fn("VcsDriverRegistry.detectWithDriver")(function* (
90 kind: VcsDriverKind,
91 driver: VcsDriver.VcsDriver["Service"],
92 cwd: string,
93 ) {
94 const repository = yield* driver.detectRepository(cwd);
95 if (!repository) {
96 return null;
97 }
98 return {
99 kind,
100 repository,
101 driver,
102 } satisfies VcsDriverHandle;
103 });
104​
105 const detectResolvedKind = Effect.fn("VcsDriverRegistry.detectResolvedKind")(function* (input: {
106 readonly cwd: string;
107 readonly requestedKind: VcsDriverKind | "auto";
108 }) {
109 const requestedKind = input.requestedKind;
110​
111 if (requestedKind !== "auto" && requestedKind !== "unknown") {
112 const driver = yield* get(requestedKind);
113 return yield* detectWithDriver(requestedKind, driver, input.cwd);
114 }
115​
116 return yield* detectWithDriver("git", git, input.cwd);
117 });
118​
119 // Symlinks can put cwd outside root; then inspect cwd alone.
120 const foldersBelowRoot = (cwd: string, rootPath: string) => {
121 const relative = path.relative(path.resolve(rootPath), path.resolve(cwd));
122 if (relative.startsWith("..") || path.isAbsolute(relative)) return [cwd];
123 return Array.from({ length: relative.split(path.sep).length }, (_, levelsUp) =>
124 path.resolve(cwd, ...Array<string>(levelsUp).fill("..")),
125 );
126 };
127​
128 const readDiskState = (cwd: string, repository: VcsRepositoryIdentity) =>
129 Effect.all({
130 gitEntries: Effect.forEach(foldersBelowRoot(cwd, repository.rootPath), (folder) =>
131 fileSystem.exists(path.join(folder, ".git")),
132 ),
133 repositoryOnDisk: Effect.forEach(
134 repository.metadataPath === null
135 ? [cwd]
136 : [cwd, path.resolve(cwd, repository.metadataPath)],
137 (target) => fileSystem.exists(target),
138 ).pipe(Effect.map((results) => results.every(Boolean))),
139 }).pipe(Effect.orElseSucceed(() => null));
140​
141 const detectionCache = yield* Cache.makeWith<
142 string,
143 { readonly handle: VcsDriverHandle; readonly gitEntries: ReadonlyArray<boolean> } | null,
144 VcsError
145 >(
146 (key) =>
147 Effect.gen(function* () {
148 const input = parseDetectionCacheKey(key);
149 const handle = yield* detectResolvedKind(input);
150 if (handle === null) return null;
151 const disk = yield* readDiskState(input.cwd, handle.repository);
152 return { handle, gitEntries: disk?.gitEntries ?? [] };
153 }),
154 {
155 capacity: DETECTION_CACHE_CAPACITY,
156 timeToLive: Exit.match({
157 onSuccess: (detected) => (detected === null ? Duration.zero : DETECTION_CACHE_TTL),
158 onFailure: () => Duration.zero,
159 }),
160 },
161 );
162​
163 const detect: VcsDriverRegistry["Service"]["detect"] = Effect.fn("VcsDriverRegistry.detect")(
164 function* (input) {
165 const requestedKind = yield* projectConfig.resolveKind(input);
166 const key = detectionCacheKey({ cwd: input.cwd, requestedKind });
167 const cached = yield* Cache.get(detectionCache, key);
168 if (cached === null) return null;
169 const disk = yield* readDiskState(input.cwd, cached.handle.repository);
170 if (
171 disk?.repositoryOnDisk &&
172 disk.gitEntries.length === cached.gitEntries.length &&
173 disk.gitEntries.every((exists, index) => exists === cached.gitEntries[index])
174 ) {
175 return cached.handle;
176 }
177 yield* Cache.invalidate(detectionCache, key);
178 return (yield* Cache.get(detectionCache, key))?.handle ?? null;
179 },
180 );
181​
182 const resolve: VcsDriverRegistry["Service"]["resolve"] = Effect.fn("VcsDriverRegistry.resolve")(
183 function* (input) {
184 const detected = yield* detect(input);
185 if (detected) {
186 return detected;
187 }
188​
189 const requestedKind = input.requestedKind ?? "auto";
190 return yield* new VcsUnsupportedOperationError({
191 operation: "VcsDriverRegistry.resolve",
192 kind: requestedKind === "auto" ? "unknown" : requestedKind,
193 detail:
194 requestedKind === "auto"
195 ? `No supported VCS repository was detected at ${input.cwd}.`
196 : `No ${requestedKind} repository was detected at ${input.cwd}.`,
197 });
198 },
199 );
200​
201 return VcsDriverRegistry.of({
202 get,
203 detect,
204 resolve,
205 });
206});
207​
208export const layer = Layer.effect(VcsDriverRegistry, make).pipe(
209 Layer.provide(VcsProjectConfig.layer),
210);