Skip to content

g1t/apps/api/src/rest.rs

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