Skip to main content

App

Struct App 

Source
pub struct App { /* private fields */ }
Available on crate feature std only.
Expand description

A command-line application.

Build with App::new, add commands with register, then call parse.

§Examples

use cli_forge::{App, Arg, Command, out};

let mut app = App::new("forge")
    .help_header("forge — project constructor")
    .help_footer("docs: https://github.com/jamesgober/cli-forge");

app.register(
    Command::new("init")
        .about("bootstrap a new project")
        .arg(Arg::positional("name").required(true))
        .run(|m| out(format!("initializing {}", m.value("name").unwrap_or("?")))),
);

let _matches = app.parse();

Implementations§

Source§

impl App

Source

pub fn new(name: impl Into<String>) -> App

Create an application with the given program name.

§Examples
use cli_forge::App;
let app = App::new("forge");
Source

pub fn auth(self, hook: impl Fn(&AuthRequest<'_>) -> bool + 'static) -> App

Available on crate feature auth only.

Set the authorization hook that enforces Command::requires_auth.

The hook receives an AuthRequest naming the command being authorized and returns whether to allow it. An auth-gated command runs only if the hook returns true; otherwise parsing yields ParseError::Unauthorized and the handler does not run. Without a hook, auth-gated commands are never authorized (the seam fails closed).

Requires the auth feature.

§Examples
use cli_forge::{App, Command, ParseError};

let mut app = App::new("demo").auth(|req| req.command() != "publish");
app.register(Command::new("publish").requires_auth(true).run(|_| {}));

let err = app.try_parse_from(["publish"]).unwrap_err();
assert!(matches!(err, ParseError::Unauthorized { .. }));
Source

pub fn version(self, version: impl Into<String>) -> App

Set the version reported by -V / --version.

Without this, the version flags are treated as ordinary unknown flags. A common idiom is to pass the crate version:

use cli_forge::App;
let app = App::new("forge").version(env!("CARGO_PKG_VERSION"));
Source

pub fn help_header(self, text: impl Into<String>) -> App

Set the header shown at the top of every generated help page.

§Examples
use cli_forge::App;
let app = App::new("forge").help_header("forge — project constructor");

Set the footer shown at the bottom of every generated help page.

§Examples
use cli_forge::App;
let app = App::new("forge").help_footer("see the docs for more");
Source

pub fn register(&mut self, cmd: Command)

Register a top-level command.

Call this from anywhere with access to the App — a different module, a plugin’s setup function, a loop over a config — at any point before parsing. A command registered outside main is reachable and behaves identically to one registered in main.

§Examples
use cli_forge::{App, Command};

let mut app = App::new("demo");
app.register(Command::new("status").about("show status"));
app.register(Command::new("sync").about("synchronize"));
Source

pub fn parse(&self) -> Matches

Parse the process arguments, run the selected command’s handler, and return the Matches.

-h / --help and -V / --version are handled here: the rendered help or version is printed to standard output and the process exits 0. On malformed input the structured ParseError is printed to standard error and the process exits 2. This never panics. For a non-exiting variant — for embedding or tests — use try_parse_from.

§Examples
use cli_forge::{App, Command, out};

let mut app = App::new("demo").version(env!("CARGO_PKG_VERSION"));
app.register(Command::new("hello").run(|_| out("hello")));
let _matches = app.parse();
Source

pub fn help(&self) -> String

Render the top-level help as a string.

Useful for printing help on demand — for example, when no command was given:

use cli_forge::{App, Command, out};

let mut app = App::new("demo");
app.register(Command::new("build").about("compile the project"));

let help = app.help();
assert!(help.contains("build"));
assert!(help.contains("compile the project"));
Source

pub fn try_parse_from<I, S>(&self, args: I) -> Result<Matches, ParseError>
where I: IntoIterator<Item = S>, S: Into<String>,

Parse an explicit argument list (excluding the program name), run the selected command’s handler, and return the Matches — or a structured ParseError on malformed input. Never exits the process; never panics.

This is the testable, embeddable counterpart to parse.

§Examples
use cli_forge::{App, Arg, Command, ParseError};

let mut app = App::new("demo");
app.register(Command::new("build").arg(Arg::option("jobs").short('j')));

// Well-formed input parses.
let matches = app.try_parse_from(["build", "-j", "4"]).unwrap();
assert_eq!(matches.subcommand().unwrap().1.value("jobs"), Some("4"));

// Malformed input returns a structured error.
let err = app.try_parse_from(["build", "--bogus"]).unwrap_err();
assert!(matches!(err, ParseError::UnknownFlag { .. }));

Trait Implementations§

Source§

impl Debug for App

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for App

§

impl !Send for App

§

impl !Sync for App

§

impl !UnwindSafe for App

§

impl Freeze for App

§

impl Unpin for App

§

impl UnsafeUnpin for App

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.