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