简体   繁体   中英

Rustlang structopt How to set the home directory

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(())
    }
}

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:

  • you can define the option as, well, an Option . If unspecified it will be set to None , and at use-site you can just swap out the None for the user's homedir
  • define a custom type with all the right bits such that it defaults to the homedir if unspecified (see the structopt doc for how to do that, it involves FromStr and optionally Default and ToString )

Either way, you can use dirs::home_dir to get the home directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM