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
34 changes: 8 additions & 26 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 6 additions & 6 deletions lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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"]
Expand All @@ -63,7 +64,6 @@ ctor = "1"
insta = "1"
pretty_assertions = "1"
serde_json = "1"
shell-words = "1"
tempfile = "3"

[[bench]]
Expand Down
140 changes: 140 additions & 0 deletions lib/src/case.rs
Original file line number Diff line number Diff line change
@@ -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::<String>();
output.push_str(&lowercase(chars.as_str()));
output
}

pub(crate) fn snake(input: &str) -> String {
words(input)
.into_iter()
.map(lowercase)
.collect::<Vec<_>>()
.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<T: AsRef<str>>(pub T);
pub(crate) struct AsPascalCase<T: AsRef<str>>(pub T);
pub(crate) struct AsLowerCamelCase<T: AsRef<str>>(pub T);

impl<T: AsRef<str>> std::fmt::Display for AsSnakeCase<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&snake(self.0.as_ref()))
}
}

impl<T: AsRef<str>> std::fmt::Display for AsPascalCase<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&pascal(self.0.as_ref()))
}
}

impl<T: AsRef<str>> std::fmt::Display for AsLowerCamelCase<T> {
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");
}
}
2 changes: 1 addition & 1 deletion lib/src/complete/bash.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
2 changes: 1 addition & 1 deletion lib/src/complete/fish.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
2 changes: 1 addition & 1 deletion lib/src/complete/nu.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use heck::ToSnakeCase;
use crate::case::ToSnakeCase;

use crate::complete::CompleteOptions;

Expand Down
2 changes: 1 addition & 1 deletion lib/src/complete/powershell.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
2 changes: 1 addition & 1 deletion lib/src/complete/zsh.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
4 changes: 2 additions & 2 deletions lib/src/docs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Loading
Loading