惯用地在Rust路径中扩展波浪号

leo*_*ukw 2 directory path home-directory rust

有时,例如,当读取某些配置文件时,您读取了用户输入的文件路径而无需通过外壳程序(例如,获得~/test)。

正如Option 2下面不写在用户主目录下的测试文件,我想知道,如果有什么比更地道Option 1

use std::env::var;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

fn write_to(path: &Path) {
    let mut f = File::create(path).unwrap();
    f.write_all("Hi".as_bytes()).unwrap();
}

fn main() {
    // Option 1
    let from_env = format!("{}/test", var("HOME").unwrap());
    let with_var = Path::new(&from_env);
    // Create $HOME/test
    write_to(with_var);

    // Option 2
    let with_tilde = Path::new("~/test");
    // Create the test file in current directory, provided a directory ./~ exists
    write_to(with_tilde);
}
Run Code Online (Sandbox Code Playgroud)

注意unwrap()此处用于使示例简短。生产代码中应该有一些错误处理。

And*_*kin 5

  1. 最惯用的方法是仅使用现有的板条箱,在这种情况下shellexpandgithubcrates.io)似乎可以满足您的要求:

    extern crate shellexpand; // 1.0.0
    
    #[test]
    fn test_shellexpand() {
        let home = std::env::var("HOME").unwrap();
        assert_eq!(shellexpand::tilde("~/foo"), format!("{}/foo", home));
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 另外,您可以尝试使用dirscrates.io)。这是一个草图:

    extern crate dirs; // 1.0.4
    
    use std::path::{Path, PathBuf};
    
    fn expand_tilde<P: AsRef<Path>>(path_user_input: P) -> Option<PathBuf> {
        let p = path_user_input.as_ref();
        if p.starts_with("~") {
            if p == Path::new("~") {
                dirs::home_dir()
            } else {
                dirs::home_dir().map(|mut h| {
                    if h == Path::new("/") {
                        // Corner case: `h` root directory;
                        // don't prepend extra `/`, just drop the tilde.
                        p.strip_prefix("~").unwrap().to_path_buf()
                    } else {
                        h.push(p.strip_prefix("~/").unwrap());
                        h
                    }
                })
            }
        } else {
            Some(p.to_path_buf())
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    用法示例:

    #[test]
    fn test_expand_tilde() {
        // Should work on your linux box during tests, would fail in stranger
        // environments!
        let home = std::env::var("HOME").unwrap();
        let projects = PathBuf::from(format!("{}/Projects", home));
        assert_eq!(expand_tilde("~/Projects"), Some(projects));
        assert_eq!(expand_tilde("/foo/bar"), Some("/foo/bar".into()));
        assert_eq!(
            expand_tilde("~alice/projects"),
            Some("~alice/projects".into())
        );
    }
    
    Run Code Online (Sandbox Code Playgroud)

    一些说明:

    • P: AsRef<Path>输入型仿标准库做什么。这就是为什么该方法接受所有Path样的投入,如&str&OsStr&Path
    • Path::new不分配任何内容,它指向与完全相同的字节&str
    • strip_prefix("~/").unwrap()应该永远不会失败,因为我们检查了路径以~而不是开头~。唯一的方法是路径以~/(因为如何starts_with 定义)开始。

  • ---&gt; 版本 1. 很有帮助 (4认同)
  • ---&gt; 版本 2. 很有帮助 (2认同)