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