tiger_lib/util.rs
1//! Miscellaneous helper functions related to filesystem operations.
2
3use std::borrow::Borrow;
4use std::path::{Path, PathBuf};
5
6/// A trait to join a string that may contain `.` or `..` to a path, and process those components
7/// for their meaning instead of just appending them.
8///
9/// This is useful when the resulting path has to be compared for equality with previously stored paths.
10///
11/// Note that this is exclusively a pathname operation. It does not check the filesystem to see if
12/// any of the pathname components are symbolic links.
13pub trait SmartJoin {
14 fn smart_join(&self, with: &str) -> PathBuf;
15 fn smart_join_parent(&self, with: &str) -> PathBuf;
16}
17
18impl SmartJoin for Path {
19 fn smart_join(&self, with: &str) -> PathBuf {
20 let mut result = self.to_path_buf();
21 for component in with.split('/') {
22 if component == "." {
23 continue;
24 }
25 if component == ".." {
26 result.pop();
27 } else {
28 result.push(component);
29 }
30 }
31 result
32 }
33 fn smart_join_parent(&self, with: &str) -> PathBuf {
34 if let Some(parent) = self.parent() {
35 parent.smart_join(with)
36 } else {
37 self.smart_join(with)
38 }
39 }
40}
41
42/// Redo a path so that all the slashes lean the correct way for the target platform.
43/// This is mostly for Windows users, to avoid showing them paths with a mix of slashes.
44pub fn fix_slashes_for_target_platform<P: Borrow<Path>>(path: P) -> PathBuf {
45 path.borrow().components().collect()
46}