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

RepositoryIdentityResolver.ts

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