The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; |
| 2 | import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; |
| 3 | import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; |
| 4 | import { canonicalRepositoryPath, normalizeGitRemoteUrl } from "@t3tools/shared/git"; |
| 5 | import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; |
| 6 | import * as Cache from "effect/Cache"; |
| 7 | import * as Context from "effect/Context"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Exit from "effect/Exit"; |
| 12 | import * as FileSystem from "effect/FileSystem"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | import * as Path from "effect/Path"; |
| 15 | |
| 16 | import * as ProcessRunner from "../processRunner.ts"; |
| 17 | import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; |
| 18 | import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; |
| 19 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 20 | |
| 21 | const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512; |
| 22 | // Minute-by-minute sweeps need cached hits; clone, publish and PR discovery force refresh. |
| 23 | const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15); |
| 24 | const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1); |
| 25 | |
| 26 | export interface RepositoryIdentityResolverOptions { |
| 27 | readonly cacheCapacity?: number; |
| 28 | readonly refine?: ( |
| 29 | identity: RepositoryIdentity, |
| 30 | ) => Effect.Effect<RepositoryIdentity, SourceControlProviderError>; |
| 31 | } |
| 32 | |
| 33 | export 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 | |
| 43 | // Local paths such as GitButler's gb-local=. would give unrelated repos the same identity. |
| 44 | function isLocalRemoteUrl(url: string): boolean { |
| 45 | if (/^file:/i.test(url)) return true; |
| 46 | if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false; |
| 47 | if (/^[a-z]:[\\/]/i.test(url)) return true; |
| 48 | // Git treats `host:path` as scp-style only when the colon precedes any slash. |
| 49 | const colonIndex = url.indexOf(":"); |
| 50 | const slashIndex = url.search(/[\\/]/); |
| 51 | return colonIndex === -1 || (slashIndex !== -1 && slashIndex < colonIndex); |
| 52 | } |
| 53 | |
| 54 | function parseRemoteFetchUrls(stdout: string): Map<string, string> { |
| 55 | const remotes = new Map<string, string>(); |
| 56 | for (const line of stdout.split(/\r?\n/)) { |
| 57 | // Git uses a tab before the URL and one space before the direction; both can occur in URLs. |
| 58 | // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. |
| 59 | const match = /^(\S+)\t(.+) \((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(line); |
| 60 | if (!match) continue; |
| 61 | const [, remoteName = "", remoteUrl = "", direction = ""] = match; |
| 62 | if ( |
| 63 | direction !== "fetch" || |
| 64 | remoteName.length === 0 || |
| 65 | remoteUrl.length === 0 || |
| 66 | isLocalRemoteUrl(remoteUrl) |
| 67 | ) { |
| 68 | continue; |
| 69 | } |
| 70 | remotes.set(remoteName, remoteUrl); |
| 71 | } |
| 72 | return remotes; |
| 73 | } |
| 74 | |
| 75 | // `gh repo set-default` marks one remote with `base`, or with OWNER/REPO when it picked a |
| 76 | // parent repository. gh reads PRs from that repository, so the identity follows the mark when |
| 77 | // a remote fetches it. The locator must name a real remote: review checkouts fetch through it. |
| 78 | function pickMarkedRemote( |
| 79 | remotes: ReadonlyMap<string, string>, |
| 80 | resolved: string, |
| 81 | ): { readonly remoteName: string; readonly remoteUrl: string } | null { |
| 82 | const marks = resolved.split("\n").flatMap((line) => { |
| 83 | const match = /^remote\.(.+)\.gh-resolved\s+(\S+)$/u.exec(line.trim()); |
| 84 | const remoteUrl = match?.[1] === undefined ? undefined : remotes.get(match[1]); |
| 85 | return match?.[1] && match[2] && remoteUrl |
| 86 | ? [{ remoteName: match[1], remoteUrl, value: match[2] }] |
| 87 | : []; |
| 88 | }); |
| 89 | // gh's choice is ambiguous with several marks; GitHubSourceControlProvider ignores them too. |
| 90 | const [mark, ...others] = marks; |
| 91 | if (!mark || others.length > 0) return null; |
| 92 | if (mark.value === "base") return { remoteName: mark.remoteName, remoteUrl: mark.remoteUrl }; |
| 93 | // Compare hosts with HTTP ports kept: one hostname can serve separate forges on two ports. |
| 94 | const host = parseGitRemoteHost(mark.remoteUrl)?.host; |
| 95 | const markedPath = mark.value.toLowerCase(); |
| 96 | const [remoteName, remoteUrl] = |
| 97 | [...remotes.entries()].find( |
| 98 | ([, url]) => |
| 99 | parseGitRemoteHost(url)?.host === host && |
| 100 | normalizeGitRemoteUrl(url).split("/").slice(1).join("/") === markedPath, |
| 101 | ) ?? []; |
| 102 | return remoteName && remoteUrl ? { remoteName, remoteUrl } : null; |
| 103 | } |
| 104 | |
| 105 | function pickPrimaryRemote( |
| 106 | remotes: ReadonlyMap<string, string>, |
| 107 | resolved: string, |
| 108 | ): { readonly remoteName: string; readonly remoteUrl: string } | null { |
| 109 | const marked = pickMarkedRemote(remotes, resolved); |
| 110 | if (marked) return marked; |
| 111 | |
| 112 | for (const preferredRemoteName of ["upstream", "origin"] as const) { |
| 113 | const remoteUrl = remotes.get(preferredRemoteName); |
| 114 | if (remoteUrl) { |
| 115 | return { remoteName: preferredRemoteName, remoteUrl }; |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | const [remoteName, remoteUrl] = |
| 120 | [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? []; |
| 121 | return remoteName && remoteUrl ? { remoteName, remoteUrl } : null; |
| 122 | } |
| 123 | |
| 124 | function repositoryPathOf(canonicalKey: string, remoteUrl: string): string { |
| 125 | const canonicalPath = canonicalKey.split("/").slice(1).join("/"); |
| 126 | const displayPath = repositoryPathFromRemoteUrl(remoteUrl); |
| 127 | if (displayPath === null) return canonicalPath; |
| 128 | // A host that names repositories literally keeps the `.git` the display path drops. |
| 129 | return ( |
| 130 | [displayPath, `${displayPath}.git`].find( |
| 131 | (path) => canonicalRepositoryPath(path) === canonicalRepositoryPath(canonicalPath), |
| 132 | ) ?? canonicalPath |
| 133 | ); |
| 134 | } |
| 135 | |
| 136 | // A leading `-` on the user or host would be read by ssh as an option. |
| 137 | const SSH_REMOTE = /^((?:ssh:\/\/)?)((?:[^-@/:][^@/:]*@)?)([A-Za-z0-9][A-Za-z0-9._-]*)([:/].*)$/su; |
| 138 | const SSH_HOST_NAME = /^[a-z0-9][a-z0-9.-]*$/u; |
| 139 | const IPV4 = /^[\d.]+$/u; |
| 140 | |
| 141 | // Keys an SSH remote by the host its ssh config alias (`Host github.com-personal`) points at. |
| 142 | // A dotted host may be a forge whose SSH endpoint has another name, so only a public forge |
| 143 | // replaces it. `ssh -G` prints the configuration it would use and opens no connection. |
| 144 | const sshResolvedRemoteUrl = Effect.fn("RepositoryIdentityResolver.sshResolvedRemoteUrl")( |
| 145 | function* (remoteUrl: string) { |
| 146 | const match = isSshRemoteUrl(remoteUrl) ? SSH_REMOTE.exec(remoteUrl.trim()) : null; |
| 147 | if (!match) return remoteUrl; |
| 148 | const [, scheme = "", user = "", host = "", rest = ""] = match; |
| 149 | if (sourceControlDefinitions.findByPublicHost(host)) return remoteUrl; |
| 150 | const processRunner = yield* ProcessRunner.ProcessRunner; |
| 151 | const result = yield* processRunner |
| 152 | .run({ |
| 153 | command: "ssh", |
| 154 | args: ["-G", `${user}${host}`], |
| 155 | timeout: Duration.seconds(5), |
| 156 | maxOutputBytes: 64_000, |
| 157 | outputMode: "truncate", |
| 158 | timeoutBehavior: "timedOutResult", |
| 159 | }) |
| 160 | .pipe(Effect.option); |
| 161 | if (result._tag === "None" || result.value.code !== 0) return remoteUrl; |
| 162 | const hostName = result.value.stdout |
| 163 | .split("\n") |
| 164 | .find((line) => line.startsWith("hostname ")) |
| 165 | ?.slice("hostname ".length) |
| 166 | .trim() |
| 167 | .toLowerCase(); |
| 168 | if ( |
| 169 | hostName === undefined || |
| 170 | !SSH_HOST_NAME.test(hostName) || |
| 171 | IPV4.test(hostName) || |
| 172 | hostName === host.toLowerCase() || |
| 173 | (host.includes(".") && !sourceControlDefinitions.findByPublicHost(hostName)) |
| 174 | ) { |
| 175 | return remoteUrl; |
| 176 | } |
| 177 | return `${scheme}${user}${hostName}${rest}`; |
| 178 | }, |
| 179 | ); |
| 180 | |
| 181 | function buildRepositoryOrigin( |
| 182 | originUrl: string | undefined, |
| 183 | originKeyUrl: string | undefined, |
| 184 | canonicalKey: string, |
| 185 | ): RepositoryIdentity["origin"] { |
| 186 | if (!originUrl) return undefined; |
| 187 | const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originKeyUrl ?? originUrl); |
| 188 | if (originKey === canonicalKey) return undefined; |
| 189 | const displayName = repositoryPathOf(originKey, originUrl); |
| 190 | return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) }; |
| 191 | } |
| 192 | |
| 193 | function buildRepositoryIdentity(input: { |
| 194 | readonly remoteName: string; |
| 195 | readonly remoteUrl: string; |
| 196 | readonly keyUrl: string; |
| 197 | readonly originUrl: string | undefined; |
| 198 | readonly originKeyUrl: string | undefined; |
| 199 | readonly rootPath: string; |
| 200 | }): RepositoryIdentity { |
| 201 | const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.keyUrl); |
| 202 | const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl); |
| 203 | const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl); |
| 204 | const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0); |
| 205 | const [owner] = repositoryPathSegments; |
| 206 | const repositoryName = repositoryPathSegments.at(-1); |
| 207 | const origin = buildRepositoryOrigin(input.originUrl, input.originKeyUrl, canonicalKey); |
| 208 | |
| 209 | return { |
| 210 | canonicalKey, |
| 211 | locator: { |
| 212 | source: "git-remote", |
| 213 | remoteName: input.remoteName, |
| 214 | remoteUrl: input.remoteUrl, |
| 215 | }, |
| 216 | rootPath: input.rootPath, |
| 217 | ...(repositoryPath ? { displayName: repositoryPath } : {}), |
| 218 | ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}), |
| 219 | ...(owner ? { owner } : {}), |
| 220 | ...(repositoryName ? { name: repositoryName } : {}), |
| 221 | ...(origin ? { origin } : {}), |
| 222 | }; |
| 223 | } |
| 224 | |
| 225 | class RepositoryIdentityCacheKey extends Data.Class<{ |
| 226 | readonly rootPath: string; |
| 227 | readonly isBare: boolean; |
| 228 | }> {} |
| 229 | |
| 230 | const gitEnv = (platform: NodeJS.Platform): NodeJS.ProcessEnv => ({ |
| 231 | ...unsetInheritedRepositoryEnv(process.env, platform), |
| 232 | ...explicitBareRepositoryEnv(process.env, platform), |
| 233 | }); |
| 234 | |
| 235 | const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")( |
| 236 | function* (cwd: string) { |
| 237 | const processRunner = yield* ProcessRunner.ProcessRunner; |
| 238 | const fileSystem = yield* FileSystem.FileSystem; |
| 239 | const path = yield* Path.Path; |
| 240 | const env = gitEnv(yield* HostProcess.Platform); |
| 241 | |
| 242 | // `git -C` cannot enter a missing folder or a file, so every probe below would fail. |
| 243 | const isFolder = yield* fileSystem.stat(cwd).pipe( |
| 244 | Effect.map((info) => info.type === "Directory"), |
| 245 | Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)), |
| 246 | Effect.orElseSucceed(() => true), |
| 247 | ); |
| 248 | if (!isFolder) return null; |
| 249 | |
| 250 | // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization. |
| 251 | const topLevelResult = yield* processRunner |
| 252 | .run({ |
| 253 | command: "git", |
| 254 | args: ["-C", cwd, "rev-parse", "--show-toplevel"], |
| 255 | env, |
| 256 | timeoutBehavior: "timedOutResult", |
| 257 | }) |
| 258 | .pipe(Effect.option); |
| 259 | if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) { |
| 260 | return null; |
| 261 | } |
| 262 | if (topLevelResult.value.code === 0) { |
| 263 | // Git appends LF on every platform; a preceding CR belongs to the path. |
| 264 | const rootPath = topLevelResult.value.stdout.replace(/\n$/, ""); |
| 265 | return rootPath.length > 0 |
| 266 | ? new RepositoryIdentityCacheKey({ rootPath, isBare: false }) |
| 267 | : null; |
| 268 | } |
| 269 | |
| 270 | // Explicit Git directories preserve safe.bareRepository=explicit for both layouts. |
| 271 | for (const [gitDir, entry] of [ |
| 272 | [".", "HEAD"], |
| 273 | [".git", ".git"], |
| 274 | ] as const) { |
| 275 | // An explicit --git-dir fails unless the folder has this entry; a symlink counts even |
| 276 | // when its target is missing, as git reads a symlinked HEAD's target text. |
| 277 | const target = path.join(cwd, entry); |
| 278 | const hasEntry = yield* fileSystem.exists(target).pipe( |
| 279 | Effect.flatMap((exists) => |
| 280 | exists |
| 281 | ? Effect.succeed(true) |
| 282 | : fileSystem.readLink(target).pipe( |
| 283 | Effect.as(true), |
| 284 | Effect.orElseSucceed(() => false), |
| 285 | ), |
| 286 | ), |
| 287 | Effect.orElseSucceed(() => true), |
| 288 | ); |
| 289 | if (!hasEntry) continue; |
| 290 | const bareResult = yield* processRunner |
| 291 | .run({ |
| 292 | command: "git", |
| 293 | args: [ |
| 294 | "-C", |
| 295 | cwd, |
| 296 | `--git-dir=${gitDir}`, |
| 297 | "rev-parse", |
| 298 | "--is-bare-repository", |
| 299 | "--absolute-git-dir", |
| 300 | ], |
| 301 | env, |
| 302 | timeoutBehavior: "timedOutResult", |
| 303 | }) |
| 304 | .pipe(Effect.option); |
| 305 | if (bareResult._tag === "None" || bareResult.value.timedOut) return null; |
| 306 | if (bareResult.value.code !== 0) continue; |
| 307 | |
| 308 | const [isBare, ...rootLines] = bareResult.value.stdout.split("\n"); |
| 309 | const rootPath = rootLines.join("\n").replace(/\n$/, ""); |
| 310 | // A checkout's .git directory contains remotes but is not a project root. |
| 311 | return isBare === "true" && rootPath.length > 0 |
| 312 | ? new RepositoryIdentityCacheKey({ rootPath, isBare: true }) |
| 313 | : null; |
| 314 | } |
| 315 | return null; |
| 316 | }, |
| 317 | ); |
| 318 | |
| 319 | const resolveRepositoryIdentityFromCacheKey = Effect.fn( |
| 320 | "RepositoryIdentityResolver.resolveFromCacheKey", |
| 321 | )(function* ( |
| 322 | cacheKey: RepositoryIdentityCacheKey, |
| 323 | ): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> { |
| 324 | const processRunner = yield* ProcessRunner.ProcessRunner; |
| 325 | const env = gitEnv(yield* HostProcess.Platform); |
| 326 | const runGit = (args: ReadonlyArray<string>) => |
| 327 | processRunner |
| 328 | .run({ |
| 329 | command: "git", |
| 330 | args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), ...args], |
| 331 | env, |
| 332 | timeoutBehavior: "timedOutResult", |
| 333 | }) |
| 334 | .pipe(Effect.option); |
| 335 | const [remoteResult, resolvedResult] = yield* Effect.all( |
| 336 | [runGit(["remote", "-v"]), runGit(["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"])], |
| 337 | { concurrency: "unbounded" }, |
| 338 | ); |
| 339 | if (remoteResult._tag === "None" || remoteResult.value.code !== 0) { |
| 340 | return null; |
| 341 | } |
| 342 | |
| 343 | const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); |
| 344 | // Exits 1 when no remote has a mark. |
| 345 | const resolved = |
| 346 | resolvedResult._tag === "Some" && resolvedResult.value.code === 0 |
| 347 | ? resolvedResult.value.stdout |
| 348 | : ""; |
| 349 | const remote = pickPrimaryRemote(remotes, resolved); |
| 350 | if (!remote) return null; |
| 351 | const originUrl = remotes.get("origin"); |
| 352 | const keyUrl = yield* sshResolvedRemoteUrl(remote.remoteUrl); |
| 353 | const originKeyUrl = |
| 354 | originUrl === undefined || originUrl === remote.remoteUrl |
| 355 | ? keyUrl |
| 356 | : yield* sshResolvedRemoteUrl(originUrl); |
| 357 | return buildRepositoryIdentity({ |
| 358 | ...remote, |
| 359 | keyUrl, |
| 360 | originUrl, |
| 361 | originKeyUrl, |
| 362 | rootPath: cacheKey.rootPath, |
| 363 | }); |
| 364 | }); |
| 365 | |
| 366 | export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( |
| 367 | options: RepositoryIdentityResolverOptions = {}, |
| 368 | ) { |
| 369 | const processRunner = yield* ProcessRunner.ProcessRunner; |
| 370 | const fileSystem = yield* FileSystem.FileSystem; |
| 371 | const path = yield* Path.Path; |
| 372 | const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY; |
| 373 | const refine = options.refine ?? Effect.succeed; |
| 374 | const timeToLive = (exit: Exit.Exit<unknown>) => |
| 375 | Exit.match(exit, { |
| 376 | onSuccess: (value) => |
| 377 | value === null ? DEFAULT_NEGATIVE_CACHE_TTL : DEFAULT_POSITIVE_CACHE_TTL, |
| 378 | onFailure: () => Duration.zero, |
| 379 | }); |
| 380 | |
| 381 | const repositoryRootCache = yield* Cache.makeWith<string, RepositoryIdentityCacheKey | null>( |
| 382 | (cwd) => |
| 383 | resolveRepositoryIdentityCacheKey(cwd).pipe( |
| 384 | Effect.provideService(ProcessRunner.ProcessRunner, processRunner), |
| 385 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 386 | Effect.provideService(Path.Path, path), |
| 387 | ), |
| 388 | { capacity: cacheCapacity, timeToLive }, |
| 389 | ); |
| 390 | |
| 391 | const repositoryIdentityCache = yield* Cache.makeWith< |
| 392 | RepositoryIdentityCacheKey, |
| 393 | RepositoryIdentity | null |
| 394 | >( |
| 395 | (cacheKey) => |
| 396 | resolveRepositoryIdentityFromCacheKey(cacheKey).pipe( |
| 397 | Effect.provideService(ProcessRunner.ProcessRunner, processRunner), |
| 398 | Effect.filterOrElse( |
| 399 | (identity): identity is null => identity === null, |
| 400 | (identity) => refine(identity).pipe(Effect.orElseSucceed(() => identity)), |
| 401 | ), |
| 402 | ), |
| 403 | { capacity: cacheCapacity, timeToLive }, |
| 404 | ); |
| 405 | |
| 406 | const resolve: RepositoryIdentityResolver["Service"]["resolve"] = Effect.fnUntraced( |
| 407 | function* (cwd, options) { |
| 408 | if (options?.refresh) yield* Cache.invalidate(repositoryRootCache, cwd); |
| 409 | const cacheKey = yield* Cache.get(repositoryRootCache, cwd); |
| 410 | if (cacheKey === null) return null; |
| 411 | if (options?.refresh) yield* Cache.invalidate(repositoryIdentityCache, cacheKey); |
| 412 | return yield* Cache.get(repositoryIdentityCache, cacheKey); |
| 413 | }, |
| 414 | ); |
| 415 | |
| 416 | return RepositoryIdentityResolver.of({ resolve }); |
| 417 | }); |
| 418 | |
| 419 | export const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe( |
| 420 | Layer.provide(ProcessRunner.layer), |
| 421 | ); |