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

RepositoryIdentityResolver.ts

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