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

RepositoryIdentityResolver.ts

308 lines11.5 KB

1import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";
2import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
3import * as Cache from "effect/Cache";
4import * as Context from "effect/Context";
5import * as Data from "effect/Data";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12​
13import * as ProcessRunner from "../processRunner.ts";
14import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
15import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17​
18const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
19// Minute-by-minute sweeps need cached hits; clone, publish and PR discovery force refresh.
20const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15);
21const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
22​
23export interface RepositoryIdentityResolverOptions {
24 readonly cacheCapacity?: number;
25 readonly refine?: (
26 identity: RepositoryIdentity,
27 ) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
29​
30export class RepositoryIdentityResolver extends Context.Service<
31 RepositoryIdentityResolver,
32 {
33 readonly resolve: (
34 cwd: string,
35 options?: { readonly refresh?: boolean },
36 ) => Effect.Effect<RepositoryIdentity | null>;
37 }
38>()("t3/project/RepositoryIdentityResolver") {}
39​
40// Local paths such as GitButler's gb-local=. would give unrelated repos the same identity.
41function isLocalRemoteUrl(url: string): boolean {
42 if (/^file:/i.test(url)) return true;
43 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false;
44 if (/^[a-z]:[\\/]/i.test(url)) return true;
45 // Git treats `host:path` as scp-style only when the colon precedes any slash.
46 const colonIndex = url.indexOf(":");
47 const slashIndex = url.search(/[\\/]/);
48 return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex);
50​
51function parseRemoteFetchUrls(stdout: string): Map<string, string> {
52 const remotes = new Map<string, string>();
53 for (const line of stdout.split("\n")) {
54 const trimmed = line.trim();
55 if (trimmed.length === 0) continue;
56 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
57 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed);
58 if (!match) continue;
59 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
60 if (
61 direction !== "fetch" ||
62 remoteName.length === 0 ||
63 remoteUrl.length === 0 ||
64 isLocalRemoteUrl(remoteUrl)
65 ) {
66 continue;
67 }
68 remotes.set(remoteName, remoteUrl);
69 }
70 return remotes;
72​
73function pickPrimaryRemote(
74 remotes: ReadonlyMap<string, string>,
75): { readonly remoteName: string; readonly remoteUrl: string } | null {
76 for (const preferredRemoteName of ["upstream", "origin"] as const) {
77 const remoteUrl = remotes.get(preferredRemoteName);
78 if (remoteUrl) {
79 return { remoteName: preferredRemoteName, remoteUrl };
80 }
81 }
82​
83 const [remoteName, remoteUrl] =
84 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
85 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
87​
88function repositoryPathOf(canonicalKey: string, remoteUrl: string): string {
89 const canonicalPath = canonicalKey.split("/").slice(1).join("/");
90 const displayPath = repositoryPathFromRemoteUrl(remoteUrl);
91 return displayPath?.toLowerCase() === canonicalPath ? displayPath : canonicalPath;
93​
94function buildRepositoryOrigin(
95 originUrl: string | undefined,
96 canonicalKey: string,
97): RepositoryIdentity["origin"] {
98 if (!originUrl) return undefined;
99 const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originUrl);
100 if (originKey === canonicalKey) return undefined;
101 const displayName = repositoryPathOf(originKey, originUrl);
102 return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
104​
105function buildRepositoryIdentity(input: {
106 readonly remoteName: string;
107 readonly remoteUrl: string;
108 readonly originUrl: string | undefined;
109 readonly rootPath: string;
110}): RepositoryIdentity {
111 const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl);
112 const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl);
113 const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
114 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
115 const [owner] = repositoryPathSegments;
116 const repositoryName = repositoryPathSegments.at(-1);
117 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
118​
119 return {
120 canonicalKey,
121 locator: {
122 source: "git-remote",
123 remoteName: input.remoteName,
124 remoteUrl: input.remoteUrl,
125 },
126 rootPath: input.rootPath,
127 ...(repositoryPath ? { displayName: repositoryPath } : {}),
128 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
129 ...(owner ? { owner } : {}),
130 ...(repositoryName ? { name: repositoryName } : {}),
131 ...(origin ? { origin } : {}),
132 };
134​
135class RepositoryIdentityCacheKey extends Data.Class<{
136 readonly rootPath: string;
137 readonly isBare: boolean;
138}> {}
139​
140const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
141 function* (cwd: string) {
142 const processRunner = yield* ProcessRunner.ProcessRunner;
143 const fileSystem = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform);
146​
147 // `git -C` cannot enter a missing folder or a file, so every probe below would fail.
148 const isFolder = yield* fileSystem.stat(cwd).pipe(
149 Effect.map((info) => info.type === "Directory"),
150 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
151 Effect.orElseSucceed(() => true),
152 );
153 if (!isFolder) return null;
154​
155 // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization.
156 const topLevelResult = yield* processRunner
157 .run({
158 command: "git",
159 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
160 env,
161 timeoutBehavior: "timedOutResult",
162 })
163 .pipe(Effect.option);
164 if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
165 return null;
166 }
167 if (topLevelResult.value.code === 0) {
168 const rootPath = topLevelResult.value.stdout.trim();
169 return rootPath.length > 0
170 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
171 : null;
172 }
173​
174 // Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
175 for (const [gitDir, entry] of [
176 [".", "HEAD"],
177 [".git", ".git"],
178 ] as const) {
179 // An explicit --git-dir fails unless the folder has this entry; a symlink counts even
180 // when its target is missing, as git reads a symlinked HEAD's target text.
181 const target = path.join(cwd, entry);
182 const hasEntry = yield* fileSystem.exists(target).pipe(
183 Effect.flatMap((exists) =>
184 exists
185 ? Effect.succeed(true)
186 : fileSystem.readLink(target).pipe(
187 Effect.as(true),
188 Effect.orElseSucceed(() => false),
189 ),
190 ),
191 Effect.orElseSucceed(() => true),
192 );
193 if (!hasEntry) continue;
194 const bareResult = yield* processRunner
195 .run({
196 command: "git",
197 args: [
198 "-C",
199 cwd,
200 `--git-dir=${gitDir}`,
201 "rev-parse",
202 "--is-bare-repository",
203 "--absolute-git-dir",
204 ],
205 env,
206 timeoutBehavior: "timedOutResult",
207 })
208 .pipe(Effect.option);
209 if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
210 if (bareResult.value.code !== 0) continue;
211​
212 const [isBare, rootPath = ""] = bareResult.value.stdout
213 .split("\n")
214 .map((line) => line.trim());
215 // A checkout's .git directory contains remotes but is not a project root.
216 return isBare === "true" && rootPath.length > 0
217 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
218 : null;
219 }
220 return null;
221 },
222);
223​
224const resolveRepositoryIdentityFromCacheKey = Effect.fn(
225 "RepositoryIdentityResolver.resolveFromCacheKey",
226)(function* (
227 cacheKey: RepositoryIdentityCacheKey,
228): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
229 const processRunner = yield* ProcessRunner.ProcessRunner;
230 const remoteResult = yield* processRunner
231 .run({
232 command: "git",
233 args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), "remote", "-v"],
234 env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
235 timeoutBehavior: "timedOutResult",
236 })
237 .pipe(Effect.option);
238 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
239 return null;
240 }
241​
242 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
243 const remote = pickPrimaryRemote(remotes);
244 return remote
245 ? buildRepositoryIdentity({
246 ...remote,
247 originUrl: remotes.get("origin"),
248 rootPath: cacheKey.rootPath,
249 })
250 : null;
251});
252​
253export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
254 options: RepositoryIdentityResolverOptions = {},
255) {
256 const processRunner = yield* ProcessRunner.ProcessRunner;
257 const fileSystem = yield* FileSystem.FileSystem;
258 const path = yield* Path.Path;
259 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
260 const refine = options.refine ?? Effect.succeed;
261 const timeToLive = (exit: Exit.Exit<unknown>) =>
262 Exit.match(exit, {
263 onSuccess: (value) =>
264 value === null ? DEFAULT_NEGATIVE_CACHE_TTL : DEFAULT_POSITIVE_CACHE_TTL,
265 onFailure: () => Duration.zero,
266 });
267​
268 const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
269 (cwd) =>
270 resolveRepositoryIdentityCacheKey(cwd).pipe(
271 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
272 Effect.provideService(FileSystem.FileSystem, fileSystem),
273 Effect.provideService(Path.Path, path),
274 ),
275 { capacity: cacheCapacity, timeToLive },
276 );
277​
278 const repositoryIdentityCache = yield* Cache.makeWith<
279 RepositoryIdentityCacheKey,
280 RepositoryIdentity | null
281 >(
282 (cacheKey) =>
283 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
284 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
285 Effect.filterOrElse(
286 (identity): identity is null => identity === null,
287 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
288 ),
289 ),
290 { capacity: cacheCapacity, timeToLive },
291 );
292​
293 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
294 function* (cwd, options) {
295 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
296 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
297 if (cacheKey === null) return null;
298 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
299 return yield* Cache.get(repositoryIdentityCache, cacheKey);
300 },
301 );
302​
303 return RepositoryIdentityResolver.of({ resolve });
304});
305​
306export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
307 Layer.provide(ProcessRunner.layer),
308);