Skip to content
1,251 linesCodeBlameRaw
1//! The OpenAPI document, generated from the same list the routes are.
2//!
3//! The docs site builds its API reference from a copy of this document,
4//! `apps/docs/src/data/openapi.json`. A test keeps the copy current: run
5//! `G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi` to rewrite it.
6
7use g1t_contracts::scopes::scope_for;
8use serde_json::{Map, Value, json};
9
10use crate::about::AboutOp;
11use crate::artifacts::ArtifactsOp;
12use crate::deploy_keys::DeployKeysOp;
13use crate::deployments::DeploymentsOp;
14use crate::protection::ProtectionOp;
15use crate::token_policy::TokenOp;
16use crate::operations::Op;
17use crate::checks::ChecksOp;
18use crate::rules::RulesOp;
19use crate::security::SecurityOp;
20use crate::rest::{ROUTES, Route};
21
22/// The sections of the API reference: a name, what it covers, and its
23/// operations in the order a reader meets them.
24const SECTIONS: &[(&str, &str, &[Op])] = &[
25 (
26 "Accounts",
27 "Signing in from a tool, who a token acts as, and your email addresses.",
28 &[Op::Whoami, Op::ListEmails, Op::AddEmail, Op::RemoveEmail, Op::UpdateEmailSettings],
29 ),
30 (
31 "Notifications",
32 "Your inbox: a thread for each thing you were told about (an issue, a pull request, a workflow on a branch, a deployment), why you were told, and what you subscribe to and watch. Your own: personal tokens and sessions only.",
33 &[
34 Op::ListNotifications,
35 Op::MarkNotificationsRead,
36 Op::GetNotificationThread,
37 Op::MarkThreadRead,
38 Op::MarkThreadDone,
39 Op::SaveThread,
40 Op::SnoozeThread,
41 Op::GetThreadSubscription,
42 Op::SetThreadSubscription,
43 Op::DeleteThreadSubscription,
44 Op::GetRepoSubscription,
45 Op::SetRepoSubscription,
46 Op::DeleteRepoSubscription,
47 Op::ListWatchedRepos,
48 ],
49 ),
50 (
51 "Pinned projects",
52 "The projects you keep at the top of a workspace's sidebar, in your order, up to eight a workspace. Your own: personal tokens and sessions only.",
53 &[Op::ListPinnedProjects, Op::PinProject, Op::UnpinProject, Op::ReorderPinnedProjects],
54 ),
55 (
56 "Projects",
57 "A project is what a workspace builds and runs, from a repository or a root directory in one. Each says what it is, where it runs and where to find it: its homepage, docs and other links.",
58 &[Op::ListProjects, Op::GetProject, Op::UpdateProject],
59 ),
60 (
61 "Workspaces",
62 "A workspace owns repositories and is the first part of their address. People and agents work in workspaces.",
63 &[Op::GetWorkspace, Op::CreateWorkspace, Op::UpdateWorkspace, Op::DeleteWorkspace],
64 ),
65 (
66 "Personal access tokens",
67 "A workspace's rules for its members' personal access tokens: whether classic and fine-grained tokens reach it, whether fine-grained tokens wait for an owner's approval, and how long a token may last; the tokens that reach it, approving or denying the ones that wait, and revoking one there. Owners only, as people.",
68 &[
69 Op::Tokens(TokenOp::GetTokenPolicy),
70 Op::Tokens(TokenOp::SetTokenPolicy),
71 Op::Tokens(TokenOp::ListMemberTokens),
72 Op::Tokens(TokenOp::ListTokenRequests),
73 Op::Tokens(TokenOp::ReviewTokenRequest),
74 Op::Tokens(TokenOp::RevokeMemberToken),
75 ],
76 ),
77 (
78 "Invites",
79 "While g1t is invite-only, every new account needs an invite. Your invites, and inviting people into a workspace by email.",
80 &[
81 Op::ListInvites,
82 Op::CreateInvite,
83 Op::RevokeInvite,
84 Op::ListWorkspaceInvites,
85 Op::InviteMember,
86 Op::RevokeWorkspaceInvite,
87 ],
88 ),
89 (
90 "Billing",
91 "A workspace's usage, its budget, its AI credit, its invoices and its AI Gateway requests. Members read them; owners change the budget and buy credit, as people. g1t's agents never change billing.",
92 &[
93 Op::GetUsage,
94 Op::GetBudget,
95 Op::SetBudget,
96 Op::GetAiCredit,
97 Op::BuyAiCredit,
98 Op::ListInvoices,
99 Op::GetBillingDetails,
100 Op::ListGatewayRequests,
101 ],
102 ),
103 (
104 "Repositories",
105 "A repository, how it handles pull requests, and its timeline: renaming, archiving, moving and deleting it.",
106 &[
107 Op::ListRepos,
108 Op::CreateRepo,
109 Op::GetRepo,
110 Op::UpdateRepo,
111 Op::RenameRepo,
112 Op::RenameBranch,
113 Op::SetRepoVisibility,
114 Op::ArchiveRepo,
115 Op::UnarchiveRepo,
116 Op::TransferRepo,
117 Op::DeleteRepo,
118 Op::ListDeletedRepos,
119 Op::RestoreRepo,
120 Op::PurgeRepo,
121 Op::GetRepoSettings,
122 Op::UpdateRepoSettings,
123 Op::ListCheckNames,
124 Op::GetCodeownersErrors,
125 Op::ListEvents,
126 ],
127 ),
128 (
129 "Repository insights",
130 "What a repository's default branch says about it, read in the background and kept by commit: the languages it is written in, who made it, and its license.",
131 &[Op::About(AboutOp::GetLanguages), Op::About(AboutOp::ListContributors), Op::About(AboutOp::GetLicense)],
132 ),
133 (
134 "Stars",
135 "Starring a repository, to keep it and to say you like it: who starred one, and what you starred.",
136 &[
137 Op::About(AboutOp::ListStargazers),
138 Op::About(AboutOp::ListStarred),
139 Op::About(AboutOp::CheckStarred),
140 Op::About(AboutOp::Star),
141 Op::About(AboutOp::Unstar),
142 ],
143 ),
144 (
145 "Releases",
146 "A release is a tag published with a title and notes. The latest is the newest published one that is neither a draft nor a prerelease.",
147 &[
148 Op::About(AboutOp::ListReleases),
149 Op::About(AboutOp::CreateRelease),
150 Op::About(AboutOp::GetLatestRelease),
151 Op::About(AboutOp::GetReleaseByTag),
152 Op::About(AboutOp::GetRelease),
153 Op::About(AboutOp::UpdateRelease),
154 Op::About(AboutOp::DeleteRelease),
155 ],
156 ),
157 (
158 "Access",
159 "Who can do what in a repository: repository roles, people given a role on one repository (outside collaborators when they are not members), invitations, a workspace's base permission, and deploy keys: SSH keys that reach one repository.",
160 &[
161 Op::ListCollaborators,
162 Op::AddCollaborator,
163 Op::UpdateCollaborator,
164 Op::RemoveCollaborator,
165 Op::GetCollaboratorPermission,
166 Op::ListRepoInvitations,
167 Op::RevokeRepoInvitation,
168 Op::ListMyRepoInvitations,
169 Op::AcceptRepoInvitation,
170 Op::DeclineRepoInvitation,
171 Op::SetBasePermission,
172 Op::ListOutsideCollaborators,
173 Op::DeployKeys(DeployKeysOp::ListDeployKeys),
174 Op::DeployKeys(DeployKeysOp::GetDeployKey),
175 Op::DeployKeys(DeployKeysOp::CreateDeployKey),
176 Op::DeployKeys(DeployKeysOp::DeleteDeployKey),
177 ],
178 ),
179 (
180 "Teams",
181 "Groups of a workspace's members: given a role on repositories together, mentioned together as @workspace/team, and asked to review together. Any member may create a team; the workspace's owners and the team's maintainers manage it.",
182 &[
183 Op::ListTeams,
184 Op::CreateTeam,
185 Op::GetTeam,
186 Op::UpdateTeam,
187 Op::DeleteTeam,
188 Op::ListTeamMembers,
189 Op::SetTeamMember,
190 Op::RemoveTeamMember,
191 Op::ListChildTeams,
192 Op::ListTeamRepos,
193 Op::SetTeamRepo,
194 Op::RemoveTeamRepo,
195 Op::SetTeamReviewAssignment,
196 Op::ListUserTeams,
197 ],
198 ),
199 (
200 "Security",
201 "Secrets found in what is pushed and in a repository's history, and dependencies with known vulnerabilities: listing the alerts, and dismissing or reopening them.",
202 &[Op::ListSecurityAlerts, Op::DismissSecurityAlert, Op::ReopenSecurityAlert],
203 ),
204 (
205 "Secret scanning",
206 "Secrets found in pushes and history, where each one is, pushing past push protection with a reason (and asking for approval when the workspace delegates bypasses), checking with a secret's issuer whether it still works, and custom patterns.",
207 &[
208 Op::Security(SecurityOp::ListSecretAlerts),
209 Op::Security(SecurityOp::GetSecretAlert),
210 Op::Security(SecurityOp::UpdateSecretAlert),
211 Op::Security(SecurityOp::ListSecretLocations),
212 Op::Security(SecurityOp::BypassPushProtection),
213 Op::Security(SecurityOp::CheckSecretValidity),
214 Op::Security(SecurityOp::ListBypassRequests),
215 Op::Security(SecurityOp::ReviewBypassRequest),
216 Op::Security(SecurityOp::ListCustomPatterns),
217 Op::Security(SecurityOp::CreateCustomPattern),
218 Op::Security(SecurityOp::UpdateCustomPattern),
219 Op::Security(SecurityOp::DeleteCustomPattern),
220 Op::Security(SecurityOp::DryRunCustomPattern),
221 ],
222 ),
223 (
224 "Code scanning",
225 "Results of static analysis tools, uploaded as SARIF: alerts on the default branch, the analyses that made them, uploads, and putting g1t on an alert to fix it.",
226 &[
227 Op::Security(SecurityOp::ListCodeAlerts),
228 Op::Security(SecurityOp::GetCodeAlert),
229 Op::Security(SecurityOp::UpdateCodeAlert),
230 Op::Security(SecurityOp::ListAnalyses),
231 Op::Security(SecurityOp::UploadSarif),
232 Op::Security(SecurityOp::GetSarifUpload),
233 Op::Security(SecurityOp::FixAlert),
234 ],
235 ),
236 (
237 "Supply chain",
238 "What a repository depends on: vulnerability alerts, the dependency graph, an SPDX SBOM of it, and comparing two commits' dependencies as dependency review does.",
239 &[
240 Op::Security(SecurityOp::ListVulnerabilityAlerts),
241 Op::Security(SecurityOp::GetVulnerabilityAlert),
242 Op::Security(SecurityOp::UpdateVulnerabilityAlert),
243 Op::Security(SecurityOp::GetDependencyGraph),
244 Op::Security(SecurityOp::GetSbom),
245 Op::Security(SecurityOp::CompareDependencies),
246 ],
247 ),
248 (
249 "Security settings",
250 "When pull request checks fail, dependency review's policy, delegated bypass and validity checks, and a workspace's security overview.",
251 &[
252 Op::Security(SecurityOp::GetSettings),
253 Op::Security(SecurityOp::UpdateSettings),
254 Op::Security(SecurityOp::GetWorkspaceSettings),
255 Op::Security(SecurityOp::UpdateWorkspaceSettings),
256 Op::Security(SecurityOp::GetOverview),
257 ],
258 ),
259 (
260 "Rules",
261 "Rulesets: what may happen to a repository's branches and tags and what a pull request needs before it merges, for a repository or across a workspace; the rules that hold for one branch; and how they judged each push and merge, with insights.",
262 &[
263 Op::Rules(RulesOp::ListRepoRulesets),
264 Op::Rules(RulesOp::CreateRepoRuleset),
265 Op::Rules(RulesOp::GetRepoRuleset),
266 Op::Rules(RulesOp::UpdateRepoRuleset),
267 Op::Rules(RulesOp::DeleteRepoRuleset),
268 Op::Rules(RulesOp::GetBranchRules),
269 Op::Rules(RulesOp::ListRuleEvaluations),
270 Op::Rules(RulesOp::ListWorkspaceRulesets),
271 Op::Rules(RulesOp::CreateWorkspaceRuleset),
272 Op::Rules(RulesOp::GetWorkspaceRuleset),
273 Op::Rules(RulesOp::UpdateWorkspaceRuleset),
274 Op::Rules(RulesOp::DeleteWorkspaceRuleset),
275 Op::Rules(RulesOp::ListWorkspaceRuleEvaluations),
276 ],
277 ),
278 (
279 "Checks",
280 "What CI, integrations and g1t Actions say about a commit, in the shapes CI tools already send: statuses (a state per context) and check runs (a lifecycle, a conclusion, a Markdown report, annotations on lines and buttons), grouped per reporter into check suites. g1t Actions jobs are check runs too. Required checks are met by either.",
281 &[
282 Op::Checks(ChecksOp::CreateCommitStatus),
283 Op::Checks(ChecksOp::ListCommitStatuses),
284 Op::Checks(ChecksOp::GetCombinedStatus),
285 Op::Checks(ChecksOp::CreateCheckRun),
286 Op::Checks(ChecksOp::UpdateCheckRun),
287 Op::Checks(ChecksOp::GetCheckRun),
288 Op::Checks(ChecksOp::ListCheckRunAnnotations),
289 Op::Checks(ChecksOp::RerequestCheckRun),
290 Op::Checks(ChecksOp::ListCheckRunsForRef),
291 Op::Checks(ChecksOp::ListCheckSuitesForRef),
292 Op::Checks(ChecksOp::GetCheckSuite),
293 Op::Checks(ChecksOp::RerequestCheckSuite),
294 ],
295 ),
296 (
297 "Issues",
298 "What should change in a repository, with labels and comments. Issues and pull requests share one sequence of numbers.",
299 &[
300 Op::ListIssues,
301 Op::CreateIssue,
302 Op::GetIssue,
303 Op::UpdateIssue,
304 Op::CloseIssue,
305 Op::ReopenIssue,
306 Op::AssignIssue,
307 Op::Delegate,
308 Op::AddComment,
309 Op::ListIssueLabels,
310 Op::AddIssueLabels,
311 Op::SetIssueLabels,
312 Op::RemoveIssueLabels,
313 ],
314 ),
315 (
316 "Labels and milestones",
317 "A repository's labels, which issues and pull requests carry by name, and its milestones, which gather them under a goal and a due date.",
318 &[
319 Op::ListLabels,
320 Op::CreateLabel,
321 Op::UpdateLabel,
322 Op::DeleteLabel,
323 Op::AddDefaultLabels,
324 Op::ListMilestones,
325 Op::CreateMilestone,
326 Op::GetMilestone,
327 Op::UpdateMilestone,
328 Op::DeleteMilestone,
329 ],
330 ),
331 (
332 "Plans",
333 "An outcome turned into the issues that would get there, with the order they must merge in.",
334 &[Op::PlanWork, Op::GetPlan, Op::ApplyPlan],
335 ),
336 (
337 "Pull requests",
338 "A proposed change in its own fork or on a branch. Several can be made for one issue; the one merged resolves it.",
339 &[
340 Op::ListPullRequests,
341 Op::CreatePullRequest,
342 Op::GetPullRequest,
343 Op::UpdatePullRequest,
344 Op::GetPullRequestChanges,
345 Op::MarkPullRequestReady,
346 Op::RequestReviewers,
347 Op::RemoveRequestedReviewers,
348 Op::ReviewPullRequest,
349 Op::MergePullRequest,
350 Op::ClosePullRequest,
351 Op::GetMergeQueue,
352 Op::MessageAgent,
353 Op::AnswerMessage,
354 Op::TakeMessages,
355 ],
356 ),
357 (
358 "Sessions",
359 "The record of how a pull request was made: prompts, reasoning and the tools that ran.",
360 &[Op::ReadSession, Op::RecordSession],
361 ),
362 (
363 "Memory",
364 "What agents and people learned that the next agent should know, for one project or across a workspace. Members and g1t's agents only; never a secret.",
365 &[Op::Remember, Op::Recall],
366 ),
367 (
368 "Search",
369 "One search across all of g1t: repositories, code, issues, pull requests, people and workspaces. Public content for everyone, and private content in workspaces you belong to.",
370 &[Op::Search],
371 ),
372 (
373 "Context",
374 "A workspace's context hub: a catalog of what it builds and runs, built from its repositories, deployments and integrations, and one search across the catalog, docs, issues, pull requests and memory.",
375 &[Op::SearchContext, Op::GetEntity],
376 ),
377 (
378 "Actions",
379 "GitHub Actions workflows in .g1t/workflows, their runs, and their jobs' logs.",
380 &[
381 Op::ListWorkflows,
382 Op::ListWorkflowRuns,
383 Op::GetWorkflowRun,
384 Op::GetJobLogs,
385 Op::DispatchWorkflow,
386 Op::CancelWorkflowRun,
387 Op::RerunWorkflowRun,
388 Op::UpdateWorkflow,
389 Op::Artifacts(ArtifactsOp::ListArtifacts),
390 Op::Artifacts(ArtifactsOp::ListRunArtifacts),
391 Op::Artifacts(ArtifactsOp::GetArtifact),
392 Op::Artifacts(ArtifactsOp::DownloadArtifact),
393 Op::Artifacts(ArtifactsOp::DeleteArtifact),
394 Op::Artifacts(ArtifactsOp::GetArtifactRetention),
395 Op::Artifacts(ArtifactsOp::SetArtifactRetention),
396 ],
397 ),
398 (
399 "Deployments",
400 "A repository's deployments wherever they run: reported from any CI with these routes, made by g1t Actions jobs with an `environment:`, or built on g1t.page. Each has statuses, shows on its commit as the check `deploy / <environment>`, and belongs to an environment.",
401 &[
402 Op::Deployments(DeploymentsOp::ListDeployments),
403 Op::Deployments(DeploymentsOp::CreateDeployment),
404 Op::Deployments(DeploymentsOp::GetDeployment),
405 Op::Deployments(DeploymentsOp::ListDeploymentStatuses),
406 Op::Deployments(DeploymentsOp::CreateDeploymentStatus),
407 Op::Deployments(DeploymentsOp::ListEnvironments),
408 Op::Deployments(DeploymentsOp::GetEnvironment),
409 ],
410 ),
411 (
412 "Run protection",
413 "What keeps workflow runs safe: environments' protection rules (required reviewers, a wait timer, which branches may deploy) and the reviews of the jobs they hold, approving a pull request's run from outside, what a job's token gets when its workflow writes no `permissions:`, and repository_dispatch, which a job's own token may send.",
414 &[
415 Op::Protection(ProtectionOp::UpdateEnvironment),
416 Op::Protection(ProtectionOp::DeleteEnvironment),
417 Op::Protection(ProtectionOp::GetPendingDeployments),
418 Op::Protection(ProtectionOp::ReviewPendingDeployments),
419 Op::Protection(ProtectionOp::ApproveWorkflowRun),
420 Op::Protection(ProtectionOp::GetWorkflowPermissions),
421 Op::Protection(ProtectionOp::SetWorkflowPermissions),
422 Op::Protection(ProtectionOp::GetForkPrApproval),
423 Op::Protection(ProtectionOp::SetForkPrApproval),
424 Op::Protection(ProtectionOp::CreateRepositoryDispatch),
425 Op::Protection(ProtectionOp::GetWorkspaceWorkflowPermissions),
426 Op::Protection(ProtectionOp::SetWorkspaceWorkflowPermissions),
427 ],
428 ),
429 (
430 "Secrets and variables",
431 "Values that workflows and deployments read, per repository or for a whole workspace, with a row per environment.",
432 &[
433 Op::ListActionsSecrets,
434 Op::SetActionsSecret,
435 Op::DeleteActionsSecret,
436 Op::ListActionsVariables,
437 Op::SetActionsVariable,
438 Op::DeleteActionsVariable,
439 ],
440 ),
441 (
442 "Runners",
443 "Self-hosted runners: your own machines, which run your workflow jobs (and, if you choose, your agents' work) for $0 of g1t compute. They register with a short-lived token and only ever connect out.",
444 &[
445 Op::ListRunners,
446 Op::CreateRunnerRegistrationToken,
447 Op::RemoveRunner,
448 Op::ListRunnerGroups,
449 Op::CreateRunnerGroup,
450 Op::UpdateRunnerGroup,
451 Op::DeleteRunnerGroup,
452 Op::GetRunnerSettings,
453 Op::UpdateRunnerSettings,
454 ],
455 ),
456 (
457 "Webhooks",
458 "Signed HTTPS requests sent to your own address as things happen, for a repository or a whole workspace.",
459 &[
460 Op::ListWebhooks,
461 Op::CreateWebhook,
462 Op::UpdateWebhook,
463 Op::DeleteWebhook,
464 Op::PingWebhook,
465 Op::ListWebhookDeliveries,
466 Op::RedeliverWebhook,
467 ],
468 ),
469 (
470 "Integrations",
471 "A workspace's connections to outside systems: model providers, alert sources and issue trackers.",
472 &[
473 Op::ListIntegrations,
474 Op::ConnectIntegration,
475 Op::UpdateIntegration,
476 Op::DisconnectIntegration,
477 Op::TestIntegration,
478 Op::GetModelRoutes,
479 Op::SetModelRoutes,
480 Op::GetContext,
481 Op::ImportIssue,
482 ],
483 ),
484];
485
486/// The section of the API reference an operation is listed under.
487fn tag(op: Op) -> &'static str {
488 SECTIONS
489 .iter()
490 .find(|(_, _, ops)| ops.contains(&op))
491 .map_or("Repositories", |(name, _, _)| name)
492}
493
494/// What an operation's page is called, as a short sentence.
495fn title(op: Op) -> &'static str {
496 match op {
497 Op::Whoami => "Get the current user",
498 Op::GetWorkspace => "Get a workspace",
499 Op::CreateWorkspace => "Create a workspace",
500 Op::DeleteWorkspace => "Delete a workspace",
501 Op::UpdateWorkspace => "Update a workspace",
502 Op::ListEmails => "List your email addresses",
503 Op::AddEmail => "Add an email address",
504 Op::RemoveEmail => "Remove an email address",
505 Op::UpdateEmailSettings => "Change your email settings",
506 Op::ListInvites => "List your invites",
507 Op::CreateInvite => "Create an invite",
508 Op::RevokeInvite => "Revoke an invite",
509 Op::ListWorkspaceInvites => "List a workspace's invites",
510 Op::InviteMember => "Invite someone to a workspace",
511 Op::RevokeWorkspaceInvite => "Revoke a workspace's invite",
512 Op::TransferRepo => "Transfer a repository",
513 Op::RenameRepo => "Rename a repository",
514 Op::RenameBranch => "Rename a branch",
515 Op::ArchiveRepo => "Archive a repository",
516 Op::UnarchiveRepo => "Unarchive a repository",
517 Op::SetRepoVisibility => "Change a repository's visibility",
518 Op::DeleteRepo => "Delete a repository",
519 Op::ListDeletedRepos => "List recently deleted repositories",
520 Op::RestoreRepo => "Restore a deleted repository",
521 Op::PurgeRepo => "Purge a deleted repository",
522 Op::ListRepos => "List repositories",
523 Op::GetRepo => "Get a repository",
524 Op::CreateRepo => "Create a repository",
525 Op::UpdateRepo => "Update a repository",
526 Op::GetRepoSettings => "Get repository settings",
527 Op::UpdateRepoSettings => "Update repository settings",
528 Op::ListCheckNames => "List check names",
529 Op::GetMergeQueue => "Get the merge queue",
530 Op::MessageAgent => "Message an agent",
531 Op::AnswerMessage => "Answer a message",
532 Op::TakeMessages => "Take new messages",
533 Op::Remember => "Remember something",
534 Op::Recall => "Recall memory",
535 Op::SearchContext => "Search the context hub",
536 Op::GetEntity => "Get a catalog entry",
537 Op::Search => "Search g1t",
538 Op::ListIssues => "List issues",
539 Op::GetIssue => "Get an issue",
540 Op::CreateIssue => "Create an issue",
541 Op::UpdateIssue => "Update an issue",
542 Op::CloseIssue => "Close an issue",
543 Op::ReopenIssue => "Reopen an issue",
544 Op::AssignIssue => "Assign an issue to g1t",
545 Op::Delegate => "Put an agent on it",
546 Op::PlanWork => "Plan work",
547 Op::GetPlan => "Get a plan",
548 Op::ApplyPlan => "Apply a plan",
549 Op::ListLabels => "List labels",
550 Op::CreateLabel => "Create a label",
551 Op::UpdateLabel => "Update a label",
552 Op::DeleteLabel => "Delete a label",
553 Op::AddDefaultLabels => "Add the default labels",
554 Op::ListIssueLabels => "List an issue's labels",
555 Op::AddIssueLabels => "Add labels to an issue",
556 Op::SetIssueLabels => "Set an issue's labels",
557 Op::RemoveIssueLabels => "Remove labels from an issue",
558 Op::ListMilestones => "List milestones",
559 Op::GetMilestone => "Get a milestone",
560 Op::CreateMilestone => "Create a milestone",
561 Op::UpdateMilestone => "Update a milestone",
562 Op::DeleteMilestone => "Delete a milestone",
563 Op::UpdatePullRequest => "Update a pull request",
564 Op::AddComment => "Add a comment",
565 Op::ReviewPullRequest => "Review a pull request",
566 Op::ListPullRequests => "List pull requests",
567 Op::GetPullRequest => "Get a pull request",
568 Op::CreatePullRequest => "Create a pull request",
569 Op::RecordSession => "Record session entries",
570 Op::ReadSession => "Read a session",
571 Op::MarkPullRequestReady => "Mark a pull request ready",
572 Op::ClosePullRequest => "Close a pull request",
573 Op::GetPullRequestChanges => "Get a pull request's changes",
574 Op::MergePullRequest => "Merge a pull request",
575 Op::ListEvents => "List repository events",
576 Op::ListIntegrations => "List integrations",
577 Op::ConnectIntegration => "Connect an integration",
578 Op::UpdateIntegration => "Update an integration",
579 Op::DisconnectIntegration => "Disconnect an integration",
580 Op::TestIntegration => "Test an integration",
581 Op::GetContext => "Look up a ticket",
582 Op::ImportIssue => "Import an issue",
583 Op::GetModelRoutes => "Get model routes",
584 Op::SetModelRoutes => "Set model routes",
585 Op::ListWebhooks => "List webhooks",
586 Op::CreateWebhook => "Create a webhook",
587 Op::UpdateWebhook => "Update a webhook",
588 Op::DeleteWebhook => "Delete a webhook",
589 Op::PingWebhook => "Ping a webhook",
590 Op::ListWebhookDeliveries => "List webhook deliveries",
591 Op::RedeliverWebhook => "Redeliver a webhook delivery",
592 Op::ListWorkflows => "List workflows",
593 Op::ListWorkflowRuns => "List workflow runs",
594 Op::GetWorkflowRun => "Get a workflow run",
595 Op::GetJobLogs => "Get a job's log",
596 Op::DispatchWorkflow => "Run a workflow",
597 Op::CancelWorkflowRun => "Cancel a workflow run",
598 Op::RerunWorkflowRun => "Re-run a workflow run",
599 Op::UpdateWorkflow => "Turn a workflow on or off",
600 Op::ListActionsSecrets => "List secrets",
601 Op::SetActionsSecret => "Set a secret",
602 Op::DeleteActionsSecret => "Delete a secret",
603 Op::ListActionsVariables => "List variables",
604 Op::SetActionsVariable => "Set a variable",
605 Op::DeleteActionsVariable => "Delete a variable",
606 Op::ListRunners => "List self-hosted runners",
607 Op::ListRunnerGroups => "List runner groups",
608 Op::GetRunnerSettings => "Get runner settings",
609 Op::CreateRunnerRegistrationToken => "Create a runner registration token",
610 Op::RemoveRunner => "Remove a self-hosted runner",
611 Op::CreateRunnerGroup => "Create a runner group",
612 Op::UpdateRunnerGroup => "Change a runner group",
613 Op::DeleteRunnerGroup => "Delete a runner group",
614 Op::UpdateRunnerSettings => "Change runner settings",
615 Op::ListCollaborators => "List who has access",
616 Op::AddCollaborator => "Add a collaborator",
617 Op::UpdateCollaborator => "Change a collaborator's role",
618 Op::RemoveCollaborator => "Remove a collaborator",
619 Op::GetCollaboratorPermission => "Get someone's permission",
620 Op::ListRepoInvitations => "List a repository's invitations",
621 Op::RevokeRepoInvitation => "Revoke a repository invitation",
622 Op::ListMyRepoInvitations => "List your repository invitations",
623 Op::AcceptRepoInvitation => "Accept a repository invitation",
624 Op::DeclineRepoInvitation => "Decline a repository invitation",
625 Op::SetBasePermission => "Set the base permission",
626 Op::ListOutsideCollaborators => "List outside collaborators",
627 Op::ListSecurityAlerts => "List security alerts",
628 Op::DismissSecurityAlert => "Dismiss a security alert",
629 Op::ReopenSecurityAlert => "Reopen a security alert",
630 Op::ListNotifications => "List notifications",
631 Op::MarkNotificationsRead => "Mark notifications read",
632 Op::GetNotificationThread => "Get a thread",
633 Op::MarkThreadRead => "Mark a thread read",
634 Op::MarkThreadDone => "Mark a thread done",
635 Op::SaveThread => "Save a thread",
636 Op::SnoozeThread => "Snooze a thread",
637 Op::GetThreadSubscription => "Get a thread subscription",
638 Op::SetThreadSubscription => "Set a thread subscription",
639 Op::DeleteThreadSubscription => "Unsubscribe from a thread",
640 Op::GetRepoSubscription => "Get how you watch a repository",
641 Op::SetRepoSubscription => "Watch a repository",
642 Op::DeleteRepoSubscription => "Stop watching a repository",
643 Op::ListWatchedRepos => "List repositories you watch",
644 Op::ListPinnedProjects => "List your pinned projects",
645 Op::GetUsage => "Get a workspace's usage",
646 Op::GetBudget => "Get a workspace's budget",
647 Op::SetBudget => "Change a workspace's budget",
648 Op::GetAiCredit => "Get a workspace's AI credit",
649 Op::BuyAiCredit => "Buy AI credit",
650 Op::ListInvoices => "List a workspace's invoices",
651 Op::GetBillingDetails => "Get a workspace's billing details",
652 Op::ListGatewayRequests => "List a workspace's AI Gateway requests",
653 Op::PinProject => "Pin a project",
654 Op::UnpinProject => "Unpin a project",
655 Op::ReorderPinnedProjects => "Reorder your pinned projects",
656 Op::ListProjects => "List a workspace's projects",
657 Op::GetProject => "Get a project",
658 Op::UpdateProject => "Update a project",
659 Op::ListTeams => "List teams",
660 Op::GetTeam => "Get a team",
661 Op::CreateTeam => "Create a team",
662 Op::UpdateTeam => "Update a team",
663 Op::DeleteTeam => "Delete a team",
664 Op::ListTeamMembers => "List a team's members",
665 Op::SetTeamMember => "Add or change a team member",
666 Op::RemoveTeamMember => "Remove a team member",
667 Op::ListChildTeams => "List child teams",
668 Op::ListTeamRepos => "List a team's repositories",
669 Op::SetTeamRepo => "Give a team a role on a repository",
670 Op::RemoveTeamRepo => "Remove a team from a repository",
671 Op::SetTeamReviewAssignment => "Set a team's review assignment",
672 Op::ListUserTeams => "List someone's teams",
673 Op::RequestReviewers => "Request reviewers",
674 Op::RemoveRequestedReviewers => "Remove requested reviewers",
675 Op::GetCodeownersErrors => "List CODEOWNERS errors",
676 Op::Security(op) => op.title(),
677 Op::Rules(op) => op.title(),
678 Op::Checks(op) => op.title(),
679 Op::About(op) => op.title(),
680 Op::Deployments(op) => op.title(),
681 Op::Protection(op) => op.title(),
682 Op::Tokens(op) => op.title(),
683 Op::Artifacts(op) => op.title(),
684 Op::DeployKeys(op) => op.title(),
685 }
686}
687
688/// Why an operation can be refused with `402 payment_required`, if it
689/// can: the ones that start an agent, when the workspace has no credit,
690/// and the ones that make a repository private in a workspace, when a free
691/// workspace's private storage has no room for it.
692fn may_need_payment(op: Op) -> Option<&'static str> {
693 match op {
694 Op::AssignIssue | Op::PlanWork | Op::ApplyPlan => Some("The workspace has no agent credit."),
695 Op::UpdateRepo | Op::SetRepoVisibility | Op::TransferRepo => Some(
696 "A free workspace's private storage has no room for this private repository.",
697 ),
698 _ => None,
699 }
700}
701
702/// What the reference says beyond each operation's own description, keyed
703/// by operation id, written by hand from what the services return: `notes`
704/// (Markdown, added to the description) and example `params` (path),
705/// `query`, `request` (body) and `response`.
706const REFERENCE: &str = include_str!("reference.json");
707
708fn examples() -> Map<String, Value> {
709 match serde_json::from_str(REFERENCE) {
710 Ok(Value::Object(examples)) => examples,
711 _ => Map::new(),
712 }
713}
714
715/// `/repos/:owner/:name` as OpenAPI writes it: `/repos/{owner}/{name}`.
716fn openapi_path(route: &Route) -> String {
717 route
718 .path
719 .split('/')
720 .map(|segment| match segment.strip_prefix(':') {
721 Some(name) => format!("{{{name}}}"),
722 None => segment.to_owned(),
723 })
724 .collect::<Vec<_>>()
725 .join("/")
726}
727
728fn error_response(description: &str) -> Value {
729 json!({
730 "description": description,
731 "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } },
732 })
733}
734
735/// A parameter in the path or the query, described by the operation's
736/// input schema where it has the same name.
737fn parameter(name: &str, place: &str, required: bool, schema: Option<&Value>) -> Value {
738 let mut schema = schema.cloned().unwrap_or_else(|| json!({ "type": "string" }));
739 let description = match name {
740 "owner" => Some(Value::from("The workspace that owns the repository.")),
741 "name" => Some(Value::from("The repository's name.")),
742 _ => schema.as_object_mut().and_then(|schema| schema.remove("description")),
743 };
744 let mut parameter = json!({
745 "name": name,
746 "in": place,
747 "required": required,
748 "schema": schema,
749 });
750 if let Some(description) = description {
751 parameter["description"] = description;
752 }
753 parameter
754}
755
756/// The operation id of a route. An operation reached at a workspace's
757/// address as well as a repository's is documented once for each, with its
758/// own id; GitHub's alternative addresses for one operation keep GitHub's
759/// names.
760fn operation_id(route: &Route) -> String {
761 let op = route.op;
762 let base = match (route.method, route.path.rsplit('/').next().unwrap_or_default()) {
763 ("PUT", "enable") => "enable_workflow".to_owned(),
764 ("PUT", "disable") => "disable_workflow".to_owned(),
765 ("POST", "rerun-failed-jobs") => "rerun_failed_jobs".to_owned(),
766 ("PATCH", ":setting") => "update_actions_variable".to_owned(),
767 ("GET", "runs") if route.path.contains("/workflows/:workflow/") => "list_runs_of_workflow".to_owned(),
768 // One repository's notifications, and an issue's subscription by
769 // its number rather than a thread's id.
770 (_, "notifications") if route.path.starts_with("/repos/") => match op {
771 Op::ListNotifications => "list_repo_notifications".to_owned(),
772 _ => "mark_repo_notifications_read".to_owned(),
773 },
774 (method, "subscription") if route.path.contains("/issues/:number/") => match method {
775 "GET" => "get_issue_subscription".to_owned(),
776 "PUT" => "set_issue_subscription".to_owned(),
777 _ => "delete_issue_subscription".to_owned(),
778 },
779 // One label off an issue, by its name in the path.
780 ("DELETE", ":label") if route.path.contains("/issues/:number/") => "remove_issue_label".to_owned(),
781 ("DELETE", "saved") => "unsave_thread".to_owned(),
782 ("DELETE", "snooze") => "unsnooze_thread".to_owned(),
783 _ => op.name().to_owned(),
784 };
785 if route.path.starts_with("/workspaces/") && ROUTES.iter().any(|other| other.op == op && other.path.starts_with("/repos/")) {
786 format!("{base}_for_workspace")
787 } else {
788 base
789 }
790}
791
792/// The summary of a route: its operation's title, or for one of GitHub's
793/// alternative addresses, what that address does.
794fn summary(route: &Route, id: &str) -> String {
795 let base = match id.trim_end_matches("_for_workspace") {
796 "enable_workflow" => "Turn a workflow on",
797 "disable_workflow" => "Turn a workflow off",
798 "rerun_failed_jobs" => "Re-run failed jobs",
799 "update_actions_variable" => "Update a variable",
800 "list_runs_of_workflow" => "List a workflow's runs",
801 "list_repo_notifications" => "List a repository's notifications",
802 "mark_repo_notifications_read" => "Mark a repository's notifications read",
803 "get_issue_subscription" => "Get your subscription to an issue",
804 "set_issue_subscription" => "Subscribe to an issue",
805 "delete_issue_subscription" => "Unsubscribe from an issue",
806 "unsave_thread" => "Unsave a thread",
807 "unsnooze_thread" => "Bring a snoozed thread back",
808 _ => title(route.op),
809 };
810 if id.ends_with("_for_workspace") {
811 format!("{base} for a workspace")
812 } else {
813 base.to_owned()
814 }
815}
816
817fn operation(route: &Route) -> Value {
818 let op = route.op;
819 let path_params: Vec<&str> = route.params().collect();
820 // `owner` and `name` in the path stand for the operation's `repo` input,
821 // so a `name` in the body, such as a check run's, is the body's own.
822 let stands_for_repo =
823 |name: &str| matches!(name, "owner" | "name") && path_params.contains(&"owner") && path_params.contains(&"name");
824 let covered = |name: &str| name == "repo" || (path_params.contains(&name) && !stands_for_repo(name));
825 let all_properties = op.properties();
826 let mut properties = all_properties.clone();
827 properties.retain(|name, _| !covered(name));
828 let required: Vec<String> = op
829 .required()
830 .into_iter()
831 .filter(|name| !covered(name))
832 .collect();
833
834 let mut parameters: Vec<Value> = path_params
835 .iter()
836 .map(|name| parameter(name, "path", true, if stands_for_repo(name) { None } else { all_properties.get(*name) }))
837 .collect();
838 let mut body = Value::Null;
839 if route.method == "GET" {
840 for (name, key) in route.query {
841 parameters.push(parameter(
842 name,
843 "query",
844 required.iter().any(|required| required == key),
845 properties.get(*key),
846 ));
847 }
848 } else if !properties.is_empty() {
849 let mut schema = json!({ "type": "object", "properties": properties });
850 if !required.is_empty() {
851 schema["required"] = json!(required);
852 }
853 body = json!({
854 "required": !required.is_empty(),
855 "content": { "application/json": { "schema": schema } },
856 });
857 }
858
859 let id = operation_id(route);
860 let mut responses = Map::new();
861 responses.insert(
862 "200".into(),
863 json!({
864 "description": "Success.",
865 "content": { "application/json": { "schema": {} } },
866 }),
867 );
868 responses.insert(
869 "401".into(),
870 error_response("A token is required, or the one sent is not valid."),
871 );
872 if let Some(reason) = may_need_payment(op) {
873 responses.insert("402".into(), error_response(reason));
874 }
875 responses.insert(
876 "403".into(),
877 error_response("Signed in, but not allowed to do this: the role you have is not enough, or the token lacks the scope it needs, which `needed_scope` names."),
878 );
879 if !matches!(op, Op::Whoami | Op::ListRepos | Op::Search) {
880 responses.insert("404".into(), error_response("It does not exist, or you cannot see it."));
881 }
882 if route.method != "GET" {
883 responses.insert(
884 "409".into(),
885 error_response("The request conflicts with the current state."),
886 );
887 }
888 if op != Op::Whoami {
889 responses.insert("422".into(), error_response("The input is not valid."));
890 }
891 // Public data can be read without a token; everything else needs one.
892 let scope: Vec<&str> = scope_for(op.name()).map(|scope| scope.as_str()).into_iter().collect();
893 let security = if op.needs_user() {
894 json!([{ "token": scope }])
895 } else {
896 json!([{ "token": scope }, {}])
897 };
898 let (tool, action) = crate::tools::TOOLS
899 .iter()
900 .find_map(|tool| {
901 tool.actions
902 .iter()
903 .find(|action| action.op == op)
904 .map(|action| (tool.name, action.name))
905 })
906 .unwrap_or_default();
907 let mut described = json!({
908 "operationId": id,
909 "tags": [tag(op)],
910 "summary": summary(route, &id),
911 "description": op.description(),
912 "x-operation": op.name(),
913 "x-mcp-tool": tool,
914 "x-mcp-action": action,
915 "x-scope": scope.first().copied(),
916 "security": security,
917 "parameters": parameters,
918 "responses": responses,
919 });
920 if !body.is_null() {
921 described["requestBody"] = body;
922 }
923 described
924}
925
926/// Entries for device sign-in, which is not an operation.
927fn onboarding() -> Map<String, Value> {
928 let paths = json!({
929 "/device/code": {
930 "post": {
931 "operationId": "device_code",
932 "tags": ["Accounts"],
933 "summary": "Start signing in",
934 "description": "Begins a device sign-in. Show the person `verification_uri_complete` and have them open it in a browser, where they sign in or register and approve the code. Then poll `/device/token`.",
935 "security": [],
936 "requestBody": {
937 "content": { "application/json": { "schema": {
938 "type": "object",
939 "properties": {
940 "client_name": {
941 "type": "string",
942 "description": "What is asking, shown to the person approving. For example, Claude Code.",
943 },
944 },
945 } } },
946 },
947 "responses": { "200": {
948 "description": "The codes for this sign-in.",
949 "content": { "application/json": { "schema": {
950 "type": "object",
951 "properties": {
952 "device_code": { "type": "string", "description": "Secret. Send it to /device/token." },
953 "user_code": { "type": "string", "description": "Shown to the person, like WDJB-MJHT." },
954 "verification_uri": { "type": "string" },
955 "verification_uri_complete": {
956 "type": "string",
957 "description": "The link to give the person; it carries the code.",
958 },
959 "expires_in": { "type": "integer", "description": "Seconds until the codes expire." },
960 "interval": { "type": "integer", "description": "Seconds to wait between polls." },
961 },
962 } } },
963 } },
964 },
965 },
966 "/device/token": {
967 "post": {
968 "operationId": "device_token",
969 "tags": ["Accounts"],
970 "summary": "Finish signing in",
971 "description": "Asks whether the person has approved. Poll no faster than the interval. The token is returned once.",
972 "security": [],
973 "requestBody": {
974 "required": true,
975 "content": { "application/json": { "schema": {
976 "type": "object",
977 "required": ["device_code"],
978 "properties": { "device_code": { "type": "string" } },
979 } } },
980 },
981 "responses": { "200": {
982 "description": "The state of the sign-in.",
983 "content": { "application/json": { "schema": {
984 "type": "object",
985 "required": ["status"],
986 "properties": {
987 "status": { "type": "string", "enum": ["pending", "approved", "denied", "expired"] },
988 "token": { "type": "string", "description": "Present when approved." },
989 "username": { "type": "string" },
990 "verified": {
991 "type": "boolean",
992 "description": "Whether the account's email is confirmed.",
993 },
994 },
995 } } },
996 } },
997 },
998 },
999 });
1000 match paths {
1001 Value::Object(paths) => paths,
1002 _ => Map::new(),
1003 }
1004}
1005
1006
1007/// Puts each operation's examples, where it has them, into its request
1008/// and response. Path and query values go under `x-example-params` and
1009/// `x-example-query`, which tools that build a request can use.
1010fn attach_examples(paths: &mut Map<String, Value>) {
1011 let examples = examples();
1012 for methods in paths.values_mut() {
1013 let Some(methods) = methods.as_object_mut() else { continue };
1014 for operation in methods.values_mut() {
1015 let id = operation["operationId"].as_str().unwrap_or_default().to_owned();
1016 let name = operation["x-operation"].as_str().unwrap_or_default().to_owned();
1017 let Some(example) = examples.get(&id).or_else(|| examples.get(&name)) else {
1018 continue;
1019 };
1020 if let Some(notes) = example.get("notes").and_then(Value::as_str) {
1021 let description = operation["description"].as_str().unwrap_or_default();
1022 operation["description"] = json!(format!("{description}\n\n{notes}"));
1023 }
1024 if let Some(response) = example.get("response") {
1025 let content = &mut operation["responses"]["200"]["content"]["application/json"];
1026 if content.is_object() {
1027 content["example"] = response.clone();
1028 }
1029 }
1030 if let Some(request) = example.get("request") {
1031 let content = &mut operation["requestBody"]["content"]["application/json"];
1032 if content.is_object() {
1033 content["example"] = request.clone();
1034 }
1035 }
1036 for (key, extension) in [("params", "x-example-params"), ("query", "x-example-query")] {
1037 if let Some(values) = example.get(key) {
1038 operation[extension] = values.clone();
1039 }
1040 }
1041 }
1042 }
1043}
1044
1045pub fn document() -> Value {
1046 let mut paths = onboarding();
1047 for route in ROUTES {
1048 let entry = paths
1049 .entry(openapi_path(route))
1050 .or_insert_with(|| json!({}));
1051 entry[route.method.to_lowercase()] = operation(route);
1052 }
1053 attach_examples(&mut paths);
1054 let tags: Vec<Value> = SECTIONS
1055 .iter()
1056 .map(|(name, description, ops)| {
1057 json!({
1058 "name": name,
1059 "description": description,
1060 // The section's operations in reading order, by MCP tool name.
1061 "x-tools": ops.iter().map(|op| op.name()).collect::<Vec<_>>(),
1062 })
1063 })
1064 .collect();
1065 let codes = ["unauthenticated", "payment_required", "forbidden", "not_found", "conflict", "invalid"];
1066 json!({
1067 "openapi": "3.1.0",
1068 "info": {
1069 "title": "g1t API",
1070 "version": "1",
1071 "description": "The REST API for g1t, a git forge built for agents. The same operations are available to agents as MCP tools at https://mcp.g1t.sh. Every name in a request or response body is `snake_case`; names you chose, such as a workflow's inputs or a secret's name, are returned as you wrote them.",
1072 "license": { "name": "MIT", "identifier": "MIT" },
1073 },
1074 "servers": [{ "url": "https://api.g1t.sh" }],
1075 "security": [{ "token": [] }, {}],
1076 "tags": tags,
1077 "paths": paths,
1078 "components": {
1079 "securitySchemes": {
1080 "token": {
1081 "type": "http",
1082 "scheme": "bearer",
1083 "description": "An access token, `g1t_…`. Public data needs none. Each operation names the scope a token needs for it; see https://docs.g1t.sh/guides/authentication/#scopes.",
1084 },
1085 },
1086 "schemas": {
1087 "Error": {
1088 "type": "object",
1089 "required": ["error"],
1090 "properties": {
1091 "error": {
1092 "type": "object",
1093 "required": ["code", "message"],
1094 "properties": {
1095 "code": { "type": "string", "enum": codes },
1096 "message": { "type": "string" },
1097 "needed_scope": {
1098 "type": "string",
1099 "description": "On a 403 for an access token without the scope the call needs: that scope, such as `issues:write`.",
1100 },
1101 },
1102 },
1103 },
1104 },
1105 },
1106 },
1107 })
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112 use super::*;
1113
1114 #[test]
1115 fn every_route_is_documented_once() {
1116 let document = document();
1117 let mut ids = Vec::new();
1118 for (_, methods) in document["paths"].as_object().unwrap() {
1119 for (_, operation) in methods.as_object().unwrap() {
1120 ids.push(operation["operationId"].as_str().unwrap().to_owned());
1121 }
1122 }
1123 for op in Op::ALL {
1124 assert_eq!(
1125 ids.iter().filter(|id| *id == op.name()).count(),
1126 1,
1127 "{}",
1128 op.name()
1129 );
1130 }
1131 let mut unique = ids.clone();
1132 unique.sort();
1133 unique.dedup();
1134 assert_eq!(unique.len(), ids.len(), "operation ids repeat");
1135 }
1136
1137 #[test]
1138 fn path_and_query_inputs_are_not_repeated_in_the_body() {
1139 let document = document();
1140 let merge = &document["paths"]["/repos/{owner}/{name}/pulls/{number}/merge"]["post"];
1141 let body = &merge["requestBody"]["content"]["application/json"]["schema"]["properties"];
1142 assert!(body.get("keep_issue_open").is_some());
1143 assert!(body.get("repo").is_none() && body.get("number").is_none());
1144 let list = &document["paths"]["/repos"]["get"];
1145 assert_eq!(list["parameters"][0]["name"], "q");
1146 assert!(list.get("requestBody").is_none());
1147 }
1148
1149 #[test]
1150 fn every_operation_is_in_one_section() {
1151 for op in Op::ALL {
1152 let sections = SECTIONS
1153 .iter()
1154 .filter(|(_, _, ops)| ops.contains(&op))
1155 .count();
1156 assert_eq!(sections, 1, "{}", op.name());
1157 }
1158 }
1159
1160 #[test]
1161 fn titles_read_as_sentences() {
1162 assert_eq!(title(Op::CreateIssue), "Create an issue");
1163 assert_eq!(title(Op::Whoami), "Get the current user");
1164 }
1165
1166 #[test]
1167 fn every_operation_has_an_example_response() {
1168 let examples = examples();
1169 assert!(!examples.is_empty(), "reference.json does not parse");
1170 let document = document();
1171 let mut known = Vec::new();
1172 for (path, methods) in document["paths"].as_object().unwrap() {
1173 for (method, operation) in methods.as_object().unwrap() {
1174 known.push(operation["operationId"].as_str().unwrap().to_owned());
1175 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1176 assert!(!example.is_null(), "{method} {path} has no example response");
1177 }
1178 }
1179 for id in examples.keys() {
1180 assert!(known.contains(id), "reference.json names {id}, which is not an operation");
1181 }
1182 }
1183
1184 #[test]
1185 fn example_requests_send_only_what_the_body_takes() {
1186 let document = document();
1187 for (path, methods) in document["paths"].as_object().unwrap() {
1188 for (method, operation) in methods.as_object().unwrap() {
1189 let content = &operation["requestBody"]["content"]["application/json"];
1190 let Some(example) = content["example"].as_object() else { continue };
1191 let properties = &content["schema"]["properties"];
1192 for key in example.keys() {
1193 assert!(!properties[key].is_null(), "{method} {path}: {key} is not in the body");
1194 }
1195 }
1196 }
1197 }
1198
1199 /// The docs site's copy of the document. Run with `G1T_WRITE_OPENAPI=1`
1200 /// to rewrite it after changing an operation.
1201 #[test]
1202 fn the_docs_copy_is_current() {
1203 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../docs/src/data/openapi.json");
1204 let current = serde_json::to_string_pretty(&document()).unwrap() + "\n";
1205 if std::env::var_os("G1T_WRITE_OPENAPI").is_some() {
1206 std::fs::write(path, &current).unwrap();
1207 return;
1208 }
1209 let copy = std::fs::read_to_string(path).unwrap_or_default().replace("\r\n", "\n");
1210 assert!(
1211 copy == current,
1212 "apps/docs/src/data/openapi.json is out of date: run G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi"
1213 );
1214 }
1215
1216 /// The reference shows responses as they are sent: `snake_case`.
1217 #[test]
1218 fn example_responses_are_snake_case() {
1219 let document = document();
1220 for (path, methods) in document["paths"].as_object().unwrap() {
1221 for (method, operation) in methods.as_object().unwrap() {
1222 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1223 let leaked = g1t_kit::wire::camel_case_keys(example);
1224 assert!(leaked.is_empty(), "{method} {path} shows {leaked:?}");
1225 }
1226 }
1227 }
1228
1229 /// Examples never hold anything that reads as a real credential, which
1230 /// secret scanners rightly flag in a public repository: they end in `…`
1231 /// after the prefix, as `whsec_…` and `g1t_…` do.
1232 #[test]
1233 fn examples_hold_no_real_looking_secrets() {
1234 let prefixes = ["whsec_", "g1t_", "g1tr_", "g1trt_", "sk_live_", "sk_test_", "ghp_", "github_pat_", "xoxb-", "AKIA"];
1235 for (line, text) in REFERENCE.lines().enumerate() {
1236 for prefix in prefixes {
1237 let mut rest = text;
1238 while let Some(at) = rest.find(prefix) {
1239 let after = &rest[at + prefix.len()..];
1240 let run = after.chars().take_while(|c| c.is_ascii_alphanumeric()).count();
1241 assert!(
1242 run < 12,
1243 "reference.json line {}: `{prefix}` followed by {run} characters reads as a real secret; write `{prefix}…`",
1244 line + 1
1245 );
1246 rest = after;
1247 }
1248 }
1249 }
1250 }
1251}