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