Skip to content

g1t/apps/api/src/rest.rs

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