diff --git a/componenttest/Cargo.lock b/componenttest/Cargo.lock new file mode 100644 index 0000000..14b13dc --- /dev/null +++ b/componenttest/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "componenttest" +version = "0.1.0" diff --git a/componenttest/Cargo.toml b/componenttest/Cargo.toml new file mode 100644 index 0000000..9a5e491 --- /dev/null +++ b/componenttest/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "componenttest" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/componenttest/README.md b/componenttest/README.md new file mode 100644 index 0000000..9db1645 --- /dev/null +++ b/componenttest/README.md @@ -0,0 +1,3 @@ +# ComponentTest + +Playing with the Component part of Path/PathBuf. diff --git a/componenttest/src/main.rs b/componenttest/src/main.rs new file mode 100644 index 0000000..0a3c00c --- /dev/null +++ b/componenttest/src/main.rs @@ -0,0 +1,55 @@ +use std::{ + ffi::OsStr, + path::{Component, Path, PathBuf}, +}; + +pub trait ExpandedExt { + fn expand(&self) -> PathBuf; +} + +impl ExpandedExt for Path { + fn expand(&self) -> PathBuf { + let mut buf = PathBuf::new(); + for component in self.components() { + match component { + Component::Normal(path) => match path.to_str() { + None => buf.push(path), // component can't be converted to str + Some(path_as_str) => { + match std::env::var_os(&path_as_str[1..]) { + None => buf.push(path), // variable is not set + Some(value) => buf.push(value), + } + } + }, + a => buf.push(a), + } + } + buf + } +} + +fn main() { + let path1 = PathBuf::from("/tmp/dir/file.txt"); + for comp in path1.components() { + println!("{:?}", comp); + } + + let path2 = PathBuf::from("$MAGIC_PATH/dir/file.txt"); + for comp in path2.components() { + println!("{:?}", comp); + } + + let new_path2 = path2 + .components() + .map(|comp| match comp { + Component::Normal(x) if x == "$MAGIC_PATH" => { + Component::Normal(OsStr::new("magical_path_expanded")) + } + x => x, + }) + .collect::(); + println!("Path2: {:?}", new_path2); + + let path3 = PathBuf::from("$USER/Projects/Personal/random/$CARGO_MANIFEST_DIR"); + println!("Path3: {:?}", path3.expand()); +}