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