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 * as Context from "effect/Context"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import * as PlatformError from "effect/PlatformError"; |
| 5 | import * as Result from "effect/Result"; |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import { |
| 8 | NonNegativeInt, |
| 9 | TrimmedNonEmptyString, |
| 10 | type SourceControlRepositoryVisibility, |
| 11 | type VcsError, |
| 12 | type VcsProcessExitFailureKind, |
| 13 | } from "@t3tools/contracts"; |
| 14 | |
| 15 | import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; |
| 16 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 17 | import { SpawnExecutableResolution } from "@t3tools/shared/shell"; |
| 18 | import { AzureCliInstallLocation } from "./azureCliLauncher.ts"; |
| 19 | import { |
| 20 | decodeAzureDevOpsPullRequestJson, |
| 21 | decodeAzureDevOpsPullRequestListJson, |
| 22 | type NormalizedAzureDevOpsPullRequestRecord, |
| 23 | } from "./azureDevOpsPullRequests.ts"; |
| 24 | import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; |
| 25 | |
| 26 | const DEFAULT_TIMEOUT_MS = 30_000; |
| 27 | |
| 28 | const azureDevOpsCommandErrorFields = { |
| 29 | operation: Schema.Literal("execute"), |
| 30 | command: Schema.Literal("az"), |
| 31 | cwd: Schema.String, |
| 32 | argumentCount: NonNegativeInt, |
| 33 | cause: Schema.Defect(), |
| 34 | }; |
| 35 | |
| 36 | export class AzureDevOpsCliUnavailableError extends Schema.TaggedError<AzureDevOpsCliUnavailableError>()( |
| 37 | "AzureDevOpsCliUnavailableError", |
| 38 | azureDevOpsCommandErrorFields, |
| 39 | ) { |
| 40 | get detail(): string { |
| 41 | return "Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH."; |
| 42 | } |
| 43 | |
| 44 | override get message(): string { |
| 45 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | export class AzureDevOpsCliAuthenticationError extends Schema.TaggedError<AzureDevOpsCliAuthenticationError>()( |
| 50 | "AzureDevOpsCliAuthenticationError", |
| 51 | azureDevOpsCommandErrorFields, |
| 52 | ) { |
| 53 | get detail(): string { |
| 54 | return "Azure DevOps CLI is not authenticated. Run `az devops login` and retry."; |
| 55 | } |
| 56 | |
| 57 | override get message(): string { |
| 58 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | export class AzureDevOpsCliRateLimitError extends Schema.TaggedError<AzureDevOpsCliRateLimitError>()( |
| 63 | "AzureDevOpsCliRateLimitError", |
| 64 | azureDevOpsCommandErrorFields, |
| 65 | ) { |
| 66 | get detail(): string { |
| 67 | return "Azure DevOps API rate limit exceeded."; |
| 68 | } |
| 69 | |
| 70 | override get message(): string { |
| 71 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | export class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedError<AzureDevOpsPullRequestNotFoundError>()( |
| 76 | "AzureDevOpsPullRequestNotFoundError", |
| 77 | azureDevOpsCommandErrorFields, |
| 78 | ) { |
| 79 | get detail(): string { |
| 80 | return "Pull request not found. Check the PR number or URL and try again."; |
| 81 | } |
| 82 | |
| 83 | override get message(): string { |
| 84 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | export class AzureDevOpsCommandFailedError extends Schema.TaggedError<AzureDevOpsCommandFailedError>()( |
| 89 | "AzureDevOpsCommandFailedError", |
| 90 | azureDevOpsCommandErrorFields, |
| 91 | ) { |
| 92 | get detail(): string { |
| 93 | return "Azure DevOps CLI command failed."; |
| 94 | } |
| 95 | |
| 96 | override get message(): string { |
| 97 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 98 | } |
| 99 | |
| 100 | static fromVcsError( |
| 101 | context: { |
| 102 | readonly operation: "execute"; |
| 103 | readonly command: "az"; |
| 104 | readonly cwd: string; |
| 105 | readonly argumentCount: number; |
| 106 | }, |
| 107 | cause: VcsError, |
| 108 | ): AzureDevOpsCliError { |
| 109 | const fields = { ...context, cause }; |
| 110 | |
| 111 | if ( |
| 112 | cause._tag === "VcsProcessSpawnError" && |
| 113 | cause.cause instanceof PlatformError.PlatformError && |
| 114 | cause.cause.reason._tag === "NotFound" && |
| 115 | cause.cause.reason.pathOrDescriptor !== context.cwd && |
| 116 | cause.cause.reason.syscall !== "chdir" |
| 117 | ) { |
| 118 | return new AzureDevOpsCliUnavailableError(fields); |
| 119 | } |
| 120 | |
| 121 | if (cause._tag === "VcsProcessExitError") { |
| 122 | if (cause.failureKind === "authentication") { |
| 123 | return new AzureDevOpsCliAuthenticationError(fields); |
| 124 | } |
| 125 | if (cause.failureKind === "rate-limited") { |
| 126 | return new AzureDevOpsCliRateLimitError(fields); |
| 127 | } |
| 128 | if (cause.failureKind === "not-found") { |
| 129 | return new AzureDevOpsPullRequestNotFoundError(fields); |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | return new AzureDevOpsCommandFailedError(fields); |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | const azureDevOpsDecodeErrorFields = { |
| 138 | command: Schema.Literal("az"), |
| 139 | cwd: Schema.String, |
| 140 | outputLength: NonNegativeInt, |
| 141 | cause: Schema.Defect(), |
| 142 | }; |
| 143 | |
| 144 | export class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedError<AzureDevOpsPullRequestListDecodeError>()( |
| 145 | "AzureDevOpsPullRequestListDecodeError", |
| 146 | { |
| 147 | operation: Schema.Literal("listPullRequests"), |
| 148 | ...azureDevOpsDecodeErrorFields, |
| 149 | }, |
| 150 | ) { |
| 151 | get detail(): string { |
| 152 | return "Azure DevOps CLI returned invalid PR list JSON."; |
| 153 | } |
| 154 | |
| 155 | override get message(): string { |
| 156 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | export class AzureDevOpsPullRequestDecodeError extends Schema.TaggedError<AzureDevOpsPullRequestDecodeError>()( |
| 161 | "AzureDevOpsPullRequestDecodeError", |
| 162 | { |
| 163 | operation: Schema.Literal("getPullRequest"), |
| 164 | ...azureDevOpsDecodeErrorFields, |
| 165 | }, |
| 166 | ) { |
| 167 | get detail(): string { |
| 168 | return "Azure DevOps CLI returned invalid pull request JSON."; |
| 169 | } |
| 170 | |
| 171 | override get message(): string { |
| 172 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | const AzureDevOpsRepositoryDecodeOperation = Schema.Literals([ |
| 177 | "getRepositoryCloneUrls", |
| 178 | "getDefaultBranch", |
| 179 | "createRepository", |
| 180 | ]); |
| 181 | |
| 182 | export class AzureDevOpsRepositoryDecodeError extends Schema.TaggedError<AzureDevOpsRepositoryDecodeError>()( |
| 183 | "AzureDevOpsRepositoryDecodeError", |
| 184 | { |
| 185 | operation: AzureDevOpsRepositoryDecodeOperation, |
| 186 | ...azureDevOpsDecodeErrorFields, |
| 187 | }, |
| 188 | ) { |
| 189 | get detail(): string { |
| 190 | return "Azure DevOps CLI returned invalid repository JSON."; |
| 191 | } |
| 192 | |
| 193 | override get message(): string { |
| 194 | return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`; |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | export const AzureDevOpsCliError = Schema.Union([ |
| 199 | AzureDevOpsCliUnavailableError, |
| 200 | AzureDevOpsCliAuthenticationError, |
| 201 | AzureDevOpsCliRateLimitError, |
| 202 | AzureDevOpsPullRequestNotFoundError, |
| 203 | AzureDevOpsCommandFailedError, |
| 204 | AzureDevOpsPullRequestListDecodeError, |
| 205 | AzureDevOpsPullRequestDecodeError, |
| 206 | AzureDevOpsRepositoryDecodeError, |
| 207 | ]); |
| 208 | export type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type; |
| 209 | |
| 210 | export interface AzureDevOpsRepositoryCloneUrls { |
| 211 | readonly nameWithOwner: string; |
| 212 | readonly url: string; |
| 213 | readonly sshUrl: string; |
| 214 | } |
| 215 | |
| 216 | export class AzureDevOpsCli extends Context.Service< |
| 217 | AzureDevOpsCli, |
| 218 | { |
| 219 | readonly execute: (input: { |
| 220 | readonly cwd: string; |
| 221 | readonly args: ReadonlyArray<string>; |
| 222 | readonly timeoutMs?: number; |
| 223 | readonly maxOutputBytes?: number; |
| 224 | /** The remote T3 selected; without one, the checkout's primary remote scopes the command. */ |
| 225 | readonly remoteUrl?: string; |
| 226 | readonly stdin?: string; |
| 227 | }) => Effect.Effect<SourceControlHost.SourceControlProcessOutput, AzureDevOpsCliError>; |
| 228 | |
| 229 | readonly listPullRequests: (input: { |
| 230 | readonly cwd: string; |
| 231 | readonly headSelector: string; |
| 232 | readonly source?: SourceControlProvider.SourceControlRefSelector; |
| 233 | readonly state: "open" | "closed" | "merged" | "all"; |
| 234 | readonly limit?: number; |
| 235 | readonly remoteUrl?: string; |
| 236 | }) => Effect.Effect<ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>, AzureDevOpsCliError>; |
| 237 | |
| 238 | readonly getPullRequest: (input: { |
| 239 | readonly cwd: string; |
| 240 | readonly reference: string; |
| 241 | readonly remoteUrl?: string; |
| 242 | }) => Effect.Effect<NormalizedAzureDevOpsPullRequestRecord, AzureDevOpsCliError>; |
| 243 | |
| 244 | readonly getRepositoryCloneUrls: (input: { |
| 245 | readonly cwd: string; |
| 246 | readonly repository: string; |
| 247 | readonly remoteUrl?: string; |
| 248 | }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>; |
| 249 | |
| 250 | readonly createRepository: (input: { |
| 251 | readonly cwd: string; |
| 252 | readonly repository: string; |
| 253 | readonly visibility: SourceControlRepositoryVisibility; |
| 254 | }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>; |
| 255 | |
| 256 | readonly createPullRequest: (input: { |
| 257 | readonly cwd: string; |
| 258 | readonly baseBranch: string; |
| 259 | readonly headSelector: string; |
| 260 | readonly source?: SourceControlProvider.SourceControlRefSelector; |
| 261 | readonly target?: SourceControlProvider.SourceControlRefSelector; |
| 262 | readonly title: string; |
| 263 | readonly bodyFile: string; |
| 264 | readonly draft?: boolean; |
| 265 | readonly remoteUrl?: string; |
| 266 | }) => Effect.Effect<void, AzureDevOpsCliError>; |
| 267 | |
| 268 | readonly getDefaultBranch: (input: { |
| 269 | readonly cwd: string; |
| 270 | readonly repository: string; |
| 271 | readonly remoteUrl?: string; |
| 272 | }) => Effect.Effect<string | null, AzureDevOpsCliError>; |
| 273 | } |
| 274 | >()("@t3tools/source-control-azure-devops/server/AzureDevOpsCli") {} |
| 275 | |
| 276 | function normalizeChangeRequestId(reference: string): string { |
| 277 | const trimmed = reference.trim().replace(/^#/, ""); |
| 278 | const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\/(\d+)(?:\D.*)?$/i.exec(trimmed); |
| 279 | return urlMatch?.[1] ?? trimmed; |
| 280 | } |
| 281 | |
| 282 | function toAzureStatus(state: "open" | "closed" | "merged" | "all"): string { |
| 283 | switch (state) { |
| 284 | case "open": |
| 285 | return "active"; |
| 286 | case "closed": |
| 287 | return "abandoned"; |
| 288 | case "merged": |
| 289 | return "completed"; |
| 290 | case "all": |
| 291 | return "all"; |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | const RawAzureDevOpsRepositorySchema = Schema.Struct({ |
| 296 | name: TrimmedNonEmptyString, |
| 297 | webUrl: TrimmedNonEmptyString, |
| 298 | remoteUrl: TrimmedNonEmptyString, |
| 299 | sshUrl: TrimmedNonEmptyString, |
| 300 | project: Schema.optional( |
| 301 | Schema.Struct({ |
| 302 | name: TrimmedNonEmptyString, |
| 303 | }), |
| 304 | ), |
| 305 | defaultBranch: Schema.optional(Schema.NullOr(Schema.String)), |
| 306 | }); |
| 307 | |
| 308 | function normalizeDefaultBranch(value: string | null | undefined): string | null { |
| 309 | const trimmed = value?.trim().replace(/^refs\/heads\//, "") ?? ""; |
| 310 | return trimmed.length > 0 ? trimmed : null; |
| 311 | } |
| 312 | |
| 313 | function normalizeRepositoryCloneUrls( |
| 314 | raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>, |
| 315 | ): AzureDevOpsRepositoryCloneUrls { |
| 316 | const projectName = raw.project?.name.trim(); |
| 317 | return { |
| 318 | nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name, |
| 319 | url: raw.remoteUrl, |
| 320 | sshUrl: raw.sshUrl, |
| 321 | }; |
| 322 | } |
| 323 | |
| 324 | function parseRepositorySpecifier(repository: string): { |
| 325 | readonly project: string | null; |
| 326 | readonly name: string; |
| 327 | } { |
| 328 | const parts: Array<string> = []; |
| 329 | for (const part of repository.split("/")) { |
| 330 | const trimmed = part.trim(); |
| 331 | if (trimmed.length > 0) { |
| 332 | parts.push(trimmed); |
| 333 | } |
| 334 | } |
| 335 | return { |
| 336 | project: parts.length > 1 ? (parts.at(-2) ?? null) : null, |
| 337 | name: parts.at(-1) ?? repository.trim(), |
| 338 | }; |
| 339 | } |
| 340 | |
| 341 | function decodeAzureDevOpsJson<S extends Schema.Top>( |
| 342 | raw: string, |
| 343 | schema: S, |
| 344 | operation: typeof AzureDevOpsRepositoryDecodeOperation.Type, |
| 345 | cwd: string, |
| 346 | ): Effect.Effect<S["Type"], AzureDevOpsRepositoryDecodeError, S["DecodingServices"]> { |
| 347 | return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe( |
| 348 | Effect.mapError( |
| 349 | (cause) => |
| 350 | new AzureDevOpsRepositoryDecodeError({ |
| 351 | operation, |
| 352 | command: "az", |
| 353 | cwd, |
| 354 | outputLength: raw.length, |
| 355 | cause, |
| 356 | }), |
| 357 | ), |
| 358 | ); |
| 359 | } |
| 360 | |
| 361 | /** The remote that scopes `az` when T3 selected none, from `git remote -v` output. */ |
| 362 | export function primaryRemoteUrl(output: string) { |
| 363 | if (!output.endsWith("\n")) return null; |
| 364 | const remotes = new Map<string, string>(); |
| 365 | for (const line of output.split("\n")) { |
| 366 | const trimmed = line.trim(); |
| 367 | if (trimmed.length === 0) continue; |
| 368 | const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/u.exec(trimmed); |
| 369 | if (!match?.[1] || !match[2]) return null; |
| 370 | if (match[3] === "fetch" && !remotes.has(match[1])) remotes.set(match[1], match[2]); |
| 371 | } |
| 372 | // Match the provider context SourceControlProviderRegistry binds, and `az`'s own detection. |
| 373 | return ( |
| 374 | remotes.get("origin") ?? |
| 375 | [...remotes.values()].find((url) => scopeFromRemoteUrl(url) !== null) ?? |
| 376 | null |
| 377 | ); |
| 378 | } |
| 379 | |
| 380 | function scopeFromRemoteUrl(remote: string) { |
| 381 | try { |
| 382 | const scp = /^(?:[^@/]+@)?([^/:]+):(.+)$/u.exec(remote); |
| 383 | const url = new URL( |
| 384 | remote.includes("://") ? remote : scp ? `ssh://${scp[1]}/${scp[2]}` : remote, |
| 385 | ); |
| 386 | if (url.search || url.hash) return null; |
| 387 | const legacy = url.hostname.endsWith(".visualstudio.com"); |
| 388 | const parts = url.pathname.slice(1).split("/").map(decodeURIComponent); |
| 389 | let organization: string | undefined; |
| 390 | if ( |
| 391 | url.protocol === "ssh:" && |
| 392 | (url.hostname === "ssh.dev.azure.com" || url.hostname === "vs-ssh.visualstudio.com") |
| 393 | ) { |
| 394 | if (parts.length !== 4 || parts.shift() !== "v3") return null; |
| 395 | organization = parts.shift(); |
| 396 | } else if (url.protocol === "https:") { |
| 397 | if (url.hostname === "dev.azure.com") organization = parts.shift(); |
| 398 | else { |
| 399 | organization = /^([^.]+)\.visualstudio\.com$/u.exec(url.hostname)?.[1]; |
| 400 | if (!organization) return null; |
| 401 | if (parts[0]?.toLowerCase() === "defaultcollection") parts.shift(); |
| 402 | } |
| 403 | if (parts.length !== 3 || parts[1] !== "_git") return null; |
| 404 | parts.splice(1, 1); |
| 405 | } else return null; |
| 406 | const [project, repository] = parts; |
| 407 | if (!organization || !project || !repository) return null; |
| 408 | // `az` replaces a value starting with `@` by the contents of that local file. |
| 409 | if ([organization, project, repository].some((part) => /^@|[\p{Cc}/\\]/u.test(part))) { |
| 410 | return null; |
| 411 | } |
| 412 | if (legacy && !/^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/u.test(organization)) |
| 413 | return null; |
| 414 | return { |
| 415 | // az keys organization-scoped credentials by the original host family. |
| 416 | organization: legacy |
| 417 | ? `https://${organization}.visualstudio.com` |
| 418 | : `https://dev.azure.com/${encodeURIComponent(organization)}`, |
| 419 | project, |
| 420 | repository, |
| 421 | }; |
| 422 | } catch { |
| 423 | return null; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | const remoteOf = (input: { readonly remoteUrl?: string }) => |
| 428 | input.remoteUrl === undefined ? {} : { remoteUrl: input.remoteUrl }; |
| 429 | |
| 430 | const hasOption = (args: ReadonlyArray<string>, pattern: RegExp) => |
| 431 | args.some((arg) => pattern.test(arg)); |
| 432 | |
| 433 | /** Whether `az` would run `--detect true`, which inspects the checkout from wherever `az` runs. */ |
| 434 | const detectsScope = (args: ReadonlyArray<string>) => { |
| 435 | const detect = args.indexOf("--detect"); |
| 436 | return ( |
| 437 | args[0] !== "account" && |
| 438 | detect !== -1 && |
| 439 | args[detect + 1] === "true" && |
| 440 | !hasOption(args, /^(?:--organization|--org)(?:=|$)/u) |
| 441 | ); |
| 442 | }; |
| 443 | |
| 444 | /** Replaces `--detect true` with the scope of an Azure remote. */ |
| 445 | export function scopeAzureCliArgs( |
| 446 | args: ReadonlyArray<string>, |
| 447 | remoteUrl: string, |
| 448 | ): ReadonlyArray<string> { |
| 449 | const scope = detectsScope(args) ? scopeFromRemoteUrl(remoteUrl) : null; |
| 450 | if (!scope) return args; |
| 451 | const scoped = [...args, "--organization", scope.organization]; |
| 452 | scoped[args.indexOf("--detect") + 1] = "false"; |
| 453 | // PR-ID commands and devops invoke accept only organization scope. |
| 454 | const acceptsProject = |
| 455 | args[0] === "repos" && |
| 456 | (args[1] === "show" || |
| 457 | args[1] === "create" || |
| 458 | (args[1] === "pr" && (args[2] === "list" || args[2] === "create"))); |
| 459 | if (!acceptsProject) return scoped; |
| 460 | // Joined so a name starting with `-` stays the option's value. |
| 461 | if (!hasOption(args, /^(?:--project|-p)(?:=|$)/u)) scoped.push(`--project=${scope.project}`); |
| 462 | if (args[1] !== "create" && !hasOption(args, /^(?:--repository|-r)(?:=|$)/u)) { |
| 463 | scoped.push(`--repository=${scope.repository}`); |
| 464 | } |
| 465 | return scoped; |
| 466 | } |
| 467 | |
| 468 | const classifyAzFailure = (stderr: string): VcsProcessExitFailureKind | null => { |
| 469 | const normalized = stderr.toLowerCase(); |
| 470 | if (normalized.includes("az devops login") || /please run '?az login'?/.test(normalized)) { |
| 471 | return "authentication"; |
| 472 | } |
| 473 | // Azure DevOps reports usage-limit throttling as TF400733, often without an HTTP status. |
| 474 | if (normalized.includes("tf400733")) return "rate-limited"; |
| 475 | return normalized.includes("pull request") && |
| 476 | (normalized.includes("not found") || normalized.includes("does not exist")) |
| 477 | ? "not-found" |
| 478 | : null; |
| 479 | }; |
| 480 | |
| 481 | export interface AzureCliInvocation { |
| 482 | readonly command: string; |
| 483 | /** Arguments `az` needs before the caller's, to run the CLI in UTF-8 mode. */ |
| 484 | readonly args: ReadonlyArray<string>; |
| 485 | readonly env?: NodeJS.ProcessEnv; |
| 486 | } |
| 487 | |
| 488 | /** |
| 489 | * `-X utf8` is the only way in: the launcher's `-I` implies `-E`, so `PYTHONUTF8` and |
| 490 | * `PYTHONIOENCODING` are ignored, and the ANSI code page loses text `az` cannot encode. |
| 491 | * Resolved once when the service is built: installing `az` later needs a restart. |
| 492 | */ |
| 493 | export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(function* () { |
| 494 | if ((yield* HostProcess.Platform) !== "win32") { |
| 495 | return { command: "az", args: [] } satisfies AzureCliInvocation; |
| 496 | } |
| 497 | const resolveExecutable = yield* SpawnExecutableResolution; |
| 498 | const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); |
| 499 | const installFor = yield* AzureCliInstallLocation; |
| 500 | const install = launcher === undefined ? undefined : installFor(launcher); |
| 501 | // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. |
| 502 | return install === undefined |
| 503 | ? ({ command: "az", args: [] } satisfies AzureCliInvocation) |
| 504 | : ({ |
| 505 | command: install.interpreter, |
| 506 | args: ["-X", "utf8", "-IBm", "azure.cli"], |
| 507 | // What the launcher sets before running this same interpreter. |
| 508 | env: { AZ_INSTALLER: install.installer }, |
| 509 | } satisfies AzureCliInvocation); |
| 510 | }); |
| 511 | |
| 512 | /** |
| 513 | * `--option=value` for free text. az replaces a value starting with `@` by that file's |
| 514 | * contents; `@-` reads it from stdin instead, which reaches az wherever it runs (WSL included). |
| 515 | */ |
| 516 | export const textOption = (option: string, value: string) => |
| 517 | value.startsWith("@") |
| 518 | ? { arg: `${option}=@-`, stdin: value } |
| 519 | : { arg: `${option}=${value}`, stdin: undefined }; |
| 520 | |
| 521 | /** @public */ |
| 522 | export const make = Effect.gen(function* () { |
| 523 | const { process } = yield* SourceControlHost.SourceControlHost; |
| 524 | const invocation = yield* azureCliInvocation(); |
| 525 | |
| 526 | const execute: AzureDevOpsCli["Service"]["execute"] = Effect.fn("AzureDevOpsCli.execute")( |
| 527 | function* (input) { |
| 528 | let args = input.args; |
| 529 | if (detectsScope(args)) { |
| 530 | // Windows az running in WSL cannot inspect the server's Linux checkout. |
| 531 | const remoteUrl = |
| 532 | input.remoteUrl ?? |
| 533 | (yield* process |
| 534 | .run({ |
| 535 | operation: "AzureDevOpsCli.resolveScope", |
| 536 | command: "git", |
| 537 | args: ["remote", "-v"], |
| 538 | cwd: input.cwd, |
| 539 | env: { |
| 540 | GIT_DIR: undefined, |
| 541 | GIT_WORK_TREE: undefined, |
| 542 | GIT_COMMON_DIR: undefined, |
| 543 | GIT_INDEX_FILE: undefined, |
| 544 | GIT_OBJECT_DIRECTORY: undefined, |
| 545 | GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined, |
| 546 | }, |
| 547 | timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, |
| 548 | maxOutputBytes: 64 * 1024, |
| 549 | allowNonZeroExit: true, |
| 550 | }) |
| 551 | .pipe( |
| 552 | Effect.map((remotes) => |
| 553 | remotes.exitCode === 0 && !remotes.stdoutTruncated && !remotes.stdoutInvalidUtf8 |
| 554 | ? primaryRemoteUrl(remotes.stdout) |
| 555 | : null, |
| 556 | ), |
| 557 | Effect.orElseSucceed(() => null), |
| 558 | )); |
| 559 | if (remoteUrl !== null) args = scopeAzureCliArgs(args, remoteUrl); |
| 560 | } |
| 561 | return yield* process |
| 562 | .run({ |
| 563 | operation: "AzureDevOpsCli.execute", |
| 564 | command: invocation.command, |
| 565 | args: [...invocation.args, ...args], |
| 566 | cwd: input.cwd, |
| 567 | ...(invocation.env === undefined ? {} : { env: invocation.env }), |
| 568 | ...(input.stdin === undefined ? {} : { stdin: input.stdin }), |
| 569 | classifyFailure: classifyAzFailure, |
| 570 | notFoundDetail: "Pull request not found.", |
| 571 | timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS, |
| 572 | ...(input.maxOutputBytes === undefined ? {} : { maxOutputBytes: input.maxOutputBytes }), |
| 573 | }) |
| 574 | .pipe( |
| 575 | Effect.mapError((error) => |
| 576 | AzureDevOpsCommandFailedError.fromVcsError( |
| 577 | { |
| 578 | operation: "execute", |
| 579 | command: "az", |
| 580 | cwd: input.cwd, |
| 581 | argumentCount: input.args.length, |
| 582 | }, |
| 583 | error, |
| 584 | ), |
| 585 | ), |
| 586 | ); |
| 587 | }, |
| 588 | ); |
| 589 | |
| 590 | const executeJson = (input: Parameters<AzureDevOpsCli["Service"]["execute"]>[0]) => |
| 591 | execute({ |
| 592 | ...input, |
| 593 | args: [...input.args, "--only-show-errors", "--output", "json"], |
| 594 | }); |
| 595 | |
| 596 | return AzureDevOpsCli.of({ |
| 597 | execute, |
| 598 | listPullRequests: Effect.fn("AzureDevOpsCli.listPullRequests")(function (input) { |
| 599 | const branch = SourceControlProvider.sourceBranch(input); |
| 600 | // az checks literal ref prefixes before constructing the request URL. |
| 601 | const refPrefix = |
| 602 | ["refs/heads/", "refs/pull/", "refs/tags/"].find((prefix) => branch.startsWith(prefix)) ?? |
| 603 | ""; |
| 604 | return executeJson({ |
| 605 | cwd: input.cwd, |
| 606 | ...remoteOf(input), |
| 607 | args: [ |
| 608 | "repos", |
| 609 | "pr", |
| 610 | "list", |
| 611 | "--detect", |
| 612 | "true", |
| 613 | "--source-branch", |
| 614 | // az puts this in the query string unescaped; a `#` would cut the request. |
| 615 | refPrefix + encodeURIComponent(branch.slice(refPrefix.length)), |
| 616 | "--status", |
| 617 | toAzureStatus(input.state), |
| 618 | "--top", |
| 619 | String(input.limit ?? 20), |
| 620 | ], |
| 621 | }).pipe( |
| 622 | Effect.map((result) => result.stdout.trim()), |
| 623 | Effect.flatMap((raw) => |
| 624 | raw.length === 0 |
| 625 | ? Effect.succeed([]) |
| 626 | : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe( |
| 627 | Effect.flatMap((decoded) => { |
| 628 | if (!Result.isSuccess(decoded)) { |
| 629 | return Effect.fail( |
| 630 | new AzureDevOpsPullRequestListDecodeError({ |
| 631 | operation: "listPullRequests", |
| 632 | command: "az", |
| 633 | cwd: input.cwd, |
| 634 | outputLength: raw.length, |
| 635 | cause: decoded.failure, |
| 636 | }), |
| 637 | ); |
| 638 | } |
| 639 | |
| 640 | return Effect.succeed(decoded.success); |
| 641 | }), |
| 642 | ), |
| 643 | ), |
| 644 | ); |
| 645 | }), |
| 646 | getPullRequest: Effect.fn("AzureDevOpsCli.getPullRequest")(function (input) { |
| 647 | return executeJson({ |
| 648 | cwd: input.cwd, |
| 649 | ...remoteOf(input), |
| 650 | args: [ |
| 651 | "repos", |
| 652 | "pr", |
| 653 | "show", |
| 654 | "--detect", |
| 655 | "true", |
| 656 | "--id", |
| 657 | normalizeChangeRequestId(input.reference), |
| 658 | ], |
| 659 | }).pipe( |
| 660 | Effect.map((result) => result.stdout.trim()), |
| 661 | Effect.flatMap((raw) => |
| 662 | Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe( |
| 663 | Effect.flatMap((decoded) => { |
| 664 | if (!Result.isSuccess(decoded)) { |
| 665 | return Effect.fail( |
| 666 | new AzureDevOpsPullRequestDecodeError({ |
| 667 | operation: "getPullRequest", |
| 668 | command: "az", |
| 669 | cwd: input.cwd, |
| 670 | outputLength: raw.length, |
| 671 | cause: decoded.failure, |
| 672 | }), |
| 673 | ); |
| 674 | } |
| 675 | |
| 676 | return Effect.succeed(decoded.success); |
| 677 | }), |
| 678 | ), |
| 679 | ), |
| 680 | ); |
| 681 | }), |
| 682 | getRepositoryCloneUrls: Effect.fn("AzureDevOpsCli.getRepositoryCloneUrls")(function (input) { |
| 683 | const repository = parseRepositorySpecifier(input.repository); |
| 684 | return executeJson({ |
| 685 | cwd: input.cwd, |
| 686 | ...remoteOf(input), |
| 687 | args: [ |
| 688 | "repos", |
| 689 | "show", |
| 690 | "--detect", |
| 691 | "true", |
| 692 | "--repository", |
| 693 | repository.name, |
| 694 | ...(repository.project ? ["--project", repository.project] : []), |
| 695 | ], |
| 696 | }).pipe( |
| 697 | Effect.map((result) => result.stdout.trim()), |
| 698 | Effect.flatMap((raw) => |
| 699 | decodeAzureDevOpsJson( |
| 700 | raw, |
| 701 | RawAzureDevOpsRepositorySchema, |
| 702 | "getRepositoryCloneUrls", |
| 703 | input.cwd, |
| 704 | ), |
| 705 | ), |
| 706 | Effect.map(normalizeRepositoryCloneUrls), |
| 707 | ); |
| 708 | }), |
| 709 | createRepository: Effect.fn("AzureDevOpsCli.createRepository")(function (input) { |
| 710 | const repository = parseRepositorySpecifier(input.repository); |
| 711 | // Project/organization permissions control visibility; `az repos create` has no flag. |
| 712 | return executeJson({ |
| 713 | cwd: input.cwd, |
| 714 | args: [ |
| 715 | "repos", |
| 716 | "create", |
| 717 | "--detect", |
| 718 | "true", |
| 719 | "--name", |
| 720 | repository.name, |
| 721 | ...(repository.project ? ["--project", repository.project] : []), |
| 722 | ], |
| 723 | }).pipe( |
| 724 | Effect.map((result) => result.stdout.trim()), |
| 725 | Effect.flatMap((raw) => |
| 726 | decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "createRepository", input.cwd), |
| 727 | ), |
| 728 | Effect.map(normalizeRepositoryCloneUrls), |
| 729 | ); |
| 730 | }), |
| 731 | createPullRequest: Effect.fn("AzureDevOpsCli.createPullRequest")(function (input) { |
| 732 | // A full ref keeps a branch named `@...` from reading as a file; az accepts either form. |
| 733 | const branch = (name: string) => (name.startsWith("@") ? `refs/heads/${name}` : name); |
| 734 | const title = textOption("--title", input.title); |
| 735 | return execute({ |
| 736 | cwd: input.cwd, |
| 737 | ...remoteOf(input), |
| 738 | args: [ |
| 739 | "repos", |
| 740 | "pr", |
| 741 | "create", |
| 742 | "--only-show-errors", |
| 743 | "--detect", |
| 744 | "true", |
| 745 | `--target-branch=${branch(input.target?.refName ?? input.baseBranch)}`, |
| 746 | `--source-branch=${branch(SourceControlProvider.sourceBranch(input))}`, |
| 747 | title.arg, |
| 748 | // Joined: az expands a separate `@file` value again, so a body of `@path` read that file. |
| 749 | `--description=@${input.bodyFile}`, |
| 750 | ...(input.draft === true ? ["--draft", "true"] : []), |
| 751 | ], |
| 752 | ...(title.stdin === undefined ? {} : { stdin: title.stdin }), |
| 753 | }).pipe(Effect.asVoid); |
| 754 | }), |
| 755 | getDefaultBranch: Effect.fn("AzureDevOpsCli.getDefaultBranch")(function (input) { |
| 756 | const repository = parseRepositorySpecifier(input.repository); |
| 757 | return executeJson({ |
| 758 | cwd: input.cwd, |
| 759 | ...remoteOf(input), |
| 760 | args: [ |
| 761 | "repos", |
| 762 | "show", |
| 763 | "--detect", |
| 764 | "true", |
| 765 | // Joined so a name starting with `-` stays the option's value. |
| 766 | `--repository=${repository.name}`, |
| 767 | ...(repository.project ? ["--project", repository.project] : []), |
| 768 | ], |
| 769 | }).pipe( |
| 770 | Effect.map((result) => result.stdout.trim()), |
| 771 | Effect.flatMap((raw) => |
| 772 | decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, "getDefaultBranch", input.cwd), |
| 773 | ), |
| 774 | Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)), |
| 775 | ); |
| 776 | }), |
| 777 | }); |
| 778 | }); |
| 779 | |
| 780 | export const layer = Layer.effect(AzureDevOpsCli, make); |