Skip to content
1,160 linesCodeBlameRaw
1//! REST: each route maps an HTTP request onto one operation.
2
3use serde_json::{Map, Value};
4
5use crate::operations::Op;
6use crate::checks::ChecksOp;
7use crate::rules::RulesOp;
8use crate::security::SecurityOp;
9
10pub struct Route {
11 pub method: &'static str,
12 /// Segments starting with `:` are parameters.
13 pub path: &'static str,
14 pub op: Op,
15 /// Query parameters the route reads, as `(name in the URL, input name)`.
16 pub query: &'static [(&'static str, &'static str)],
17}
18
19const fn route(
20 method: &'static str,
21 path: &'static str,
22 op: Op,
23 query: &'static [(&'static str, &'static str)],
24) -> Route {
25 Route {
26 method,
27 path,
28 op,
29 query,
30 }
31}
32
33pub const ROUTES: &[Route] = &[
34 route("GET", "/user", Op::Whoami, &[]),
35 route("POST", "/workspaces", Op::CreateWorkspace, &[]),
36 route("GET", "/workspaces/:workspace", Op::GetWorkspace, &[]),
37 route("DELETE", "/workspaces/:workspace", Op::DeleteWorkspace, &[]),
38 route("GET", "/user/emails", Op::ListEmails, &[]),
39 route("POST", "/user/emails", Op::AddEmail, &[]),
40 route("DELETE", "/user/emails/:email", Op::RemoveEmail, &[]),
41 route("PATCH", "/user/email-settings", Op::UpdateEmailSettings, &[]),
42 route("GET", "/user/invites", Op::ListInvites, &[]),
43 route("POST", "/user/invites", Op::CreateInvite, &[]),
44 route("DELETE", "/user/invites/:id", Op::RevokeInvite, &[]),
45 route("GET", "/workspaces/:workspace/invitations", Op::ListWorkspaceInvites, &[]),
46 route("POST", "/workspaces/:workspace/invitations", Op::InviteMember, &[]),
47 route("DELETE", "/workspaces/:workspace/invitations/:id", Op::RevokeWorkspaceInvite, &[]),
48 // Who has access. GitHub's addresses, but for adding someone, which
49 // takes an email address as well as a username.
50 route("GET", "/repos/:owner/:name/collaborators", Op::ListCollaborators, &[]),
51 route("POST", "/repos/:owner/:name/collaborators", Op::AddCollaborator, &[]),
52 route("PATCH", "/repos/:owner/:name/collaborators/:username", Op::UpdateCollaborator, &[]),
53 route("DELETE", "/repos/:owner/:name/collaborators/:username", Op::RemoveCollaborator, &[]),
54 route(
55 "GET",
56 "/repos/:owner/:name/collaborators/:username/permission",
57 Op::GetCollaboratorPermission,
58 &[],
59 ),
60 route("GET", "/repos/:owner/:name/invitations", Op::ListRepoInvitations, &[]),
61 route("DELETE", "/repos/:owner/:name/invitations/:id", Op::RevokeRepoInvitation, &[]),
62 route("GET", "/user/repository_invitations", Op::ListMyRepoInvitations, &[]),
63 // Your notifications: threads, marking them, and what you subscribe
64 // to and watch. GitHub's addresses, with g1t's saved and snoozed.
65 route("GET", "/notifications", Op::ListNotifications, &[("all", "all"), ("participating", "participating"), ("view", "view"), ("reason", "reason"), ("severity", "severity"), ("since", "since"), ("before", "before"), ("cursor", "cursor"), ("per_page", "per_page")]),
66 route("PUT", "/notifications", Op::MarkNotificationsRead, &[]),
67 route("GET", "/notifications/threads/:id", Op::GetNotificationThread, &[]),
68 route("PATCH", "/notifications/threads/:id", Op::MarkThreadRead, &[]),
69 route("DELETE", "/notifications/threads/:id", Op::MarkThreadDone, &[]),
70 route("PUT", "/notifications/threads/:id/saved", Op::SaveThread, &[]),
71 route("DELETE", "/notifications/threads/:id/saved", Op::SaveThread, &[]),
72 route("PUT", "/notifications/threads/:id/snooze", Op::SnoozeThread, &[]),
73 route("DELETE", "/notifications/threads/:id/snooze", Op::SnoozeThread, &[]),
74 route("GET", "/notifications/threads/:id/subscription", Op::GetThreadSubscription, &[]),
75 route("PUT", "/notifications/threads/:id/subscription", Op::SetThreadSubscription, &[]),
76 route("DELETE", "/notifications/threads/:id/subscription", Op::DeleteThreadSubscription, &[]),
77 route("GET", "/repos/:owner/:name/notifications", Op::ListNotifications, &[("all", "all"), ("participating", "participating"), ("view", "view"), ("reason", "reason"), ("severity", "severity"), ("since", "since"), ("before", "before"), ("cursor", "cursor"), ("per_page", "per_page")]),
78 route("PUT", "/repos/:owner/:name/notifications", Op::MarkNotificationsRead, &[]),
79 route("GET", "/repos/:owner/:name/subscription", Op::GetRepoSubscription, &[]),
80 route("PUT", "/repos/:owner/:name/subscription", Op::SetRepoSubscription, &[]),
81 route("DELETE", "/repos/:owner/:name/subscription", Op::DeleteRepoSubscription, &[]),
82 route("GET", "/repos/:owner/:name/issues/:number/subscription", Op::GetThreadSubscription, &[]),
83 route("PUT", "/repos/:owner/:name/issues/:number/subscription", Op::SetThreadSubscription, &[]),
84 route("DELETE", "/repos/:owner/:name/issues/:number/subscription", Op::DeleteThreadSubscription, &[]),
85 route("GET", "/user/subscriptions", Op::ListWatchedRepos, &[]),
86 // Your pinned projects in a workspace, in your order.
87 route("GET", "/user/pinned_projects/:workspace", Op::ListPinnedProjects, &[]),
88 route("PUT", "/user/pinned_projects/:workspace", Op::ReorderPinnedProjects, &[]),
89 route("PUT", "/user/pinned_projects/:workspace/:project", Op::PinProject, &[]),
90 route("DELETE", "/user/pinned_projects/:workspace/:project", Op::UnpinProject, &[]),
91 route("PATCH", "/user/repository_invitations/:id", Op::AcceptRepoInvitation, &[]),
92 route("DELETE", "/user/repository_invitations/:id", Op::DeclineRepoInvitation, &[]),
93 route("PATCH", "/workspaces/:workspace", Op::UpdateWorkspace, &[]),
94 route("PUT", "/workspaces/:workspace/base_permission", Op::SetBasePermission, &[]),
95 route(
96 "GET",
97 "/workspaces/:workspace/outside_collaborators",
98 Op::ListOutsideCollaborators,
99 &[],
100 ),
101 // Teams: a workspace's groups of members, with roles on repositories.
102 route("GET", "/workspaces/:workspace/teams", Op::ListTeams, &[("q", "query")]),
103 route("POST", "/workspaces/:workspace/teams", Op::CreateTeam, &[]),
104 route("GET", "/workspaces/:workspace/teams/:team", Op::GetTeam, &[]),
105 route("PATCH", "/workspaces/:workspace/teams/:team", Op::UpdateTeam, &[]),
106 route("DELETE", "/workspaces/:workspace/teams/:team", Op::DeleteTeam, &[]),
107 route(
108 "GET",
109 "/workspaces/:workspace/teams/:team/members",
110 Op::ListTeamMembers,
111 &[("include_child_teams", "include_child_teams")],
112 ),
113 route("PUT", "/workspaces/:workspace/teams/:team/members/:username", Op::SetTeamMember, &[]),
114 route("DELETE", "/workspaces/:workspace/teams/:team/members/:username", Op::RemoveTeamMember, &[]),
115 route("GET", "/workspaces/:workspace/teams/:team/teams", Op::ListChildTeams, &[]),
116 route("GET", "/workspaces/:workspace/teams/:team/repos", Op::ListTeamRepos, &[]),
117 route("PUT", "/workspaces/:workspace/teams/:team/repos/:repo", Op::SetTeamRepo, &[]),
118 route("DELETE", "/workspaces/:workspace/teams/:team/repos/:repo", Op::RemoveTeamRepo, &[]),
119 route(
120 "PUT",
121 "/workspaces/:workspace/teams/:team/review_assignment",
122 Op::SetTeamReviewAssignment,
123 &[],
124 ),
125 route("GET", "/workspaces/:workspace/members/:username/teams", Op::ListUserTeams, &[]),
126 // A workspace's billing: usage, budget, AI credit and invoices.
127 route(
128 "GET",
129 "/workspaces/:workspace/usage",
130 Op::GetUsage,
131 &[("from", "from"), ("until", "until"), ("products", "products"), ("projects", "projects"), ("group_by", "group_by")],
132 ),
133 route("GET", "/workspaces/:workspace/budget", Op::GetBudget, &[]),
134 route("PUT", "/workspaces/:workspace/budget", Op::SetBudget, &[]),
135 route("GET", "/workspaces/:workspace/ai_credit", Op::GetAiCredit, &[]),
136 route("POST", "/workspaces/:workspace/ai_credit/checkout", Op::BuyAiCredit, &[]),
137 route("GET", "/workspaces/:workspace/invoices", Op::ListInvoices, &[]),
138 route("GET", "/workspaces/:workspace/billing_details", Op::GetBillingDetails, &[]),
139 // The AI Gateway's log of a workspace's requests.
140 route("GET", "/workspaces/:workspace/gateway/requests", Op::ListGatewayRequests, &[("limit", "limit"), ("before", "before")]),
141 // Code owners: the CODEOWNERS file, checked.
142 route("GET", "/repos/:owner/:name/codeowners/errors", Op::GetCodeownersErrors, &[("ref", "ref")]),
143 // Security alerts: secrets and vulnerable dependencies.
144 route(
145 "GET",
146 "/repos/:owner/:name/security/alerts",
147 Op::ListSecurityAlerts,
148 &[("state", "state"), ("kind", "kind")],
149 ),
150 route("POST", "/repos/:owner/:name/security/alerts/:id/dismiss", Op::DismissSecurityAlert, &[]),
151 route("POST", "/repos/:owner/:name/security/alerts/:id/reopen", Op::ReopenSecurityAlert, &[]),
152 // The security suite: secret scanning, code scanning, vulnerability
153 // alerts and the supply chain, at the common addresses.
154 route("GET", "/repos/:owner/:name/secret-scanning/alerts", Op::Security(SecurityOp::ListSecretAlerts), &[("state", "state"), ("secret_type", "secret_type"), ("validity", "validity"), ("bypassed", "bypassed")]),
155 route("GET", "/workspaces/:workspace/secret-scanning/alerts", Op::Security(SecurityOp::ListSecretAlerts), &[("state", "state"), ("secret_type", "secret_type"), ("validity", "validity"), ("bypassed", "bypassed")]),
156 route("GET", "/repos/:owner/:name/secret-scanning/alerts/:id", Op::Security(SecurityOp::GetSecretAlert), &[]),
157 route("PATCH", "/repos/:owner/:name/secret-scanning/alerts/:id", Op::Security(SecurityOp::UpdateSecretAlert), &[]),
158 route("GET", "/repos/:owner/:name/secret-scanning/alerts/:id/locations", Op::Security(SecurityOp::ListSecretLocations), &[]),
159 route("POST", "/repos/:owner/:name/secret-scanning/alerts/:id/bypass", Op::Security(SecurityOp::BypassPushProtection), &[]),
160 route("POST", "/repos/:owner/:name/secret-scanning/alerts/:id/validity", Op::Security(SecurityOp::CheckSecretValidity), &[]),
161 route("GET", "/workspaces/:workspace/secret-scanning/bypass-requests", Op::Security(SecurityOp::ListBypassRequests), &[("state", "state"), ("repo", "repo")]),
162 route("PATCH", "/workspaces/:workspace/secret-scanning/bypass-requests/:id", Op::Security(SecurityOp::ReviewBypassRequest), &[]),
163 route("POST", "/repos/:owner/:name/secret-scanning/custom-patterns/dry-run", Op::Security(SecurityOp::DryRunCustomPattern), &[]),
164 route("POST", "/workspaces/:workspace/secret-scanning/custom-patterns/dry-run", Op::Security(SecurityOp::DryRunCustomPattern), &[]),
165 route("GET", "/repos/:owner/:name/secret-scanning/custom-patterns", Op::Security(SecurityOp::ListCustomPatterns), &[]),
166 route("GET", "/workspaces/:workspace/secret-scanning/custom-patterns", Op::Security(SecurityOp::ListCustomPatterns), &[]),
167 route("POST", "/repos/:owner/:name/secret-scanning/custom-patterns", Op::Security(SecurityOp::CreateCustomPattern), &[]),
168 route("POST", "/workspaces/:workspace/secret-scanning/custom-patterns", Op::Security(SecurityOp::CreateCustomPattern), &[]),
169 route("PATCH", "/repos/:owner/:name/secret-scanning/custom-patterns/:id", Op::Security(SecurityOp::UpdateCustomPattern), &[]),
170 route("PATCH", "/workspaces/:workspace/secret-scanning/custom-patterns/:id", Op::Security(SecurityOp::UpdateCustomPattern), &[]),
171 route("DELETE", "/repos/:owner/:name/secret-scanning/custom-patterns/:id", Op::Security(SecurityOp::DeleteCustomPattern), &[]),
172 route("DELETE", "/workspaces/:workspace/secret-scanning/custom-patterns/:id", Op::Security(SecurityOp::DeleteCustomPattern), &[]),
173 route("GET", "/repos/:owner/:name/code-scanning/alerts", Op::Security(SecurityOp::ListCodeAlerts), &[("state", "state"), ("severity", "severity"), ("tool", "tool"), ("rule_id", "rule_id")]),
174 route("GET", "/workspaces/:workspace/code-scanning/alerts", Op::Security(SecurityOp::ListCodeAlerts), &[("state", "state"), ("severity", "severity"), ("tool", "tool"), ("rule_id", "rule_id")]),
175 route("GET", "/repos/:owner/:name/code-scanning/alerts/:number", Op::Security(SecurityOp::GetCodeAlert), &[]),
176 route("PATCH", "/repos/:owner/:name/code-scanning/alerts/:number", Op::Security(SecurityOp::UpdateCodeAlert), &[]),
177 route("GET", "/repos/:owner/:name/code-scanning/analyses", Op::Security(SecurityOp::ListAnalyses), &[]),
178 route("POST", "/repos/:owner/:name/code-scanning/sarifs", Op::Security(SecurityOp::UploadSarif), &[]),
179 route("GET", "/repos/:owner/:name/code-scanning/sarifs/:id", Op::Security(SecurityOp::GetSarifUpload), &[]),
180 route("GET", "/repos/:owner/:name/vulnerability-alerts", Op::Security(SecurityOp::ListVulnerabilityAlerts), &[("state", "state"), ("severity", "severity"), ("ecosystem", "ecosystem"), ("package", "package")]),
181 route("GET", "/workspaces/:workspace/vulnerability-alerts", Op::Security(SecurityOp::ListVulnerabilityAlerts), &[("state", "state"), ("severity", "severity"), ("ecosystem", "ecosystem"), ("package", "package")]),
182 route("GET", "/repos/:owner/:name/vulnerability-alerts/:id", Op::Security(SecurityOp::GetVulnerabilityAlert), &[]),
183 route("PATCH", "/repos/:owner/:name/vulnerability-alerts/:id", Op::Security(SecurityOp::UpdateVulnerabilityAlert), &[]),
184 route("POST", "/repos/:owner/:name/security/alerts/:id/fix", Op::Security(SecurityOp::FixAlert), &[]),
185 route("GET", "/repos/:owner/:name/dependency-graph", Op::Security(SecurityOp::GetDependencyGraph), &[]),
186 route("GET", "/repos/:owner/:name/dependency-graph/sbom", Op::Security(SecurityOp::GetSbom), &[]),
187 route("GET", "/repos/:owner/:name/dependency-graph/compare/:basehead", Op::Security(SecurityOp::CompareDependencies), &[]),
188 route("GET", "/repos/:owner/:name/security/settings", Op::Security(SecurityOp::GetSettings), &[]),
189 route("PATCH", "/repos/:owner/:name/security/settings", Op::Security(SecurityOp::UpdateSettings), &[]),
190 route("GET", "/workspaces/:workspace/security/settings", Op::Security(SecurityOp::GetWorkspaceSettings), &[]),
191 route("PATCH", "/workspaces/:workspace/security/settings", Op::Security(SecurityOp::UpdateWorkspaceSettings), &[]),
192 route("GET", "/workspaces/:workspace/security/overview", Op::Security(SecurityOp::GetOverview), &[("days", "days")]),
193 route("GET", "/repos", Op::ListRepos, &[("q", "query")]),
194 route(
195 "GET",
196 "/search",
197 Op::Search,
198 &[("q", "query"), ("type", "type"), ("page", "page"), ("per_page", "per_page")],
199 ),
200 route("POST", "/repos", Op::CreateRepo, &[]),
201 route("GET", "/repos/:owner/:name", Op::GetRepo, &[]),
202 route("PATCH", "/repos/:owner/:name", Op::UpdateRepo, &[]),
203 route("POST", "/repos/:owner/:name/transfer", Op::TransferRepo, &[]),
204 route("DELETE", "/repos/:owner/:name", Op::DeleteRepo, &[]),
205 route(
206 "GET",
207 "/workspaces/:workspace/repos/deleted",
208 Op::ListDeletedRepos,
209 &[],
210 ),
211 route("POST", "/repos/:owner/:name/restore", Op::RestoreRepo, &[]),
212 route("POST", "/repos/:owner/:name/purge", Op::PurgeRepo, &[]),
213 route("POST", "/repos/:owner/:name/rename", Op::RenameRepo, &[]),
214 route("POST", "/repos/:owner/:name/archive", Op::ArchiveRepo, &[]),
215 route("POST", "/repos/:owner/:name/unarchive", Op::UnarchiveRepo, &[]),
216 route(
217 "POST",
218 "/repos/:owner/:name/visibility",
219 Op::SetRepoVisibility,
220 &[],
221 ),
222 route(
223 "POST",
224 "/repos/:owner/:name/branches/:branch/rename",
225 Op::RenameBranch,
226 &[],
227 ),
228 route(
229 "GET",
230 "/repos/:owner/:name/settings",
231 Op::GetRepoSettings,
232 &[],
233 ),
234 route(
235 "PATCH",
236 "/repos/:owner/:name/settings",
237 Op::UpdateRepoSettings,
238 &[],
239 ),
240 route("GET", "/repos/:owner/:name/check-names", Op::ListCheckNames, &[]),
241 // Checks: GitHub's addresses for statuses, check runs and check suites.
242 route("POST", "/repos/:owner/:name/statuses/:sha", Op::Checks(ChecksOp::CreateCommitStatus), &[]),
243 route("GET", "/repos/:owner/:name/commits/:ref/statuses", Op::Checks(ChecksOp::ListCommitStatuses), &[]),
244 route("GET", "/repos/:owner/:name/commits/:ref/status", Op::Checks(ChecksOp::GetCombinedStatus), &[]),
245 route(
246 "GET",
247 "/repos/:owner/:name/commits/:ref/check-runs",
248 Op::Checks(ChecksOp::ListCheckRunsForRef),
249 &[("check_name", "check_name"), ("status", "status"), ("app", "app"), ("filter", "filter")],
250 ),
251 route(
252 "GET",
253 "/repos/:owner/:name/commits/:ref/check-suites",
254 Op::Checks(ChecksOp::ListCheckSuitesForRef),
255 &[("app", "app"), ("check_name", "check_name")],
256 ),
257 route("POST", "/repos/:owner/:name/check-runs", Op::Checks(ChecksOp::CreateCheckRun), &[]),
258 route("GET", "/repos/:owner/:name/check-runs/:id", Op::Checks(ChecksOp::GetCheckRun), &[]),
259 route("PATCH", "/repos/:owner/:name/check-runs/:id", Op::Checks(ChecksOp::UpdateCheckRun), &[]),
260 route("GET", "/repos/:owner/:name/check-runs/:id/annotations", Op::Checks(ChecksOp::ListCheckRunAnnotations), &[]),
261 route("POST", "/repos/:owner/:name/check-runs/:id/rerequest", Op::Checks(ChecksOp::RerequestCheckRun), &[]),
262 route("GET", "/repos/:owner/:name/check-suites/:id", Op::Checks(ChecksOp::GetCheckSuite), &[]),
263 route("POST", "/repos/:owner/:name/check-suites/:id/rerequest", Op::Checks(ChecksOp::RerequestCheckSuite), &[]),
264 // Rulesets: a repository's, a workspace's, the rules of one branch,
265 // and how they judged pushes and merges.
266 route("GET", "/repos/:owner/:name/rulesets", Op::Rules(RulesOp::ListRepoRulesets), &[("include_parents", "include_parents")]),
267 route("POST", "/repos/:owner/:name/rulesets", Op::Rules(RulesOp::CreateRepoRuleset), &[]),
268 route("GET", "/repos/:owner/:name/rulesets/:id", Op::Rules(RulesOp::GetRepoRuleset), &[]),
269 route("PUT", "/repos/:owner/:name/rulesets/:id", Op::Rules(RulesOp::UpdateRepoRuleset), &[]),
270 route("DELETE", "/repos/:owner/:name/rulesets/:id", Op::Rules(RulesOp::DeleteRepoRuleset), &[]),
271 route("GET", "/repos/:owner/:name/rules/branches/:branch", Op::Rules(RulesOp::GetBranchRules), &[("target", "target")]),
272 route(
273 "GET",
274 "/repos/:owner/:name/rules/evaluations",
275 Op::Rules(RulesOp::ListRuleEvaluations),
276 &[("ruleset_id", "ruleset_id"), ("verdict", "verdict"), ("problems_only", "problems_only"), ("before", "before"), ("limit", "limit")],
277 ),
278 route("GET", "/workspaces/:workspace/rulesets", Op::Rules(RulesOp::ListWorkspaceRulesets), &[]),
279 route("POST", "/workspaces/:workspace/rulesets", Op::Rules(RulesOp::CreateWorkspaceRuleset), &[]),
280 route("GET", "/workspaces/:workspace/rulesets/:id", Op::Rules(RulesOp::GetWorkspaceRuleset), &[]),
281 route("PUT", "/workspaces/:workspace/rulesets/:id", Op::Rules(RulesOp::UpdateWorkspaceRuleset), &[]),
282 route("DELETE", "/workspaces/:workspace/rulesets/:id", Op::Rules(RulesOp::DeleteWorkspaceRuleset), &[]),
283 route(
284 "GET",
285 "/workspaces/:workspace/rules/evaluations",
286 Op::Rules(RulesOp::ListWorkspaceRuleEvaluations),
287 &[("ruleset_id", "ruleset_id"), ("verdict", "verdict"), ("problems_only", "problems_only"), ("before", "before"), ("limit", "limit")],
288 ),
289 route("GET", "/repos/:owner/:name/queue", Op::GetMergeQueue, &[]),
290 route(
291 "POST",
292 "/repos/:owner/:name/pulls/:number/messages",
293 Op::MessageAgent,
294 &[],
295 ),
296 route(
297 "POST",
298 "/repos/:owner/:name/pulls/:number/messages/take",
299 Op::TakeMessages,
300 &[],
301 ),
302 route(
303 "POST",
304 "/repos/:owner/:name/messages/:id/answer",
305 Op::AnswerMessage,
306 &[],
307 ),
308 route("POST", "/repos/:owner/:name/memory", Op::Remember, &[]),
309 route(
310 "GET",
311 "/repos/:owner/:name/memory",
312 Op::Recall,
313 &[("q", "query"), ("limit", "limit")],
314 ),
315 route(
316 "GET",
317 "/repos/:owner/:name/events",
318 Op::ListEvents,
319 &[("before", "before")],
320 ),
321 route("GET", "/repos/:owner/:name/labels", Op::ListLabels, &[]),
322 route("POST", "/repos/:owner/:name/labels", Op::CreateLabel, &[]),
323 route("POST", "/repos/:owner/:name/labels/defaults", Op::AddDefaultLabels, &[]),
324 route("PATCH", "/repos/:owner/:name/labels/:label", Op::UpdateLabel, &[]),
325 route("DELETE", "/repos/:owner/:name/labels/:label", Op::DeleteLabel, &[]),
326 route("GET", "/repos/:owner/:name/issues/:number/labels", Op::ListIssueLabels, &[]),
327 route("POST", "/repos/:owner/:name/issues/:number/labels", Op::AddIssueLabels, &[]),
328 route("PUT", "/repos/:owner/:name/issues/:number/labels", Op::SetIssueLabels, &[]),
329 route("DELETE", "/repos/:owner/:name/issues/:number/labels", Op::RemoveIssueLabels, &[]),
330 route("DELETE", "/repos/:owner/:name/issues/:number/labels/:label", Op::RemoveIssueLabels, &[]),
331 route("GET", "/repos/:owner/:name/milestones", Op::ListMilestones, &[("state", "state")]),
332 route("POST", "/repos/:owner/:name/milestones", Op::CreateMilestone, &[]),
333 route("GET", "/repos/:owner/:name/milestones/:milestone", Op::GetMilestone, &[]),
334 route("PATCH", "/repos/:owner/:name/milestones/:milestone", Op::UpdateMilestone, &[]),
335 route("DELETE", "/repos/:owner/:name/milestones/:milestone", Op::DeleteMilestone, &[]),
336 route(
337 "GET",
338 "/repos/:owner/:name/issues",
339 Op::ListIssues,
340 &[("state", "state"), ("label", "label"), ("milestone", "milestone")],
341 ),
342 route("POST", "/repos/:owner/:name/issues", Op::CreateIssue, &[]),
343 route(
344 "GET",
345 "/repos/:owner/:name/issues/:number",
346 Op::GetIssue,
347 &[],
348 ),
349 route(
350 "PATCH",
351 "/repos/:owner/:name/issues/:number",
352 Op::UpdateIssue,
353 &[],
354 ),
355 route(
356 "POST",
357 "/repos/:owner/:name/issues/:number/close",
358 Op::CloseIssue,
359 &[],
360 ),
361 route(
362 "POST",
363 "/repos/:owner/:name/issues/:number/reopen",
364 Op::ReopenIssue,
365 &[],
366 ),
367 route(
368 "POST",
369 "/repos/:owner/:name/issues/:number/assign",
370 Op::AssignIssue,
371 &[],
372 ),
373 route(
374 "POST",
375 "/repos/:owner/:name/issues/import",
376 Op::ImportIssue,
377 &[],
378 ),
379 route(
380 "POST",
381 "/repos/:owner/:name/issues/delegate",
382 Op::Delegate,
383 &[],
384 ),
385 route(
386 "GET",
387 "/repos/:owner/:name/context",
388 Op::GetContext,
389 &[("reference", "reference")],
390 ),
391 route(
392 "GET",
393 "/workspaces/:workspace/context/search",
394 Op::SearchContext,
395 &[("q", "query"), ("project", "project"), ("kinds", "kinds"), ("limit", "limit")],
396 ),
397 route(
398 "GET",
399 "/workspaces/:workspace/context/:kind/:id",
400 Op::GetEntity,
401 &[],
402 ),
403 route(
404 "GET",
405 "/workspaces/:workspace/integrations",
406 Op::ListIntegrations,
407 &[],
408 ),
409 route(
410 "POST",
411 "/workspaces/:workspace/integrations",
412 Op::ConnectIntegration,
413 &[],
414 ),
415 route(
416 "GET",
417 "/repos/:owner/:name/hooks",
418 Op::ListWebhooks,
419 &[],
420 ),
421 route(
422 "POST",
423 "/repos/:owner/:name/hooks",
424 Op::CreateWebhook,
425 &[],
426 ),
427 route(
428 "PATCH",
429 "/repos/:owner/:name/hooks/:id",
430 Op::UpdateWebhook,
431 &[],
432 ),
433 route(
434 "DELETE",
435 "/repos/:owner/:name/hooks/:id",
436 Op::DeleteWebhook,
437 &[],
438 ),
439 route(
440 "POST",
441 "/repos/:owner/:name/hooks/:id/pings",
442 Op::PingWebhook,
443 &[],
444 ),
445 route(
446 "GET",
447 "/repos/:owner/:name/hooks/:id/deliveries",
448 Op::ListWebhookDeliveries,
449 &[],
450 ),
451 route(
452 "POST",
453 "/repos/:owner/:name/hooks/:id/deliveries/:delivery/redeliver",
454 Op::RedeliverWebhook,
455 &[],
456 ),
457 route(
458 "GET",
459 "/workspaces/:workspace/hooks",
460 Op::ListWebhooks,
461 &[],
462 ),
463 route(
464 "POST",
465 "/workspaces/:workspace/hooks",
466 Op::CreateWebhook,
467 &[],
468 ),
469 route(
470 "PATCH",
471 "/workspaces/:workspace/hooks/:id",
472 Op::UpdateWebhook,
473 &[],
474 ),
475 route(
476 "DELETE",
477 "/workspaces/:workspace/hooks/:id",
478 Op::DeleteWebhook,
479 &[],
480 ),
481 route(
482 "POST",
483 "/workspaces/:workspace/hooks/:id/pings",
484 Op::PingWebhook,
485 &[],
486 ),
487 route(
488 "GET",
489 "/workspaces/:workspace/hooks/:id/deliveries",
490 Op::ListWebhookDeliveries,
491 &[],
492 ),
493 route(
494 "POST",
495 "/workspaces/:workspace/hooks/:id/deliveries/:delivery/redeliver",
496 Op::RedeliverWebhook,
497 &[],
498 ),
499 route(
500 "GET",
501 "/workspaces/:workspace/model-routes",
502 Op::GetModelRoutes,
503 &[],
504 ),
505 route(
506 "PUT",
507 "/workspaces/:workspace/model-routes",
508 Op::SetModelRoutes,
509 &[],
510 ),
511 route(
512 "DELETE",
513 "/workspaces/:workspace/integrations/:id",
514 Op::DisconnectIntegration,
515 &[],
516 ),
517 route(
518 "POST",
519 "/workspaces/:workspace/integrations/:id/test",
520 Op::TestIntegration,
521 &[],
522 ),
523 route(
524 "GET",
525 "/repos/:owner/:name/actions/workflows",
526 Op::ListWorkflows,
527 &[],
528 ),
529 route(
530 "GET",
531 "/repos/:owner/:name/actions/workflows/:workflow/runs",
532 Op::ListWorkflowRuns,
533 &[("branch", "branch"), ("event", "event"), ("per_page", "limit")],
534 ),
535 route(
536 "POST",
537 "/repos/:owner/:name/actions/workflows/:workflow/dispatches",
538 Op::DispatchWorkflow,
539 &[],
540 ),
541 route(
542 "PATCH",
543 "/repos/:owner/:name/actions/workflows/:workflow",
544 Op::UpdateWorkflow,
545 &[],
546 ),
547 route(
548 "PUT",
549 "/repos/:owner/:name/actions/workflows/:workflow/enable",
550 Op::UpdateWorkflow,
551 &[],
552 ),
553 route(
554 "PUT",
555 "/repos/:owner/:name/actions/workflows/:workflow/disable",
556 Op::UpdateWorkflow,
557 &[],
558 ),
559 route(
560 "GET",
561 "/repos/:owner/:name/actions/runs",
562 Op::ListWorkflowRuns,
563 &[("workflow", "workflow"), ("branch", "branch"), ("event", "event"), ("pull", "pull"), ("head_sha", "sha"), ("per_page", "limit")],
564 ),
565 route(
566 "GET",
567 "/repos/:owner/:name/actions/runs/:id",
568 Op::GetWorkflowRun,
569 &[],
570 ),
571 route(
572 "POST",
573 "/repos/:owner/:name/actions/runs/:id/cancel",
574 Op::CancelWorkflowRun,
575 &[],
576 ),
577 route(
578 "POST",
579 "/repos/:owner/:name/actions/runs/:id/rerun",
580 Op::RerunWorkflowRun,
581 &[],
582 ),
583 route(
584 "POST",
585 "/repos/:owner/:name/actions/runs/:id/rerun-failed-jobs",
586 Op::RerunWorkflowRun,
587 &[],
588 ),
589 route(
590 "GET",
591 "/repos/:owner/:name/actions/jobs/:job/logs",
592 Op::GetJobLogs,
593 &[("after", "after")],
594 ),
595 route(
596 "GET",
597 "/repos/:owner/:name/actions/secrets",
598 Op::ListActionsSecrets,
599 &[],
600 ),
601 route(
602 "PUT",
603 "/repos/:owner/:name/actions/secrets/:setting",
604 Op::SetActionsSecret,
605 &[],
606 ),
607 route(
608 "DELETE",
609 "/repos/:owner/:name/actions/secrets/:setting",
610 Op::DeleteActionsSecret,
611 &[],
612 ),
613 route(
614 "GET",
615 "/repos/:owner/:name/actions/variables",
616 Op::ListActionsVariables,
617 &[],
618 ),
619 route(
620 "POST",
621 "/repos/:owner/:name/actions/variables",
622 Op::SetActionsVariable,
623 &[],
624 ),
625 route(
626 "PATCH",
627 "/repos/:owner/:name/actions/variables/:setting",
628 Op::SetActionsVariable,
629 &[],
630 ),
631 route(
632 "DELETE",
633 "/repos/:owner/:name/actions/variables/:setting",
634 Op::DeleteActionsVariable,
635 &[],
636 ),
637 route(
638 "GET",
639 "/workspaces/:workspace/actions/secrets",
640 Op::ListActionsSecrets,
641 &[],
642 ),
643 route(
644 "PUT",
645 "/workspaces/:workspace/actions/secrets/:setting",
646 Op::SetActionsSecret,
647 &[],
648 ),
649 route(
650 "DELETE",
651 "/workspaces/:workspace/actions/secrets/:setting",
652 Op::DeleteActionsSecret,
653 &[],
654 ),
655 route(
656 "GET",
657 "/workspaces/:workspace/actions/variables",
658 Op::ListActionsVariables,
659 &[],
660 ),
661 route(
662 "POST",
663 "/workspaces/:workspace/actions/variables",
664 Op::SetActionsVariable,
665 &[],
666 ),
667 route(
668 "PATCH",
669 "/workspaces/:workspace/actions/variables/:setting",
670 Op::SetActionsVariable,
671 &[],
672 ),
673 route(
674 "DELETE",
675 "/workspaces/:workspace/actions/variables/:setting",
676 Op::DeleteActionsVariable,
677 &[],
678 ),
679 // Self-hosted runners: a repository's own, or a workspace's.
680 route("GET", "/repos/:owner/:name/actions/runners", Op::ListRunners, &[]),
681 route("POST", "/repos/:owner/:name/actions/runners/registration-token", Op::CreateRunnerRegistrationToken, &[]),
682 route("DELETE", "/repos/:owner/:name/actions/runners/:id", Op::RemoveRunner, &[]),
683 route("GET", "/repos/:owner/:name/actions/runner-settings", Op::GetRunnerSettings, &[]),
684 route("PATCH", "/repos/:owner/:name/actions/runner-settings", Op::UpdateRunnerSettings, &[]),
685 route("GET", "/workspaces/:workspace/actions/runners", Op::ListRunners, &[]),
686 route("POST", "/workspaces/:workspace/actions/runners/registration-token", Op::CreateRunnerRegistrationToken, &[]),
687 route("DELETE", "/workspaces/:workspace/actions/runners/:id", Op::RemoveRunner, &[]),
688 route("GET", "/workspaces/:workspace/actions/runner-settings", Op::GetRunnerSettings, &[]),
689 route("PATCH", "/workspaces/:workspace/actions/runner-settings", Op::UpdateRunnerSettings, &[]),
690 route("GET", "/workspaces/:workspace/actions/runner-groups", Op::ListRunnerGroups, &[]),
691 route("POST", "/workspaces/:workspace/actions/runner-groups", Op::CreateRunnerGroup, &[]),
692 route("PATCH", "/workspaces/:workspace/actions/runner-groups/:id", Op::UpdateRunnerGroup, &[]),
693 route("DELETE", "/workspaces/:workspace/actions/runner-groups/:id", Op::DeleteRunnerGroup, &[]),
694 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
695 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
696 route(
697 "POST",
698 "/repos/:owner/:name/plans/:plan/apply",
699 Op::ApplyPlan,
700 &[],
701 ),
702 route(
703 "POST",
704 "/repos/:owner/:name/issues/:number/comments",
705 Op::AddComment,
706 &[],
707 ),
708 route(
709 "GET",
710 "/repos/:owner/:name/pulls",
711 Op::ListPullRequests,
712 &[("state", "state"), ("label", "label"), ("milestone", "milestone"), ("base", "base")],
713 ),
714 route(
715 "POST",
716 "/repos/:owner/:name/pulls",
717 Op::CreatePullRequest,
718 &[],
719 ),
720 route(
721 "GET",
722 "/repos/:owner/:name/pulls/:number",
723 Op::GetPullRequest,
724 &[],
725 ),
726 route(
727 "PATCH",
728 "/repos/:owner/:name/pulls/:number",
729 Op::UpdatePullRequest,
730 &[],
731 ),
732 route(
733 "GET",
734 "/repos/:owner/:name/pulls/:number/changes",
735 Op::GetPullRequestChanges,
736 &[],
737 ),
738 route(
739 "POST",
740 "/repos/:owner/:name/pulls/:number/reviews",
741 Op::ReviewPullRequest,
742 &[],
743 ),
744 route(
745 "POST",
746 "/repos/:owner/:name/pulls/:number/requested_reviewers",
747 Op::RequestReviewers,
748 &[],
749 ),
750 route(
751 "DELETE",
752 "/repos/:owner/:name/pulls/:number/requested_reviewers",
753 Op::RemoveRequestedReviewers,
754 &[],
755 ),
756 route(
757 "GET",
758 "/repos/:owner/:name/pulls/:number/session",
759 Op::ReadSession,
760 &[("after", "after")],
761 ),
762 route(
763 "POST",
764 "/repos/:owner/:name/pulls/:number/session",
765 Op::RecordSession,
766 &[],
767 ),
768 route(
769 "POST",
770 "/repos/:owner/:name/pulls/:number/ready",
771 Op::MarkPullRequestReady,
772 &[],
773 ),
774 route(
775 "POST",
776 "/repos/:owner/:name/pulls/:number/close",
777 Op::ClosePullRequest,
778 &[],
779 ),
780 route(
781 "POST",
782 "/repos/:owner/:name/pulls/:number/merge",
783 Op::MergePullRequest,
784 &[],
785 ),
786];
787
788impl Route {
789 /// The names of the route's path parameters, in order.
790 pub fn params(&self) -> impl Iterator<Item = &'static str> {
791 self.path
792 .split('/')
793 .filter_map(|segment| segment.strip_prefix(':'))
794 }
795
796 /// The values of the path parameters, if `path` is this route's.
797 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
798 let mut values = Vec::new();
799 let mut actual = path.trim_end_matches('/').split('/');
800 for expected in self.path.split('/') {
801 let segment = actual.next()?;
802 match expected.strip_prefix(':') {
803 Some(name) if !segment.is_empty() => values.push((name, segment)),
804 Some(_) => return None,
805 None if expected == segment => {}
806 None => return None,
807 }
808 }
809 actual.next().is_none().then_some(values)
810 }
811}
812
813/// A path segment with its `%XX` escapes decoded; as given when that is not
814/// UTF-8.
815fn percent_decoded(segment: &str) -> String {
816 let bytes = segment.as_bytes();
817 let mut out = Vec::with_capacity(bytes.len());
818 let mut i = 0;
819 while i < bytes.len() {
820 let escaped = (bytes[i] == b'%')
821 .then(|| segment.get(i + 1..i + 3))
822 .flatten()
823 .filter(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
824 .and_then(|hex| u8::from_str_radix(hex, 16).ok());
825 match escaped {
826 Some(byte) => {
827 out.push(byte);
828 i += 3;
829 }
830 None => {
831 out.push(bytes[i]);
832 i += 1;
833 }
834 }
835 }
836 String::from_utf8(out).unwrap_or_else(|_| segment.to_owned())
837}
838
839/// The route for a request, and the operation input it describes.
840///
841/// The input is the JSON body, overlaid with the query parameters the route
842/// reads and then with what the path names: `owner` and `name` become
843/// `repo`, as does a team's `repo` with its `workspace`, and `number`
844/// becomes an integer.
845pub fn resolve(
846 method: &str,
847 path: &str,
848 query: &[(String, String)],
849 body: Value,
850) -> Option<(&'static Route, Value)> {
851 let (route, params) = ROUTES
852 .iter()
853 .filter(|route| route.method == method)
854 .find_map(|route| Some((route, route.matches(path)?)))?;
855
856 let mut input = match body {
857 Value::Object(fields) => fields,
858 _ => Map::new(),
859 };
860 for (name, key) in route.query {
861 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
862 input.insert((*key).to_owned(), Value::String(value.clone()));
863 }
864 }
865 let param = |wanted: &str| {
866 params
867 .iter()
868 .find(|(name, _)| *name == wanted)
869 .map(|(_, value)| *value)
870 };
871 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
872 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
873 }
874 for key in ["plan", "id", "workspace", "delivery", "workflow", "job", "setting", "username", "team", "basehead"] {
875 if let Some(value) = param(key) {
876 input.insert(key.to_owned(), Value::String(value.to_owned()));
877 }
878 }
879 // A repository of a team's workspace, named by itself.
880 if let (Some(workspace), Some(name)) = (param("workspace"), param("repo")) {
881 input.insert("repo".to_owned(), Value::String(format!("{workspace}/{name}")));
882 }
883 // A branch name may hold slashes, sent URL-encoded as one segment, and
884 // a label's name spaces.
885 if let Some(branch) = param("branch") {
886 input.insert("branch".to_owned(), Value::String(percent_decoded(branch)));
887 }
888 if let Some(label) = param("label") {
889 input.insert("label".to_owned(), Value::String(percent_decoded(label)));
890 }
891 // A commit, by SHA, or by a branch or tag, which may hold slashes.
892 if let Some(sha) = param("sha") {
893 input.insert("sha".to_owned(), Value::String(sha.to_owned()));
894 }
895 if let Some(git_ref) = param("ref") {
896 input.insert("ref".to_owned(), Value::String(percent_decoded(git_ref)));
897 }
898 if let Some(milestone) = param("milestone") {
899 // Not a number: zero, which no milestone has.
900 input.insert("milestone".to_owned(), milestone.parse::<u32>().unwrap_or(0).into());
901 }
902 // GitHub says some things with the path alone.
903 if route.path.ends_with("/enable") || route.path.ends_with("/disable") {
904 input.insert("enabled".to_owned(), Value::Bool(route.path.ends_with("/enable")));
905 }
906 if route.path.ends_with("/rerun-failed-jobs") {
907 input.insert("failed_only".to_owned(), Value::Bool(true));
908 }
909 // Unsaving and waking a thread are a DELETE of what PUT made.
910 if route.method == "DELETE" && route.path.ends_with("/saved") {
911 input.insert("saved".to_owned(), Value::Bool(false));
912 }
913 if route.method == "DELETE" && route.path.ends_with("/snooze") {
914 input.remove("until");
915 }
916 if let Some(number) = param("number") {
917 // Not a number: zero, which no issue or pull request has.
918 input.insert(
919 "number".to_owned(),
920 number.parse::<u32>().unwrap_or(0).into(),
921 );
922 }
923 Some((route, Value::Object(input)))
924}
925
926#[cfg(test)]
927mod tests {
928 use serde_json::json;
929
930 use super::*;
931
932 #[test]
933 fn a_path_resolves_to_its_operation_and_input() {
934 let (route, input) = resolve(
935 "POST",
936 "/repos/flagon-io/hello/pulls/14/merge",
937 &[],
938 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
939 )
940 .unwrap();
941 assert_eq!(route.op, Op::MergePullRequest);
942 // What the path names wins over the body.
943 assert_eq!(
944 input,
945 json!({ "keep_issue_open": true, "number": 14, "repo": "flagon-io/hello" })
946 );
947 }
948
949 #[test]
950 fn a_branch_with_slashes_is_one_encoded_segment() {
951 let (route, input) = resolve(
952 "POST",
953 "/repos/flagon-io/hello/branches/feature%2Flogin/rename",
954 &[],
955 json!({ "new_name": "feature/sign-in" }),
956 )
957 .unwrap();
958 assert_eq!(route.op, Op::RenameBranch);
959 assert_eq!(
960 input,
961 json!({ "new_name": "feature/sign-in", "branch": "feature/login", "repo": "flagon-io/hello" })
962 );
963 assert_eq!(percent_decoded("100%"), "100%");
964 assert_eq!(percent_decoded("a%2bb%zz"), "a+b%zz");
965 }
966
967 #[test]
968 fn a_collaborator_is_named_by_username() {
969 let (route, input) = resolve(
970 "PATCH",
971 "/repos/flagon-io/hello/collaborators/ada",
972 &[],
973 json!({ "role": "maintain" }),
974 )
975 .unwrap();
976 assert_eq!(route.op, Op::UpdateCollaborator);
977 assert_eq!(input, json!({ "role": "maintain", "username": "ada", "repo": "flagon-io/hello" }));
978 let (route, input) = resolve("DELETE", "/user/repository_invitations/rin_1", &[], Value::Null).unwrap();
979 assert_eq!(route.op, Op::DeclineRepoInvitation);
980 assert_eq!(input, json!({ "id": "rin_1" }));
981 }
982
983 #[test]
984 fn teams_are_addressed_by_workspace_and_slug() {
985 let query = [("q".to_owned(), "back".to_owned())];
986 let (route, input) = resolve("GET", "/workspaces/acme/teams", &query, Value::Null).unwrap();
987 assert_eq!(route.op, Op::ListTeams);
988 assert_eq!(input, json!({ "query": "back", "workspace": "acme" }));
989 let (route, input) = resolve("PATCH", "/workspaces/acme/teams/backend", &[], json!({ "name": "Back end" })).unwrap();
990 assert_eq!(route.op, Op::UpdateTeam);
991 assert_eq!(input, json!({ "name": "Back end", "workspace": "acme", "team": "backend" }));
992 let (route, input) =
993 resolve("PUT", "/workspaces/acme/teams/backend/members/ana", &[], json!({ "role": "maintainer" })).unwrap();
994 assert_eq!(route.op, Op::SetTeamMember);
995 assert_eq!(input, json!({ "role": "maintainer", "workspace": "acme", "team": "backend", "username": "ana" }));
996 let query = [("include_child_teams".to_owned(), "true".to_owned())];
997 let (route, input) = resolve("GET", "/workspaces/acme/teams/backend/members", &query, Value::Null).unwrap();
998 assert_eq!(route.op, Op::ListTeamMembers);
999 assert_eq!(input, json!({ "include_child_teams": "true", "workspace": "acme", "team": "backend" }));
1000 // A repository is named by itself, in the team's workspace.
1001 let (route, input) =
1002 resolve("PUT", "/workspaces/acme/teams/backend/repos/rocket", &[], json!({ "role": "write" })).unwrap();
1003 assert_eq!(route.op, Op::SetTeamRepo);
1004 assert_eq!(input, json!({ "role": "write", "workspace": "acme", "team": "backend", "repo": "acme/rocket" }));
1005 let op = |method: &str, path: &str| resolve(method, path, &[], Value::Null).unwrap().0.op;
1006 assert_eq!(op("DELETE", "/workspaces/acme/teams/backend/repos/rocket"), Op::RemoveTeamRepo);
1007 assert_eq!(op("GET", "/workspaces/acme/teams/backend/teams"), Op::ListChildTeams);
1008 assert_eq!(op("GET", "/workspaces/acme/teams/backend/repos"), Op::ListTeamRepos);
1009 assert_eq!(op("PUT", "/workspaces/acme/teams/backend/review_assignment"), Op::SetTeamReviewAssignment);
1010 assert_eq!(op("DELETE", "/workspaces/acme/teams/backend"), Op::DeleteTeam);
1011 assert_eq!(op("POST", "/workspaces/acme/teams"), Op::CreateTeam);
1012 assert_eq!(op("GET", "/workspaces/acme/teams/backend"), Op::GetTeam);
1013 assert_eq!(op("DELETE", "/workspaces/acme/teams/backend/members/ana"), Op::RemoveTeamMember);
1014 let (route, input) = resolve("GET", "/workspaces/acme/members/ana/teams", &[], Value::Null).unwrap();
1015 assert_eq!(route.op, Op::ListUserTeams);
1016 assert_eq!(input, json!({ "workspace": "acme", "username": "ana" }));
1017 }
1018
1019 #[test]
1020 fn reviewers_are_requested_and_code_owners_checked_on_a_repository() {
1021 let body = json!({ "reviewers": ["ana"], "team_reviewers": ["backend"] });
1022 let (route, input) = resolve("POST", "/repos/acme/rocket/pulls/7/requested_reviewers", &[], body.clone()).unwrap();
1023 assert_eq!(route.op, Op::RequestReviewers);
1024 assert_eq!(
1025 input,
1026 json!({ "reviewers": ["ana"], "team_reviewers": ["backend"], "repo": "acme/rocket", "number": 7 })
1027 );
1028 let (route, _) = resolve("DELETE", "/repos/acme/rocket/pulls/7/requested_reviewers", &[], body).unwrap();
1029 assert_eq!(route.op, Op::RemoveRequestedReviewers);
1030 let query = [("ref".to_owned(), "main".to_owned())];
1031 let (route, input) = resolve("GET", "/repos/acme/rocket/codeowners/errors", &query, Value::Null).unwrap();
1032 assert_eq!(route.op, Op::GetCodeownersErrors);
1033 assert_eq!(input, json!({ "ref": "main", "repo": "acme/rocket" }));
1034 }
1035
1036 #[test]
1037 fn notifications_are_addressed_as_threads_and_by_issue() {
1038 let (route, input) = resolve("DELETE", "/notifications/threads/ntf_1", &[], Value::Null).unwrap();
1039 assert_eq!(route.op, Op::MarkThreadDone);
1040 assert_eq!(input, json!({ "id": "ntf_1" }));
1041 let (route, input) = resolve("DELETE", "/notifications/threads/ntf_1/saved", &[], Value::Null).unwrap();
1042 assert_eq!(route.op, Op::SaveThread);
1043 assert_eq!(input, json!({ "id": "ntf_1", "saved": false }));
1044 let (route, input) = resolve("DELETE", "/notifications/threads/ntf_1/snooze", &[], json!({ "until": "x" })).unwrap();
1045 assert_eq!(route.op, Op::SnoozeThread);
1046 assert_eq!(input, json!({ "id": "ntf_1" }));
1047 let query = [("all".to_owned(), "true".to_owned()), ("per_page".to_owned(), "50".to_owned())];
1048 let (route, input) = resolve("GET", "/repos/acme/rocket/notifications", &query, Value::Null).unwrap();
1049 assert_eq!(route.op, Op::ListNotifications);
1050 assert_eq!(input, json!({ "all": "true", "per_page": "50", "repo": "acme/rocket" }));
1051 let (route, input) = resolve("PUT", "/repos/acme/rocket/issues/7/subscription", &[], json!({ "ignored": true })).unwrap();
1052 assert_eq!(route.op, Op::SetThreadSubscription);
1053 assert_eq!(input, json!({ "ignored": true, "number": 7, "repo": "acme/rocket" }));
1054 assert_eq!(resolve("GET", "/user/subscriptions", &[], Value::Null).unwrap().0.op, Op::ListWatchedRepos);
1055 }
1056
1057 #[test]
1058 fn labels_and_milestones_are_named_in_the_path() {
1059 let (route, input) = resolve("PATCH", "/repos/acme/web/labels/good%20first%20issue", &[], json!({ "color": "7057ff" })).unwrap();
1060 assert_eq!(route.op, Op::UpdateLabel);
1061 assert_eq!(input, json!({ "color": "7057ff", "label": "good first issue", "repo": "acme/web" }));
1062 let (route, input) = resolve("DELETE", "/repos/acme/web/issues/7/labels/bug", &[], Value::Null).unwrap();
1063 assert_eq!(route.op, Op::RemoveIssueLabels);
1064 assert_eq!(input, json!({ "label": "bug", "number": 7, "repo": "acme/web" }));
1065 let (route, input) = resolve("DELETE", "/repos/acme/web/issues/7/labels", &[], Value::Null).unwrap();
1066 assert_eq!(route.op, Op::RemoveIssueLabels);
1067 assert_eq!(input, json!({ "number": 7, "repo": "acme/web" }));
1068 let (route, _) = resolve("POST", "/repos/acme/web/labels/defaults", &[], Value::Null).unwrap();
1069 assert_eq!(route.op, Op::AddDefaultLabels);
1070 let (route, input) = resolve("PATCH", "/repos/acme/web/milestones/3", &[], json!({ "state": "closed" })).unwrap();
1071 assert_eq!(route.op, Op::UpdateMilestone);
1072 assert_eq!(input, json!({ "state": "closed", "milestone": 3, "repo": "acme/web" }));
1073 let (route, input) = resolve("PATCH", "/repos/acme/web/pulls/9", &[], json!({ "base": "release" })).unwrap();
1074 assert_eq!(route.op, Op::UpdatePullRequest);
1075 assert_eq!(input, json!({ "base": "release", "number": 9, "repo": "acme/web" }));
1076 }
1077
1078 #[test]
1079 fn billing_is_addressed_by_workspace() {
1080 let query = [("from".to_owned(), "2026-10-01".to_owned()), ("products".to_owned(), "agent,sandboxes".to_owned())];
1081 let (route, input) = resolve("GET", "/workspaces/acme/usage", &query, Value::Null).unwrap();
1082 assert_eq!(route.op, Op::GetUsage);
1083 assert_eq!(input, json!({ "from": "2026-10-01", "products": "agent,sandboxes", "workspace": "acme" }));
1084 let (route, input) = resolve("PUT", "/workspaces/acme/budget", &[], json!({ "alerts": [50] })).unwrap();
1085 assert_eq!(route.op, Op::SetBudget);
1086 assert_eq!(input, json!({ "alerts": [50], "workspace": "acme" }));
1087 let op = |method: &str, path: &str| resolve(method, path, &[], Value::Null).unwrap().0.op;
1088 assert_eq!(op("GET", "/workspaces/acme/budget"), Op::GetBudget);
1089 assert_eq!(op("GET", "/workspaces/acme/ai_credit"), Op::GetAiCredit);
1090 assert_eq!(op("POST", "/workspaces/acme/ai_credit/checkout"), Op::BuyAiCredit);
1091 assert_eq!(op("GET", "/workspaces/acme/invoices"), Op::ListInvoices);
1092 assert_eq!(op("GET", "/workspaces/acme/billing_details"), Op::GetBillingDetails);
1093 assert_eq!(op("GET", "/workspaces/acme/gateway/requests"), Op::ListGatewayRequests);
1094 }
1095
1096 #[test]
1097 fn checks_are_at_githubs_addresses() {
1098 let sha = "a".repeat(40);
1099 let body = json!({ "state": "success", "context": "ci/build" });
1100 let (route, input) = resolve("POST", &format!("/repos/acme/web/statuses/{sha}"), &[], body).unwrap();
1101 assert_eq!(route.op, Op::Checks(ChecksOp::CreateCommitStatus));
1102 assert_eq!(input, json!({ "state": "success", "context": "ci/build", "sha": sha, "repo": "acme/web" }));
1103 let (route, input) = resolve("GET", "/repos/acme/web/commits/release%2F1.x/status", &[], Value::Null).unwrap();
1104 assert_eq!(route.op, Op::Checks(ChecksOp::GetCombinedStatus));
1105 assert_eq!(input, json!({ "ref": "release/1.x", "repo": "acme/web" }));
1106 let query = [("check_name".to_owned(), "lint".to_owned())];
1107 let (route, input) = resolve("GET", "/repos/acme/web/commits/main/check-runs", &query, Value::Null).unwrap();
1108 assert_eq!(route.op, Op::Checks(ChecksOp::ListCheckRunsForRef));
1109 assert_eq!(input, json!({ "check_name": "lint", "ref": "main", "repo": "acme/web" }));
1110 let (route, input) = resolve("PATCH", "/repos/acme/web/check-runs/cr_1", &[], json!({ "conclusion": "success" })).unwrap();
1111 assert_eq!(route.op, Op::Checks(ChecksOp::UpdateCheckRun));
1112 assert_eq!(input, json!({ "conclusion": "success", "id": "cr_1", "repo": "acme/web" }));
1113 let op = |method: &str, path: &str| resolve(method, path, &[], Value::Null).unwrap().0.op;
1114 assert_eq!(op("POST", "/repos/acme/web/check-runs"), Op::Checks(ChecksOp::CreateCheckRun));
1115 assert_eq!(op("GET", "/repos/acme/web/check-runs/cr_1/annotations"), Op::Checks(ChecksOp::ListCheckRunAnnotations));
1116 assert_eq!(op("POST", "/repos/acme/web/check-suites/cs_1/rerequest"), Op::Checks(ChecksOp::RerequestCheckSuite));
1117 assert_eq!(op("GET", "/repos/acme/web/commits/main/check-suites"), Op::Checks(ChecksOp::ListCheckSuitesForRef));
1118 }
1119
1120 #[test]
1121 fn query_parameters_are_renamed() {
1122 let query = [
1123 ("q".to_owned(), "parser".to_owned()),
1124 ("x".to_owned(), "y".to_owned()),
1125 ];
1126 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
1127 assert_eq!(route.op, Op::ListRepos);
1128 assert_eq!(input, json!({ "query": "parser" }));
1129 }
1130
1131 #[test]
1132 fn method_and_shape_must_match() {
1133 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
1134 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
1135 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
1136 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
1137 }
1138
1139 #[test]
1140 fn every_parameter_and_query_name_is_an_input() {
1141 for route in ROUTES {
1142 let properties = route.op.properties();
1143 for (_, key) in route.query {
1144 assert!(properties.contains_key(*key), "{}: {key}", route.path);
1145 }
1146 for name in route.params() {
1147 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
1148 || properties.contains_key(name);
1149 assert!(covered, "{}: {name}", route.path);
1150 }
1151 }
1152 }
1153
1154 #[test]
1155 fn every_operation_has_a_route() {
1156 for op in Op::ALL {
1157 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
1158 }
1159 }
1160}