Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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