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