use super::Mode;
use yash_env::path::Path;
#[must_use]
pub fn shorten<'a>(target: &'a Path, pwd: &Path, mode: Mode) -> &'a Path {
match mode {
Mode::Physical => target,
Mode::Logical => {
let result = target.strip_prefix(pwd).unwrap_or(target);
if result == Path::new("") {
Path::new(".")
} else {
result
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn target_not_starting_with_pwd() {
let result = shorten(Path::new("/foo/bar"), Path::new("/foo/baz"), Mode::Logical);
assert_eq!(result, Path::new("/foo/bar"));
}
#[test]
fn target_starting_with_pwd() {
let result = shorten(Path::new("/foo/bar"), Path::new("/foo"), Mode::Logical);
assert_eq!(result, Path::new("bar"));
let result = shorten(Path::new("/foo/bar"), Path::new("/"), Mode::Logical);
assert_eq!(result, Path::new("foo/bar"));
}
#[test]
fn target_equals_pwd() {
let result = shorten(Path::new("/foo"), Path::new("/foo"), Mode::Logical);
assert_eq!(result, Path::new("."));
let result = shorten(Path::new("/one/two"), Path::new("/one/two"), Mode::Logical);
assert_eq!(result, Path::new("."));
}
#[test]
fn physical_mode() {
let result = shorten(Path::new("/foo/bar"), Path::new("/foo"), Mode::Physical);
assert_eq!(result, Path::new("/foo/bar"));
}
}