Clap - PathBuf 的默认值

Ele*_*ios 6 rust clap

如何设置 clap PathBuf 参数的默认值?它甚至可行吗?我不断地从一个错误跳到另一个错误。

当我尝试以“结构”方式进行操作时:

use std::{env, path::PathBuf};
use clap::{Parser, Args};

fn get_default_log_path() -> PathBuf {
    let mut path = env::current_exe().unwrap();
    path.pop();
    path.push("log/debug.log");
    path
}

#[derive(Parser, Debug)]
struct Cli {
  #[arg(default_value_t=get_default_log_path())]
  log_path: PathBuf
}

fn main() {
  let args = Cli::parse();
  println!("{:?}", args);
}
Run Code Online (Sandbox Code Playgroud)

我得到:std::path::PathBuf doesn't implement std::fmt::Display...

当我用字符串尝试时:

#[arg(default_value = get_default_log_path().as_os_str())]
log_path: PathBuf
Run Code Online (Sandbox Code Playgroud)

我得到:temporary value dropped while borrowed

如果我对其执行 .to_owned() ,它会输出:the trait bound clap::builder::OsStr: From<OsString> is not satisfied

这可能吗还是我做错了什么?我知道它可以在主函数中完成Option<PathBuf>并处理它。但这可以这样完成吗?

Fin*_*nis 13

由于默认值打印在帮助 ( --help/ -h) 页面中,因此它们必须实现Display.

PathBuf遗憾的是没有这样做,因此您无法default_value_t为其提供默认值。不过,您可以default_value毫无问题地使用。

您将面临的下一个问题是,默认情况下,clap 仅支持默认值的静态字符串引用。要启用动态的、拥有的默认值,您需要string在您的 中启用 clap 功能Cargo.toml

clap = { version = "4.3.0", features = ["derive", "string"] }
Run Code Online (Sandbox Code Playgroud)

然后,进行以下工作:

use clap::Parser;
use std::{env, path::PathBuf};

fn get_default_log_path() -> PathBuf {
    let mut path = env::current_exe().unwrap();
    path.pop();
    path.push("log/debug.log");
    path
}

#[derive(Parser, Debug)]
struct Cli {
    #[arg(default_value=get_default_log_path().into_os_string())]
    log_path: PathBuf,
}

fn main() {
    let args = Cli::parse();
    println!("{:?}", args);
}
Run Code Online (Sandbox Code Playgroud)
$ cargo build --release
...

$ target\release\rust-tmp.exe
Cli { log_path: "D:\\Projects\\rust-tmp\\target\\release\\log/debug.log" }

$ target\release\rust-tmp.exe --help
Cli { log_path: "D:\\Projects\\rust-tmp\\target\\release\\log/debug.log" }

D:\Projects\rust-tmp>target\release\rust-tmp.exe --help
Usage: rust-tmp.exe [LOG_PATH]

Arguments:
  [LOG_PATH]  [default: D:\Projects\rust-tmp\target\release\log/debug.log]

Options:
  -h, --help  Print help
Run Code Online (Sandbox Code Playgroud)

但请注意混合的/\。不要/在 a 中使用PathBuf- 使用多个push()s 代替。像这样:

$ cargo build --release
...

$ target\release\rust-tmp.exe
Cli { log_path: "D:\\Projects\\rust-tmp\\target\\release\\log/debug.log" }

$ target\release\rust-tmp.exe --help
Cli { log_path: "D:\\Projects\\rust-tmp\\target\\release\\log/debug.log" }

D:\Projects\rust-tmp>target\release\rust-tmp.exe --help
Usage: rust-tmp.exe [LOG_PATH]

Arguments:
  [LOG_PATH]  [default: D:\Projects\rust-tmp\target\release\log/debug.log]

Options:
  -h, --help  Print help
Run Code Online (Sandbox Code Playgroud)
Cli { log_path: "D:\\Projects\\rust-tmp\\target\\release\\log\\debug.log" }
Run Code Online (Sandbox Code Playgroud)