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