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