Skip to main content

cj_path_util/
path_util.rs

1use std::path::{Path, PathBuf};
2
3use anyhow::{anyhow, Context, Result};
4
5/// Make it easy to append a segment to an existing path.
6pub trait AppendToPath {
7    /// Note: `segment` should be a single file/folder name and *not*
8    /// contain `/` or `\\` characters!
9    fn append<P: AsRef<Path>>(self, segment: P) -> PathBuf;
10}
11
12impl<'p> AppendToPath for &'p Path {
13    fn append<P: AsRef<Path>>(self, segment: P) -> PathBuf {
14        let mut path = self.to_owned();
15        path.push(segment);
16        path
17    }
18}
19
20impl<'p> AppendToPath for &'p PathBuf {
21    fn append<P: AsRef<Path>>(self, segment: P) -> PathBuf {
22        let mut path = self.clone();
23        path.push(segment);
24        path
25    }
26}
27
28impl AppendToPath for PathBuf {
29    fn append<P: AsRef<Path>>(mut self, segment: P) -> PathBuf {
30        self.push(segment);
31        self
32    }
33}
34
35pub fn remove_extension(path: impl AsRef<Path>) -> Option<PathBuf> {
36    let path = path.as_ref();
37    let stem = path.file_stem()?;
38    let base = path.parent()?;
39    Some(base.append(stem))
40}
41
42#[test]
43fn t_remove_extension() {
44    // assert_eq!(remove_extension("foo"), None);
45    assert_eq!(remove_extension(""), None);
46    // assert_eq!(remove_extension("foo/"), None);
47    // assert_eq!(remove_extension("foo/bar"), None);
48    let t = |s| {
49        remove_extension(s)
50            .unwrap()
51            .to_str()
52            .expect("unicode")
53            .to_owned()
54    };
55    assert_eq!(t("foo.tmp"), "foo");
56    assert_eq!(t("foo/bar.tmp"), "foo/bar");
57    assert_eq!(t("foo/bar.gz.tmp"), "foo/bar.gz");
58    // I didn't expect these to return a result, but they do:
59    assert_eq!(t("foo"), "foo");
60    assert_eq!(t("foo/bar"), "foo/bar");
61    assert_eq!(t("foo/"), "foo");
62}
63
64/// Rename a file with a path with a ".tmp" or similar suffix to the
65/// path without that suffix
66pub fn rename_tmp_path(tmp_path: impl AsRef<Path>) -> Result<()> {
67    let tmp_path = tmp_path.as_ref();
68    let path = remove_extension(&tmp_path)
69        .ok_or_else(|| anyhow!("tmp path does not have a suffix: {tmp_path:?}"))?;
70    std::fs::rename(tmp_path, &path).with_context(|| anyhow!("renaming {tmp_path:?} to {path:?}"))
71}