Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions argv/src/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,8 @@ impl Framing {
pub struct OutputMeta<'a> {
/// The token a user types for it.
pub name: &'a str,
/// The media type of the bytes, independent of their stream framing.
pub media_type: Option<&'a str>,
pub framing: Framing,
pub help: Option<&'a str>,
/// What the command writes when nothing selects otherwise.
Expand All @@ -1366,6 +1368,7 @@ impl OutputMeta<'_> {
/// A named output with nothing else said about it, for struct-update syntax.
pub const EMPTY: OutputMeta<'static> = OutputMeta {
name: "",
media_type: None,
framing: Framing::Text,
help: None,
default: false,
Expand Down Expand Up @@ -2167,6 +2170,9 @@ fn write_outputs(out: &mut String, meta: &CommandMeta<'_>, depth: usize) -> core
for output in meta.outputs {
indent(out, depth)?;
write!(out, "output {}", quoted(output.name))?;
if let Some(media_type) = output.media_type {
write!(out, " media_type={}", quoted(media_type))?;
}
if output.framing != Framing::Text {
write!(out, " framing={}", quoted(output.framing.as_str()))?;
}
Expand Down
1 change: 1 addition & 0 deletions conformance/src/tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,7 @@ fn outputs(list: &[SpecOutput]) -> &'static [OutputMeta<'static>] {
list.iter()
.map(|o| OutputMeta {
name: leak(&o.name),
media_type: opt(&o.media_type),
framing: match o.framing {
Framing::Text => ArgvFraming::Text,
Framing::Json => ArgvFraming::Json,
Expand Down
48 changes: 45 additions & 3 deletions conformance/tests/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,18 @@ use usage_derive::{Args, Cli, Subcommands};
output("human", default, help = "A human-readable report"),
output(
"json",
media_type = "application/json",
framing = "json",
help = "One report object",
schema = "{\n \"type\": \"object\"\n}"
),
output("jsonl", framing = "jsonl", help = "One event per line"),
output(
"jsonl",
media_type = "application/x-ndjson",
framing = "jsonl",
help = "One event per line"
),
output("checkstyle", media_type = "application/xml"),
output("legacy", hide),
exit_code(0, "all checks passed"),
exit_code(1, "a check failed")
Expand Down Expand Up @@ -102,12 +109,42 @@ fn a_name_and_a_framing_are_different_things() {
("human", "text"),
("json", "json"),
("jsonl", "jsonl"),
("checkstyle", "text"),
("legacy", "text"),
]
);
assert!(check.outputs[0].default);
assert!(check.outputs[2].framing.is_streaming());
assert!(check.outputs[3].hide);
assert!(check.outputs[4].hide);
assert_eq!(
check.outputs[1].media_type.as_deref(),
Some("application/json")
);
assert_eq!(
check.outputs[2].media_type.as_deref(),
Some("application/x-ndjson")
);
assert_eq!(
check.outputs[3].media_type.as_deref(),
Some("application/xml")
);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

#[test]
fn a_media_type_without_a_selector_starts_a_markdown_list() {
let spec: LibSpec = r#"
name "ex"
output "xml" media_type="application/xml"
"#
.parse()
.expect("standalone output spec");
let markdown = usage::docs::markdown::MarkdownRenderer::new(spec.clone())
.render_cmd(&spec.cmd)
.expect("markdown page");
assert!(
markdown.contains("`xml`\n\n- **Media type**: `application/xml`"),
"{markdown}"
);
}

#[test]
Expand Down Expand Up @@ -139,7 +176,12 @@ fn a_field_level_select_names_its_own_flag() {
.as_ref()
.and_then(|a| a.choices.as_ref())
.map(|c| c.values()),
Some(vec!["human".into(), "json".into(), "jsonl".into()])
Some(vec![
"human".into(),
"json".into(),
"jsonl".into(),
"checkstyle".into(),
])
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Takes a while.
}
arg <tool> help="the tool to install"
output human help="a progress log" default=#true
output json framing=json {
output json media_type="application/json" framing=json {
schema #"""
{
"type": "object"
Expand Down
5 changes: 5 additions & 0 deletions conformance/tests/spec_roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ static INSTALL_META: CommandMeta = CommandMeta {
},
OutputMeta {
name: "json",
media_type: Some("application/json"),
framing: Framing::Json,
schema: Some("{\n \"type\": \"object\"\n}"),
..OutputMeta::EMPTY
Expand Down Expand Up @@ -721,6 +722,10 @@ fn outputs_and_exit_codes_survive() {
vec![("human", "text"), ("json", "json"), ("jsonl", "jsonl")]
);
assert!(install.outputs[0].default);
assert_eq!(
install.outputs[1].media_type.as_deref(),
Some("application/json")
);
assert_eq!(
install.outputs[1].schema.as_deref(),
Some("{\n \"type\": \"object\"\n}"),
Expand Down
2 changes: 2 additions & 0 deletions derive/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3934,6 +3934,7 @@ fn output_tokens(cli: &Cli) -> OutputTokens {
.enumerate()
.map(|(i, output)| {
let name = &output.name;
let media_type = option_str(output.media_type.as_deref());
let framing = match output.framing.as_str() {
"json" => quote!(usage_argv::spec::Framing::Json),
"jsonl" => quote!(usage_argv::spec::Framing::Jsonl),
Expand Down Expand Up @@ -3977,6 +3978,7 @@ fn output_tokens(cli: &Cli) -> OutputTokens {
quote! {
usage_argv::spec::OutputMeta {
name: #name,
media_type: #media_type,
framing: #framing,
help: #help,
default: #default,
Expand Down
21 changes: 15 additions & 6 deletions derive/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,11 @@ pub struct ViewDecl {
pub globals: Vec<String>,
}

/// One `output("json", framing = "json", schema_from = Report)` declaration.
/// One `output("json", media_type = "application/json", framing = "json")` declaration.
pub struct OutputDecl {
pub name: String,
/// An IANA media type such as `application/json` or `application/xml`.
pub media_type: Option<String>,
/// Written as the spec spells it — `text`, `json`, `jsonl` — and checked here so a
/// typo is a compile error rather than something usage-lib rejects later.
pub framing: String,
Expand Down Expand Up @@ -4481,10 +4483,11 @@ fn view_decl(meta: &Meta) -> syn::Result<ViewDecl> {
})
}

/// `output("json", framing = "json", help = "…", default, schema_from = Report)`
/// `output("json", media_type = "application/json", framing = "json", help = "…")`
///
/// The leading string is the token a user types; `framing` is the wire format a consumer
/// reads. They are separate on purpose — see `lib/src/spec/output.rs`.
/// The leading string is the token a user types; `media_type` identifies the content and
/// `framing` describes the stream. They are separate on purpose — see
/// `lib/src/spec/output.rs`.
fn output_decl(meta: &Meta) -> syn::Result<OutputDecl> {
let Meta::List(list) = meta else {
return Err(syn::Error::new_spanned(
Expand All @@ -4496,6 +4499,7 @@ fn output_decl(meta: &Meta) -> syn::Result<OutputDecl> {
let name: syn::LitStr = input.parse()?;
let mut output = OutputDecl {
name: name.value(),
media_type: None,
framing: "text".to_string(),
help: None,
default: false,
Expand Down Expand Up @@ -4550,6 +4554,7 @@ fn output_decl(meta: &Meta) -> syn::Result<OutputDecl> {
}
output.framing = framing;
}
"media_type" => output.media_type = Some(value.value()),
"help" => output.help = Some(value.value()),
"select" => output.select = Some(value.value()),
"schema" => output.schema = Some(SchemaSource::Literal(value.value())),
Expand All @@ -4558,7 +4563,7 @@ fn output_decl(meta: &Meta) -> syn::Result<OutputDecl> {
property,
format!(
"unknown output property `{other}`; an output takes \
`framing`, `help`, `select`, `schema`, `schema_from`, \
`media_type`, `framing`, `help`, `select`, `schema`, `schema_from`, \
`schema_fn`, and bare `default` and `hide`"
),
));
Expand Down Expand Up @@ -6950,7 +6955,7 @@ mod tests {
let parsed = cli(r#"
#[usage(
output("human", default, help = "A table"),
output("ndjson", framing = "jsonl"),
output("ndjson", media_type = "application/x-ndjson", framing = "jsonl"),
select = "--format"
)]
struct Ex {
Expand All @@ -6965,6 +6970,10 @@ mod tests {
assert_eq!(parsed.outputs[0].help.as_deref(), Some("A table"));
// aube's spelling, hk's contract.
assert_eq!(parsed.outputs[1].name, "ndjson");
assert_eq!(
parsed.outputs[1].media_type.as_deref(),
Some("application/x-ndjson")
);
assert_eq!(parsed.outputs[1].framing, "jsonl");
assert_eq!(parsed.select.as_deref(), Some("--format"));
}
Expand Down
8 changes: 5 additions & 3 deletions docs/rust/args-and-flags.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,8 @@ SDKs:
#[derive(usage::Args)]
#[usage(
output("human", default, help = "A human-readable report"),
output("json", framing = "json", schema_from = Report),
output("json", media_type = "application/json", framing = "json", schema_from = Report),
output("checkstyle", media_type = "application/xml"),
exit_code(0, "all checks passed"),
exit_code(1, "a check failed"),
)]
Expand All @@ -379,8 +380,9 @@ struct Check {
`select` on a value-taking flag names it as the selector, and its choices are filled from the
output names. A boolean flag that picks one output is named from the output instead —
`output("json", framing = "json", select = "--json")` — and `select = "--format"` as a
container attribute is the same thing spelled the way the KDL node is. An output also takes
`hide`, and a schema comes from `schema = "…"`, `schema_from = Type` (via `schemars`), or
container attribute is the same thing spelled the way the KDL node is. `media_type` identifies
the content independently of `text`/`json`/`jsonl` stream framing. An output also takes `hide`,
and a schema comes from `schema = "…"`, `schema_from = Type` (via `schemars`), or
`schema_fn = path` where the function returns a `String`. Declared on the root `#[derive(Cli)]`
struct, outputs and exit codes apply CLI-wide, and a command can refine what it inherits. The
full model — framings, schema files, inheritance — is on the
Expand Down
22 changes: 14 additions & 8 deletions docs/spec/reference/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ cmd "check" {
flag "--format <FORMAT>" help="Output format"

output "human" default=#true help="Human-readable report"
output "json" framing="json" help="One report object" {
output "json" media_type="application/json" framing="json" help="One report object" {
schema #"""
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
Expand All @@ -19,29 +19,34 @@ cmd "check" {
"""#
}
output "jsonl" framing="jsonl" help="One event per line"
output "checkstyle" media_type="application/xml" help="Checkstyle report"
select "--format"

exit_code 0 "all checks passed"
exit_code 1 "a check failed"
}
```

`output`'s first argument is the value a user types. `framing` is the wire contract a
consumer reads:
`output`'s first argument is the value a user types. `media_type` identifies the content
using an IANA media type such as `application/json` or `application/xml`. `framing` is the
stream contract a consumer reads:

| Framing | Meaning |
| ------- | -------------------------------------------------- |
| `text` | Unstructured text; the default |
| `json` | One JSON document, read to end of stream |
| `jsonl` | One JSON document per line, consumed incrementally |

The name and framing are deliberately separate. An output named `ndjson` can declare
The name, media type, and framing are deliberately separate. XML can use the default `text`
framing because it is one document read to end of stream, while JSON Lines uses `jsonl`
framing because it contains independently consumable records. An output named `ndjson` can declare
`framing="jsonl"`, allowing consumers to treat equivalent formats alike without knowing each
CLI's spelling.

An output also accepts `help`, `default=#true`, and `hide=#true`. At most one effective output
may be the default. `schema` is carried verbatim, so it can use any JSON Schema draft and can
contain references that another tool resolves.
An output also accepts `help`, `default=#true`, and `hide=#true`. The media type is optional and
is not inferred from either the output name or framing. At most one effective output may be the
default. `schema` is carried verbatim, so it can use any JSON Schema draft and can contain
references that another tool resolves.

For a schema kept next to the spec, name its file instead of embedding it:

Expand Down Expand Up @@ -109,7 +114,8 @@ Typed Rust declarations use the same vocabulary:
#[derive(usage::Args)]
#[usage(
output("human", default, help = "Human-readable report"),
output("json", framing = "json", schema_from = Report),
output("json", media_type = "application/json", framing = "json", schema_from = Report),
output("checkstyle", media_type = "application/xml"),
exit_code(0, "all checks passed"),
exit_code(1, "a check failed"),
)]
Expand Down
3 changes: 3 additions & 0 deletions lib/src/docs/manpage/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,9 @@ impl ManpageRenderer {
}
roff.text([bold(label)]);
let mut described = format!("{} output", output.framing);
if let Some(media_type) = &output.media_type {
described.push_str(&format!(" with media type {media_type}"));
}
if output.streaming {
described.push_str(", one document per line as it arrives");
}
Expand Down
6 changes: 6 additions & 0 deletions lib/src/docs/markdown/templates/cmd_template.md.tera
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@
{%- if output.select %}

- **Select**: `{{ output.select }}`
{%- if output.media_type %}
- **Media type**: `{{ output.media_type }}`
{%- endif %}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
{%- elif output.media_type %}

- **Media type**: `{{ output.media_type }}`
{%- endif %}
- **Framing**: `{{ output.framing }}`{% if output.streaming %} — one document per line, read as it arrives{% endif %}
{%- if output.help %}
Expand Down
2 changes: 2 additions & 0 deletions lib/src/docs/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,7 @@ fn group_by_heading<T: Clone>(
#[derive(Debug, Default, Serialize, Clone)]
pub struct SpecOutput {
pub name: String,
pub media_type: Option<String>,
pub framing: String,
pub streaming: bool,
pub default: bool,
Expand All @@ -436,6 +437,7 @@ impl SpecOutput {
fn from(output: &crate::SpecOutput, cmd: &crate::SpecCommand) -> Self {
Self {
name: output.name.clone(),
media_type: output.media_type.clone(),
framing: output.framing.as_str().to_string(),
streaming: output.framing.is_streaming(),
default: output.default,
Expand Down
Loading