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

RepositoryIdentityResolver.ts

213 lines7.8 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);
20const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
21​
22export interface RepositoryIdentityResolverOptions {
23 readonly cacheCapacity?: number;
24 readonly positiveCacheTtl?: Duration.Input;
25 readonly negativeCacheTtl?: Duration.Input;
26 readonly refine?: (
27 identity: RepositoryIdentity,
28 ) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>;
30​
31export class RepositoryIdentityResolver extends Context.Service<
32 RepositoryIdentityResolver,
33 {
34 readonly resolve: (
35 cwd: string,
36 options?: { readonly refresh?: boolean },
37 ) => Effect.Effect<RepositoryIdentity | null>;
38 }
39>()("t3/project/RepositoryIdentityResolver") {}
40​
41function parseRemoteFetchUrls(stdout: string): Map<string, string> {
42 const remotes = new Map<string, string>();
43 for (const line of stdout.split("\n")) {
44 const trimmed = line.trim();
45 if (trimmed.length === 0) continue;
46 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
47 if (!match) continue;
48 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
49 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
50 continue;
51 }
52 remotes.set(remoteName, remoteUrl);
53 }
54 return remotes;
56​
57function pickPrimaryRemote(
58 remotes: ReadonlyMap<string, string>,
59): { readonly remoteName: string; readonly remoteUrl: string } | null {
60 for (const preferredRemoteName of ["upstream", "origin"] as const) {
61 const remoteUrl = remotes.get(preferredRemoteName);
62 if (remoteUrl) {
63 return { remoteName: preferredRemoteName, remoteUrl };
64 }
65 }
66​
67 const [remoteName, remoteUrl] =
68 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
69 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
71​
72function repositoryPathOf(canonicalKey: string): string {
73 return canonicalKey.split("/").slice(1).join("/");
75​
76function buildRepositoryOrigin(
77 originUrl: string | undefined,
78 canonicalKey: string,
79): RepositoryIdentity["origin"] {
80 if (!originUrl) return undefined;
81 const originKey = normalizeGitRemoteUrl(originUrl);
82 if (originKey === canonicalKey) return undefined;
83 const displayName = repositoryPathOf(originKey);
84 return { canonicalKey: originKey, ...(displayName ? { displayName } : {}) };
86​
87function buildRepositoryIdentity(input: {
88 readonly remoteName: string;
89 readonly remoteUrl: string;
90 readonly originUrl: string | undefined;
91 readonly rootPath: string;
92}): RepositoryIdentity {
93 const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
94 const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
95 const repositoryPath = repositoryPathOf(canonicalKey);
96 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
97 const [owner] = repositoryPathSegments;
98 const repositoryName = repositoryPathSegments.at(-1);
99 const origin = buildRepositoryOrigin(input.originUrl, canonicalKey);
100​
101 return {
102 canonicalKey,
103 locator: {
104 source: "git-remote",
105 remoteName: input.remoteName,
106 remoteUrl: input.remoteUrl,
107 },
108 rootPath: input.rootPath,
109 ...(repositoryPath ? { displayName: repositoryPath } : {}),
110 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
111 ...(owner ? { owner } : {}),
112 ...(repositoryName ? { name: repositoryName } : {}),
113 ...(origin ? { origin } : {}),
114 };
116​
117const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")(
118 function* (cwd: string) {
119 const processRunner = yield* ProcessRunner.ProcessRunner;
120​
121 // git is a real executable on every platform — no cmd.exe shell mode, which
122 // would split paths containing spaces during cmd's re-tokenization.
123 const topLevelResult = yield* processRunner
124 .run({
125 command: "git",
126 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
127 timeoutBehavior: "timedOutResult",
128 })
129 .pipe(Effect.option);
130 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
131 return null;
132 }
133​
134 const candidate = topLevelResult.value.stdout.trim();
135 return candidate.length > 0 ? candidate : null;
136 },
137);
138​
139const resolveRepositoryIdentityFromCacheKey = Effect.fn(
140 "RepositoryIdentityResolver.resolveFromCacheKey",
141)(function* (
142 cacheKey: string,
143): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
144 const processRunner = yield* ProcessRunner.ProcessRunner;
145 const remoteResult = yield* processRunner
146 .run({
147 command: "git",
148 args: ["-C", cacheKey, "remote", "-v"],
149 timeoutBehavior: "timedOutResult",
150 })
151 .pipe(Effect.option);
152 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
153 return null;
154 }
155​
156 const remotes = parseRemoteFetchUrls(remoteResult.value.stdout);
157 const remote = pickPrimaryRemote(remotes);
158 return remote
159 ? buildRepositoryIdentity({ ...remote, originUrl: remotes.get("origin"), rootPath: cacheKey })
160 : null;
161});
162​
163export const make = Effect.fn("RepositoryIdentityResolver.make")(function* (
164 options: RepositoryIdentityResolverOptions = {},
165) {
166 const processRunner = yield* ProcessRunner.ProcessRunner;
167 const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY;
168 const refine = options.refine ?? Effect.succeed;
169 const timeToLive = (exit: Exit.Exit<unknown>) =>
170 Exit.match(exit, {
171 onSuccess: (value) =>
172 value === null
173 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
174 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
175 onFailure: () => Duration.zero,
176 });
177​
178 const repositoryRootCache = yield* Cache.makeWith<string, string | null>(
179 (cwd) =>
180 resolveRepositoryIdentityCacheKey(cwd).pipe(
181 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
182 ),
183 { capacity: cacheCapacity, timeToLive },
184 );
185​
186 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
187 (cacheKey) =>
188 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
189 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
190 Effect.filterOrElse(
191 (identity): identity is null => identity === null,
192 (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)),
193 ),
194 ),
195 { capacity: cacheCapacity, timeToLive },
196 );
197​
198 const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced(
199 function* (cwd, options) {
200 if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd);
201 const cacheKey = yield* Cache.get(repositoryRootCache, cwd);
202 if (cacheKey === null) return null;
203 if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey);
204 return yield* Cache.get(repositoryIdentityCache, cacheKey);
205 },
206 );
207​
208 return RepositoryIdentityResolver.of({ resolve });
209});
210​
211export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(
212 Layer.provide(ProcessRunner.layer),
213);