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.

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