Skip to content

g1t/apps/api/src/rest.rs

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