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