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

AzureDevOpsSourceControlProvider.ts

329 lines12.7 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 probeTimeoutMs: AzureDevOpsCli.AZ_TIMEOUT_MS,
53 parseAuth: parseAzureAuth,
54 installHint:
55 "Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.",
56} satisfies SourceControlCliDiscoverySpec;
57​
58/**
59 * The repository name a remote ends in; `az` takes it decoded and finds org and project itself.
60 * Azure clone URLs carry no `.git` suffix, so a trailing `.git` is part of the name.
61 */
62function repositoryNameFromRemote(remoteUrl: string): string | null {
63 const path = URL.parse(remoteUrl.trim())?.pathname ?? remoteUrl.trim();
64 const encoded = path.replace(/\/+$/u, "").split(/[/:]/u).at(-1);
65 if (!encoded) return null;
66 let name = encoded;
67 try {
68 name = decodeURIComponent(encoded);
69 } catch {}
70 // `az` replaces any argument value starting with `@` by the contents of that local file.
71 return name.startsWith("@") ? null : name;
73​
74/** The remote T3 selected, which scopes `az` instead of the checkout's primary remote. */
75const remoteOf = (input: { readonly context?: { readonly remoteUrl: string } | undefined }) =>
76 input.context === undefined ? {} : { remoteUrl: input.context.remoteUrl };
77​
78function toChangeRequest(summary: NormalizedAzureDevOpsPullRequestRecord): ChangeRequest {
79 return {
80 provider: SourceControlProviderKind.make("azure-devops"),
81 number: summary.number,
82 title: summary.title,
83 url: summary.url,
84 baseRefName: summary.baseRefName,
85 headRefName: summary.headRefName,
86 ...(summary.headSha !== undefined ? { headSha: summary.headSha } : {}),
87 state: summary.state,
88 ...(summary.isDraft === true ? { isDraft: true } : {}),
89 closedAt: summary.closedAt ?? null,
90 mergedAt: summary.mergedAt ?? null,
91 updatedAt: summary.updatedAt,
92 isCrossRepository: summary.isCrossRepository,
93 };
95​
96export const make = Effect.gen(function* () {
97 const azure = yield* AzureDevOpsCli.AzureDevOpsCli;
98 const { git } = yield* SourceControlHost.SourceControlHost;
99​
100 return SourceControlProvider.SourceControlProvider.of({
101 kind: SourceControlProviderKind.make("azure-devops"),
102 // Azure lists fork pull requests by source branch with no owner filter, so read a full page.
103 headBranchProbe: ({ headSelectors }) => ({
104 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
105 limit: 100,
106 }),
107 readChangeRequestTemplate: Effect.fn(
108 "AzureDevOpsSourceControlProvider.readChangeRequestTemplate",
109 )(
110 function* ({ cwd }) {
111 // Azure uses the repository default branch even when the PR targets another branch.
112 const remoteName = yield* git.resolvePrimaryRemoteName(cwd);
113 const defaultRef = yield* git.execute({
114 operation: "AzureDevOpsSourceControlProvider.resolveDefaultBranch",
115 cwd,
116 args: ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`],
117 });
118 return yield* AzureDevOpsChangeRequestTemplate.detect(
119 cwd,
120 defaultRef.stdout.replace(/\r?\n$/, ""),
121 git.execute,
122 );
123 },
124 Effect.orElseSucceed(() => Option.none()),
125 ),
126 listChangeRequests: Effect.fn("AzureDevOpsSourceControlProvider.listChangeRequests")(
127 function (input) {
128 const source = SourceControlProvider.sourceControlRefFromInput(input);
129 return azure
130 .listPullRequests({
131 cwd: input.cwd,
132 ...remoteOf(input),
133 headSelector: input.headSelector,
134 ...(source !== undefined ? { source } : {}),
135 state: input.state,
136 ...(input.limit !== undefined ? { limit: input.limit } : {}),
137 })
138 .pipe(
139 Effect.map((items) => items.map(toChangeRequest)),
140 Effect.mapError(
141 (error) =>
142 new SourceControlProviderError({
143 provider: SourceControlProviderKind.make("azure-devops"),
144 operation: "listChangeRequests",
145 command: error.command,
146 cwd: input.cwd,
147 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
148 input.headSelector,
149 ),
150 detail: error.detail,
151 cause: error,
152 }),
153 ),
154 );
155 },
156 ),
157 getChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.getChangeRequest")(
158 function (input) {
159 return azure
160 .getPullRequest({ cwd: input.cwd, reference: input.reference, ...remoteOf(input) })
161 .pipe(
162 Effect.map(toChangeRequest),
163 Effect.mapError(
164 (error) =>
165 new SourceControlProviderError({
166 provider: SourceControlProviderKind.make("azure-devops"),
167 operation: "getChangeRequest",
168 command: error.command,
169 cwd: input.cwd,
170 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
171 input.reference,
172 ),
173 detail: error.detail,
174 cause: error,
175 }),
176 ),
177 );
178 },
179 ),
180 createsDraftChangeRequests: true,
181 createChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.createChangeRequest")(
182 function (input) {
183 const source = SourceControlProvider.sourceControlRefFromInput(input);
184 return azure
185 .createPullRequest({
186 cwd: input.cwd,
187 ...remoteOf(input),
188 baseBranch: input.baseRefName,
189 headSelector: input.headSelector,
190 ...(source !== undefined ? { source } : {}),
191 ...(input.target !== undefined ? { target: input.target } : {}),
192 title: input.title,
193 bodyFile: input.bodyFile,
194 ...(input.draft === true ? { draft: true } : {}),
195 })
196 .pipe(
197 Effect.mapError(
198 (error) =>
199 new SourceControlProviderError({
200 provider: SourceControlProviderKind.make("azure-devops"),
201 operation: "createChangeRequest",
202 command: error.command,
203 cwd: input.cwd,
204 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
205 input.headSelector,
206 ),
207 detail: error.detail,
208 cause: error,
209 }),
210 ),
211 );
212 },
213 ),
214 getRepositoryCloneUrls: Effect.fn("AzureDevOpsSourceControlProvider.getRepositoryCloneUrls")(
215 function (input) {
216 return azure
217 .getRepositoryCloneUrls({
218 cwd: input.cwd,
219 repository: input.repository,
220 ...remoteOf(input),
221 })
222 .pipe(
223 Effect.mapError(
224 (error) =>
225 new SourceControlProviderError({
226 provider: SourceControlProviderKind.make("azure-devops"),
227 operation: "getRepositoryCloneUrls",
228 command: error.command,
229 cwd: input.cwd,
230 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
231 input.repository,
232 ),
233 detail: error.detail,
234 cause: error,
235 }),
236 ),
237 );
238 },
239 ),
240 createRepository: Effect.fn("AzureDevOpsSourceControlProvider.createRepository")(
241 function (input) {
242 return azure.createRepository(input).pipe(
243 Effect.mapError(
244 (error) =>
245 new SourceControlProviderError({
246 provider: SourceControlProviderKind.make("azure-devops"),
247 operation: "createRepository",
248 command: error.command,
249 cwd: input.cwd,
250 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
251 input.repository,
252 ),
253 detail: error.detail,
254 cause: error,
255 }),
256 ),
257 );
258 },
259 ),
260 getDefaultBranch: Effect.fn("AzureDevOpsSourceControlProvider.getDefaultBranch")(
261 function (input) {
262 const remoteUrl = input.context?.remoteUrl;
263 const repository = remoteUrl === undefined ? null : repositoryNameFromRemote(remoteUrl);
264 if (remoteUrl === undefined || repository === null) return Effect.succeed(null);
265 return azure.getDefaultBranch({ cwd: input.cwd, repository, remoteUrl }).pipe(
266 Effect.mapError(
267 (error) =>
268 new SourceControlProviderError({
269 provider: SourceControlProviderKind.make("azure-devops"),
270 operation: "getDefaultBranch",
271 command: error.command,
272 cwd: input.cwd,
273 detail: error.detail,
274 cause: error,
275 }),
276 ),
277 );
278 },
279 ),
280 // `az repos pr checkout` ignores git failures: in a single-branch clone its checkout fails
281 // and its pull then merges the pull request into the current branch.
282 checkoutChangeRequest: Effect.fn("AzureDevOpsSourceControlProvider.checkoutChangeRequest")(
283 function* (input) {
284 const pullRequest = yield* azure.getPullRequest({
285 cwd: input.cwd,
286 reference: input.reference,
287 ...remoteOf(input),
288 });
289 if (pullRequest.isCrossRepository)
290 return yield* new SourceControlProviderError({
291 provider: SourceControlProviderKind.make("azure-devops"),
292 operation: "checkoutChangeRequest",
293 cwd: input.cwd,
294 reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),
295 detail: "Checking out an Azure DevOps pull request from a fork is not supported.",
296 });
297 const branch = pullRequest.headRefName;
298 const remoteBranch = {
299 cwd: input.cwd,
300 remoteName: input.context?.remoteName ?? "origin",
301 remoteBranch: branch,
302 };
303 // An existing branch is only switched to; the caller advances it without losing commits.
304 if ((yield* git.listLocalBranchNames(input.cwd)).includes(branch))
305 yield* git.fetchRemoteTrackingBranch(remoteBranch);
306 else yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch: branch });
307 yield* git.switchRef({ cwd: input.cwd, refName: branch });
308 },
309 (effect, input) =>
310 effect.pipe(
311 Effect.mapError((error) =>
312 error._tag === "SourceControlProviderError"
313 ? error
314 : new SourceControlProviderError({
315 provider: SourceControlProviderKind.make("azure-devops"),
316 operation: "checkoutChangeRequest",
317 command: error.command,
318 cwd: input.cwd,
319 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
320 input.reference,
321 ),
322 detail: error.detail,
323 cause: error,
324 }),
325 ),
326 ),
327 ),
328 });
329});