From 78b918087e0255db5867214701148d360b3c0b4c Mon Sep 17 00:00:00 2001 From: veeso Date: Tue, 24 Aug 2021 09:29:40 +0200 Subject: [PATCH] absolutize path common functions --- src/utils/path.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/utils/path.rs diff --git a/src/utils/path.rs b/src/utils/path.rs new file mode 100644 index 0000000..1621009 --- /dev/null +++ b/src/utils/path.rs @@ -0,0 +1,43 @@ +//! # Path +//! +//! Path related utilities + +use std::path::{Path, PathBuf}; + +/// ### absolutize +/// +/// Absolutize target path if relative. +/// For example: +/// +/// ```rust +/// assert_eq!(absolutize(&Path::new("/home/omar"), &Path::new("readme.txt")).as_path(), Path::new("/home/omar/readme.txt")); +/// assert_eq!(absolutize(&Path::new("/home/omar"), &Path::new("/tmp/readme.txt")).as_path(), Path::new("/tmp/readme.txt")); +/// ``` +pub fn absolutize(wrkdir: &Path, target: &Path) -> PathBuf { + match target.is_absolute() { + true => target.to_path_buf(), + false => { + let mut p: PathBuf = wrkdir.to_path_buf(); + p.push(target); + p + } + } +} + +#[cfg(test)] +mod test { + + use super::*; + + #[test] + fn absolutize_path() { + assert_eq!( + absolutize(&Path::new("/home/omar"), &Path::new("readme.txt")).as_path(), + Path::new("/home/omar/readme.txt") + ); + assert_eq!( + absolutize(&Path::new("/home/omar"), &Path::new("/tmp/readme.txt")).as_path(), + Path::new("/tmp/readme.txt") + ); + } +}