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

RepositoryIdentityResolver.ts

171 lines5.9 KB

1import type { RepositoryIdentity } from "@t3tools/contracts";
2import * as Cache from "effect/Cache";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import {
8 detectSourceControlProviderFromGitRemoteUrl,
9 normalizeGitRemoteUrl,
10} from "@t3tools/shared/git";
11​
12import * as ProcessRunner from "../../processRunner.ts";
13import {
14 RepositoryIdentityResolver,
15 type RepositoryIdentityResolverShape,
16} from "../Services/RepositoryIdentityResolver.ts";
17​
18function parseRemoteFetchUrls(stdout: string): Map<string, string> {
19 const remotes = new Map<string, string>();
20 for (const line of stdout.split("\n")) {
21 const trimmed = line.trim();
22 if (trimmed.length === 0) continue;
23 const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed);
24 if (!match) continue;
25 const [, remoteName = "", remoteUrl = "", direction = ""] = match;
26 if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) {
27 continue;
28 }
29 remotes.set(remoteName, remoteUrl);
30 }
31 return remotes;
33​
34function pickPrimaryRemote(
35 remotes: ReadonlyMap<string, string>,
36): { readonly remoteName: string; readonly remoteUrl: string } | null {
37 for (const preferredRemoteName of ["upstream", "origin"] as const) {
38 const remoteUrl = remotes.get(preferredRemoteName);
39 if (remoteUrl) {
40 return { remoteName: preferredRemoteName, remoteUrl };
41 }
42 }
43​
44 const [remoteName, remoteUrl] =
45 [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];
46 return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;
48​
49function buildRepositoryIdentity(input: {
50 readonly remoteName: string;
51 readonly remoteUrl: string;
52 readonly rootPath: string;
53}): RepositoryIdentity {
54 const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);
55 const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);
56 const repositoryPath = canonicalKey.split("/").slice(1).join("/");
57 const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0);
58 const [owner] = repositoryPathSegments;
59 const repositoryName = repositoryPathSegments.at(-1);
60​
61 return {
62 canonicalKey,
63 locator: {
64 source: "git-remote",
65 remoteName: input.remoteName,
66 remoteUrl: input.remoteUrl,
67 },
68 rootPath: input.rootPath,
69 ...(repositoryPath ? { displayName: repositoryPath } : {}),
70 ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),
71 ...(owner ? { owner } : {}),
72 ...(repositoryName ? { name: repositoryName } : {}),
73 };
75​
76const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;
77const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);
78const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);
79​
80interface RepositoryIdentityResolverOptions {
81 readonly cacheCapacity?: number;
82 readonly positiveCacheTtl?: Duration.Input;
83 readonly negativeCacheTtl?: Duration.Input;
85​
86const resolveRepositoryIdentityCacheKey = Effect.fn("resolveRepositoryIdentityCacheKey")(function* (
87 cwd: string,
88) {
89 const processRunner = yield* ProcessRunner.ProcessRunner;
90 let cacheKey = cwd;
91​
92 const topLevelResult = yield* processRunner
93 .run({
94 command: "git",
95 args: ["-C", cwd, "rev-parse", "--show-toplevel"],
96 timeoutBehavior: "timedOutResult",
97 })
98 .pipe(Effect.option);
99 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
100 return cacheKey;
101 }
102​
103 const candidate = topLevelResult.value.stdout.trim();
104 if (candidate.length > 0) {
105 cacheKey = candidate;
106 }
107​
108 return cacheKey;
109});
110​
111const resolveRepositoryIdentityFromCacheKey = Effect.fn("resolveRepositoryIdentityFromCacheKey")(
112 function* (
113 cacheKey: string,
114 ): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
115 const processRunner = yield* ProcessRunner.ProcessRunner;
116 const remoteResult = yield* processRunner
117 .run({
118 command: "git",
119 args: ["-C", cacheKey, "remote", "-v"],
120 timeoutBehavior: "timedOutResult",
121 })
122 .pipe(Effect.option);
123 if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
124 return null;
125 }
126​
127 const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));
128 return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
129 },
130);
131​
132export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
133 function* (options: RepositoryIdentityResolverOptions = {}) {
134 const processRunner = yield* ProcessRunner.ProcessRunner;
135​
136 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
137 (cacheKey) =>
138 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
139 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
140 ),
141 {
142 capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
143 timeToLive: Exit.match({
144 onSuccess: (value) =>
145 value === null
146 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
147 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
148 onFailure: () => Duration.zero,
149 }),
150 },
151 );
152​
153 const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
154 "RepositoryIdentityResolver.resolve",
155 )(function* (cwd) {
156 const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
157 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
158 );
159 return yield* Cache.get(repositoryIdentityCache, cacheKey);
160 });
161​
162 return {
163 resolve,
164 } satisfies RepositoryIdentityResolverShape;
165 },
166);
167​
168export const RepositoryIdentityResolverLive = Layer.effect(
169 RepositoryIdentityResolver,
170 makeRepositoryIdentityResolver(),
171).pipe(Layer.provide(ProcessRunner.layer));