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

RepositoryIdentityResolver.ts

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