diff --git a/Cargo.lock b/Cargo.lock index 5808eea7f..956a733c9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1031,7 +1031,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" dependencies = [ "cfg-if", - "unicode-width", + "unicode-width 0.1.14", ] [[package]] @@ -1749,27 +1749,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "strum" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" -dependencies = [ - "strum_macros", -] - -[[package]] -name = "strum_macros" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "syn" version = "2.0.119" @@ -2025,6 +2004,12 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "usage-argv" version = "6.3.0" @@ -2109,7 +2094,6 @@ dependencies = [ "clap", "criterion", "ctor", - "heck", "indexmap 2.14.0", "insta", "itertools 0.15.0", @@ -2122,12 +2106,10 @@ dependencies = [ "semver", "serde", "serde_json", - "shell-words", - "strum", "tempfile", "tera", "thiserror", - "unicode-width", + "unicode-width 0.2.2", "usage-validation", "winnow 0.7.15", ] diff --git a/NOTICE.md b/NOTICE.md index 24cdc088b..62ef210e4 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -20,6 +20,21 @@ does not contain miette's implementation. Both projects are distributed under the Apache License, Version 2.0. Usage takes them under that license, reproduced in `third-party/LICENSE-APACHE-2.0`. +## heck and shell-words + +`lib/src/case.rs` is a focused adaptation of the word-boundary algorithm from +[heck 0.5.0](https://github.com/withoutboats/heck/tree/0.5.0). It retains only the +snake_case, lowerCamelCase, and PascalCase conversions used by Usage. + +`lib/src/shell_words.rs` is a focused adaptation of +[shell-words 1.1.1](https://github.com/tmiasko/shell-words/tree/1.1.1). It retains the +POSIX word splitting and quoting needed for mounted commands and parser output. +shell-words is copyright 2018 Tomasz Miąsko. + +Both projects are distributed under the terms of either the MIT License or the Apache +License, Version 2.0. Usage takes the adapted code under the Apache License, reproduced +in `lib/third-party/LICENSE-APACHE-2.0`. + ## clap Usage's design owes a great deal to [clap](https://github.com/clap-rs/clap). No diff --git a/lib/Cargo.toml b/lib/Cargo.toml index aa107ae46..a09aba06b 100644 --- a/lib/Cargo.toml +++ b/lib/Cargo.toml @@ -24,7 +24,6 @@ name = "usage" [dependencies] clap = { version = "4", features = ["derive", "env", "string"], optional = true } -heck = "0.5" indexmap = { version = "2", features = ["serde"] } itertools = "0.15" log = "0.4" @@ -34,11 +33,9 @@ regex = "1" roff = { version = "1.0", optional = true } semver = "1" serde = { version = "1", features = ["derive"] } -shell-words = "1" -strum = { version = "0.28", features = ["derive"] } tera = { version = "2", optional = true } thiserror = "2" -unicode-width = "0.1" +unicode-width = "0.2" # `unstable-recover` is explicitly semver-exempt, so pin the parser version we test. winnow = { version = "=0.7.15", features = ["alloc", "unstable-recover"] } # No `xx`: three helpers (a lazy-regex macro, `file::read_to_string`, `check_status`) were @@ -51,7 +48,11 @@ usage-validation = { workspace = true, optional = true } default = ["docs"] # CLI help is useful to lightweight consumers that do not generate Markdown or manpages. cli-help = ["tera"] -docs = ["cli-help", "roff"] +markdown = ["cli-help"] +manpage = ["cli-help", "dep:roff"] +docs = ["markdown", "manpage", "roff"] +# Compatibility alias for callers that enabled the implicit optional-dependency feature. +roff = ["manpage"] # Let applications that already use miette pass usage errors directly to their reporter. miette = ["dep:miette"] validation = ["dep:usage-validation"] @@ -63,7 +64,6 @@ ctor = "1" insta = "1" pretty_assertions = "1" serde_json = "1" -shell-words = "1" tempfile = "3" [[bench]] diff --git a/lib/src/case.rs b/lib/src/case.rs new file mode 100644 index 000000000..46abd87f1 --- /dev/null +++ b/lib/src/case.rs @@ -0,0 +1,140 @@ +//! The identifier case conversions Usage needs when generating code and completions. +//! +//! This is intentionally smaller than a general-purpose casing crate: Usage only emits +//! snake_case, lowerCamelCase, and PascalCase identifiers. The word-boundary rules follow +//! `heck` so generated APIs do not change when the dependency is removed. + +#[derive(Clone, Copy, PartialEq)] +enum WordMode { + Boundary, + Lowercase, + Uppercase, +} + +fn words(input: &str) -> Vec<&str> { + let mut words = Vec::new(); + for segment in input.split(|c: char| !c.is_alphanumeric()) { + let mut chars = segment.char_indices().peekable(); + let mut start = 0; + let mut mode = WordMode::Boundary; + + while let Some((index, current)) = chars.next() { + if let Some(&(next_index, next)) = chars.peek() { + let next_mode = if current.is_lowercase() { + WordMode::Lowercase + } else if current.is_uppercase() { + WordMode::Uppercase + } else { + mode + }; + + if next_mode == WordMode::Lowercase && next.is_uppercase() { + words.push(&segment[start..next_index]); + start = next_index; + mode = WordMode::Boundary; + } else if mode == WordMode::Uppercase + && current.is_uppercase() + && next.is_lowercase() + { + if start != index { + words.push(&segment[start..index]); + } + start = index; + mode = WordMode::Boundary; + } else { + mode = next_mode; + } + } else if start < segment.len() { + words.push(&segment[start..]); + } + } + } + words +} + +fn lowercase(word: &str) -> String { + let mut output = String::new(); + let mut chars = word.chars().peekable(); + while let Some(c) = chars.next() { + if c == 'Σ' && chars.peek().is_none() { + output.push('ς'); + } else { + output.extend(c.to_lowercase()); + } + } + output +} + +fn capitalize(word: &str) -> String { + let mut chars = word.chars(); + let Some(first) = chars.next() else { + return String::new(); + }; + let mut output = first.to_uppercase().collect::(); + output.push_str(&lowercase(chars.as_str())); + output +} + +pub(crate) fn snake(input: &str) -> String { + words(input) + .into_iter() + .map(lowercase) + .collect::>() + .join("_") +} + +pub(crate) fn pascal(input: &str) -> String { + words(input).into_iter().map(capitalize).collect() +} + +pub(crate) fn lower_camel(input: &str) -> String { + let mut words = words(input).into_iter(); + let mut output = words.next().map(lowercase).unwrap_or_default(); + output.extend(words.map(capitalize)); + output +} + +pub(crate) trait ToSnakeCase { + fn to_snake_case(&self) -> String; +} + +impl ToSnakeCase for str { + fn to_snake_case(&self) -> String { + snake(self) + } +} + +pub(crate) struct AsSnakeCase>(pub T); +pub(crate) struct AsPascalCase>(pub T); +pub(crate) struct AsLowerCamelCase>(pub T); + +impl> std::fmt::Display for AsSnakeCase { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&snake(self.0.as_ref())) + } +} + +impl> std::fmt::Display for AsPascalCase { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&pascal(self.0.as_ref())) + } +} + +impl> std::fmt::Display for AsLowerCamelCase { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&lower_camel(self.0.as_ref())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_heck_word_boundaries() { + assert_eq!(snake("MixedUP CamelCase"), "mixed_up_camel_case"); + assert_eq!(snake("XMLHttpRequest"), "xml_http_request"); + assert_eq!(pascal("SHOUTY_SNAKE_CASE"), "ShoutySnakeCase"); + assert_eq!(lower_camel("XMLHttpRequest"), "xmlHttpRequest"); + } +} diff --git a/lib/src/complete/bash.rs b/lib/src/complete/bash.rs index 5cdab9289..ffcb76b1b 100644 --- a/lib/src/complete/bash.rs +++ b/lib/src/complete/bash.rs @@ -1,5 +1,5 @@ +use crate::case::ToSnakeCase; use crate::complete::CompleteOptions; -use heck::ToSnakeCase; pub fn complete_bash(opts: &CompleteOptions) -> String { let usage_bin = &opts.usage_bin; diff --git a/lib/src/complete/fish.rs b/lib/src/complete/fish.rs index d23a816f7..f4247680b 100644 --- a/lib/src/complete/fish.rs +++ b/lib/src/complete/fish.rs @@ -1,5 +1,5 @@ +use crate::case::ToSnakeCase; use crate::complete::CompleteOptions; -use heck::ToSnakeCase; pub fn complete_fish(opts: &CompleteOptions) -> String { let usage_bin = &opts.usage_bin; diff --git a/lib/src/complete/nu.rs b/lib/src/complete/nu.rs index 05047c8a9..6079be7a4 100644 --- a/lib/src/complete/nu.rs +++ b/lib/src/complete/nu.rs @@ -1,4 +1,4 @@ -use heck::ToSnakeCase; +use crate::case::ToSnakeCase; use crate::complete::CompleteOptions; diff --git a/lib/src/complete/powershell.rs b/lib/src/complete/powershell.rs index 0f0df7fdc..15ccf5343 100644 --- a/lib/src/complete/powershell.rs +++ b/lib/src/complete/powershell.rs @@ -1,5 +1,5 @@ +use crate::case::ToSnakeCase; use crate::complete::CompleteOptions; -use heck::ToSnakeCase; pub fn complete_powershell(opts: &CompleteOptions) -> String { let usage_bin = &opts.usage_bin; diff --git a/lib/src/complete/zsh.rs b/lib/src/complete/zsh.rs index 6352f06a1..acf785030 100644 --- a/lib/src/complete/zsh.rs +++ b/lib/src/complete/zsh.rs @@ -1,5 +1,5 @@ +use crate::case::ToSnakeCase; use crate::complete::CompleteOptions; -use heck::ToSnakeCase; /// The completion loop that both `complete_zsh` (per-bin script) and /// `complete_zsh_init` (shebang-fallback handler) need to emit. diff --git a/lib/src/docs/mod.rs b/lib/src/docs/mod.rs index 6cadd872e..c379dc0d3 100644 --- a/lib/src/docs/mod.rs +++ b/lib/src/docs/mod.rs @@ -2,9 +2,9 @@ pub mod cli; #[cfg(feature = "cli-help")] mod layout; -#[cfg(feature = "docs")] +#[cfg(feature = "manpage")] pub mod manpage; -#[cfg(feature = "docs")] +#[cfg(feature = "markdown")] pub mod markdown; #[cfg(feature = "cli-help")] pub(crate) mod models; diff --git a/lib/src/docs/models.rs b/lib/src/docs/models.rs index b78a24621..cd63ad824 100644 --- a/lib/src/docs/models.rs +++ b/lib/src/docs/models.rs @@ -1,4 +1,4 @@ -#[cfg(feature = "docs")] +#[cfg(feature = "markdown")] use crate::docs::markdown::MarkdownRenderer; use crate::spec::cmd::SpecHeading; use crate::spec::effect::SpecCommandEffect; @@ -268,7 +268,7 @@ pub struct SpecConfigChoice { } impl SpecConfig { - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; @@ -284,14 +284,14 @@ impl SpecConfig { } } - #[cfg(feature = "docs")] + #[cfg(any(feature = "markdown", feature = "manpage"))] pub fn is_empty(&self) -> bool { self.props.is_empty() && self.files.is_empty() } } impl SpecConfigProp { - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; @@ -1183,7 +1183,7 @@ impl From<&crate::SpecArg> for SpecArg { } impl Spec { - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; @@ -1201,7 +1201,7 @@ impl Spec { } impl SpecCommand { - #[cfg(feature = "docs")] + #[cfg(any(feature = "markdown", feature = "manpage"))] pub fn all_subcommands(&self) -> Vec<&SpecCommand> { let mut cmds = vec![]; for cmd in self.subcommands.values() { @@ -1211,7 +1211,7 @@ impl SpecCommand { cmds } - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; @@ -1253,7 +1253,7 @@ impl SpecCommand { /// Rebuild the grouped views from `flags` and `args`. /// /// Anything that mutates either list has to call this, or the groups go stale. - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] fn regroup(&mut self) { self.flag_groups = group_by_heading(&self.flags, |f| f.help_heading.as_deref()); self.arg_groups = group_by_heading(&self.args, |a| a.help_heading.as_deref()); @@ -1264,7 +1264,7 @@ impl SpecCommand { } impl SpecFlag { - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; @@ -1286,7 +1286,7 @@ impl SpecFlag { } impl SpecArg { - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; @@ -1301,7 +1301,7 @@ impl SpecArg { } impl SpecExample { - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] pub fn render_md(&mut self, renderer: &MarkdownRenderer) { if self.rendered { return; diff --git a/lib/src/enum_value.rs b/lib/src/enum_value.rs new file mode 100644 index 000000000..77e9c2101 --- /dev/null +++ b/lib/src/enum_value.rs @@ -0,0 +1,33 @@ +//! Manual string-enum implementations shared by the spec model. + +pub(crate) trait StringEnum { + const VARIANTS: &'static [&'static str]; +} + +macro_rules! impl_string_enum { + ($type:ty { $($variant:path => $value:literal),+ $(,)? }) => { + impl std::fmt::Display for $type { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let value = match self { + $($variant => $value),+ + }; + f.write_str(value) + } + } + + impl std::str::FromStr for $type { + type Err = crate::error::EnumParseError; + + fn from_str(value: &str) -> std::result::Result { + match value { + $($value => Ok($variant)),+, + _ => Err(crate::error::EnumParseError(value.to_string())), + } + } + } + + impl crate::enum_value::StringEnum for $type { + const VARIANTS: &'static [&'static str] = &[$($value),+]; + } + }; +} diff --git a/lib/src/error.rs b/lib/src/error.rs index 5100066f8..5b6fe427d 100644 --- a/lib/src/error.rs +++ b/lib/src/error.rs @@ -2,6 +2,10 @@ use crate::kdl; use crate::miette::{NamedSource, SourceSpan}; use thiserror::Error; +#[derive(Debug, Error)] +#[error("invalid enum value `{0}`")] +pub struct EnumParseError(pub String); + /// Everything that can go wrong reading a spec or a command line against one. /// /// `#[non_exhaustive]`, so a caller matching on it needs a `_` arm. That is the point: @@ -66,7 +70,7 @@ pub enum UsageErr { IO(#[from] std::io::Error), #[error(transparent)] - Strum(#[from] strum::ParseError), + Strum(#[from] EnumParseError), #[error(transparent)] FromUtf8Error(#[from] std::string::FromUtf8Error), diff --git a/lib/src/go/mod.rs b/lib/src/go/mod.rs index e54c12419..5372a1170 100644 --- a/lib/src/go/mod.rs +++ b/lib/src/go/mod.rs @@ -35,7 +35,7 @@ mod structs; use std::collections::{BTreeMap, HashMap}; use std::fmt::Write as _; -use heck::AsPascalCase; +use crate::case::AsPascalCase; use crate::spec::unknown_flags::UnknownFlags; use crate::{ diff --git a/lib/src/lib.rs b/lib/src/lib.rs index 954729ea4..c51cf65e6 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -27,10 +27,13 @@ pub use crate::warn::{Warning, WarningKind}; #[macro_use] #[allow(unused_assignments)] // Fields in struct variants are read by derive macros pub mod error; +mod case; #[doc(hidden)] pub mod kdl; pub mod miette; #[macro_use] +mod enum_value; +#[macro_use] pub mod macros; pub mod complete; pub mod spec; @@ -43,6 +46,8 @@ pub mod help_template; pub mod parse; pub mod sdk; pub mod sh; +#[doc(hidden)] +pub mod shell_words; pub(crate) mod string; #[cfg(test)] mod test; diff --git a/lib/src/parse.rs b/lib/src/parse.rs index 0b62c3e88..724a3a1dd 100644 --- a/lib/src/parse.rs +++ b/lib/src/parse.rs @@ -1,12 +1,10 @@ use crate::miette::{self, bail}; -use heck::ToSnakeCase; use indexmap::IndexMap; use itertools::Itertools; use log::trace; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::fmt::{Debug, Display, Formatter}; use std::sync::Arc; -use strum::EnumTryAs; #[cfg(feature = "cli-help")] use crate::docs; @@ -465,7 +463,7 @@ impl ParseOutput { } } -#[derive(Debug, EnumTryAs, Clone)] +#[derive(Debug, Clone)] pub enum ParseValue { Bool(bool), String(String), @@ -473,6 +471,92 @@ pub enum ParseValue { MultiString(Vec), } +impl ParseValue { + pub fn try_as_bool(self) -> Option { + match self { + Self::Bool(value) => Some(value), + _ => None, + } + } + + pub const fn try_as_bool_ref(&self) -> Option<&bool> { + match self { + Self::Bool(value) => Some(value), + _ => None, + } + } + + pub fn try_as_bool_mut(&mut self) -> Option<&mut bool> { + match self { + Self::Bool(value) => Some(value), + _ => None, + } + } + + pub fn try_as_string(self) -> Option { + match self { + Self::String(value) => Some(value), + _ => None, + } + } + + pub const fn try_as_string_ref(&self) -> Option<&String> { + match self { + Self::String(value) => Some(value), + _ => None, + } + } + + pub fn try_as_string_mut(&mut self) -> Option<&mut String> { + match self { + Self::String(value) => Some(value), + _ => None, + } + } + + pub fn try_as_multi_bool(self) -> Option> { + match self { + Self::MultiBool(value) => Some(value), + _ => None, + } + } + + pub const fn try_as_multi_bool_ref(&self) -> Option<&Vec> { + match self { + Self::MultiBool(value) => Some(value), + _ => None, + } + } + + pub fn try_as_multi_bool_mut(&mut self) -> Option<&mut Vec> { + match self { + Self::MultiBool(value) => Some(value), + _ => None, + } + } + + pub fn try_as_multi_string(self) -> Option> { + match self { + Self::MultiString(value) => Some(value), + _ => None, + } + } + + pub const fn try_as_multi_string_ref(&self) -> Option<&Vec> { + match self { + Self::MultiString(value) => Some(value), + _ => None, + } + } + + pub fn try_as_multi_string_mut(&mut self) -> Option<&mut Vec> { + match self { + Self::MultiString(value) => Some(value), + _ => None, + } + } +} + /// The deprecated declarations argv itself named: the commands it descended through, and the /// flags it bound. /// @@ -3973,17 +4057,17 @@ impl ParseOutput { pub fn as_env(&self) -> BTreeMap { let mut env = BTreeMap::new(); for (flag, val) in &self.flags { - let key = format!("usage_{}", flag.name.to_snake_case()); + let key = format!("usage_{}", crate::case::snake(&flag.name)); let val = match val { ParseValue::Bool(b) => if *b { "true" } else { "false" }.to_string(), ParseValue::String(s) => s.clone(), ParseValue::MultiBool(b) => b.iter().filter(|b| **b).count().to_string(), - ParseValue::MultiString(s) => shell_words::join(s), + ParseValue::MultiString(s) => crate::shell_words::join(s), }; env.insert(key, val); } for (arg, val) in &self.args { - let key = format!("usage_{}", arg.name.to_snake_case()); + let key = format!("usage_{}", crate::case::snake(&arg.name)); env.insert(key, val.to_string()); } env @@ -3996,7 +4080,7 @@ impl Display for ParseValue { ParseValue::Bool(b) => write!(f, "{b}"), ParseValue::String(s) => write!(f, "{s}"), ParseValue::MultiBool(b) => write!(f, "{}", b.iter().join(" ")), - ParseValue::MultiString(s) => write!(f, "{}", shell_words::join(s)), + ParseValue::MultiString(s) => write!(f, "{}", crate::shell_words::join(s)), } } } @@ -8822,7 +8906,7 @@ cmd "ls" let spec: Spec = r#"arg "[other_args]" var=#true"#.parse().unwrap(); // Single unknown --flag=value: must not produce a stray "3" positional. - // as_env() shell-joins via shell_words::join, so "=" gets quoted. + // as_env() shell-joins values, so "=" gets quoted. let input: Vec = vec!["test", "--option=3"] .into_iter() .map(String::from) diff --git a/lib/src/sdk/mod.rs b/lib/src/sdk/mod.rs index 157c89ba2..511f9f965 100644 --- a/lib/src/sdk/mod.rs +++ b/lib/src/sdk/mod.rs @@ -2,7 +2,7 @@ use std::fmt; use std::path::PathBuf; -use heck::AsPascalCase; +use crate::case::AsPascalCase; use indexmap::IndexMap; use crate::spec::cmd::SpecCommand; diff --git a/lib/src/sdk/python/mod.rs b/lib/src/sdk/python/mod.rs index 7cda001c3..092330232 100644 --- a/lib/src/sdk/python/mod.rs +++ b/lib/src/sdk/python/mod.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use heck::AsPascalCase; +use crate::case::{AsPascalCase, AsSnakeCase}; use crate::sdk::{ collect_choice_types, collect_type_imports, command_type_name, escape_py_docstring, @@ -525,7 +525,7 @@ fn config_prop_type(prop: &SpecConfigProp) -> String { fn flag_property_name_py(flag: &SpecFlag) -> String { // Python uses snake_case for attributes if let Some(long) = flag.long.first() { - return sanitize_py_ident(&heck::AsSnakeCase(long).to_string()); + return sanitize_py_ident(&AsSnakeCase(long).to_string()); } if let Some(short) = flag.short.first() { return short.to_string(); @@ -534,7 +534,7 @@ fn flag_property_name_py(flag: &SpecFlag) -> String { } fn sanitize_py_ident(name: &str) -> String { - let snake = heck::AsSnakeCase(name).to_string(); + let snake = AsSnakeCase(name).to_string(); match snake.as_str() { "async" | "await" | "nonlocal" | "class" | "def" | "return" | "import" | "from" | "global" | "lambda" | "pass" | "raise" | "with" | "yield" | "del" | "try" | "except" diff --git a/lib/src/sdk/typescript/mod.rs b/lib/src/sdk/typescript/mod.rs index 7cfd23b56..5105ca318 100644 --- a/lib/src/sdk/typescript/mod.rs +++ b/lib/src/sdk/typescript/mod.rs @@ -36,7 +36,7 @@ pub fn generate(spec: &Spec, opts: &SdkOptions) -> SdkOutput { } fn render_index(package_name: &str) -> String { - let class_name = heck::AsPascalCase(package_name).to_string(); + let class_name = crate::case::AsPascalCase(package_name).to_string(); format!( "export {{ {class_name} }} from \"./client\";\n\ export {{ CliResult, CliJsonResult, CliStream, CliError }} from \"./runtime\";\n\ diff --git a/lib/src/sdk/typescript/types.rs b/lib/src/sdk/typescript/types.rs index 91fa4a757..8230b6244 100644 --- a/lib/src/sdk/typescript/types.rs +++ b/lib/src/sdk/typescript/types.rs @@ -1,4 +1,4 @@ -use heck::AsPascalCase; +use crate::case::{AsLowerCamelCase, AsPascalCase}; use crate::spec::cmd::SpecCommand; use crate::spec::config::SpecConfigProp; @@ -377,7 +377,7 @@ fn config_prop_type(prop: &SpecConfigProp) -> String { pub(crate) fn flag_property_name(flag: &SpecFlag) -> String { if let Some(long) = flag.long.first() { - return sanitize_ident(&heck::AsLowerCamelCase(long).to_string()); + return sanitize_ident(&AsLowerCamelCase(long).to_string()); } if let Some(short) = flag.short.first() { return short.to_string(); @@ -386,7 +386,7 @@ pub(crate) fn flag_property_name(flag: &SpecFlag) -> String { } pub(crate) fn sanitize_ident(name: &str) -> String { - let camel = heck::AsLowerCamelCase(name).to_string(); + let camel = AsLowerCamelCase(name).to_string(); match camel.as_str() { "function" | "class" | "const" | "let" | "var" | "type" | "interface" | "new" | "delete" | "return" | "export" | "import" | "default" | "in" | "instanceof" | "exec" diff --git a/lib/src/sdk/typescript/wrappers.rs b/lib/src/sdk/typescript/wrappers.rs index fb1a48952..a6d64160e 100644 --- a/lib/src/sdk/typescript/wrappers.rs +++ b/lib/src/sdk/typescript/wrappers.rs @@ -1,4 +1,4 @@ -use heck::{AsLowerCamelCase, AsPascalCase}; +use crate::case::{AsLowerCamelCase, AsPascalCase}; use crate::sdk::{ collect_choice_types, collect_type_imports, escape_jsdoc, escape_ts_string, generated_header, diff --git a/lib/src/shell_words.rs b/lib/src/shell_words.rs new file mode 100644 index 000000000..d81b4dace --- /dev/null +++ b/lib/src/shell_words.rs @@ -0,0 +1,204 @@ +//! Minimal POSIX shell word splitting and quoting used by specs and parser output. +//! +//! Adapted from `shell-words` 1.1.1. Keeping this narrow implementation in-tree avoids +//! making every `usage-lib` consumer compile a crate for four internal call sites. + +use std::borrow::Cow; +use std::fmt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ParseError; + +impl fmt::Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("missing closing quote") + } +} + +impl std::error::Error for ParseError {} + +enum State { + Delimiter, + Backslash, + Unquoted, + UnquotedBackslash, + SingleQuoted, + DoubleQuoted, + DoubleQuotedBackslash, + Comment, +} + +pub fn split(input: &str) -> Result, ParseError> { + use State::*; + + let mut words = Vec::new(); + let mut word = String::new(); + let mut chars = input.chars(); + let mut state = Delimiter; + + loop { + let current = chars.next(); + state = match state { + Delimiter => match current { + None => break, + Some('\'') => SingleQuoted, + Some('"') => DoubleQuoted, + Some('\\') => Backslash, + Some('\t' | ' ' | '\n') => Delimiter, + Some('#') => Comment, + Some(c) => { + word.push(c); + Unquoted + } + }, + Backslash => match current { + None => { + word.push('\\'); + words.push(std::mem::take(&mut word)); + break; + } + Some('\n') => Delimiter, + Some(c) => { + word.push(c); + Unquoted + } + }, + Unquoted => match current { + None => { + words.push(std::mem::take(&mut word)); + break; + } + Some('\'') => SingleQuoted, + Some('"') => DoubleQuoted, + Some('\\') => UnquotedBackslash, + Some('\t' | ' ' | '\n') => { + words.push(std::mem::take(&mut word)); + Delimiter + } + Some(c) => { + word.push(c); + Unquoted + } + }, + UnquotedBackslash => match current { + None => { + word.push('\\'); + words.push(std::mem::take(&mut word)); + break; + } + Some('\n') => Unquoted, + Some(c) => { + word.push(c); + Unquoted + } + }, + SingleQuoted => match current { + None => return Err(ParseError), + Some('\'') => Unquoted, + Some(c) => { + word.push(c); + SingleQuoted + } + }, + DoubleQuoted => match current { + None => return Err(ParseError), + Some('"') => Unquoted, + Some('\\') => DoubleQuotedBackslash, + Some(c) => { + word.push(c); + DoubleQuoted + } + }, + DoubleQuotedBackslash => match current { + None => return Err(ParseError), + Some('\n') => DoubleQuoted, + Some(c @ ('$' | '`' | '"' | '\\')) => { + word.push(c); + DoubleQuoted + } + Some(c) => { + word.push('\\'); + word.push(c); + DoubleQuoted + } + }, + Comment => match current { + None => break, + Some('\n') => Delimiter, + Some(_) => Comment, + }, + }; + } + + Ok(words) +} + +fn quote(word: &str) -> Cow<'_, str> { + if !word.is_empty() + && !word.chars().any(|c| { + matches!( + c, + '\n' | '\'' + | '|' + | '&' + | ';' + | '<' + | '>' + | '(' + | ')' + | '$' + | '`' + | '\\' + | '"' + | ' ' + | '\t' + | '*' + | '?' + | '[' + | '#' + | '~' + | '=' + | '%' + ) + }) + { + return Cow::Borrowed(word); + } + + let mut quoted = String::with_capacity(word.len() + 2); + quoted.push('\''); + for c in word.chars() { + if c == '\'' { + quoted.push_str("'\\''"); + } else { + quoted.push(c); + } + } + quoted.push('\''); + Cow::Owned(quoted) +} + +pub fn join(words: I) -> String +where + I: IntoIterator, + S: AsRef, +{ + words + .into_iter() + .map(|word| quote(word.as_ref()).into_owned()) + .collect::>() + .join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn split_and_join_shell_words() { + let words = split("one 'two three' four\\ five # ignored").unwrap(); + assert_eq!(words, ["one", "two three", "four five"]); + assert_eq!(split(&join(&words)).unwrap(), words); + assert!(split("'unterminated").is_err()); + } +} diff --git a/lib/src/spec/arg.rs b/lib/src/spec/arg.rs index a5d2b0d07..fde52cc30 100644 --- a/lib/src/spec/arg.rs +++ b/lib/src/spec/arg.rs @@ -22,8 +22,7 @@ pub struct SpecRequiredIfEq { pub value: String, } -#[derive(Debug, Default, Clone, Serialize, PartialEq, Eq, strum::EnumString, strum::Display)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Default, Clone, Serialize, PartialEq, Eq)] pub enum SpecDoubleDashChoices { /// Once an arg is entered, behave as if "--" was passed Automatic, @@ -36,6 +35,13 @@ pub enum SpecDoubleDashChoices { Preserve, } +impl_string_enum!(SpecDoubleDashChoices { + SpecDoubleDashChoices::Automatic => "automatic", + SpecDoubleDashChoices::Optional => "optional", + SpecDoubleDashChoices::Required => "required", + SpecDoubleDashChoices::Preserve => "preserve", +}); + /// A positional argument specification. /// /// Arguments are positional values passed to a command without a flag prefix. diff --git a/lib/src/spec/choices.rs b/lib/src/spec/choices.rs index 5385479d9..1512696c7 100644 --- a/lib/src/spec/choices.rs +++ b/lib/src/spec/choices.rs @@ -384,7 +384,7 @@ arg "" { spec.cmd.args[0].choices.as_ref().unwrap().details ); assert!(choices.ignore_case); - #[cfg(feature = "docs")] + #[cfg(feature = "markdown")] assert_eq!(choices.for_help().choices, vec!["always", "yes"]); } diff --git a/lib/src/spec/cmd.rs b/lib/src/spec/cmd.rs index 321d58d06..977e2e3bc 100644 --- a/lib/src/spec/cmd.rs +++ b/lib/src/spec/cmd.rs @@ -1045,14 +1045,14 @@ impl SpecCommand { // Parse the mount command into tokens, insert global flags after the first token // e.g., "mise tasks ls" becomes "mise --cd dir2 tasks ls" // Handles quoted arguments correctly: "cmd 'arg with spaces'" stays correct - let mut tokens = shell_words::split(&mount.run) + let mut tokens = crate::shell_words::split(&mount.run) .expect("mount command should be valid shell syntax"); if !tokens.is_empty() { // Insert global flags after the first token (the command name) tokens.splice(1..1, global_flag_args.iter().cloned()); } // Join tokens back into a properly quoted command string - shell_words::join(tokens) + crate::shell_words::join(tokens) }; let output = match injected { Some(outputs) => outputs diff --git a/lib/src/spec/config.rs b/lib/src/spec/config.rs index a1adf3d57..b259120b0 100644 --- a/lib/src/spec/config.rs +++ b/lib/src/spec/config.rs @@ -242,19 +242,7 @@ pub struct SpecConfigFile { } /// Which class of file a location belongs to. -#[derive( - Debug, - Default, - Copy, - Clone, - PartialEq, - Eq, - strum::Display, - strum::EnumString, - strum::VariantNames, - Serialize, -)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum SpecConfigFileScope { /// Somewhere a repository can carry — the least trusted. @@ -266,20 +254,14 @@ pub enum SpecConfigFileScope { System, } +impl_string_enum!(SpecConfigFileScope { + SpecConfigFileScope::Project => "project", + SpecConfigFileScope::Global => "global", + SpecConfigFileScope::System => "system", +}); + /// How values for one property combine across sources. -#[derive( - Debug, - Default, - Copy, - Clone, - PartialEq, - Eq, - strum::Display, - strum::EnumString, - strum::VariantNames, - Serialize, -)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum SpecConfigMerge { /// The highest-precedence source wins outright. @@ -291,20 +273,14 @@ pub enum SpecConfigMerge { Deep, } +impl_string_enum!(SpecConfigMerge { + SpecConfigMerge::Replace => "replace", + SpecConfigMerge::Union => "union", + SpecConfigMerge::Deep => "deep", +}); + /// Which sources a property may be read from. -#[derive( - Debug, - Default, - Copy, - Clone, - PartialEq, - Eq, - strum::Display, - strum::EnumString, - strum::VariantNames, - Serialize, -)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum SpecConfigScope { /// Any declared source. @@ -319,6 +295,12 @@ pub enum SpecConfigScope { Env, } +impl_string_enum!(SpecConfigScope { + SpecConfigScope::Any => "any", + SpecConfigScope::Global => "global", + SpecConfigScope::Env => "env", +}); + /// One of a property's allowed values. #[derive(Debug, Clone, PartialEq, Serialize)] #[non_exhaustive] @@ -915,7 +897,7 @@ fn parse_enum( value: &ParseEntry<'_>, ) -> Result where - T: std::str::FromStr + strum::VariantNames, + T: std::str::FromStr + crate::enum_value::StringEnum, { let text = value.ensure_string()?; text.parse().map_err(|_| { diff --git a/lib/src/spec/data_types.rs b/lib/src/spec/data_types.rs index fd5927d3d..8bf126a76 100644 --- a/lib/src/spec/data_types.rs +++ b/lib/src/spec/data_types.rs @@ -1,13 +1,11 @@ use serde::Serialize; -use strum::{Display, EnumString}; /// The type a config property's values take. /// /// `Display` is the KDL spelling, so a parsed spec can be written back out — without it /// `data_type` was read and then silently dropped by the serializer, which is how a /// `data_type="integer"` came back as `Null` after one round trip. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Display, EnumString, Serialize, Default)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Default)] #[serde(rename_all = "snake_case")] pub enum SpecDataTypes { #[default] @@ -17,3 +15,11 @@ pub enum SpecDataTypes { Float, Boolean, } + +impl_string_enum!(SpecDataTypes { + SpecDataTypes::Null => "null", + SpecDataTypes::String => "string", + SpecDataTypes::Integer => "integer", + SpecDataTypes::Float => "float", + SpecDataTypes::Boolean => "boolean", +}); diff --git a/lib/src/spec/effect.rs b/lib/src/spec/effect.rs index 6ac631583..e7bcaa2f0 100644 --- a/lib/src/spec/effect.rs +++ b/lib/src/spec/effect.rs @@ -1,5 +1,4 @@ use serde::Serialize; -use strum::{Display as StrumDisplay, EnumString}; /// What running a command does to the world. /// @@ -28,10 +27,7 @@ use strum::{Display as StrumDisplay, EnumString}; /// Ordered least to most dangerous, so `Ord` gives the combining rule: the /// effect of an invocation is the maximum of the command's effect and the /// effect of every flag and argument actually supplied. -#[derive( - Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, EnumString, StrumDisplay, Serialize, -)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] #[serde(rename_all = "snake_case")] pub enum SpecCommandEffect { /// Only inspects state. Running it twice is the same as running it once, @@ -45,6 +41,12 @@ pub enum SpecCommandEffect { Destructive, } +impl_string_enum!(SpecCommandEffect { + SpecCommandEffect::Read => "read", + SpecCommandEffect::Write => "write", + SpecCommandEffect::Destructive => "destructive", +}); + impl SpecCommandEffect { pub fn as_str(&self) -> &'static str { match self { diff --git a/lib/src/spec/output.rs b/lib/src/spec/output.rs index 898a547e1..df98eeea4 100644 --- a/lib/src/spec/output.rs +++ b/lib/src/spec/output.rs @@ -55,7 +55,6 @@ use std::path::Path; use crate::kdl::{KdlDocument, KdlEntry, KdlNode}; use serde::Serialize; -use strum::{Display as StrumDisplay, EnumString}; use crate::error::{Result, UsageErr}; use crate::spec::choices::{SpecChoice, SpecChoices}; @@ -77,10 +76,7 @@ fn invalid(msg: String) -> UsageErr { /// decides a consumer's *shape*: [`Framing::Json`] is read to EOF and parsed once, so a /// generated client returns a value; [`Framing::Jsonl`] arrives a line at a time and may /// never end, so a generated client has to return an iterator and must not buffer. -#[derive( - Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, EnumString, StrumDisplay, Serialize, -)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)] #[serde(rename_all = "snake_case")] pub enum Framing { /// Human-readable text. Nothing may be assumed about its structure, and it is the @@ -94,6 +90,12 @@ pub enum Framing { Jsonl, } +impl_string_enum!(Framing { + Framing::Text => "text", + Framing::Json => "json", + Framing::Jsonl => "jsonl", +}); + impl Framing { pub fn as_str(&self) -> &'static str { match self { diff --git a/lib/src/spec/unknown_flags.rs b/lib/src/spec/unknown_flags.rs index 23bd5c377..32ca2f3b3 100644 --- a/lib/src/spec/unknown_flags.rs +++ b/lib/src/spec/unknown_flags.rs @@ -1,5 +1,4 @@ use serde::Serialize; -use strum::{Display as StrumDisplay, EnumString}; /// What to do with a token that looks like a flag but names no declared flag. /// @@ -21,8 +20,7 @@ use strum::{Display as StrumDisplay, EnumString}; /// instead of an error, and whether it does depends on whether a positional is /// free to take it. A CLI that owns all of its flags — as opposed to forwarding /// them — should say [`UnknownFlags::Error`] and get the stricter reading. -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, EnumString, StrumDisplay, Serialize)] -#[strum(serialize_all = "snake_case")] +#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum UnknownFlags { /// Offer the token to the positional arguments, like any other word. If none @@ -36,6 +34,11 @@ pub enum UnknownFlags { Error, } +impl_string_enum!(UnknownFlags { + UnknownFlags::Value => "value", + UnknownFlags::Error => "error", +}); + impl UnknownFlags { pub fn as_str(&self) -> &'static str { match self { diff --git a/lib/tests/parse.rs b/lib/tests/parse.rs index d1fbae3f0..42307ac93 100644 --- a/lib/tests/parse.rs +++ b/lib/tests/parse.rs @@ -8,7 +8,7 @@ macro_rules! tests { #[test] fn $name() { let spec: Spec = $spec.parse().unwrap(); - let mut args = shell_words::split($args).unwrap(); + let mut args = usage::shell_words::split($args).unwrap(); args.insert(0, "test".to_string()); match parse(&spec, &args) { Ok(env) => assert_str_eq!(format!("{:?}", env.as_env()).trim(), $expected.trim()),