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 { canonicalRepositoryPath, 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>;
30}
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);
51}
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;
72}
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;
102}
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;
121}
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(
130 (path) => canonicalRepositoryPath(path) === canonicalRepositoryPath(canonicalPath),
131 ) ?? canonicalPath
132 );
133}
134
135function buildRepositoryOrigin(
136 originUrl: string | undefined,
137 canonicalKey: string,
138): RepositoryIdentity["origin"] {
139 if (!originUrl) return undefined;
140 const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originUrl);
141 if (originKey === canonicalKey) return undefined;
142 const displayName = repositoryPathOf(originKey, originUrl);
143 return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
144}
145
146function buildRepositoryIdentity(input: {
147 readonly remoteName: string;
148 readonly remoteUrl: string;
149 readonly originUrl: string | undefined;
150 readonly rootPath: string;
151}): RepositoryIdentity {
152 const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl);
153 const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl);
154 const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
155 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
156 const [owner] = repositoryPathSegments;
157 const repositoryName = repositoryPathSegments.at(-1);
158 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
159
160 return {
161 canonicalKey,
162 locator: {
163 source: "git-remote",
164 remoteName: input.remoteName,
165 remoteUrl: input.remoteUrl,
166 },
167 rootPath: input.rootPath,
168 ...(repositoryPath ? { displayName: repositoryPath } : {}),
169 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
170 ...(owner ? { owner } : {}),
171 ...(repositoryName ? { name: repositoryName } : {}),
172 ...(origin ? { origin } : {}),
173 };
174}
175
176class RepositoryIdentityCacheKey extends Data.Class<{
177 readonly rootPath: string;
178 readonly isBare: boolean;
179}> {}
180
181const gitEnv = (platform: NodeJS.Platform): NodeJS.ProcessEnv => ({
182 ...unsetInheritedRepositoryEnv(process.env, platform),
183 ...explicitBareRepositoryEnv(process.env, platform),
184});
185
186const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
187 function* (cwd: string) {
188 const processRunner = yield* ProcessRunner.ProcessRunner;
189 const fileSystem = yield* FileSystem.FileSystem;
190 const path = yield* Path.Path;
191 const env = gitEnv(yield* HostProcess.Platform);
192
193 // `git -C` cannot enter a missing folder or a file, so every probe below would fail.
194 const isFolder = yield* fileSystem.stat(cwd).pipe(
195 Effect.map((info) => info.type === "Directory"),
196 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
197 Effect.orElseSucceed(() => true),
198 );
199 if (!isFolder) return null;
200
201 // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization.
202 const topLevelResult = yield* processRunner
203 .run({
204 command: "git",
205 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
206 env,
207 timeoutBehavior: "timedOutResult",
208 })
209 .pipe(Effect.option);
210 if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
211 return null;
212 }
213 if (topLevelResult.value.code === 0) {
214 // Paths may end in spaces, so strip only git's line terminator.
215 const rootPath = topLevelResult.value.stdout.replace(/\r?\n$/, "");
216 return rootPath.length > 0
217 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
218 : null;
219 }
220
221 // Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
222 for (const [gitDir, entry] of [
223 [".", "HEAD"],
224 [".git", ".git"],
225 ] as const) {
226 // An explicit --git-dir fails unless the folder has this entry; a symlink counts even
227 // when its target is missing, as git reads a symlinked HEAD's target text.
228 const target = path.join(cwd, entry);
229 const hasEntry = yield* fileSystem.exists(target).pipe(
230 Effect.flatMap((exists) =>
231 exists
232 ? Effect.succeed(true)
233 : fileSystem.readLink(target).pipe(
234 Effect.as(true),
235 Effect.orElseSucceed(() => false),
236 ),
237 ),
238 Effect.orElseSucceed(() => true),
239 );
240 if (!hasEntry) continue;
241 const bareResult = yield* processRunner
242 .run({
243 command: "git",
244 args: [
245 "-C",
246 cwd,
247 `--git-dir=${gitDir}`,
248 "rev-parse",
249 "--is-bare-repository",
250 "--absolute-git-dir",
251 ],
252 env,
253 timeoutBehavior: "timedOutResult",
254 })
255 .pipe(Effect.option);
256 if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
257 if (bareResult.value.code !== 0) continue;
258
259 const [isBare, rootPath = ""] = bareResult.value.stdout.split(/\r?\n/);
260 // A checkout's .git directory contains remotes but is not a project root.
261 return isBare === "true" && rootPath.length > 0
262 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
263 : null;
264 }
265 return null;
266 },
267);
268
269const resolveRepositoryIdentityFromCacheKey = Effect.fn(
270 "RepositoryIdentityResolver.resolveFromCacheKey",
271)(function* (
272 cacheKey: RepositoryIdentityCacheKey,
273): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
274 const processRunner = yield* ProcessRunner.ProcessRunner;
275 const env = gitEnv(yield* HostProcess.Platform);
276 const runGit = (args: ReadonlyArray<string>) =>
277 processRunner
278 .run({
279 command: "git",
280 args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args],
281 env,
282 timeoutBehavior: "timedOutResult",
283 })
284 .pipe(Effect.option);
285 const [remoteResult, resolvedResult] = yield* Effect.all(
286 [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])],
287 { concurrency: "unbounded" },
288 );
289 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
290 return null;
291 }
292
293 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
294 // Exits 1 when no remote has a mark.
295 const resolved =
296 resolvedResult._tag === "Some" && resolvedResult.value.code === 0
297 ? resolvedResult.value.stdout
298 : "";
299 const remote = pickPrimaryRemote(remotes, resolved);
300 return remote
301 ? buildRepositoryIdentity({
302 ...remote,
303 originUrl: remotes.get("origin"),
304 rootPath: cacheKey.rootPath,
305 })
306 : null;
307});
308
309export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
310 options: RepositoryIdentityResolverOptions = {},
311) {
312 const processRunner = yield* ProcessRunner.ProcessRunner;
313 const fileSystem = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
316 const refine = options.refine ?? Effect.succeed;
317 const timeToLive = (exit: Exit.Exit<unknown>) =>
318 Exit.match(exit, {
319 onSuccess: (value) =>
320 value === null ? DEFAULT_NEGATIVE_CACHE_TTL : DEFAULT_POSITIVE_CACHE_TTL,
321 onFailure: () => Duration.zero,
322 });
323
324 const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
325 (cwd) =>
326 resolveRepositoryIdentityCacheKey(cwd).pipe(
327 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
328 Effect.provideService(FileSystem.FileSystem, fileSystem),
329 Effect.provideService(Path.Path, path),
330 ),
331 { capacity: cacheCapacity, timeToLive },
332 );
333
334 const repositoryIdentityCache = yield* Cache.makeWith<
335 RepositoryIdentityCacheKey,
336 RepositoryIdentity | null
337 >(
338 (cacheKey) =>
339 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
340 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
341 Effect.filterOrElse(
342 (identity): identity is null => identity === null,
343 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
344 ),
345 ),
346 { capacity: cacheCapacity, timeToLive },
347 );
348
349 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
350 function* (cwd, options) {
351 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
352 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
353 if (cacheKey === null) return null;
354 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
355 return yield* Cache.get(repositoryIdentityCache, cacheKey);
356 },
357 );
358
359 return RepositoryIdentityResolver.of({ resolve });
360});
361
362export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
363 Layer.provide(ProcessRunner.layer),
364);