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