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