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

RepositoryIdentityResolver.ts

184 lines6.4 KB

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