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