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

AzureDevOpsPullRequestProvider.ts

277 lines10.8 KB

1import * as Effect from "effect/Effect";
2import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
3​
4import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
5import {
6 PullRequestProviderError,
7 type PullRequestProviderFailure,
8 type ProviderChangeRequest,
9 type ProviderChangeRequestActivity,
10 type ProviderChangeRequestDetail,
11 type PullRequestProviderApi,
12} from "./PullRequestProvider.ts";
13import type { AzureDevOpsPullRequest } from "./azureDevOpsPullRequestJson.ts";
14​
15const CAPABILITIES: PullRequestCapabilities = {
16 // `az repos pr` has no diff command, and the REST route reports changed files without their
17 // contents, so there is no patch to show. The Code tab is hidden rather than empty.
18 diff: false,
19 // Reading a conversation is a plain REST read, but posting one is not something this can
20 // claim without having run it, so the composer stays hidden.
21 comment: false,
22 actions: [
23 "merge",
24 "ready",
25 "draft",
26 "close",
27 "reopen",
28 "enable-auto-merge",
29 "disable-auto-merge",
30 ],
31 // Azure squashes as a completion option; it has no rebase strategy of its own.
32 mergeMethods: ["merge", "squash"],
33 // `az repos pr list` filters by status, creator, reviewer and branch, and by no text at all.
34 search: false,
35 reactions: false,
36 // With no patch to show there are no lines to write against, so nothing here is offered.
37 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
38 // `az repos pr reviewer add` and `remove` name identities, and nothing anywhere in `az repos`
39 // lists the ones this repository could name — that lives behind the identity and graph APIs, a
40 // different service with its own permissions. So the page takes a name here rather than being
41 // handed a menu built out of a guess.
42 reviewers: { request: true, listCandidates: false },
43 // A new title and description travel on the same `az repos pr update` that moves a pull request.
44 // Rewriting a remark is false for the same reason posting one is: this cannot put a remark on
45 // Azure DevOps at all, so there is nothing here it could rewrite either.
46 edit: { changeRequest: true, comment: false },
47};
48​
49/**
50 * Everything this host offers, granted to whoever is signed in. Azure DevOps states no permission
51 * anywhere `az repos pr show` or `az repos pr list` reach: the answer lives in the security
52 * namespaces, behind identity descriptors and token paths that would be several calls per pull
53 * request to resolve.
54 *
55 * So the actions stay live and a viewer who may not take one is told so by Azure, at the moment
56 * they try. That is the safer half of an unknown: hiding a control from someone entitled to it
57 * leaves them no way through and no reason given.
58 */
59export const AZURE_DEVOPS_VIEWER_PERMISSIONS: PullRequestViewerPermissions = {
60 actions: CAPABILITIES.actions,
61 comment: CAPABILITIES.comment,
62 resolve: CAPABILITIES.review.resolve,
63 verdicts: CAPABILITIES.review.verdicts,
64 requestReviewers: CAPABILITIES.reviewers.request,
65};
66​
67/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
68export function azureDevOpsProviderFailure(
69 error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError,
70): PullRequestProviderFailure {
71 if (error._tag === "AzureDevOpsCliUnavailableError") return { reason: "missing-tool" };
72 if (error._tag === "AzureDevOpsCliAuthenticationError") return { reason: "unauthenticated" };
73 if (error._tag === "AzureDevOpsCliRateLimitError") return { reason: "rate-limited" };
74 return { reason: "failed" };
76​
77function toChangeRequest(pullRequest: AzureDevOpsPullRequest): ProviderChangeRequest {
78 return {
79 number: pullRequest.number,
80 title: pullRequest.title,
81 url: pullRequest.url,
82 author: pullRequest.author,
83 headBranch: pullRequest.headBranch,
84 baseBranch: pullRequest.baseBranch,
85 state: pullRequest.state,
86 isDraft: pullRequest.isDraft,
87 mergeability: pullRequest.mergeability,
88 // Azure reports no line counts on a pull request, and with no patch to read there is
89 // nothing to count them from either.
90 additions: 0,
91 deletions: 0,
92 createdAt: pullRequest.createdAt,
93 updatedAt: pullRequest.updatedAt,
94 reviewRequestLogins: pullRequest.reviewRequestLogins,
95 // Azure keeps labels on work items rather than on the pull request.
96 labels: [],
97 };
99​
100export const make = Effect.gen(function* () {
101 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
102​
103 const fail =
104 (operation: string) => (error: AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCliError) =>
105 new PullRequestProviderError({
106 provider: "azure-devops",
107 operation,
108 ...azureDevOpsProviderFailure(error),
109 detail: error.detail,
110 cause: error,
111 });
112​
113 /** Refuses what the capabilities already say this host cannot do. */
114 const unsupported = (operation: string) =>
115 Effect.fail(
116 new PullRequestProviderError({
117 provider: "azure-devops",
118 operation,
119 reason: "failed",
120 detail: "Azure DevOps reviews cannot be written from here yet.",
121 }),
122 );
123​
124 const provider: PullRequestProviderApi = {
125 kind: "azure-devops",
126 capabilities: CAPABILITIES,
127​
128 getViewer: (input) =>
129 cli.getViewer({ cwd: input.cwd }).pipe(Effect.mapError(fail("getViewer"))),
130​
131 // `input.query` is deliberately dropped: `az repos pr list` filters by status, creator,
132 // reviewer and branch, and has nothing that matches text. Sending it as one of those would
133 // narrow by the wrong thing, so the page comes back unnarrowed and the caller filters it.
134 listChangeRequests: (input) =>
135 cli
136 .listPullRequests({
137 cwd: input.cwd,
138 repository: input.repository,
139 state: input.state,
140 involvement: input.involvement,
141 viewer: input.viewer,
142 limit: input.limit,
143 cursor: input.cursor,
144 })
145 .pipe(
146 Effect.mapError(fail("listChangeRequests")),
147 Effect.map((batch) => ({
148 items: batch.items.map(toChangeRequest),
149 truncated: batch.truncated,
150 cursorAdvance: batch.cursorAdvance,
151 // Azure answers in one order whether or not it is being carried on from, so a slice
152 // can always be stepped past — by counting, which is all Azure offers.
153 continues: true,
154 })),
155 ),
156​
157 getChangeRequest: (input) =>
158 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
159 Effect.mapError(fail("getChangeRequest")),
160 Effect.map(
161 (pullRequest): ProviderChangeRequestDetail => ({
162 ...toChangeRequest(pullRequest),
163 body: pullRequest.body,
164 changedFiles: 0,
165 mergedAt: pullRequest.state === "merged" ? pullRequest.closedAt : null,
166 closedAt: pullRequest.state === "closed" ? pullRequest.closedAt : null,
167 reviewers: pullRequest.reviewers,
168 checks: [],
169 mergeCapabilities: { merge: true, squash: true, rebase: false },
170 viewerPermissions: AZURE_DEVOPS_VIEWER_PERMISSIONS,
171 autoMergeEnabled: pullRequest.autoMergeEnabled,
172 ...(pullRequest.autoMergeMethod === undefined
173 ? {}
174 : { autoMergeMethod: pullRequest.autoMergeMethod }),
175 }),
176 ),
177 ),
178​
179 getChangeRequestActivity: (input) =>
180 cli.getPullRequest({ cwd: input.cwd, number: input.number }).pipe(
181 Effect.mapError(fail("getChangeRequestActivity")),
182 Effect.flatMap((pullRequest) =>
183 (pullRequest.threadsUrl === null
184 ? Effect.succeed({ comments: [], truncated: true })
185 : cli.listThreads({ cwd: input.cwd, threadsUrl: pullRequest.threadsUrl }).pipe(
186 Effect.map((comments) => ({ comments, truncated: false })),
187 Effect.orElseSucceed(() => ({ comments: [], truncated: true })),
188 )
189 ).pipe(
190 Effect.map(
191 (conversation): ProviderChangeRequestActivity => ({
192 comments: conversation.comments,
193 commentCount: conversation.comments.length,
194 commentsTruncated: conversation.truncated,
195 reviewThreads: [],
196 commits: [],
197 }),
198 ),
199 ),
200 ),
201 ),
202​
203 // No request at all: Azure has nothing to say about the viewer that a pull request read can
204 // reach, so the answer is the same constant the detail carries.
205 getViewerPermissions: () => Effect.succeed(AZURE_DEVOPS_VIEWER_PERMISSIONS),
206​
207 // Never called: `capabilities.diff` is false, and the service refuses a diff without it.
208 getDiff: () =>
209 Effect.fail(
210 new PullRequestProviderError({
211 provider: "azure-devops",
212 operation: "getDiff",
213 reason: "failed",
214 detail: "Azure DevOps cannot produce a patch for a pull request.",
215 }),
216 ),
217​
218 runAction: (input) =>
219 cli
220 .runPullRequestAction({
221 cwd: input.cwd,
222 number: input.number,
223 action: input.action,
224 ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }),
225 })
226 .pipe(Effect.mapError(fail("runAction"))),
227​
228 updateChangeRequest: (input) =>
229 cli
230 .updatePullRequest({
231 cwd: input.cwd,
232 number: input.number,
233 title: input.title,
234 body: input.body,
235 })
236 .pipe(Effect.mapError(fail("updateChangeRequest"))),
237​
238 // Never called: `capabilities.reviewers.listCandidates` is false, and the service refuses the
239 // list without it.
240 listReviewerCandidates: () =>
241 Effect.fail(
242 new PullRequestProviderError({
243 provider: "azure-devops",
244 operation: "listReviewerCandidates",
245 reason: "failed",
246 detail: "Azure DevOps cannot say who may review a pull request.",
247 }),
248 ),
249​
250 setReviewerRequest: (input) =>
251 cli
252 .setPullRequestReviewers({
253 cwd: input.cwd,
254 number: input.number,
255 // Azure names an identity by an email address or a guid, and has no team to ask, so a
256 // candidate's id is the whole of what it takes.
257 reviewers: input.reviewers.map((reviewer) => reviewer.id),
258 requested: input.requested,
259 })
260 .pipe(Effect.mapError(fail("setReviewerRequest"))),
261​
262 // Never called: `capabilities.comment` is false, and the service refuses a comment without it.
263 comment: () => unsupported("comment"),
264​
265 // Declared unsupported above, so the service refuses these before a provider is reached.
266 // They exist because every provider answers the whole port.
267 submitReview: () => unsupported("submitReview"),
268​
269 replyToThread: () => unsupported("replyToThread"),
270​
271 setThreadResolution: () => unsupported("setThreadResolution"),
272​
273 setReaction: () => unsupported("setReaction"),
274 };
275​
276 return provider;
277});