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