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

AzureDevOpsSourceControlProvider.ts

310 lines11.9 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import { SourceControlProviderError, type ChangeRequest } from "@t3tools/contracts";
5​
6import * as AzureDevOpsChangeRequestTemplate from "./azureDevOpsChangeRequestTemplate.ts";
7import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
8import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
9import type { NormalizedAzureDevOpsPullRequestRecord } from "./azureDevOpsPullRequests.ts";
10import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
11import {
12 combinedAuthOutput,
13 firstSafeAuthLine,
14 providerAuth,
15 type SourceControlAuthProbeInput,
16 type SourceControlCliDiscoverySpec,
17} from "@t3tools/source-control-core/server/discovery";
18​
19function parseAzureAuth(input: SourceControlAuthProbeInput) {
20 const account = input.stdout.trim().split(/\r?\n/)[0]?.trim();
21​
22 if (input.exitCode !== 0) {
23 return providerAuth({
24 status: "unauthenticated",
25 detail:
26 firstSafeAuthLine(combinedAuthOutput(input)) ?? "Run `az login` to authenticate Azure CLI.",
27 });
28 }
29​
30 if (account !== undefined && account.length > 0) {
31 return providerAuth({
32 status: "authenticated",
33 account,
34 host: "dev.azure.com",
35 });
36 }
37​
38 return providerAuth({
39 status: "unknown",
40 host: "dev.azure.com",
41 detail: "Azure CLI account status could not be parsed.",
42 });
44​
45export const discovery = {
46 type: "cli",
47 kind: SourceControlProviderKind.make("azure-devops"),
48 label: "Azure DevOps",
49 executable: "az",
50 versionArgs: ["--version"],
51 authArgs: ["account", "show", "--query", "user.name", "-o", "tsv"],
52 // `az --version` starts Python and takes ~6s on Windows, exceeding the default probe timeout.
53 probeTimeoutMs: 20_000,
54 parseAuth: parseAzureAuth,
55 installHint:
56 "Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.",
57} satisfies SourceControlCliDiscoverySpec;
58​
59/**
60 * The repository name a remote ends in; `az` takes it decoded and finds org and project itself.
61 * Azure clone URLs carry no `.git` suffix, so a trailing `.git` is part of the name.
62 */
63function repositoryNameFromRemote(remoteUrl: string): string | null {
64 const path = URL.parse(remoteUrl.trim())?.pathname ?? remoteUrl.trim();
65 const encoded = path.replace(/\/+$/u, "").split(/[/:]/u).at(-1);
66 if (!encoded) return null;
67 let name = encoded;
68 try {
69 name = decodeURIComponent(encoded);
70 } catch {}
71 // `az` replaces any argument value starting with `@` by the contents of that local file.
72 return name.startsWith("@") ? null : name;
74​
75function toChangeRequest(summary: NormalizedAzureDevOpsPullRequestRecord): ChangeRequest {
76 return {
77 provider: SourceControlProviderKind.make("azure-devops"),
78 number: summary.number,
79 title: summary.title,
80 url: summary.url,
81 baseRefName: summary.baseRefName,
82 headRefName: summary.headRefName,
83 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
84 state: summary.state,
85 ...(summary.isDraft === true ? { isDraft: true } : {}),
86 closedAt: summary.closedAt ?? null,
87 mergedAt: summary.mergedAt ?? null,
88 updatedAt: summary.updatedAt,
89 isCrossRepository: summary.isCrossRepository,
90 };
92​
93export const make = Effect.gen(function* () {
94 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
95 const { git } = yield* SourceControlHost.SourceControlHost;
96​
97 return SourceControlProvider.SourceControlProvider.of({
98 kind: SourceControlProviderKind.make("azure-devops"),
99 // Azure lists fork pull requests by source branch with no owner filter, so read a full page.
100 headBranchProbe: ({ headSelectors }) => ({
101 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
102 limit: 100,
103 }),
104 readChangeRequestTemplate: Effect.fn(
105 "AzureDevOpsSourceControlProvider.readChangeRequestTemplate",
106 )(
107 function* ({ cwd }) {
108 // Azure uses the repository default branch even when the PR targets another branch.
109 const remoteName = yield* git.resolvePrimaryRemoteName(cwd);
110 const defaultRef = yield* git.execute({
111 operation: "AzureDevOpsSourceControlProvider.resolveDefaultBranch",
112 cwd,
113 args: ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`],
114 });
115 return yield* AzureDevOpsChangeRequestTemplate.detect(
116 cwd,
117 defaultRef.stdout.trim(),
118 git.execute,
119 );
120 },
121 Effect.orElseSucceed(() => Option.none()),
122 ),
123 listChangeRequests: Effect.fn("AzureDevOpsSourceControlProvider.listChangeRequests")(
124 function (input) {
125 const source = SourceControlProvider.sourceControlRefFromInput(input);
126 return azure
127 .listPullRequests({
128 cwd: input.cwd,
129 headSelector: input.headSelector,
130 ...(source !== undefined ? { source } : {}),
131 state: input.state,
132 ...(input.limit !== undefined ? { limit: input.limit } : {}),
133 })
134 .pipe(
135 Effect.map((items) => items.map(toChangeRequest)),
136 Effect.mapError(
137 (error) =>
138 new SourceControlProviderError({
139 provider: SourceControlProviderKind.make("azure-devops"),
140 operation: "listChangeRequests",
141 command: error.command,
142 cwd: input.cwd,
143 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
144 input.headSelector,
145 ),
146 detail: error.detail,
147 cause: error,
148 }),
149 ),
150 );
151 },
152 ),
153 getChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.getChangeRequest")(
154 function (input) {
155 return azure.getPullRequest(input).pipe(
156 Effect.map(toChangeRequest),
157 Effect.mapError(
158 (error) =>
159 new SourceControlProviderError({
160 provider: SourceControlProviderKind.make("azure-devops"),
161 operation: "getChangeRequest",
162 command: error.command,
163 cwd: input.cwd,
164 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
165 input.reference,
166 ),
167 detail: error.detail,
168 cause: error,
169 }),
170 ),
171 );
172 },
173 ),
174 createChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.createChangeRequest")(
175 function (input) {
176 const source = SourceControlProvider.sourceControlRefFromInput(input);
177 return azure
178 .createPullRequest({
179 cwd: input.cwd,
180 baseBranch: input.baseRefName,
181 headSelector: input.headSelector,
182 ...(source !== undefined ? { source } : {}),
183 ...(input.target !== undefined ? { target: input.target } : {}),
184 title: input.title,
185 bodyFile: input.bodyFile,
186 })
187 .pipe(
188 Effect.mapError(
189 (error) =>
190 new SourceControlProviderError({
191 provider: SourceControlProviderKind.make("azure-devops"),
192 operation: "createChangeRequest",
193 command: error.command,
194 cwd: input.cwd,
195 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
196 input.headSelector,
197 ),
198 detail: error.detail,
199 cause: error,
200 }),
201 ),
202 );
203 },
204 ),
205 getRepositoryCloneUrls: Effect.fn("AzureDevOpsSourceControlProvider.getRepositoryCloneUrls")(
206 function (input) {
207 return azure.getRepositoryCloneUrls(input).pipe(
208 Effect.mapError(
209 (error) =>
210 new SourceControlProviderError({
211 provider: SourceControlProviderKind.make("azure-devops"),
212 operation: "getRepositoryCloneUrls",
213 command: error.command,
214 cwd: input.cwd,
215 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
216 input.repository,
217 ),
218 detail: error.detail,
219 cause: error,
220 }),
221 ),
222 );
223 },
224 ),
225 createRepository: Effect.fn("AzureDevOpsSourceControlProvider.createRepository")(
226 function (input) {
227 return azure.createRepository(input).pipe(
228 Effect.mapError(
229 (error) =>
230 new SourceControlProviderError({
231 provider: SourceControlProviderKind.make("azure-devops"),
232 operation: "createRepository",
233 command: error.command,
234 cwd: input.cwd,
235 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
236 input.repository,
237 ),
238 detail: error.detail,
239 cause: error,
240 }),
241 ),
242 );
243 },
244 ),
245 getDefaultBranch: Effect.fn("AzureDevOpsSourceControlProvider.getDefaultBranch")(
246 function (input) {
247 const repository =
248 input.context === undefined ? null : repositoryNameFromRemote(input.context.remoteUrl);
249 if (repository === null) return Effect.succeed(null);
250 return azure.getDefaultBranch({ cwd: input.cwd, repository }).pipe(
251 Effect.mapError(
252 (error) =>
253 new SourceControlProviderError({
254 provider: SourceControlProviderKind.make("azure-devops"),
255 operation: "getDefaultBranch",
256 command: error.command,
257 cwd: input.cwd,
258 detail: error.detail,
259 cause: error,
260 }),
261 ),
262 );
263 },
264 ),
265 // `az repos pr checkout` ignores git failures: in a single-branch clone its checkout fails
266 // and its pull then merges the pull request into the current branch.
267 checkoutChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.checkoutChangeRequest")(
268 function* (input) {
269 const pullRequest = yield* azure.getPullRequest(input);
270 if (pullRequest.isCrossRepository)
271 return yield* new SourceControlProviderError({
272 provider: SourceControlProviderKind.make("azure-devops"),
273 operation: "checkoutChangeRequest",
274 cwd: input.cwd,
275 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
276 detail: "Checking out an Azure DevOps pull request from a fork is not supported.",
277 });
278 const branch = pullRequest.headRefName;
279 const remoteBranch = {
280 cwd: input.cwd,
281 remoteName: input.context?.remoteName ?? "origin",
282 remoteBranch: branch,
283 };
284 // An existing branch is only switched to; the caller advances it without losing commits.
285 if ((yield* git.listLocalBranchNames(input.cwd)).includes(branch))
286 yield* git.fetchRemoteTrackingBranch(remoteBranch);
287 else yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch: branch });
288 yield* git.switchRef({ cwd: input.cwd, refName: branch });
289 },
290 (effect, input) =>
291 effect.pipe(
292 Effect.mapError((error) =>
293 error._tag === "SourceControlProviderError"
294 ? error
295 : new SourceControlProviderError({
296 provider: SourceControlProviderKind.make("azure-devops"),
297 operation: "checkoutChangeRequest",
298 command: error.command,
299 cwd: input.cwd,
300 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
301 input.reference,
302 ),
303 detail: error.detail,
304 cause: error,
305 }),
306 ),
307 ),
308 ),
309 });
310});