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

RepositoryIdentityResolver.ts

197 lines7.4 KB

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>;
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​
42function parseRemoteFetchUrls(stdout: string): Map<string, string> {
43 const remotes = new Map<string, string>();
44 for (const line of stdout.split("\n")) {
45 const trimmed = line.trim();
46 if (trimmed.length === 0) continue;
47 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
48 if (!match) continue;
49 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
50 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
51 continue;
52 }
53 remotes.set(remoteName, remoteUrl);
54 }
55 return remotes;
57​
58function pickPrimaryRemote(
59 remotes: ReadonlyMap<string, string>,
60): { readonly remoteName: string; readonly remoteUrl: string } | null {
61 for (const preferredRemoteName of ["upstream", "origin"] as const) {
62 const remoteUrl = remotes.get(preferredRemoteName);
63 if (remoteUrl) {
64 return { remoteName: preferredRemoteName, remoteUrl };
65 }
66 }
67​
68 const [remoteName, remoteUrl] =
69 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
70 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
72​
73function buildRepositoryIdentity(input: {
74 readonly remoteName: string;
75 readonly remoteUrl: string;
76 readonly rootPath: string;
77}): RepositoryIdentity {
78 const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
79 const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
80 const repositoryPath = canonicalKey.split("/").slice(1).join("/");
81 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
82 const [owner] = repositoryPathSegments;
83 const repositoryName = repositoryPathSegments.at(-1);
84​
85 return {
86 canonicalKey,
87 locator: {
88 source: "git-remote",
89 remoteName: input.remoteName,
90 remoteUrl: input.remoteUrl,
91 },
92 rootPath: input.rootPath,
93 ...(repositoryPath ? { displayName: repositoryPath } : {}),
94 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
95 ...(owner ? { owner } : {}),
96 ...(repositoryName ? { name: repositoryName } : {}),
97 };
99​
100const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
101 function* (cwd: string) {
102 const processRunner = yield* ProcessRunner.ProcessRunner;
103​
104 // git is a real executable on every platform — no cmd.exe shell mode, which
105 // would split paths containing spaces during cmd's re-tokenization.
106 const topLevelResult = yield* processRunner
107 .run({
108 command: "git",
109 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
110 timeoutBehavior: "timedOutResult",
111 })
112 .pipe(Effect.option);
113 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
114 return null;
115 }
116​
117 const candidate = topLevelResult.value.stdout.trim();
118 return candidate.length > 0 ? candidate : null;
119 },
120);
121​
122const resolveRepositoryIdentityFromCacheKey = Effect.fn(
123 "RepositoryIdentityResolver.resolveFromCacheKey",
124)(function* (
125 cacheKey: string,
126): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
127 const processRunner = yield* ProcessRunner.ProcessRunner;
128 const remoteResult = yield* processRunner
129 .run({
130 command: "git",
131 args: ["-C", cacheKey, "remote", "-v"],
132 timeoutBehavior: "timedOutResult",
133 })
134 .pipe(Effect.option);
135 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
136 return null;
137 }
138​
139 const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));
140 return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
141});
142​
143export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
144 options: RepositoryIdentityResolverOptions = {},
145) {
146 const processRunner = yield* ProcessRunner.ProcessRunner;
147 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
148 const refine = options.refine ?? Effect.succeed;
149 // Git errors and timeouts resolve to null, so they use the negative TTL like
150 // "no repository" or "no remote". Only interrupts and defects skip the cache.
151 const timeToLive = (exit: Exit.Exit<unknown>) =>
152 Exit.match(exit, {
153 onSuccess: (value) =>
154 value === null
155 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
156 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
157 onFailure: () => Duration.zero,
158 });
159​
160 const repositoryRootCache = yield* Cache.makeWith<string, string | null>(
161 (cwd) =>
162 resolveRepositoryIdentityCacheKey(cwd).pipe(
163 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
164 ),
165 { capacity: cacheCapacity, timeToLive },
166 );
167​
168 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
169 (cacheKey) =>
170 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
171 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
172 Effect.filterOrElse(
173 (identity): identity is null => identity === null,
174 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
175 ),
176 ),
177 { capacity: cacheCapacity, timeToLive },
178 );
179​
180 // Untraced because almost every call is a cache hit. The lookups that spawn
181 // git keep their own spans.
182 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
183 function* (cwd, options) {
184 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
185 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
186 if (cacheKey === null) return null;
187 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
188 return yield* Cache.get(repositoryIdentityCache, cacheKey);
189 },
190 );
191​
192 return RepositoryIdentityResolver.of({ resolve });
193});
194​
195export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
196 Layer.provide(ProcessRunner.layer),
197);