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