Browse Source

Playing with Path components

master
Julio Biason 1 year ago
parent
commit
50f77460bc
  1. 7
      componenttest/Cargo.lock
  2. 8
      componenttest/Cargo.toml
  3. 3
      componenttest/README.md
  4. 55
      componenttest/src/main.rs

7
componenttest/Cargo.lock generated

@ -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"

8
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]

3
componenttest/README.md

@ -0,0 +1,3 @@
# ComponentTest
Playing with the Component part of Path/PathBuf.

55
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::<PathBuf>();
println!("Path2: {:?}", new_path2);
let path3 = PathBuf::from("$USER/Projects/Personal/random/$CARGO_MANIFEST_DIR");
println!("Path3: {:?}", path3.expand());
}
Loading…
Cancel
Save