Skip to content

g1t/apps/api/src/rest.rs

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