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

RepositoryIdentityResolver.ts

237 lines9.0 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 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
62 if (!match) continue;
63 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
64 if (
65 direction !== "fetch" ||
66 remoteName.length === 0 ||
67 remoteUrl.length === 0 ||
68 isLocalRemoteUrl(remoteUrl)
69 ) {
70 continue;
71 }
72 remotes.set(remoteName, remoteUrl);
73 }
74 return remotes;
76​
77function pickPrimaryRemote(
78 remotes: ReadonlyMap<string, string>,
79): { readonly remoteName: string; readonly remoteUrl: string } | null {
80 for (const preferredRemoteName of ["upstream", "origin"] as const) {
81 const remoteUrl = remotes.get(preferredRemoteName);
82 if (remoteUrl) {
83 return { remoteName: preferredRemoteName, remoteUrl };
84 }
85 }
86​
87 const [remoteName, remoteUrl] =
88 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
89 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
91​
92function repositoryPathOf(canonicalKey: string, remoteUrl: string): string {
93 const canonicalPath = canonicalKey.split("/").slice(1).join("/");
94 const displayPath = repositoryPathFromRemoteUrl(remoteUrl);
95 return displayPath?.toLowerCase() === canonicalPath ? displayPath : canonicalPath;
97​
98function buildRepositoryOrigin(
99 originUrl: string | undefined,
100 canonicalKey: string,
101): RepositoryIdentity["origin"] {
102 if (!originUrl) return undefined;
103 const originKey = normalizeGitRemoteUrl(originUrl);
104 if (originKey === canonicalKey) return undefined;
105 const displayName = repositoryPathOf(originKey, originUrl);
106 return { canonicalKey: originKey, ...(displayName ? { displayName } : {}) };
108​
109function buildRepositoryIdentity(input: {
110 readonly remoteName: string;
111 readonly remoteUrl: string;
112 readonly originUrl: string | undefined;
113 readonly rootPath: string;
114}): RepositoryIdentity {
115 const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
116 const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
117 const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl);
118 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
119 const [owner] = repositoryPathSegments;
120 const repositoryName = repositoryPathSegments.at(-1);
121 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
122​
123 return {
124 canonicalKey,
125 locator: {
126 source: "git-remote",
127 remoteName: input.remoteName,
128 remoteUrl: input.remoteUrl,
129 },
130 rootPath: input.rootPath,
131 ...(repositoryPath ? { displayName: repositoryPath } : {}),
132 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
133 ...(owner ? { owner } : {}),
134 ...(repositoryName ? { name: repositoryName } : {}),
135 ...(origin ? { origin } : {}),
136 };
138​
139const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
140 function* (cwd: string) {
141 const processRunner = yield* ProcessRunner.ProcessRunner;
142​
143 // git is a real executable on every platform — no cmd.exe shell mode, which
144 // would split paths containing spaces during cmd's re-tokenization.
145 const topLevelResult = yield* processRunner
146 .run({
147 command: "git",
148 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
149 env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
150 timeoutBehavior: "timedOutResult",
151 })
152 .pipe(Effect.option);
153 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
154 return null;
155 }
156​
157 const candidate = topLevelResult.value.stdout.trim();
158 return candidate.length > 0 ? candidate : null;
159 },
160);
161​
162const resolveRepositoryIdentityFromCacheKey = Effect.fn(
163 "RepositoryIdentityResolver.resolveFromCacheKey",
164)(function* (
165 cacheKey: string,
166): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
167 const processRunner = yield* ProcessRunner.ProcessRunner;
168 const remoteResult = yield* processRunner
169 .run({
170 command: "git",
171 args: ["-C", cacheKey, "remote", "-v"],
172 env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform),
173 timeoutBehavior: "timedOutResult",
174 })
175 .pipe(Effect.option);
176 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
177 return null;
178 }
179​
180 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
181 const remote = pickPrimaryRemote(remotes);
182 return remote
183 ? buildRepositoryIdentity({ ...remote, originUrl: remotes.get("origin"), rootPath: cacheKey })
184 : null;
185});
186​
187export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
188 options: RepositoryIdentityResolverOptions = {},
189) {
190 const processRunner = yield* ProcessRunner.ProcessRunner;
191 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
192 const refine = options.refine ?? Effect.succeed;
193 const timeToLive = (exit: Exit.Exit<unknown>) =>
194 Exit.match(exit, {
195 onSuccess: (value) =>
196 value === null
197 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
198 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
199 onFailure: () => Duration.zero,
200 });
201​
202 const repositoryRootCache = yield* Cache.makeWith<string, string | null>(
203 (cwd) =>
204 resolveRepositoryIdentityCacheKey(cwd).pipe(
205 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
206 ),
207 { capacity: cacheCapacity, timeToLive },
208 );
209​
210 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
211 (cacheKey) =>
212 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
213 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
214 Effect.filterOrElse(
215 (identity): identity is null => identity === null,
216 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
217 ),
218 ),
219 { capacity: cacheCapacity, timeToLive },
220 );
221​
222 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
223 function* (cwd, options) {
224 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
225 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
226 if (cacheKey === null) return null;
227 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
228 return yield* Cache.get(repositoryIdentityCache, cacheKey);
229 },
230 );
231​
232 return RepositoryIdentityResolver.of({ resolve });
233});
234​
235export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
236 Layer.provide(ProcessRunner.layer),
237);