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

RepositoryIdentityResolver.ts

363 lines14.1 KB

1import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";
2import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition";
3import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
4import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
5import * as Cache from "effect/Cache";
6import * as Context from "effect/Context";
7import * as Data from "effect/Data";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14​
15import * as ProcessRunner from "../processRunner.ts";
16import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
17import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19​
20const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
21// Minute-by-minute sweeps need cached hits; clone, publish and PR discovery force refresh.
22const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15);
23const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
24​
25export interface RepositoryIdentityResolverOptions {
26 readonly cacheCapacity?: number;
27 readonly refine?: (
28 identity: RepositoryIdentity,
29 ) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
31​
32export class RepositoryIdentityResolver extends Context.Service<
33 RepositoryIdentityResolver,
34 {
35 readonly resolve: (
36 cwd: string,
37 options?: { readonly refresh?: boolean },
38 ) => Effect.Effect<RepositoryIdentity | null>;
39 }
40>()("t3/project/RepositoryIdentityResolver") {}
41​
42// Local paths such as GitButler's gb-local=. would give unrelated repos the same identity.
43function isLocalRemoteUrl(url: string): boolean {
44 if (/^file:/i.test(url)) return true;
45 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false;
46 if (/^[a-z]:[\\/]/i.test(url)) return true;
47 // Git treats `host:path` as scp-style only when the colon precedes any slash.
48 const colonIndex = url.indexOf(":");
49 const slashIndex = url.search(/[\\/]/);
50 return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex);
52​
53function parseRemoteFetchUrls(stdout: string): Map<string, string> {
54 const remotes = new Map<string, string>();
55 for (const line of stdout.split(/\r?\n/)) {
56 // Git uses a tab before the URL and one space before the direction; both can occur in URLs.
57 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
58 const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line);
59 if (!match) continue;
60 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
61 if (
62 direction !== "fetch" ||
63 remoteName.length === 0 ||
64 remoteUrl.length === 0 ||
65 isLocalRemoteUrl(remoteUrl)
66 ) {
67 continue;
68 }
69 remotes.set(remoteName, remoteUrl);
70 }
71 return remotes;
73​
74// `gh repo set-default` marks one remote with `base`, or with OWNER/REPO when it picked a
75// parent repository. gh reads PRs from that repository, so the identity follows the mark when
76// a remote fetches it. The locator must name a real remote: review checkouts fetch through it.
77function pickMarkedRemote(
78 remotes: ReadonlyMap<string, string>,
79 resolved: string,
80): { readonly remoteName: string; readonly remoteUrl: string } | null {
81 const marks = resolved.split("\n").flatMap((line) => {
82 const match = /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim());
83 const remoteUrl = match?.[1] === undefined ? undefined : remotes.get(match[1]);
84 return match?.[1] && match[2] && remoteUrl
85 ? [{ remoteName: match[1], remoteUrl, value: match[2] }]
86 : [];
87 });
88 // gh's choice is ambiguous with several marks; GitHubSourceControlProvider ignores them too.
89 const [mark, ...others] = marks;
90 if (!mark || others.length > 0) return null;
91 if (mark.value === "base") return { remoteName: mark.remoteName, remoteUrl: mark.remoteUrl };
92 // Compare hosts with HTTP ports kept: one hostname can serve separate forges on two ports.
93 const host = parseGitRemoteHost(mark.remoteUrl)?.host;
94 const markedPath = mark.value.toLowerCase();
95 const [remoteName, remoteUrl] =
96 [...remotes.entries()].find(
97 ([, url]) =>
98 parseGitRemoteHost(url)?.host === host &&
99 normalizeGitRemoteUrl(url).split("/").slice(1).join("/") === markedPath,
100 ) ?? [];
101 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
103​
104function pickPrimaryRemote(
105 remotes: ReadonlyMap<string, string>,
106 resolved: string,
107): { readonly remoteName: string; readonly remoteUrl: string } | null {
108 const marked = pickMarkedRemote(remotes, resolved);
109 if (marked) return marked;
110​
111 for (const preferredRemoteName of ["upstream", "origin"] as const) {
112 const remoteUrl = remotes.get(preferredRemoteName);
113 if (remoteUrl) {
114 return { remoteName: preferredRemoteName, remoteUrl };
115 }
116 }
117​
118 const [remoteName, remoteUrl] =
119 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
120 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
122​
123function repositoryPathOf(canonicalKey: string, remoteUrl: string): string {
124 const canonicalPath = canonicalKey.split("/").slice(1).join("/");
125 const displayPath = repositoryPathFromRemoteUrl(remoteUrl);
126 if (displayPath === null) return canonicalPath;
127 // A host that names repositories literally keeps the `.git` the display path drops.
128 return (
129 [displayPath, `${displayPath}.git`].find((path) => path.toLowerCase() === canonicalPath) ??
130 canonicalPath
131 );
133​
134function buildRepositoryOrigin(
135 originUrl: string | undefined,
136 canonicalKey: string,
137): RepositoryIdentity["origin"] {
138 if (!originUrl) return undefined;
139 const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originUrl);
140 if (originKey === canonicalKey) return undefined;
141 const displayName = repositoryPathOf(originKey, originUrl);
142 return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
144​
145function buildRepositoryIdentity(input: {
146 readonly remoteName: string;
147 readonly remoteUrl: string;
148 readonly originUrl: string | undefined;
149 readonly rootPath: string;
150}): RepositoryIdentity {
151 const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl);
152 const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl);
153 const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
154 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
155 const [owner] = repositoryPathSegments;
156 const repositoryName = repositoryPathSegments.at(-1);
157 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
158​
159 return {
160 canonicalKey,
161 locator: {
162 source: "git-remote",
163 remoteName: input.remoteName,
164 remoteUrl: input.remoteUrl,
165 },
166 rootPath: input.rootPath,
167 ...(repositoryPath ? { displayName: repositoryPath } : {}),
168 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
169 ...(owner ? { owner } : {}),
170 ...(repositoryName ? { name: repositoryName } : {}),
171 ...(origin ? { origin } : {}),
172 };
174​
175class RepositoryIdentityCacheKey extends Data.Class<{
176 readonly rootPath: string;
177 readonly isBare: boolean;
178}> {}
179​
180const gitEnv = (platform: NodeJS.Platform): NodeJS.ProcessEnv => ({
181 ...unsetInheritedRepositoryEnv(process.env, platform),
182 ...explicitBareRepositoryEnv(process.env, platform),
183});
184​
185const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
186 function* (cwd: string) {
187 const processRunner = yield* ProcessRunner.ProcessRunner;
188 const fileSystem = yield* FileSystem.FileSystem;
189 const path = yield* Path.Path;
190 const env = gitEnv(yield* HostProcess.Platform);
191​
192 // `git -C` cannot enter a missing folder or a file, so every probe below would fail.
193 const isFolder = yield* fileSystem.stat(cwd).pipe(
194 Effect.map((info) => info.type === "Directory"),
195 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
196 Effect.orElseSucceed(() => true),
197 );
198 if (!isFolder) return null;
199​
200 // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization.
201 const topLevelResult = yield* processRunner
202 .run({
203 command: "git",
204 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
205 env,
206 timeoutBehavior: "timedOutResult",
207 })
208 .pipe(Effect.option);
209 if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
210 return null;
211 }
212 if (topLevelResult.value.code === 0) {
213 // Paths may end in spaces, so strip only git's line terminator.
214 const rootPath = topLevelResult.value.stdout.replace(/\r?\n$/, "");
215 return rootPath.length > 0
216 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
217 : null;
218 }
219​
220 // Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
221 for (const [gitDir, entry] of [
222 [".", "HEAD"],
223 [".git", ".git"],
224 ] as const) {
225 // An explicit --git-dir fails unless the folder has this entry; a symlink counts even
226 // when its target is missing, as git reads a symlinked HEAD's target text.
227 const target = path.join(cwd, entry);
228 const hasEntry = yield* fileSystem.exists(target).pipe(
229 Effect.flatMap((exists) =>
230 exists
231 ? Effect.succeed(true)
232 : fileSystem.readLink(target).pipe(
233 Effect.as(true),
234 Effect.orElseSucceed(() => false),
235 ),
236 ),
237 Effect.orElseSucceed(() => true),
238 );
239 if (!hasEntry) continue;
240 const bareResult = yield* processRunner
241 .run({
242 command: "git",
243 args: [
244 "-C",
245 cwd,
246 `--git-dir=${gitDir}`,
247 "rev-parse",
248 "--is-bare-repository",
249 "--absolute-git-dir",
250 ],
251 env,
252 timeoutBehavior: "timedOutResult",
253 })
254 .pipe(Effect.option);
255 if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
256 if (bareResult.value.code !== 0) continue;
257​
258 const [isBare, rootPath = ""] = bareResult.value.stdout.split(/\r?\n/);
259 // A checkout's .git directory contains remotes but is not a project root.
260 return isBare === "true" && rootPath.length > 0
261 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
262 : null;
263 }
264 return null;
265 },
266);
267​
268const resolveRepositoryIdentityFromCacheKey = Effect.fn(
269 "RepositoryIdentityResolver.resolveFromCacheKey",
270)(function* (
271 cacheKey: RepositoryIdentityCacheKey,
272): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
273 const processRunner = yield* ProcessRunner.ProcessRunner;
274 const env = gitEnv(yield* HostProcess.Platform);
275 const runGit = (args: ReadonlyArray<string>) =>
276 processRunner
277 .run({
278 command: "git",
279 args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args],
280 env,
281 timeoutBehavior: "timedOutResult",
282 })
283 .pipe(Effect.option);
284 const [remoteResult, resolvedResult] = yield* Effect.all(
285 [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])],
286 { concurrency: "unbounded" },
287 );
288 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
289 return null;
290 }
291​
292 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
293 // Exits 1 when no remote has a mark.
294 const resolved =
295 resolvedResult._tag === "Some" && resolvedResult.value.code === 0
296 ? resolvedResult.value.stdout
297 : "";
298 const remote = pickPrimaryRemote(remotes, resolved);
299 return remote
300 ? buildRepositoryIdentity({
301 ...remote,
302 originUrl: remotes.get("origin"),
303 rootPath: cacheKey.rootPath,
304 })
305 : null;
306});
307​
308export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
309 options: RepositoryIdentityResolverOptions = {},
310) {
311 const processRunner = yield* ProcessRunner.ProcessRunner;
312 const fileSystem = yield* FileSystem.FileSystem;
313 const path = yield* Path.Path;
314 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
315 const refine = options.refine ?? Effect.succeed;
316 const timeToLive = (exit: Exit.Exit<unknown>) =>
317 Exit.match(exit, {
318 onSuccess: (value) =>
319 value === null ? DEFAULT_NEGATIVE_CACHE_TTL : DEFAULT_POSITIVE_CACHE_TTL,
320 onFailure: () => Duration.zero,
321 });
322​
323 const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
324 (cwd) =>
325 resolveRepositoryIdentityCacheKey(cwd).pipe(
326 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
327 Effect.provideService(FileSystem.FileSystem, fileSystem),
328 Effect.provideService(Path.Path, path),
329 ),
330 { capacity: cacheCapacity, timeToLive },
331 );
332​
333 const repositoryIdentityCache = yield* Cache.makeWith<
334 RepositoryIdentityCacheKey,
335 RepositoryIdentity | null
336 >(
337 (cacheKey) =>
338 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
339 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
340 Effect.filterOrElse(
341 (identity): identity is null => identity === null,
342 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
343 ),
344 ),
345 { capacity: cacheCapacity, timeToLive },
346 );
347​
348 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
349 function* (cwd, options) {
350 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
351 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
352 if (cacheKey === null) return null;
353 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
354 return yield* Cache.get(repositoryIdentityCache, cacheKey);
355 },
356 );
357​
358 return RepositoryIdentityResolver.of({ resolve });
359});
360​
361export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
362 Layer.provide(ProcessRunner.layer),
363);