In my CLI program the usage examples are provided as part of the help message. Using the clap
derive interface I can do the following
#[derive(Parser, Debug, Default)]
#[clap( after_help = "EXAMPLES:\n $ foo abc.txt")]
pub struct CmdLine {...}
The program name foo
is hard coded in the literal string above.
How can I avoid hard-coding the program name and get it dynamically; for example, from std::env::args[0]
or clap::App:get_bin_name()
?
clap provides a macro called crate_name! that will take the name from your
cargo.toml
.For example, suppose you have this in your
cargo.toml
.Then, in your application, you can fetch these values using the macros, like this:
The section below is appended to respond to the original poster's specific question. See the comments below for context. Also, including some learnings as well.
Appended per the discussion in comments.
Based on the comments/discussion below, initial thought is just to stuff the binary name from the arguments into a string and pass into the
after_help()
function. For example, something like this:Taking this approach, you quickly run into a lifetime requirement in the function signature for
after_help()
. From clap's repo:In fact, if you look, there are many fields in the
Command
struct that have the lifetime annotation (&'help
) on them. TheCommand::new()
method doesn't have this lifetime annotation so it worked fine to just pass itbin_name
as shown above.Below is an abbreviated solution that dynamically generates after-help text in a manner that adheres to the lifetime requirements. Assuming a clean binary (application), called "foo", add the following code:
cargo.toml
main.rs
lib.rs
Running the solution (
cargo run -- --help
) will produce the following output: