Skip to main content

Module cli

Module cli 

Source
Available on crate feature print only.
Expand description

§Printting and Command Line Interface

There are 4 feature flags related to CLI

  • print: This is the most minimal feature set. Using features from this feature flag means you acknowledge your code is being called from a program that uses cu::cli (i.e. the cli feature)
  • cli: Use this if your crate is the end binary (i.e. not a library). This integrates and re-exports clap.
    • This turns on print automatically
  • prompt: This implies print and will also enable the ability to show prompts in the terminal, including password prompts (which hide the input when user types into the terminal).

§Integration with clap

When the cli feature is enabled, clap is re-exported from the prelude, so you can use clap as if it’s a dependency, without actually adding it to your Cargo.toml

use cu::pre::*;
use clap::Parser;

#[derive(Parser)]
struct MyCli {
    /// Just an example flag
    #[clap(short, long)]
    hello: bool,
}

§Common Command Options

The Flags struct implement clap::Args to provide common options that integrates with the rest of the crate:

  • --verbose/-v to increase verbose level.
  • --quiet/-q to decrease verbose level.
  • --color to set color mode

The prompt feature enables these additional options:

  • --yes/-y to answer y to all yes/no prompts.
  • --non-interactive: Disallow prompts, prompts will fail with an error instead
    • With --yes --non-interactive, yes/no prompts gets answered yes and other prompts are blocked
  • --interactive: This is the default, and cancels the effect of one --non-interactive

The cu::cli macro generates a shim to parse the flags and pass it to your main function. It also handles the Result returned back. See the example below and more usage examples in the documentation for the macro.

use cu::pre::*;
// clap will be part of the prelude
// when the `cli` feature is enabled

// Typically, you want to have a wrapper struct
// so you can derive additional options with clap,
// and provide a description via doc comments, like below

// clap will parse the doc comment of the Args struct
// as the help text

/// My program
///
/// This is my program, it is very good.
#[derive(clap::Parser, Clone)]
struct Args {
    /// Input of the program
    #[clap(short, long)]
    input: String,
    /// Output of the program
    #[clap(short, long)]
    output: Option<String>,
    #[clap(flatten)]
    inner: cu::cli::Flags,
}
// use the flags attribute to refer to the cu::cli::Flags field inside the Args struct
#[cu::cli(flags = "inner")]
fn main(args: Args) -> cu::Result<()> {
    cu::info!("input is {}", args.input);
    cu::info!("output is {:?}", args.output);
    Ok(())
}

§Printing and Logging

In addition to the logging macros re-exported from the log crate, cu provides print and hint macros:

  • print: like info, but has a higher importance
  • hint: like print, but specifically for hinting actions the user can take (to resolve an error, for example).

These 2 levels are not directly controlled by log, and can still print when logging is statically disabled.

The following table shows what are printed for each level,

-qq -q -v-vv
error!❌✅✅✅✅
hint!❌✅✅✅✅
print!❌✅✅✅✅
warn!❌❌✅✅✅
info!❌❌✅✅✅
debug!❌❌❌✅✅
trace!❌❌❌❌✅

The RUST_LOG environment variable is also supported in the same way as in env_logger. When mixing RUST_LOG and verbosity flags, logging messages are filtered by RUST_LOG, and the verbosity would only apply to print and hint

§Other

When setting up test, you can use cu::cli::level to quickly inititialize logging without dealing with the details.

cu::cli::set_thread_name can be used to add a prefix to all messages printed by the current thread.

Messages that are too long and multi-line messages are automatically wrapped.

§Manual Parsing CLI args

cu::cli::try_parse and cu::cli::print_help can be useful when you want to manually invoke a command parser. These respect the --color option passed to the program.

§Ctrl-C Signals

We wrap the ctrlc crate because it only allows for one global handler. See Handling Ctrl-C

§Progress Bars

See Progress Bars

§Prompting

See Prompting

Structs§

CtrlcBuilder
Builder for a new frame for handling Ctrl-C signals. The canonical factory function for this is cu::cli::ctrlc_frame. See Handling Ctrl-C.
CtrlcSignal
Signal passed into a task executing inside a Ctrl-C action frame, for it to check if Ctrl-C has been signaled
DefaultLogConfig
The default LogConfig
Flagscli
Common flags for cu::cli
ProgressBar
Handle for a progress bar (This is the internal state, the handle is Arc<ProgressBar>)
ProgressBarBuilder
Builder for a progress bar
PromptBuilderprompt
See Prompting

Enums§

Target
Target for printing output

Traits§

LogConfig
Hook to configure the level and format before logging

Functions§

add_global_ctrlc_handlercli
Add a global handler to handle Ctrl-C signals
animate_to
Set the target for animation messages (prompts and bars)
ctrlc_frame
Handling Ctrl-C
init_options
Set global CLI options
level
Shorthand to quickly setup logging. Can be useful in tests.
password_chars_legalprompt
Check if the password contains all “legal” characters (and is non-empty)
print_helpcli
Print the help text from a command parser.
print_to
Set the target for printing messages
progress
Progress Bars
promptprompt
Prompting
reset_colorcli
Reset terminal color
reset_thread_name
Reset the current thread to not show a name
set_thread_name
Set the name to show up in messages printed by the current thread
try_parsecli
Try to parse arguments from an iterator and print the error/help on failure.
yesnoprompt
Show a Yes/No prompt

Type Aliases§

ProgressHandle
Convenience type for Arc<cu::ProgressBar>