Skip to content

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

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