Skip to content

g1t/apps/api/src/rest.rs

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