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

RepositoryIdentityResolver.ts

278 lines10.3 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 positiveCacheTtl?: Duration.Input;
24 readonly negativeCacheTtl?: Duration.Input;
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 env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform);
144​
145 // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization.
146 const topLevelResult = yield* processRunner
147 .run({
148 command: "git",
149 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
150 env,
151 timeoutBehavior: "timedOutResult",
152 })
153 .pipe(Effect.option);
154 if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
155 return null;
156 }
157 if (topLevelResult.value.code === 0) {
158 const rootPath = topLevelResult.value.stdout.trim();
159 return rootPath.length > 0
160 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
161 : null;
162 }
163​
164 // Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
165 for (const gitDir of [".", ".git"]) {
166 const bareResult = yield* processRunner
167 .run({
168 command: "git",
169 args: [
170 "-C",
171 cwd,
172 `--git-dir=${gitDir}`,
173 "rev-parse",
174 "--is-bare-repository",
175 "--absolute-git-dir",
176 ],
177 env,
178 timeoutBehavior: "timedOutResult",
179 })
180 .pipe(Effect.option);
181 if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
182 if (bareResult.value.code !== 0) continue;
183​
184 const [isBare, rootPath = ""] = bareResult.value.stdout
185 .split("\n")
186 .map((line) => line.trim());
187 // A checkout's .git directory contains remotes but is not a project root.
188 return isBare === "true" && rootPath.length > 0
189 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
190 : null;
191 }
192 return null;
193 },
194);
195​
196const resolveRepositoryIdentityFromCacheKey = Effect.fn(
197 "RepositoryIdentityResolver.resolveFromCacheKey",
198)(function* (
199 cacheKey: RepositoryIdentityCacheKey,
200): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
201 const processRunner = yield* ProcessRunner.ProcessRunner;
202 const remoteResult = yield* processRunner
203 .run({
204 command: "git",
205 args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), "remote", "-v"],
206 env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
207 timeoutBehavior: "timedOutResult",
208 })
209 .pipe(Effect.option);
210 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
211 return null;
212 }
213​
214 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
215 const remote = pickPrimaryRemote(remotes);
216 return remote
217 ? buildRepositoryIdentity({
218 ...remote,
219 originUrl: remotes.get("origin"),
220 rootPath: cacheKey.rootPath,
221 })
222 : null;
223});
224​
225export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
226 options: RepositoryIdentityResolverOptions = {},
227) {
228 const processRunner = yield* ProcessRunner.ProcessRunner;
229 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
230 const refine = options.refine ?? Effect.succeed;
231 const timeToLive = (exit: Exit.Exit<unknown>) =>
232 Exit.match(exit, {
233 onSuccess: (value) =>
234 value === null
235 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
236 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
237 onFailure: () => Duration.zero,
238 });
239​
240 const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
241 (cwd) =>
242 resolveRepositoryIdentityCacheKey(cwd).pipe(
243 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
244 ),
245 { capacity: cacheCapacity, timeToLive },
246 );
247​
248 const repositoryIdentityCache = yield* Cache.makeWith<
249 RepositoryIdentityCacheKey,
250 RepositoryIdentity | null
251 >(
252 (cacheKey) =>
253 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
254 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
255 Effect.filterOrElse(
256 (identity): identity is null => identity === null,
257 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
258 ),
259 ),
260 { capacity: cacheCapacity, timeToLive },
261 );
262​
263 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
264 function* (cwd, options) {
265 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
266 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
267 if (cacheKey === null) return null;
268 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
269 return yield* Cache.get(repositoryIdentityCache, cacheKey);
270 },
271 );
272​
273 return RepositoryIdentityResolver.of({ resolve });
274});
275​
276export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
277 Layer.provide(ProcessRunner.layer),
278);