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