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