wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! CLI command definitions. One module per subcommand.

pub mod date;
mod diffh;
mod io;
mod numcrn;
mod template;

use clap::{CommandFactory, Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(
    name = "wdxtools",
    version,
    about = "Everyday formatting tools for the command line",
    long_about = "Lightning-fast Rust ports of popular library functions that deserve their own binary.",
    subcommand_required = true,
    arg_required_else_help = true
)]
pub struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    Numcrn(numcrn::NumcrnArgs),
    Diffh(diffh::DiffhArgs),
    /// Print version and exit
    Version,
}

/// Parses the command line and runs the selected subcommand.
///
/// Busybox pattern: when invoked through a `diffh` or `numcrn` symlink, the
/// matching subcommand is injected so the symlinks work as standalone tools.
pub fn execute() -> i32 {
    let mut args: Vec<std::ffi::OsString> = std::env::args_os().collect();

    if let Some(base) = args
        .first()
        .and_then(|a| std::path::Path::new(a).file_stem())
        .and_then(|s| s.to_str())
    {
        if matches!(base, "diffh" | "numcrn") {
            args.insert(1, base.into());
        }
    }

    match Cli::parse_from(args).command {
        Command::Numcrn(a) => numcrn::run(a),
        Command::Diffh(a) => diffh::run(a),
        Command::Version => {
            println!("wdxtools {}", env!("CARGO_PKG_VERSION"));
            0
        }
    }
}

/// Prints a subcommand's help, matching the original's behavior when a command
/// is run with neither arguments nor piped input.
fn print_help(name: &str) {
    let mut cmd = Cli::command();
    if let Some(sub) = cmd.find_subcommand_mut(name) {
        let _ = sub.clone().print_help();
    }
}