Skip to content

g1t/apps/api/src/rest.rs

1,105 lines47,414 bytesCodeBlame
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 "DELETE",
489 "/workspaces/:workspace/integrations/:id",
490 Op::DisconnectIntegration,
491 &[],
492 ),
493 route(
494 "POST",
495 "/workspaces/:workspace/integrations/:id/test",
496 Op::TestIntegration,
497 &[],
498 ),
499 route(
500 "GET",
501 "/repos/:owner/:name/actions/workflows",
502 Op::ListWorkflows,
503 &[],
504 ),
505 route(
506 "GET",
507 "/repos/:owner/:name/actions/workflows/:workflow/runs",
508 Op::ListWorkflowRuns,
509 &[("branch", "branch"), ("event", "event"), ("per_page", "limit")],
510 ),
511 route(
512 "POST",
513 "/repos/:owner/:name/actions/workflows/:workflow/dispatches",
514 Op::DispatchWorkflow,
515 &[],
516 ),
517 route(
518 "PATCH",
519 "/repos/:owner/:name/actions/workflows/:workflow",
520 Op::UpdateWorkflow,
521 &[],
522 ),
523 route(
524 "PUT",
525 "/repos/:owner/:name/actions/workflows/:workflow/enable",
526 Op::UpdateWorkflow,
527 &[],
528 ),
529 route(
530 "PUT",
531 "/repos/:owner/:name/actions/workflows/:workflow/disable",
532 Op::UpdateWorkflow,
533 &[],
534 ),
535 route(
536 "GET",
537 "/repos/:owner/:name/actions/runs",
538 Op::ListWorkflowRuns,
539 &[("workflow", "workflow"), ("branch", "branch"), ("event", "event"), ("pull", "pull"), ("head_sha", "sha"), ("per_page", "limit")],
540 ),
541 route(
542 "GET",
543 "/repos/:owner/:name/actions/runs/:id",
544 Op::GetWorkflowRun,
545 &[],
546 ),
547 route(
548 "POST",
549 "/repos/:owner/:name/actions/runs/:id/cancel",
550 Op::CancelWorkflowRun,
551 &[],
552 ),
553 route(
554 "POST",
555 "/repos/:owner/:name/actions/runs/:id/rerun",
556 Op::RerunWorkflowRun,
557 &[],
558 ),
559 route(
560 "POST",
561 "/repos/:owner/:name/actions/runs/:id/rerun-failed-jobs",
562 Op::RerunWorkflowRun,
563 &[],
564 ),
565 route(
566 "GET",
567 "/repos/:owner/:name/actions/jobs/:job/logs",
568 Op::GetJobLogs,
569 &[("after", "after")],
570 ),
571 route(
572 "GET",
573 "/repos/:owner/:name/actions/secrets",
574 Op::ListActionsSecrets,
575 &[],
576 ),
577 route(
578 "PUT",
579 "/repos/:owner/:name/actions/secrets/:setting",
580 Op::SetActionsSecret,
581 &[],
582 ),
583 route(
584 "DELETE",
585 "/repos/:owner/:name/actions/secrets/:setting",
586 Op::DeleteActionsSecret,
587 &[],
588 ),
589 route(
590 "GET",
591 "/repos/:owner/:name/actions/variables",
592 Op::ListActionsVariables,
593 &[],
594 ),
595 route(
596 "POST",
597 "/repos/:owner/:name/actions/variables",
598 Op::SetActionsVariable,
599 &[],
600 ),
601 route(
602 "PATCH",
603 "/repos/:owner/:name/actions/variables/:setting",
604 Op::SetActionsVariable,
605 &[],
606 ),
607 route(
608 "DELETE",
609 "/repos/:owner/:name/actions/variables/:setting",
610 Op::DeleteActionsVariable,
611 &[],
612 ),
613 route(
614 "GET",
615 "/workspaces/:workspace/actions/secrets",
616 Op::ListActionsSecrets,
617 &[],
618 ),
619 route(
620 "PUT",
621 "/workspaces/:workspace/actions/secrets/:setting",
622 Op::SetActionsSecret,
623 &[],
624 ),
625 route(
626 "DELETE",
627 "/workspaces/:workspace/actions/secrets/:setting",
628 Op::DeleteActionsSecret,
629 &[],
630 ),
631 route(
632 "GET",
633 "/workspaces/:workspace/actions/variables",
634 Op::ListActionsVariables,
635 &[],
636 ),
637 route(
638 "POST",
639 "/workspaces/:workspace/actions/variables",
640 Op::SetActionsVariable,
641 &[],
642 ),
643 route(
644 "PATCH",
645 "/workspaces/:workspace/actions/variables/:setting",
646 Op::SetActionsVariable,
647 &[],
648 ),
649 route(
650 "DELETE",
651 "/workspaces/:workspace/actions/variables/:setting",
652 Op::DeleteActionsVariable,
653 &[],
654 ),
655 // Self-hosted runners: a repository's own, or a workspace's.
656 route("GET", "/repos/:owner/:name/actions/runners", Op::ListRunners, &[]),
657 route("POST", "/repos/:owner/:name/actions/runners/registration-token", Op::CreateRunnerRegistrationToken, &[]),
658 route("DELETE", "/repos/:owner/:name/actions/runners/:id", Op::RemoveRunner, &[]),
659 route("GET", "/repos/:owner/:name/actions/runner-settings", Op::GetRunnerSettings, &[]),
660 route("PATCH", "/repos/:owner/:name/actions/runner-settings", Op::UpdateRunnerSettings, &[]),
661 route("GET", "/workspaces/:workspace/actions/runners", Op::ListRunners, &[]),
662 route("POST", "/workspaces/:workspace/actions/runners/registration-token", Op::CreateRunnerRegistrationToken, &[]),
663 route("DELETE", "/workspaces/:workspace/actions/runners/:id", Op::RemoveRunner, &[]),
664 route("GET", "/workspaces/:workspace/actions/runner-settings", Op::GetRunnerSettings, &[]),
665 route("PATCH", "/workspaces/:workspace/actions/runner-settings", Op::UpdateRunnerSettings, &[]),
666 route("GET", "/workspaces/:workspace/actions/runner-groups", Op::ListRunnerGroups, &[]),
667 route("POST", "/workspaces/:workspace/actions/runner-groups", Op::CreateRunnerGroup, &[]),
668 route("PATCH", "/workspaces/:workspace/actions/runner-groups/:id", Op::UpdateRunnerGroup, &[]),
669 route("DELETE", "/workspaces/:workspace/actions/runner-groups/:id", Op::DeleteRunnerGroup, &[]),
670 route("POST", "/repos/:owner/:name/plans", Op::PlanWork, &[]),
671 route("GET", "/repos/:owner/:name/plans/:plan", Op::GetPlan, &[]),
672 route(
673 "POST",
674 "/repos/:owner/:name/plans/:plan/apply",
675 Op::ApplyPlan,
676 &[],
677 ),
678 route(
679 "POST",
680 "/repos/:owner/:name/issues/:number/comments",
681 Op::AddComment,
682 &[],
683 ),
684 route(
685 "GET",
686 "/repos/:owner/:name/pulls",
687 Op::ListPullRequests,
688 &[("state", "state"), ("label", "label"), ("milestone", "milestone"), ("base", "base")],
689 ),
690 route(
691 "POST",
692 "/repos/:owner/:name/pulls",
693 Op::CreatePullRequest,
694 &[],
695 ),
696 route(
697 "GET",
698 "/repos/:owner/:name/pulls/:number",
699 Op::GetPullRequest,
700 &[],
701 ),
702 route(
703 "PATCH",
704 "/repos/:owner/:name/pulls/:number",
705 Op::UpdatePullRequest,
706 &[],
707 ),
708 route(
709 "GET",
710 "/repos/:owner/:name/pulls/:number/changes",
711 Op::GetPullRequestChanges,
712 &[],
713 ),
714 route(
715 "POST",
716 "/repos/:owner/:name/pulls/:number/reviews",
717 Op::ReviewPullRequest,
718 &[],
719 ),
720 route(
721 "POST",
722 "/repos/:owner/:name/pulls/:number/requested_reviewers",
723 Op::RequestReviewers,
724 &[],
725 ),
726 route(
727 "DELETE",
728 "/repos/:owner/:name/pulls/:number/requested_reviewers",
729 Op::RemoveRequestedReviewers,
730 &[],
731 ),
732 route(
733 "GET",
734 "/repos/:owner/:name/pulls/:number/session",
735 Op::ReadSession,
736 &[("after", "after")],
737 ),
738 route(
739 "POST",
740 "/repos/:owner/:name/pulls/:number/session",
741 Op::RecordSession,
742 &[],
743 ),
744 route(
745 "POST",
746 "/repos/:owner/:name/pulls/:number/ready",
747 Op::MarkPullRequestReady,
748 &[],
749 ),
750 route(
751 "POST",
752 "/repos/:owner/:name/pulls/:number/close",
753 Op::ClosePullRequest,
754 &[],
755 ),
756 route(
757 "POST",
758 "/repos/:owner/:name/pulls/:number/merge",
759 Op::MergePullRequest,
760 &[],
761 ),
762];
763
764impl Route {
765 /// The names of the route's path parameters, in order.
766 pub fn params(&self) -> impl Iterator<Item = &'static str> {
767 self.path
768 .split('/')
769 .filter_map(|segment| segment.strip_prefix(':'))
770 }
771
772 /// The values of the path parameters, if `path` is this route's.
773 fn matches<'a>(&self, path: &'a str) -> Option<Vec<(&'static str, &'a str)>> {
774 let mut values = Vec::new();
775 let mut actual = path.trim_end_matches('/').split('/');
776 for expected in self.path.split('/') {
777 let segment = actual.next()?;
778 match expected.strip_prefix(':') {
779 Some(name) if !segment.is_empty() => values.push((name, segment)),
780 Some(_) => return None,
781 None if expected == segment => {}
782 None => return None,
783 }
784 }
785 actual.next().is_none().then_some(values)
786 }
787}
788
789/// A path segment with its `%XX` escapes decoded; as given when that is not
790/// UTF-8.
791fn percent_decoded(segment: &str) -> String {
792 let bytes = segment.as_bytes();
793 let mut out = Vec::with_capacity(bytes.len());
794 let mut i = 0;
795 while i < bytes.len() {
796 let escaped = (bytes[i] == b'%')
797 .then(|| segment.get(i + 1..i + 3))
798 .flatten()
799 .filter(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
800 .and_then(|hex| u8::from_str_radix(hex, 16).ok());
801 match escaped {
802 Some(byte) => {
803 out.push(byte);
804 i += 3;
805 }
806 None => {
807 out.push(bytes[i]);
808 i += 1;
809 }
810 }
811 }
812 String::from_utf8(out).unwrap_or_else(|_| segment.to_owned())
813}
814
815/// The route for a request, and the operation input it describes.
816///
817/// The input is the JSON body, overlaid with the query parameters the route
818/// reads and then with what the path names: `owner` and `name` become
819/// `repo`, as does a team's `repo` with its `workspace`, and `number`
820/// becomes an integer.
821pub fn resolve(
822 method: &str,
823 path: &str,
824 query: &[(String, String)],
825 body: Value,
826) -> Option<(&'static Route, Value)> {
827 let (route, params) = ROUTES
828 .iter()
829 .filter(|route| route.method == method)
830 .find_map(|route| Some((route, route.matches(path)?)))?;
831
832 let mut input = match body {
833 Value::Object(fields) => fields,
834 _ => Map::new(),
835 };
836 for (name, key) in route.query {
837 if let Some((_, value)) = query.iter().find(|(query_name, _)| query_name == name) {
838 input.insert((*key).to_owned(), Value::String(value.clone()));
839 }
840 }
841 let param = |wanted: &str| {
842 params
843 .iter()
844 .find(|(name, _)| *name == wanted)
845 .map(|(_, value)| *value)
846 };
847 if let (Some(owner), Some(name)) = (param("owner"), param("name")) {
848 input.insert("repo".to_owned(), Value::String(format!("{owner}/{name}")));
849 }
850 for key in ["plan", "id", "workspace", "delivery", "workflow", "job", "setting", "username", "team", "basehead"] {
851 if let Some(value) = param(key) {
852 input.insert(key.to_owned(), Value::String(value.to_owned()));
853 }
854 }
855 // A repository of a team's workspace, named by itself.
856 if let (Some(workspace), Some(name)) = (param("workspace"), param("repo")) {
857 input.insert("repo".to_owned(), Value::String(format!("{workspace}/{name}")));
858 }
859 // A branch name may hold slashes, sent URL-encoded as one segment, and
860 // a label's name spaces.
861 if let Some(branch) = param("branch") {
862 input.insert("branch".to_owned(), Value::String(percent_decoded(branch)));
863 }
864 if let Some(label) = param("label") {
865 input.insert("label".to_owned(), Value::String(percent_decoded(label)));
866 }
867 if let Some(milestone) = param("milestone") {
868 // Not a number: zero, which no milestone has.
869 input.insert("milestone".to_owned(), milestone.parse::<u32>().unwrap_or(0).into());
870 }
871 // GitHub says some things with the path alone.
872 if route.path.ends_with("/enable") || route.path.ends_with("/disable") {
873 input.insert("enabled".to_owned(), Value::Bool(route.path.ends_with("/enable")));
874 }
875 if route.path.ends_with("/rerun-failed-jobs") {
876 input.insert("failed_only".to_owned(), Value::Bool(true));
877 }
878 // Unsaving and waking a thread are a DELETE of what PUT made.
879 if route.method == "DELETE" && route.path.ends_with("/saved") {
880 input.insert("saved".to_owned(), Value::Bool(false));
881 }
882 if route.method == "DELETE" && route.path.ends_with("/snooze") {
883 input.remove("until");
884 }
885 if let Some(number) = param("number") {
886 // Not a number: zero, which no issue or pull request has.
887 input.insert(
888 "number".to_owned(),
889 number.parse::<u32>().unwrap_or(0).into(),
890 );
891 }
892 Some((route, Value::Object(input)))
893}
894
895#[cfg(test)]
896mod tests {
897 use serde_json::json;
898
899 use super::*;
900
901 #[test]
902 fn a_path_resolves_to_its_operation_and_input() {
903 let (route, input) = resolve(
904 "POST",
905 "/repos/flagon-io/hello/pulls/14/merge",
906 &[],
907 json!({ "keep_issue_open": true, "number": 99, "repo": "someone/else" }),
908 )
909 .unwrap();
910 assert_eq!(route.op, Op::MergePullRequest);
911 // What the path names wins over the body.
912 assert_eq!(
913 input,
914 json!({ "keep_issue_open": true, "number": 14, "repo": "flagon-io/hello" })
915 );
916 }
917
918 #[test]
919 fn a_branch_with_slashes_is_one_encoded_segment() {
920 let (route, input) = resolve(
921 "POST",
922 "/repos/flagon-io/hello/branches/feature%2Flogin/rename",
923 &[],
924 json!({ "new_name": "feature/sign-in" }),
925 )
926 .unwrap();
927 assert_eq!(route.op, Op::RenameBranch);
928 assert_eq!(
929 input,
930 json!({ "new_name": "feature/sign-in", "branch": "feature/login", "repo": "flagon-io/hello" })
931 );
932 assert_eq!(percent_decoded("100%"), "100%");
933 assert_eq!(percent_decoded("a%2bb%zz"), "a+b%zz");
934 }
935
936 #[test]
937 fn a_collaborator_is_named_by_username() {
938 let (route, input) = resolve(
939 "PATCH",
940 "/repos/flagon-io/hello/collaborators/ada",
941 &[],
942 json!({ "role": "maintain" }),
943 )
944 .unwrap();
945 assert_eq!(route.op, Op::UpdateCollaborator);
946 assert_eq!(input, json!({ "role": "maintain", "username": "ada", "repo": "flagon-io/hello" }));
947 let (route, input) = resolve("DELETE", "/user/repository_invitations/rin_1", &[], Value::Null).unwrap();
948 assert_eq!(route.op, Op::DeclineRepoInvitation);
949 assert_eq!(input, json!({ "id": "rin_1" }));
950 }
951
952 #[test]
953 fn teams_are_addressed_by_workspace_and_slug() {
954 let query = [("q".to_owned(), "back".to_owned())];
955 let (route, input) = resolve("GET", "/workspaces/acme/teams", &query, Value::Null).unwrap();
956 assert_eq!(route.op, Op::ListTeams);
957 assert_eq!(input, json!({ "query": "back", "workspace": "acme" }));
958 let (route, input) = resolve("PATCH", "/workspaces/acme/teams/backend", &[], json!({ "name": "Back end" })).unwrap();
959 assert_eq!(route.op, Op::UpdateTeam);
960 assert_eq!(input, json!({ "name": "Back end", "workspace": "acme", "team": "backend" }));
961 let (route, input) =
962 resolve("PUT", "/workspaces/acme/teams/backend/members/ana", &[], json!({ "role": "maintainer" })).unwrap();
963 assert_eq!(route.op, Op::SetTeamMember);
964 assert_eq!(input, json!({ "role": "maintainer", "workspace": "acme", "team": "backend", "username": "ana" }));
965 let query = [("include_child_teams".to_owned(), "true".to_owned())];
966 let (route, input) = resolve("GET", "/workspaces/acme/teams/backend/members", &query, Value::Null).unwrap();
967 assert_eq!(route.op, Op::ListTeamMembers);
968 assert_eq!(input, json!({ "include_child_teams": "true", "workspace": "acme", "team": "backend" }));
969 // A repository is named by itself, in the team's workspace.
970 let (route, input) =
971 resolve("PUT", "/workspaces/acme/teams/backend/repos/rocket", &[], json!({ "role": "write" })).unwrap();
972 assert_eq!(route.op, Op::SetTeamRepo);
973 assert_eq!(input, json!({ "role": "write", "workspace": "acme", "team": "backend", "repo": "acme/rocket" }));
974 let op = |method: &str, path: &str| resolve(method, path, &[], Value::Null).unwrap().0.op;
975 assert_eq!(op("DELETE", "/workspaces/acme/teams/backend/repos/rocket"), Op::RemoveTeamRepo);
976 assert_eq!(op("GET", "/workspaces/acme/teams/backend/teams"), Op::ListChildTeams);
977 assert_eq!(op("GET", "/workspaces/acme/teams/backend/repos"), Op::ListTeamRepos);
978 assert_eq!(op("PUT", "/workspaces/acme/teams/backend/review_assignment"), Op::SetTeamReviewAssignment);
979 assert_eq!(op("DELETE", "/workspaces/acme/teams/backend"), Op::DeleteTeam);
980 assert_eq!(op("POST", "/workspaces/acme/teams"), Op::CreateTeam);
981 assert_eq!(op("GET", "/workspaces/acme/teams/backend"), Op::GetTeam);
982 assert_eq!(op("DELETE", "/workspaces/acme/teams/backend/members/ana"), Op::RemoveTeamMember);
983 let (route, input) = resolve("GET", "/workspaces/acme/members/ana/teams", &[], Value::Null).unwrap();
984 assert_eq!(route.op, Op::ListUserTeams);
985 assert_eq!(input, json!({ "workspace": "acme", "username": "ana" }));
986 }
987
988 #[test]
989 fn reviewers_are_requested_and_code_owners_checked_on_a_repository() {
990 let body = json!({ "reviewers": ["ana"], "team_reviewers": ["backend"] });
991 let (route, input) = resolve("POST", "/repos/acme/rocket/pulls/7/requested_reviewers", &[], body.clone()).unwrap();
992 assert_eq!(route.op, Op::RequestReviewers);
993 assert_eq!(
994 input,
995 json!({ "reviewers": ["ana"], "team_reviewers": ["backend"], "repo": "acme/rocket", "number": 7 })
996 );
997 let (route, _) = resolve("DELETE", "/repos/acme/rocket/pulls/7/requested_reviewers", &[], body).unwrap();
998 assert_eq!(route.op, Op::RemoveRequestedReviewers);
999 let query = [("ref".to_owned(), "main".to_owned())];
1000 let (route, input) = resolve("GET", "/repos/acme/rocket/codeowners/errors", &query, Value::Null).unwrap();
1001 assert_eq!(route.op, Op::GetCodeownersErrors);
1002 assert_eq!(input, json!({ "ref": "main", "repo": "acme/rocket" }));
1003 }
1004
1005 #[test]
1006 fn notifications_are_addressed_as_threads_and_by_issue() {
1007 let (route, input) = resolve("DELETE", "/notifications/threads/ntf_1", &[], Value::Null).unwrap();
1008 assert_eq!(route.op, Op::MarkThreadDone);
1009 assert_eq!(input, json!({ "id": "ntf_1" }));
1010 let (route, input) = resolve("DELETE", "/notifications/threads/ntf_1/saved", &[], Value::Null).unwrap();
1011 assert_eq!(route.op, Op::SaveThread);
1012 assert_eq!(input, json!({ "id": "ntf_1", "saved": false }));
1013 let (route, input) = resolve("DELETE", "/notifications/threads/ntf_1/snooze", &[], json!({ "until": "x" })).unwrap();
1014 assert_eq!(route.op, Op::SnoozeThread);
1015 assert_eq!(input, json!({ "id": "ntf_1" }));
1016 let query = [("all".to_owned(), "true".to_owned()), ("per_page".to_owned(), "50".to_owned())];
1017 let (route, input) = resolve("GET", "/repos/acme/rocket/notifications", &query, Value::Null).unwrap();
1018 assert_eq!(route.op, Op::ListNotifications);
1019 assert_eq!(input, json!({ "all": "true", "per_page": "50", "repo": "acme/rocket" }));
1020 let (route, input) = resolve("PUT", "/repos/acme/rocket/issues/7/subscription", &[], json!({ "ignored": true })).unwrap();
1021 assert_eq!(route.op, Op::SetThreadSubscription);
1022 assert_eq!(input, json!({ "ignored": true, "number": 7, "repo": "acme/rocket" }));
1023 assert_eq!(resolve("GET", "/user/subscriptions", &[], Value::Null).unwrap().0.op, Op::ListWatchedRepos);
1024 }
1025
1026 #[test]
1027 fn labels_and_milestones_are_named_in_the_path() {
1028 let (route, input) = resolve("PATCH", "/repos/acme/web/labels/good%20first%20issue", &[], json!({ "color": "7057ff" })).unwrap();
1029 assert_eq!(route.op, Op::UpdateLabel);
1030 assert_eq!(input, json!({ "color": "7057ff", "label": "good first issue", "repo": "acme/web" }));
1031 let (route, input) = resolve("DELETE", "/repos/acme/web/issues/7/labels/bug", &[], Value::Null).unwrap();
1032 assert_eq!(route.op, Op::RemoveIssueLabels);
1033 assert_eq!(input, json!({ "label": "bug", "number": 7, "repo": "acme/web" }));
1034 let (route, input) = resolve("DELETE", "/repos/acme/web/issues/7/labels", &[], Value::Null).unwrap();
1035 assert_eq!(route.op, Op::RemoveIssueLabels);
1036 assert_eq!(input, json!({ "number": 7, "repo": "acme/web" }));
1037 let (route, _) = resolve("POST", "/repos/acme/web/labels/defaults", &[], Value::Null).unwrap();
1038 assert_eq!(route.op, Op::AddDefaultLabels);
1039 let (route, input) = resolve("PATCH", "/repos/acme/web/milestones/3", &[], json!({ "state": "closed" })).unwrap();
1040 assert_eq!(route.op, Op::UpdateMilestone);
1041 assert_eq!(input, json!({ "state": "closed", "milestone": 3, "repo": "acme/web" }));
1042 let (route, input) = resolve("PATCH", "/repos/acme/web/pulls/9", &[], json!({ "base": "release" })).unwrap();
1043 assert_eq!(route.op, Op::UpdatePullRequest);
1044 assert_eq!(input, json!({ "base": "release", "number": 9, "repo": "acme/web" }));
1045 }
1046
1047 #[test]
1048 fn billing_is_addressed_by_workspace() {
1049 let query = [("from".to_owned(), "2026-10-01".to_owned()), ("products".to_owned(), "agent,sandboxes".to_owned())];
1050 let (route, input) = resolve("GET", "/workspaces/acme/usage", &query, Value::Null).unwrap();
1051 assert_eq!(route.op, Op::GetUsage);
1052 assert_eq!(input, json!({ "from": "2026-10-01", "products": "agent,sandboxes", "workspace": "acme" }));
1053 let (route, input) = resolve("PUT", "/workspaces/acme/budget", &[], json!({ "alerts": [50] })).unwrap();
1054 assert_eq!(route.op, Op::SetBudget);
1055 assert_eq!(input, json!({ "alerts": [50], "workspace": "acme" }));
1056 let op = |method: &str, path: &str| resolve(method, path, &[], Value::Null).unwrap().0.op;
1057 assert_eq!(op("GET", "/workspaces/acme/budget"), Op::GetBudget);
1058 assert_eq!(op("GET", "/workspaces/acme/ai_credit"), Op::GetAiCredit);
1059 assert_eq!(op("POST", "/workspaces/acme/ai_credit/checkout"), Op::BuyAiCredit);
1060 assert_eq!(op("GET", "/workspaces/acme/invoices"), Op::ListInvoices);
1061 assert_eq!(op("GET", "/workspaces/acme/billing_details"), Op::GetBillingDetails);
1062 assert_eq!(op("GET", "/workspaces/acme/gateway/requests"), Op::ListGatewayRequests);
1063 }
1064
1065 #[test]
1066 fn query_parameters_are_renamed() {
1067 let query = [
1068 ("q".to_owned(), "parser".to_owned()),
1069 ("x".to_owned(), "y".to_owned()),
1070 ];
1071 let (route, input) = resolve("GET", "/repos", &query, Value::Null).unwrap();
1072 assert_eq!(route.op, Op::ListRepos);
1073 assert_eq!(input, json!({ "query": "parser" }));
1074 }
1075
1076 #[test]
1077 fn method_and_shape_must_match() {
1078 assert!(resolve("GET", "/repos/a/b/issues/1/close", &[], Value::Null).is_none());
1079 assert!(resolve("GET", "/repos/a", &[], Value::Null).is_none());
1080 assert!(resolve("GET", "/repos/a/b/issues/1/extra", &[], Value::Null).is_none());
1081 assert!(resolve("GET", "/repos/a/b/", &[], Value::Null).is_some());
1082 }
1083
1084 #[test]
1085 fn every_parameter_and_query_name_is_an_input() {
1086 for route in ROUTES {
1087 let properties = route.op.properties();
1088 for (_, key) in route.query {
1089 assert!(properties.contains_key(*key), "{}: {key}", route.path);
1090 }
1091 for name in route.params() {
1092 let covered = matches!(name, "owner" | "name") && properties.contains_key("repo")
1093 || properties.contains_key(name);
1094 assert!(covered, "{}: {name}", route.path);
1095 }
1096 }
1097 }
1098
1099 #[test]
1100 fn every_operation_has_a_route() {
1101 for op in Op::ALL {
1102 assert!(ROUTES.iter().any(|route| route.op == op), "{}", op.name());
1103 }
1104 }
1105}