Reputation: 447
I am using the crate structopt for my cli program. I want to set home directory as default, if output dir in args not passed. Below is my code, please suggest me how i can implement.
Command.rs
pub enum Command {
#[structopt(name = "init")]
Init(InitCmd),
}
impl Command {
/// Wrapper around `StructOpt::from_args` method.
pub fn from_args() -> Self {
<Self as StructOpt>::from_args()
}
}
mod commands;
pub use commands::Command;
fn main(){
match Command::from_args() {
Command::Init(cmd) => {
println!("{:?}", cmd.execute())
},
}
}
impl InitCmd {
/// Run the command
pub fn execute(&self) -> Result<(), Error> {
Ok(())
}
}
Upvotes: 0
Views: 488
Reputation: 42492
structopt
fields can take default values, but there is also an ENV fallback which will go and get a default value from the envvar if the option is not provided explicitely.
If you can assume running on a POSIX system, then HOME will be set to the current user's home.
If you can not assume POSIX, then I think there are two ways:
Option
. If unspecified it will be set to None
, and at use-site you can just swap out the None
for the user's homedirFromStr
and optionally Default
and ToString
)Either way, you can use dirs::home_dir to get the home directory.
Upvotes: 0