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