简体   繁体   English

Rustlang structopt 如何设置主目录

[英]Rustlang structopt How to set the home directory

I am using the crate structopt for my cli program.我正在为我的 cli 程序使用 crate structopt I want to set home directory as default, if output dir in args not passed.如果 args 中的 output 目录未通过,我想将主目录设置为默认目录。 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. structopt字段可以采用默认值,但还有一个 ENV 回退,如果未明确提供该选项,它将 go 并从 envvar 获取默认值。

If you can assume running on a POSIX system, then HOME will be set to the current user's home.如果您可以假设在 POSIX 系统上运行,那么 HOME 将被设置为当前用户的家。

If you can not assume POSIX, then I think there are two ways:如果你不能假设POSIX,那么我认为有两种方法:

  • you can define the option as, well, an Option .您可以将选项定义为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如果未指定,它将被设置为None ,并且在使用站点您可以将None换成用户的 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 )定义一个具有所有正确位的自定义类型,如果未指定则默认为 homedir(请参阅 structopt 文档以了解如何执行此操作,它涉及FromStr以及可选的DefaultToString

Either way, you can use dirs::home_dir to get the home directory.无论哪种方式,您都可以使用dirs::home_dir来获取主目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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