Skip to content

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

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