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