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