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