Open History to see the last commit
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;
32}
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;
47}
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 };
74}
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;
84}
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 shell: process.platform === "win32",
98 })
99 .pipe(Effect.option);
100 if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
101 return cacheKey;
102 }
103
104 const candidate = topLevelResult.value.stdout.trim();
105 if (candidate.length > 0) {
106 cacheKey = candidate;
107 }
108
109 return cacheKey;
110});
111
112const resolveRepositoryIdentityFromCacheKey = Effect.fn("resolveRepositoryIdentityFromCacheKey")(
113 function* (
114 cacheKey: string,
115 ): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
116 const processRunner = yield* ProcessRunner.ProcessRunner;
117 const remoteResult = yield* processRunner
118 .run({
119 command: "git",
120 args: ["-C", cacheKey, "remote", "-v"],
121 timeoutBehavior: "timedOutResult",
122 shell: process.platform === "win32",
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);
133
134export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
135 function* (options: RepositoryIdentityResolverOptions = {}) {
136 const processRunner = yield* ProcessRunner.ProcessRunner;
137
138 const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
139 (cacheKey) =>
140 resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
141 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
142 ),
143 {
144 capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
145 timeToLive: Exit.match({
146 onSuccess: (value) =>
147 value === null
148 ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)
149 : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),
150 onFailure: () => Duration.zero,
151 }),
152 },
153 );
154
155 const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
156 "RepositoryIdentityResolver.resolve",
157 )(function* (cwd) {
158 const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
159 Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
160 );
161 return yield* Cache.get(repositoryIdentityCache, cacheKey);
162 });
163
164 return {
165 resolve,
166 } satisfies RepositoryIdentityResolverShape;
167 },
168);
169
170export const RepositoryIdentityResolverLive = Layer.effect(
171 RepositoryIdentityResolver,
172 makeRepositoryIdentityResolver(),
173).pipe(Layer.provide(ProcessRunner.layer));