Skip to content

feat(opencli): names from an extension, declared fragments, root options, default headers, body files - #4

Merged
zdunecki merged 11 commits into
masterfrom
feat/opencli-names-and-root-options
Nov 10, 2026
Merged

zdunecki merged 11 commits into
masterfrom
feat/opencli-names-and-root-options

Conversation

@zdunecki

Copy link
Copy Markdown
Member

OpenCLI generation grows the pieces a documented, hand-extended CLI needs, without changing any existing output: every fixture that does not opt in is byte-identical.

Converter (openapi2opencli)

  • namesFrom: a dotted operation extension (e.g. x-docs.path) whose value <group>/…/<verb> names the command; namesFromRequired makes a missing value an error listing every operation; retrieve keeps its get alias; sibling collisions on names AND aliases are refused, naming both commands.
  • pathPrefixStrip: a leading static prefix stripped from the name only (the request keeps the full path; the command's shape still sees parameters inside the prefix).
  • headersFromExtension (a dotted path under info, then the root) and defaultHeaders → x-openapi.defaultHeaders.
  • includeSecurity (opt-in): per-command x-openapi.security as schema-conformant XOpenApiSecurity entries (the scheme's descriptor + ref + scopes); groups created by namesFrom take the matching tag's description.
  • Command.metadata (docsPath when namesFrom is used). The OpenCLI JSON Schema is vendored under the converter's tests and every fixture output is validated against it.

opensdk opencli — emits the OpenCLI document for a target (--spec, --config, --lang, --sdk-name, --output) and merges hand-written fragments with --declare: root options / exitCodes / info.description replace, commands append, a same-named top-level command merges its description/aliases/hidden only; a name or alias already taken is an error; unknown root keys keep their position. generate --spec <opencli.json> accepts an OpenCLI document directly (a config that also declares SDK languages is refused before anything is written).

Rust backend (opencli2rust) — root options rendered as clap args (recursive → global, under a "Global options" help heading) with a collision check against the commands' options and clap's built-ins; CliOverrides::before_dispatch and print_usage_error; Context.headers seeded from DEFAULT_HEADERS; never two Authorization headers; --body @file / @- / @@literal; a declared Content-Type for JSON-style bodies (flatten/multipart stay JSON); a resource with only declared commands emits no one-arm match; a try_opencli2rust that returns the new errors. Fixes: the JSON --body was also sent as ?body=; baseURL in a CLI section was dropped (baseUrl only); regen.toml passes version_from / base_url.

Tests: new fixtures (converter 13–15, backend 11–12, cli/__fixtures__/opencli 1–2 with byte goldens), tests/schema.rs, cli/tests/opencli.rs, a runtime smoke (XYD_SMOKE_RUST=1, fails on any build failure). cargo test --workspace 569 passed; fmt and clippy -D warnings clean. Reviewed adversarially; the review's items are folded in. CHANGELOG 0.3.0; the version bump is the last commit (the tag v0.3.0 goes on the merge commit).

…prefix, default headers and per-command security

Command names were always derived from the method and path, so a document
that already states where each operation lives (a docs path, say) could not
hand that placement to the CLI, and a version segment such as `/v3` became a
command group of its own.

New converter options (also accepted in the root `x-cli` block):

- `namesFrom`: a dotted path to an OPERATION extension (`x-docs.path`) whose
  value `<group>/.../<verb>` places the command: every segment but the last
  is the group path, the last is the verb, each kebab-cased; a `retrieve`
  verb keeps its `get` alias. The value is recorded on the command as the
  `docsPath` metadata entry. Without the extension an operation falls back
  to the derived name; a named command is resource-first, so it never pairs
  into a verb-first read. Per-operation `x-cli` still overrides it, and two
  operations naming one command is the existing collision error.
- `namesFromRequired`: a missing `namesFrom` value is an error listing every
  offending operation (`Error::MissingName`).
- `pathPrefixStrip`: drop a leading, segment-aligned path prefix before the
  default derivation; the binding keeps the full path and the positionals
  still follow it.
- `defaultHeaders` + `headersFromExtension` (header -> a dotted path under
  `info`, then the document root; a present value wins over a literal of the
  same name): resolved into the root `x-openapi.defaultHeaders`.
- `includeSecurity`: `x-openapi.security` on every command, one
  `{ scheme, scopes }` entry per scheme of the operation's `security` (else
  the document's; an empty list means none), as written.

Model: `Command.metadata`, `XOpenApiCommand.security`,
`XOpenApiRoot.defaultHeaders` — all omitted when empty, so every existing
golden converts unchanged. Fixtures `13.names-from` and
`14.headers-and-security`.
…quest bodies from files

A CLI whose surface is part generated and part hand-written needs a few
things the generated runtime did not offer: the document's root options as
real arguments, a place to read them before any command runs, control over
a usage error's exit code, and a way to authenticate from an option without
the environment credential riding along as a second `Authorization` header.

The root seam, switched on by root `options`, root `exitCodes` or
`x-openapi.defaultHeaders` (any other document generates byte-identically):

- root `options` become clap args on the root command; `recursive` ->
  `.global(true)` (a recursive option cannot also be required in clap, so it
  is emitted optional, with a warning);
- `CliOverrides::before_dispatch(&self, ctx: &mut Context, root: &ArgMatches)`
  runs after parsing and before any dispatch;
- parsing goes through `try_get_matches` and
  `CliOverrides::print_usage_error(&self, err: &clap::Error) -> ExitCode`
  (default: clap's print and exit code);
- `Context::headers`, seeded from `config::DEFAULT_HEADERS` (the document's
  default headers), are sent on every request that lacks them, and an
  `Authorization` header on the request or the context replaces the
  environment credential instead of being sent beside it.

Request bodies, in every generated CLI: a JSON-style `--body` reads `@file`
and `@-` (stdin) besides an inline value; a body declared with a media type
other than `application/json` is sent with that `Content-Type`
(multipart/form bindings keep JSON, which is what this backend sends); and
the `--body` option is no longer also sent as a `?body=` query parameter.

Also: `baseURL` — the spelling the CLI sections document and the option
split accepts — now reaches the generated config in both backends (it was
silently dropped; `baseUrl` still works), and `regen` reads `version_from`
and `base_url` from `regen.toml`.

Fixtures `11.root-options` and `12.default-headers`; fixtures 1-10 are
unchanged. `tests/runtime_smoke.rs` (XYD_SMOKE_RUST=1) builds both fixture
crates and checks the requests on the wire: one `Authorization` whichever
source wins, default headers yielding to the request's own, `@file`/`@-`
bodies and their `Content-Type`, `before_dispatch` reading a global option
given before or after the subcommand, and a mapped usage-error exit code.
…rom an OpenCLI document

`generate --lang rust-cli|go-cli` ran the converter and handed its result
straight to the backend, so the OpenCLI document a CLI is built from could
not be inspected, versioned, or extended with the hand-written half of the
CLI.

- `opensdk opencli --spec <openapi> [--config sdk.json] [--lang rust-cli|go-cli]
  [--declare <fragment.json>]... [--output <file>] [--sdk-name <name>]` runs the
  converter with the CLI section's options (`--lang`, else the first CLI
  section in the config; the cliName/version defaults `generate` applies) and
  writes the OpenCLI JSON. Each `--declare` fragment merges in order: root
  `options`, `exitCodes` and `info.description` replace; `commands` append,
  except a fragment command named like an existing top-level command (the
  `rootCommand` wrapper), which updates that command's description, aliases
  and hidden flag and leaves its children alone. Any other field on such a
  command, or an unknown root key, is an error. `--spec` defaults to the
  config's `api`; an OpenCLI document as `--spec` is taken as is.
- `generate --spec <opencli.json>` sniffs the root `opencli` key and drives a
  CLI target from the document, skipping the converter; an SDK language
  refuses it with a pointer to the CLI targets.
- The CLI sections accept the converter's new keys: `namesFrom`,
  `namesFromRequired`, `pathPrefixStrip`, `headersFromExtension`,
  `defaultHeaders`, `includeSecurity`. The ten cli-split goldens embed the
  allowlist verbatim and are hand-edited for it (the documented exception);
  `9.all-converter-keys` carries every key again.

Fixtures `cli/__fixtures__/opencli/{1.converter-options,2.declare}` with byte
goldens of the written file (`XYD_BLESS=1` re-mints), and `tests/opencli.rs`:
the same tree from the OpenAPI and from the emitted document, the merged
document driving the Rust backend, the argv layer, the SDK-language refusal.
…, prefix shape, named group help

- `x-openapi.security` on a command is now an OpenCLI `XOpenApiSecurity`
  entry: the scheme's descriptor exactly as its root entry reads (`type`,
  `kind`, `envVar`, `scheme`/`in`/`name`/`bearerFormat`), plus `ref` (the
  `components.securitySchemes` key) and `scopes`. The `{ scheme, scopes }`
  pair had no `type`, which the schema requires, and gave `scheme` a second
  meaning. A requirement naming an undeclared scheme is left out with a
  warning.
- The OpenCLI JSON Schema is vendored verbatim under
  `crates/openapi2opencli/tests/opencli-spec.json` (provenance in
  `tests/schema.rs`), and `tests/schema.rs` validates every converter fixture
  output, every OpenCLI input of both backends' fixtures, and the
  `opensdk opencli` goldens against it (jsonschema, test-only, no network).
  Two backend fixture inputs gained the required `type` on their root
  security entry; their generated output does not read it.
- The command tree checks names AND aliases among siblings: a stated
  `widgets/get` beside `widgets/retrieve` (alias `get`), two siblings sharing
  an alias, or a group created under a sibling's alias is the collision
  error, naming both commands and the shared spelling — clap rejected all
  three at runtime.
- `namesFromRequired` without `namesFrom` is an error
  (`Error::InvalidOptions`) instead of a silent no-op.
- `pathPrefixStrip`: the stripped path names the command, but whether it has
  parameters and ends in one is read from the FULL path, so a parameter
  inside the prefix still promotes a trailing custom verb and makes a
  prefix-only path an item read. A `{param}` prefix segment matches any
  parameter segment. Fixture `15.path-prefix-params`.
- A group created by `namesFrom` gets help text: the description of the tag
  whose kebab-cased name matches, else `<name> commands`. Derived groups are
  unchanged. Fixture 13 gained a tag.
…nfig refusing OpenCLI up front

- `--declare` key placement: a known key a fragment adds now goes right after
  the last known key that precedes it (else before the first that follows
  it, else at the end), and keys the order does not know keep their places —
  a leading `$schema` no longer pulled `options`/`exitCodes` above `opencli`.
- A fragment command whose name or alias another top-level command already
  answers to — an appended command named like an existing alias, an alias
  equal to an existing name, a merged alias equal to a sibling's name — is an
  error naming both commands and the spelling; clap rejected the duplicate at
  runtime.
- `generate` with an OpenCLI document and a config declaring SDK languages
  beside the CLI targets refuses before writing anything; it used to write
  the CLI targets first and then fail on the SDK refusal.
…nly media type, no one-arm match

- Root options are checked at generation time against clap's built-ins
  (`-h/--help`, and `-V/--version` when the root has a version), against
  each other, and — for a recursive (global) option, which clap copies onto
  every subcommand — against every command's options and positionals: a
  shared id, long or short is an error naming both sides. clap panicked on
  these in debug builds, and in release a subcommand flag sharing a global's
  id silently answered as the root option. `try_opencli2rust` returns the
  error (`opencli2rust::Error`); `opencli2rust` keeps its signature and
  panics on it. The `rust-cli` target and `regen` use the fallible form.
- A global root option carries `.help_heading("Global options")`, so a
  subcommand's `--help` lists it apart from the command's own flags.
- `--body @@...` sends the literal value with one `@` dropped — a body that
  itself starts with `@`, which a non-JSON media type allows.
- The declared `Content-Type` is sent for a `json`-style body only: a
  `flatten` body is assembled from flags into JSON just as a `multipart` one
  is, so labelling it with another media type misdescribed it.
- A resource with no API leaf (only non-API actions) emitted a `match` whose
  only arm is `_`, which `clippy::match_single_binding` rejects in the
  generated crate; its `run` is now the fallback body. Fixtures
  `6.local-tool` and `7.mixed` are re-blessed for it, and
  `tests/generated_lints.rs` now flags the pattern.
- `tests/runtime_smoke.rs` runs only for `XYD_SMOKE_RUST=1` and then fails on
  any build error, an unfetchable dependency included (it used to skip); it
  also checks the `@@` body and the Global options heading.
@zdunecki
zdunecki merged commit 6e54a4f into master Nov 10, 2026
3 checks passed
@zdunecki
zdunecki deleted the feat/opencli-names-and-root-options branch November 15, 2026 02:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant