Skip to main content

jt_consoleutils/
help.rs

1//! Help and version printing helpers for CLI tools.
2//!
3//! Provides two diverging functions that print to stdout and exit:
4//! - `print_help(text: &str) -> !` — colorize and print a help string, then exit 0
5//! - `print_version(version_str: &str) -> !` — print a version string, then exit 0
6//!
7//! Both functions are intended to be called from argument parsing code when
8//! `-h`/`--help` or `--version` flags are detected.
9
10use crate::{colorize::colorize_text_with_width, terminal::terminal_width};
11
12/// Colorize `text` with a left-to-right rainbow spanning the current terminal
13/// width, print it to stdout, and exit with code 0.
14///
15/// This is the standard help-printing pattern shared by CLI tools in this
16/// ecosystem. Call it when `-h` or `--help` is detected.
17///
18/// # Example
19///
20/// ```rust,ignore
21/// if args.iter().any(|a| a == "-h" || a == "--help") {
22///     jt_consoleutils::help::print_help(&build_help_text());
23/// }
24/// ```
25pub fn print_help(text: &str) -> ! {
26   let width = terminal_width();
27   println!("{}", colorize_text_with_width(text, Some(width)));
28   std::process::exit(0);
29}
30
31/// Print `version_str` to stdout and exit with code 0.
32///
33/// Call this when `--version` is detected. `version_str` is typically produced
34/// by `jt_consoleutils::version::version_string(BUILD_DATE, GIT_HASH)`.
35///
36/// # Example
37///
38/// ```rust,ignore
39/// if raw.version {
40///     jt_consoleutils::help::print_version(&version::version_string());
41/// }
42/// ```
43pub fn print_version(version_str: &str) -> ! {
44   println!("{version_str}");
45   std::process::exit(0);
46}
47
48#[cfg(test)]
49mod tests {
50   // print_help and print_version call process::exit, so they cannot be tested
51   // for their exit behaviour in-process. The colorize and terminal modules
52   // have their own tests; there is nothing further to unit-test here.
53}