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

RepositoryIdentityResolver.ts

282 lines10.5 KB

1import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts";
2import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider";
3import * as Cache from "effect/Cache";
4import * as Context from "effect/Context";
5import * as Data from "effect/Data";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Layer from "effect/Layer";
10​
11import * as ProcessRunner from "../processRunner.ts";
12import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts";
13import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15​
16const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
17// Background sweeps resolve every project each minute. A long TTL keeps them
18// from spawning git each time. Clone, publish, and PR discovery (after a turn
19// and before it saves links) resolve with `refresh: true`.
20const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15);
21const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
22​
23export interface RepositoryIdentityResolverOptions {
24 readonly cacheCapacity?: number;
25 readonly positiveCacheTtl?: Duration.Input;
26 readonly negativeCacheTtl?: Duration.Input;
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 remotes (GitButler's `gb-local` is `.`) name a path on this machine,
43// not a repository, so unrelated repos would share one identity.
44function isLocalRemoteUrl(url: string): boolean {
45 if (/^file:/i.test(url)) return true;
46 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false;
47 if (/^[a-z]:[\\/]/i.test(url)) return true;
48 // Git treats `host:path` as scp-style only when the colon precedes any slash.
49 const colonIndex = url.indexOf(":");
50 const slashIndex = url.search(/[\\/]/);
51 return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex);
53​
54function parseRemoteFetchUrls(stdout: string): Map<string, string> {
55 const remotes = new Map<string, string>();
56 for (const line of stdout.split("\n")) {
57 const trimmed = line.trim();
58 if (trimmed.length === 0) continue;
59 // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`.
60 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed);
61 if (!match) continue;
62 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
63 if (
64 direction !== "fetch" ||
65 remoteName.length === 0 ||
66 remoteUrl.length === 0 ||
67 isLocalRemoteUrl(remoteUrl)
68 ) {
69 continue;
70 }
71 remotes.set(remoteName, remoteUrl);
72 }
73 return remotes;
75​
76function pickPrimaryRemote(
77 remotes: ReadonlyMap<string, string>,
78): { readonly remoteName: string; readonly remoteUrl: string } | null {
79 for (const preferredRemoteName of ["upstream", "origin"] as const) {
80 const remoteUrl = remotes.get(preferredRemoteName);
81 if (remoteUrl) {
82 return { remoteName: preferredRemoteName, remoteUrl };
83 }
84 }
85​
86 const [remoteName, remoteUrl] =
87 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
88 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
90​
91function repositoryPathOf(canonicalKey: string, remoteUrl: string): string {
92 const canonicalPath = canonicalKey.split("/").slice(1).join("/");
93 const displayPath = repositoryPathFromRemoteUrl(remoteUrl);
94 return displayPath?.toLowerCase() === canonicalPath ? displayPath : canonicalPath;
96​
97function buildRepositoryOrigin(
98 originUrl: string | undefined,
99 canonicalKey: string,
100): RepositoryIdentity["origin"] {
101 if (!originUrl) return undefined;
102 const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originUrl);
103 if (originKey === canonicalKey) return undefined;
104 const displayName = repositoryPathOf(originKey, originUrl);
105 return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) };
107​
108function buildRepositoryIdentity(input: {
109 readonly remoteName: string;
110 readonly remoteUrl: string;
111 readonly originUrl: string | undefined;
112 readonly rootPath: string;
113}): RepositoryIdentity {
114 const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl);
115 const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl);
116 const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
117 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
118 const [owner] = repositoryPathSegments;
119 const repositoryName = repositoryPathSegments.at(-1);
120 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
121​
122 return {
123 canonicalKey,
124 locator: {
125 source: "git-remote",
126 remoteName: input.remoteName,
127 remoteUrl: input.remoteUrl,
128 },
129 rootPath: input.rootPath,
130 ...(repositoryPath ? { displayName: repositoryPath } : {}),
131 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
132 ...(owner ? { owner } : {}),
133 ...(repositoryName ? { name: repositoryName } : {}),
134 ...(origin ? { origin } : {}),
135 };
137​
138class RepositoryIdentityCacheKey extends Data.Class<{
139 readonly rootPath: string;
140 readonly isBare: boolean;
141}> {}
142​
143const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
144 function* (cwd: string) {
145 const processRunner = yield* ProcessRunner.ProcessRunner;
146 const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform);
147​
148 // git is a real executable on every platform — no cmd.exe shell mode, which
149 // would split paths containing spaces during cmd's re-tokenization.
150 const topLevelResult = yield* processRunner
151 .run({
152 command: "git",
153 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
154 env,
155 timeoutBehavior: "timedOutResult",
156 })
157 .pipe(Effect.option);
158 if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) {
159 return null;
160 }
161 if (topLevelResult.value.code === 0) {
162 const rootPath = topLevelResult.value.stdout.trim();
163 return rootPath.length > 0
164 ? new RepositoryIdentityCacheKey({ rootPath, isBare: false })
165 : null;
166 }
167​
168 // Explicit Git directories preserve safe.bareRepository=explicit for both layouts.
169 for (const gitDir of [".", ".git"]) {
170 const bareResult = yield* processRunner
171 .run({
172 command: "git",
173 args: [
174 "-C",
175 cwd,
176 `--git-dir=${gitDir}`,
177 "rev-parse",
178 "--is-bare-repository",
179 "--absolute-git-dir",
180 ],
181 env,
182 timeoutBehavior: "timedOutResult",
183 })
184 .pipe(Effect.option);
185 if (bareResult._tag === "None" || bareResult.value.timedOut) return null;
186 if (bareResult.value.code !== 0) continue;
187​
188 const [isBare, rootPath = ""] = bareResult.value.stdout
189 .split("\n")
190 .map((line) => line.trim());
191 // A checkout's .git directory contains remotes but is not a project root.
192 return isBare === "true" && rootPath.length > 0
193 ? new RepositoryIdentityCacheKey({ rootPath, isBare: true })
194 : null;
195 }
196 return null;
197 },
198);
199​
200const resolveRepositoryIdentityFromCacheKey = Effect.fn(
201 "RepositoryIdentityResolver.resolveFromCacheKey",
202)(function* (
203 cacheKey: RepositoryIdentityCacheKey,
204): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
205 const processRunner = yield* ProcessRunner.ProcessRunner;
206 const remoteResult = yield* processRunner
207 .run({
208 command: "git",
209 args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), "remote", "-v"],
210 env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
211 timeoutBehavior: "timedOutResult",
212 })
213 .pipe(Effect.option);
214 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
215 return null;
216 }
217​
218 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
219 const remote = pickPrimaryRemote(remotes);
220 return remote
221 ? buildRepositoryIdentity({
222 ...remote,
223 originUrl: remotes.get("origin"),
224 rootPath: cacheKey.rootPath,
225 })
226 : null;
227});
228​
229export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
230 options: RepositoryIdentityResolverOptions = {},
231) {
232 const processRunner = yield* ProcessRunner.ProcessRunner;
233 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
234 const refine = options.refine ?? Effect.succeed;
235 const timeToLive = (exit: Exit.Exit<unknown>) =>
236 Exit.match(exit, {
237 onSuccess: (value) =>
238 value === null
239 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
240 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
241 onFailure: () => Duration.zero,
242 });
243​
244 const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>(
245 (cwd) =>
246 resolveRepositoryIdentityCacheKey(cwd).pipe(
247 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
248 ),
249 { capacity: cacheCapacity, timeToLive },
250 );
251​
252 const repositoryIdentityCache = yield* Cache.makeWith<
253 RepositoryIdentityCacheKey,
254 RepositoryIdentity | null
255 >(
256 (cacheKey) =>
257 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
258 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
259 Effect.filterOrElse(
260 (identity): identity is null => identity === null,
261 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
262 ),
263 ),
264 { capacity: cacheCapacity, timeToLive },
265 );
266​
267 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
268 function* (cwd, options) {
269 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
270 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
271 if (cacheKey === null) return null;
272 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
273 return yield* Cache.get(repositoryIdentityCache, cacheKey);
274 },
275 );
276​
277 return RepositoryIdentityResolver.of({ resolve });
278});
279​
280export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
281 Layer.provide(ProcessRunner.layer),
282);