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

RepositoryIdentityResolver.ts

448 lines17.6 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 { withoutRemoteUrlCredentials } from "@t3tools/shared/cloneUrl";
5import { canonicalRepositoryPath, normalizeGitRemoteUrl } from "@t3tools/shared/git";
6import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
7import * as Cache from "effect/Cache";
8import * as Context from "effect/Context";
9import * as Data from "effect/Data";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Path from "effect/Path";
16​
17import * as ProcessRunner from "../processRunner.ts";
18import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
19import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts";
20import * as HostProcess from "@t3tools/shared/HostProcess";
21​
22const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
23// Minute-by-minute sweeps need cached hits; clone, publish and PR discovery force refresh.
24const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15);
25const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
26​
27export interface RepositoryIdentityResolverOptions {
28 readonly cacheCapacity?: number;
29 readonly refine?: (
30 identity: RepositoryIdentity,
31 ) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
33​
34export class RepositoryIdentityResolver extends Context.Service<
35 RepositoryIdentityResolver,
36 {
37 readonly resolve: (
38 cwd: string,
39 options?: { readonly refresh?: boolean },
40 ) => Effect.Effect<RepositoryIdentity | null>;
41 }
42>()("t3/project/RepositoryIdentityResolver") {}
43​
44// Local paths such as GitButler's gb-local=. would give unrelated repos the same identity.
45function isLocalRemoteUrl(url: string): boolean {
46 if (/^file:/i.test(url)) return true;
47 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false;
48 if (/^[a-z]:[\\/]/i.test(url)) return true;
49 // Git treats `host:path` as scp-style only when the colon precedes any slash.
50 const colonIndex = url.indexOf(":");
51 const slashIndex = url.search(/[\\/]/);
52 return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex);
54​
55// `git remote -v` applies url.*.insteadOf, which can point a GitHub remote at a proxy or mirror.
56// A configured URL that names a forge wins; a shorthand like `gh:` is known only once rewritten.
57function parseConfiguredRemoteUrls(config: string): Map<string, string> {
58 const urls = new Map<string, string>();
59 for (const line of config.split("\n")) {
60 const match = /^remote\.(\S+)\.url (.+)$/u.exec(line);
61 // Git fetches from the first of several configured URLs.
62 if (match?.[1] && match[2] && !urls.has(match[1])) urls.set(match[1], match[2]);
63 }
64 return urls;
66​
67function parseRemoteFetchUrls(
68 stdout: string,
69 configuredUrls: ReadonlyMap<string, string>,
70): Map<string, string> {
71 const remotes = new Map<string, string>();
72 for (const line of stdout.split(/\r?\n/)) {
73 // Git uses a tab before the URL and one space before the direction; both can occur in URLs.
74 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
75 const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line);
76 if (!match) continue;
77 const [, remoteName = "", fetchUrl = "", direction = ""] = match;
78 const configuredUrl = configuredUrls.get(remoteName);
79 const remoteUrl =
80 configuredUrl !== undefined &&
81 (sourceControlDefinitions.recognizeRemote(configuredUrl)?.kind ?? "unknown") !== "unknown"
82 ? configuredUrl
83 : fetchUrl;
84 if (
85 direction !== "fetch" ||
86 remoteName.length === 0 ||
87 remoteUrl.length === 0 ||
88 isLocalRemoteUrl(remoteUrl)
89 ) {
90 continue;
91 }
92 // The identity names the remote, not the login used to reach it.
93 remotes.set(remoteName, withoutRemoteUrlCredentials(remoteUrl));
94 }
95 return remotes;
97​
98// `gh repo set-default` marks one remote with `base`, or with OWNER/REPO when it picked a
99// parent repository. gh reads PRs from that repository, so the identity follows the mark when
100// a remote fetches it. The locator must name a real remote: review checkouts fetch through it.
101function pickMarkedRemote(
102 remotes: ReadonlyMap<string, string>,
103 resolved: string,
104): { readonly remoteName: string; readonly remoteUrl: string } | null {
105 const marks = resolved.split("\n").flatMap((line) => {
106 const match = /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim());
107 const remoteUrl = match?.[1] === undefined ? undefined : remotes.get(match[1]);
108 return match?.[1] && match[2] && remoteUrl
109 ? [{ remoteName: match[1], remoteUrl, value: match[2] }]
110 : [];
111 });
112 // gh's choice is ambiguous with several marks; GitHubSourceControlProvider ignores them too.
113 const [mark, ...others] = marks;
114 if (!mark || others.length > 0) return null;
115 if (mark.value === "base") return { remoteName: mark.remoteName, remoteUrl: mark.remoteUrl };
116 // Compare hosts with HTTP ports kept: one hostname can serve separate forges on two ports.
117 const host = parseGitRemoteHost(mark.remoteUrl)?.host;
118 const markedPath = mark.value.toLowerCase();
119 const [remoteName, remoteUrl] =
120 [...remotes.entries()].find(
121 ([, url]) =>
122 parseGitRemoteHost(url)?.host === host &&
123 normalizeGitRemoteUrl(url).split("/").slice(1).join("/") === markedPath,
124 ) ?? [];
125 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
127​
128function pickPrimaryRemote(
129 remotes: ReadonlyMap<string, string>,
130 resolved: string,
131): { readonly remoteName: string; readonly remoteUrl: string } | null {
132 const marked = pickMarkedRemote(remotes, resolved);
133 if (marked) return marked;
134​
135 for (const preferredRemoteName of ["upstream", "origin"] as const) {
136 const remoteUrl = remotes.get(preferredRemoteName);
137 if (remoteUrl) {
138 return { remoteName: preferredRemoteName, remoteUrl };
139 }
140 }
141​
142 const [remoteName, remoteUrl] =
143 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
144 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
146​
147function repositoryPathOf(canonicalKey: string, remoteUrl: string): string {
148 const canonicalPath = canonicalKey.split("/").slice(1).join("/");
149 const displayPath = repositoryPathFromRemoteUrl(remoteUrl);
150 if (displayPath === null) return canonicalPath;
151 // A host that names repositories literally keeps the `.git` the display path drops.
152 return (
153 [displayPath, `${displayPath}.git`].find(
154 (path) => canonicalRepositoryPath(path) === canonicalRepositoryPath(canonicalPath),
155 ) ?? canonicalPath
156 );
158​
159// A leading `-` on the user or host would be read by ssh as an option.
160const SSH_REMOTE = /^((?:ssh:\/\/)?)((?:[^-@/:][^@/:]*@)?)([A-Za-z0-9][A-Za-z0-9._-]*)([:/].*)$/su;
161const SSH_HOST_NAME = /^[a-z0-9][a-z0-9.-]*$/u;
162const IPV4 = /^[\d.]+$/u;
163​
164// Keys an SSH remote by the host its ssh config alias (`Host github.com-personal`) points at.
165// A dotted host may be a forge whose SSH endpoint has another name, so only a public forge
166// replaces it. `ssh -G` prints the configuration it would use and opens no connection.
167const sshResolvedRemoteUrl = Effect.fn("RepositoryIdentityResolver.sshResolvedRemoteUrl")(
168 function* (remoteUrl: string) {
169 const match = isSshRemoteUrl(remoteUrl) ? SSH_REMOTE.exec(remoteUrl.trim()) : null;
170 if (!match) return remoteUrl;
171 const [, scheme = "", user = "", host = "", rest = ""] = match;
172 if (sourceControlDefinitions.findByPublicHost(host)) return remoteUrl;
173 const processRunner = yield* ProcessRunner.ProcessRunner;
174 const result = yield* processRunner
175 .run({
176 command: "ssh",
177 args: ["-G", `${user}${host}`],
178 timeout: Duration.seconds(5),
179 maxOutputBytes: 64_000,
180 outputMode: "truncate",
181 timeoutBehavior: "timedOutResult",
182 })
183 .pipe(Effect.option);
184 if (result._tag === "None" || result.value.code !== 0) return remoteUrl;
185 const hostName = result.value.stdout
186 .split("\n")
187 .find((line) => line.startsWith("hostname "))
188 ?.slice("hostname ".length)
189 .trim()
190 .toLowerCase();
191 if (
192 hostName === undefined ||
193 !SSH_HOST_NAME.test(hostName) ||
194 IPV4.test(hostName) ||
195 hostName === host.toLowerCase() ||
196 (host.includes(".") && !sourceControlDefinitions.findByPublicHost(hostName))
197 ) {
198 return remoteUrl;
199 }
200 return `${scheme}${user}${hostName}${rest}`;
201 },
202);
203​
204function buildRepositoryOrigin(
205 originUrl: string | undefined,
206 originKeyUrl: string | undefined,
207 canonicalKey: string,
208): RepositoryIdentity["origin"] {
209 if (!originUrl) return undefined;
210 const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originKeyUrl ?? originUrl);
211 if (originKey === canonicalKey) return undefined;
212 const displayName = repositoryPathOf(originKey, originUrl);
213 return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
215​
216function buildRepositoryIdentity(input: {
217 readonly remoteName: string;
218 readonly remoteUrl: string;
219 readonly keyUrl: string;
220 readonly originUrl: string | undefined;
221 readonly originKeyUrl: string | undefined;
222 readonly rootPath: string;
223}): RepositoryIdentity {
224 const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.keyUrl);
225 const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl);
226 const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
227 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
228 const [owner] = repositoryPathSegments;
229 const repositoryName = repositoryPathSegments.at(-1);
230 const origin = buildRepositoryOrigin(input.originUrl, input.originKeyUrl, canonicalKey);
231​
232 return {
233 canonicalKey,
234 locator: {
235 source: "git-remote",
236 remoteName: input.remoteName,
237 remoteUrl: input.remoteUrl,
238 },
239 rootPath: input.rootPath,
240 ...(repositoryPath ? { displayName: repositoryPath } : {}),
241 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
242 ...(owner ? { owner } : {}),
243 ...(repositoryName ? { name: repositoryName } : {}),
244 ...(origin ? { origin } : {}),
245 };
247​
248class RepositoryIdentityCacheKey extends Data.Class<{
249 readonly rootPath: string;
250 readonly isBare: boolean;
251}> {}
252​
253const gitEnv = (platform: NodeJS.Platform): NodeJS.ProcessEnv => ({
254 ...unsetInheritedRepositoryEnv(process.env, platform),
255 ...explicitBareRepositoryEnv(process.env, platform),
256});
257​
258const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
259 function* (cwd: string) {
260 const processRunner = yield* ProcessRunner.ProcessRunner;
261 const fileSystem = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const env = gitEnv(yield* HostProcess.Platform);
264​
265 // `git -C` cannot enter a missing folder or a file, so every probe below would fail.
266 const isFolder = yield* fileSystem.stat(cwd).pipe(
267 Effect.map((info) => info.type === "Directory"),
268 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
269 Effect.orElseSucceed(() => true),
270 );
271 if (!isFolder) return null;
272​
273 // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization.
274 const topLevelResult = yield* processRunner
275 .run({
276 command: "git",
277 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
278 env,
279 timeoutBehavior: "timedOutResult",
280 })
281 .pipe(Effect.option);
282 if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
283 return null;
284 }
285 if (topLevelResult.value.code === 0) {
286 // Git appends LF on every platform; a preceding CR belongs to the path.
287 const rootPath = topLevelResult.value.stdout.replace(/\n$/, "");
288 return rootPath.length > 0
289 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
290 : null;
291 }
292​
293 // Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
294 for (const [gitDir, entry] of [
295 [".", "HEAD"],
296 [".git", ".git"],
297 ] as const) {
298 // An explicit --git-dir fails unless the folder has this entry; a symlink counts even
299 // when its target is missing, as git reads a symlinked HEAD's target text.
300 const target = path.join(cwd, entry);
301 const hasEntry = yield* fileSystem.exists(target).pipe(
302 Effect.flatMap((exists) =>
303 exists
304 ? Effect.succeed(true)
305 : fileSystem.readLink(target).pipe(
306 Effect.as(true),
307 Effect.orElseSucceed(() => false),
308 ),
309 ),
310 Effect.orElseSucceed(() => true),
311 );
312 if (!hasEntry) continue;
313 const bareResult = yield* processRunner
314 .run({
315 command: "git",
316 args: [
317 "-C",
318 cwd,
319 `--git-dir=${gitDir}`,
320 "rev-parse",
321 "--is-bare-repository",
322 "--absolute-git-dir",
323 ],
324 env,
325 timeoutBehavior: "timedOutResult",
326 })
327 .pipe(Effect.option);
328 if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
329 if (bareResult.value.code !== 0) continue;
330​
331 const [isBare, ...rootLines] = bareResult.value.stdout.split("\n");
332 const rootPath = rootLines.join("\n").replace(/\n$/, "");
333 // A checkout's .git directory contains remotes but is not a project root.
334 return isBare === "true" && rootPath.length > 0
335 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
336 : null;
337 }
338 return null;
339 },
340);
341​
342const resolveRepositoryIdentityFromCacheKey = Effect.fn(
343 "RepositoryIdentityResolver.resolveFromCacheKey",
344)(function* (
345 cacheKey: RepositoryIdentityCacheKey,
346): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
347 const processRunner = yield* ProcessRunner.ProcessRunner;
348 const env = gitEnv(yield* HostProcess.Platform);
349 const runGit = (args: ReadonlyArray<string>) =>
350 processRunner
351 .run({
352 command: "git",
353 args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args],
354 env,
355 timeoutBehavior: "timedOutResult",
356 })
357 .pipe(Effect.option);
358 const [remoteResult, configResult] = yield* Effect.all(
359 [
360 runGit(["remote", "-v"]),
361 runGit(["config", "--get-regexp", "^remote\\..*\\.(url|gh-resolved)$"]),
362 ],
363 { concurrency: "unbounded" },
364 );
365 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
366 return null;
367 }
368​
369 // Exits 1 when no key matches.
370 const resolved =
371 configResult._tag === "Some" && configResult.value.code === 0 ? configResult.value.stdout : "";
372 const remotes = parseRemoteFetchUrls(
373 remoteResult.value.stdout,
374 parseConfiguredRemoteUrls(resolved),
375 );
376 const remote = pickPrimaryRemote(remotes, resolved);
377 if (!remote) return null;
378 const originUrl = remotes.get("origin");
379 const keyUrl = yield* sshResolvedRemoteUrl(remote.remoteUrl);
380 const originKeyUrl =
381 originUrl === undefined || originUrl === remote.remoteUrl
382 ? keyUrl
383 : yield* sshResolvedRemoteUrl(originUrl);
384 return buildRepositoryIdentity({
385 ...remote,
386 keyUrl,
387 originUrl,
388 originKeyUrl,
389 rootPath: cacheKey.rootPath,
390 });
391});
392​
393export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
394 options: RepositoryIdentityResolverOptions = {},
395) {
396 const processRunner = yield* ProcessRunner.ProcessRunner;
397 const fileSystem = yield* FileSystem.FileSystem;
398 const path = yield* Path.Path;
399 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
400 const refine = options.refine ?? Effect.succeed;
401 const timeToLive = (exit: Exit.Exit<unknown>) =>
402 Exit.match(exit, {
403 onSuccess: (value) =>
404 value === null ? DEFAULT_NEGATIVE_CACHE_TTL : DEFAULT_POSITIVE_CACHE_TTL,
405 onFailure: () => Duration.zero,
406 });
407​
408 const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
409 (cwd) =>
410 resolveRepositoryIdentityCacheKey(cwd).pipe(
411 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
412 Effect.provideService(FileSystem.FileSystem, fileSystem),
413 Effect.provideService(Path.Path, path),
414 ),
415 { capacity: cacheCapacity, timeToLive },
416 );
417​
418 const repositoryIdentityCache = yield* Cache.makeWith<
419 RepositoryIdentityCacheKey,
420 RepositoryIdentity | null
421 >(
422 (cacheKey) =>
423 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
424 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
425 Effect.filterOrElse(
426 (identity): identity is null => identity === null,
427 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
428 ),
429 ),
430 { capacity: cacheCapacity, timeToLive },
431 );
432​
433 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
434 function* (cwd, options) {
435 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
436 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
437 if (cacheKey === null) return null;
438 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
439 return yield* Cache.get(repositoryIdentityCache, cacheKey);
440 },
441 );
442​
443 return RepositoryIdentityResolver.of({ resolve });
444});
445​
446export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
447 Layer.provide(ProcessRunner.layer),
448);