From 6d07f702e1d662f28463f4c9e4346b197da4cb63 Mon Sep 17 00:00:00 2001 From: Ilia <43654815+istudyatuni@users.noreply.github.com> Date: Wed, 29 May 2024 14:06:27 +0300 Subject: [PATCH] Add ability to choose between minified and pretty-printed JSON (#4161) --- crates/typst-cli/src/args.rs | 4 ++++ crates/typst-cli/src/query.rs | 18 +++++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/typst-cli/src/args.rs b/crates/typst-cli/src/args.rs index f49d35c75..22769fb2e 100644 --- a/crates/typst-cli/src/args.rs +++ b/crates/typst-cli/src/args.rs @@ -153,6 +153,10 @@ pub struct QueryCommand { /// The format to serialize in #[clap(long = "format", default_value = "json")] pub format: SerializationFormat, + + /// Whether to pretty-print the serialized output + #[clap(long)] + pub pretty: bool, } // Output file format for query command diff --git a/crates/typst-cli/src/query.rs b/crates/typst-cli/src/query.rs index 0b14a8936..6422af949 100644 --- a/crates/typst-cli/src/query.rs +++ b/crates/typst-cli/src/query.rs @@ -99,20 +99,28 @@ fn format(elements: Vec, command: &QueryCommand) -> StrResult { let Some(value) = mapped.first() else { bail!("no such field found for element"); }; - serialize(value, command.format) + serialize(value, command.format, command.pretty) } else { - serialize(&mapped, command.format) + serialize(&mapped, command.format, command.pretty) } } /// Serialize data to the output format. -fn serialize(data: &impl Serialize, format: SerializationFormat) -> StrResult { +fn serialize( + data: &impl Serialize, + format: SerializationFormat, + pretty: bool, +) -> StrResult { match format { SerializationFormat::Json => { - serde_json::to_string_pretty(data).map_err(|e| eco_format!("{e}")) + if pretty { + serde_json::to_string_pretty(data).map_err(|e| eco_format!("{e}")) + } else { + serde_json::to_string(data).map_err(|e| eco_format!("{e}")) + } } SerializationFormat::Yaml => { - serde_yaml::to_string(&data).map_err(|e| eco_format!("{e}")) + serde_yaml::to_string(data).map_err(|e| eco_format!("{e}")) } } }