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

RepositoryIdentityResolver.ts

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