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

RepositoryIdentityResolver.ts

285 lines10.5 KB

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