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