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";
12import * as Option from "effect/Option";
13
14import * as ProcessRunner from "../processRunner.ts";
15import * as GitMetadataFastPath from "../vcs/GitMetadataFastPath.ts";
16
17const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
18// Background sweeps resolve every project each minute. A long TTL keeps them
19// from spawning git each time. Clone, publish, and PR discovery (after a turn
20// and before it saves links) resolve with `refresh: true`.
21const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15);
22// Short, so a folder that gains a repository or a remote shows up quickly.
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>;
32}
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
44function parseRemoteFetchUrls(stdout: string): Map<string, string> {
45 const remotes = new Map<string, string>();
46 for (const line of stdout.split("\n")) {
47 const trimmed = line.trim();
48 if (trimmed.length === 0) continue;
49 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
50 if (!match) continue;
51 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
52 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
53 continue;
54 }
55 remotes.set(remoteName, remoteUrl);
56 }
57 return remotes;
58}
59
60function pickPrimaryRemote(
61 remotes: ReadonlyMap<string, string>,
62): { readonly remoteName: string; readonly remoteUrl: string } | null {
63 for (const preferredRemoteName of ["upstream", "origin"] as const) {
64 const remoteUrl = remotes.get(preferredRemoteName);
65 if (remoteUrl) {
66 return { remoteName: preferredRemoteName, remoteUrl };
67 }
68 }
69
70 const [remoteName, remoteUrl] =
71 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
72 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
73}
74
75function repositoryPathOf(canonicalKey: string): string {
76 return canonicalKey.split("/").slice(1).join("/");
77}
78
79function buildRepositoryOrigin(
80 originUrl: string | undefined,
81 canonicalKey: string,
82): RepositoryIdentity["origin"] {
83 if (!originUrl) return undefined;
84 const originKey = normalizeGitRemoteUrl(originUrl);
85 if (originKey === canonicalKey) return undefined;
86 const displayName = repositoryPathOf(originKey);
87 return { canonicalKey: originKey, ...(displayName ? { displayName } : {}) };
88}
89
90function buildRepositoryIdentity(input: {
91 readonly remoteName: string;
92 readonly remoteUrl: string;
93 readonly originUrl: string | undefined;
94 readonly rootPath: string;
95}): RepositoryIdentity {
96 const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
97 const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
98 const repositoryPath = repositoryPathOf(canonicalKey);
99 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
100 const [owner] = repositoryPathSegments;
101 const repositoryName = repositoryPathSegments.at(-1);
102 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
103
104 return {
105 canonicalKey,
106 locator: {
107 source: "git-remote",
108 remoteName: input.remoteName,
109 remoteUrl: input.remoteUrl,
110 },
111 rootPath: input.rootPath,
112 ...(repositoryPath ? { displayName: repositoryPath } : {}),
113 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
114 ...(owner ? { owner } : {}),
115 ...(repositoryName ? { name: repositoryName } : {}),
116 ...(origin ? { origin } : {}),
117 };
118}
119
120/** Reads the answer from the repository files when possible, otherwise spawns git. */
121const runGitMetadataCommand = Effect.fn("RepositoryIdentityResolver.runGitMetadataCommand")(
122 function* (cwd: string, args: ReadonlyArray<string>) {
123 const answer = yield* Effect.promise(() =>
124 GitMetadataFastPath.tryAnswerGitCommand({ cwd, args }),
125 );
126 if (answer !== null) return Option.some({ code: answer.exitCode, stdout: answer.stdout });
127
128 const processRunner = yield* ProcessRunner.ProcessRunner;
129 // git is a real executable on every platform — no cmd.exe shell mode, which
130 // would split paths containing spaces during cmd's re-tokenization.
131 return yield* processRunner
132 .run({ command: "git", args: ["-C", cwd, ...args], timeoutBehavior: "timedOutResult" })
133 .pipe(Effect.option);
134 },
135);
136
137const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
138 function* (cwd: string) {
139 const topLevelResult = yield* runGitMetadataCommand(cwd, ["rev-parse", "--show-toplevel"]);
140 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
141 return null;
142 }
143
144 const candidate = topLevelResult.value.stdout.trim();
145 return candidate.length > 0 ? candidate : null;
146 },
147);
148
149const resolveRepositoryIdentityFromCacheKey = Effect.fn(
150 "RepositoryIdentityResolver.resolveFromCacheKey",
151)(function* (
152 cacheKey: string,
153): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
154 const remoteResult = yield* runGitMetadataCommand(cacheKey, ["remote", "-v"]);
155 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
156 return null;
157 }
158
159 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
160 const remote = pickPrimaryRemote(remotes);
161 return remote
162 ? buildRepositoryIdentity({ ...remote, originUrl: remotes.get("origin"), rootPath: cacheKey })
163 : null;
164});
165
166export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
167 options: RepositoryIdentityResolverOptions = {},
168) {
169 const processRunner = yield* ProcessRunner.ProcessRunner;
170 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
171 const refine = options.refine ?? Effect.succeed;
172 // Git errors and timeouts resolve to null, so they use the negative TTL like
173 // "no repository" or "no remote". Only interrupts and defects skip the cache.
174 const timeToLive = (exit: Exit.Exit<unknown>) =>
175 Exit.match(exit, {
176 onSuccess: (value) =>
177 value === null
178 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
179 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
180 onFailure: () => Duration.zero,
181 });
182
183 const repositoryRootCache = yield* Cache.makeWith<string, string | null>(
184 (cwd) =>
185 resolveRepositoryIdentityCacheKey(cwd).pipe(
186 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
187 ),
188 { capacity: cacheCapacity, timeToLive },
189 );
190
191 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
192 (cacheKey) =>
193 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
194 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
195 Effect.filterOrElse(
196 (identity): identity is null => identity === null,
197 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
198 ),
199 ),
200 { capacity: cacheCapacity, timeToLive },
201 );
202
203 // Untraced because almost every call is a cache hit. The lookups that spawn
204 // git keep their own spans.
205 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
206 function* (cwd, options) {
207 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
208 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
209 if (cacheKey === null) return null;
210 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
211 return yield* Cache.get(repositoryIdentityCache, cacheKey);
212 },
213 );
214
215 return RepositoryIdentityResolver.of({ resolve });
216});
217
218export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
219 Layer.provide(ProcessRunner.layer),
220);