cj-path-util 0.3.0

Utilities to make working with Path/PathBuf more productive
Documentation
use std::path::{Path, PathBuf};

use anyhow::{anyhow, Context, Result};

/// Make it easy to append a segment to an existing path.
pub trait AppendToPath {
    /// Note: `segment` should be a single file/folder name and *not*
    /// contain `/` or `\\` characters!
    fn append<P: AsRef<Path>>(self, segment: P) -> PathBuf;
}

impl<'p> AppendToPath for &'p Path {
    fn append<P: AsRef<Path>>(self, segment: P) -> PathBuf {
        let mut path = self.to_owned();
        path.push(segment);
        path
    }
}

impl<'p> AppendToPath for &'p PathBuf {
    fn append<P: AsRef<Path>>(self, segment: P) -> PathBuf {
        let mut path = self.clone();
        path.push(segment);
        path
    }
}

impl AppendToPath for PathBuf {
    fn append<P: AsRef<Path>>(mut self, segment: P) -> PathBuf {
        self.push(segment);
        self
    }
}

pub fn remove_extension(path: impl AsRef<Path>) -> Option<PathBuf> {
    let path = path.as_ref();
    let stem = path.file_stem()?;
    let base = path.parent()?;
    Some(base.append(stem))
}

#[test]
fn t_remove_extension() {
    // assert_eq!(remove_extension("foo"), None);
    assert_eq!(remove_extension(""), None);
    // assert_eq!(remove_extension("foo/"), None);
    // assert_eq!(remove_extension("foo/bar"), None);
    let t = |s| {
        remove_extension(s)
            .unwrap()
            .to_str()
            .expect("unicode")
            .to_owned()
    };
    assert_eq!(t("foo.tmp"), "foo");
    assert_eq!(t("foo/bar.tmp"), "foo/bar");
    assert_eq!(t("foo/bar.gz.tmp"), "foo/bar.gz");
    // I didn't expect these to return a result, but they do:
    assert_eq!(t("foo"), "foo");
    assert_eq!(t("foo/bar"), "foo/bar");
    assert_eq!(t("foo/"), "foo");
}

/// Rename a file with a path with a ".tmp" or similar suffix to the
/// path without that suffix
pub fn rename_tmp_path(tmp_path: impl AsRef<Path>) -> Result<()> {
    let tmp_path = tmp_path.as_ref();
    let path = remove_extension(&tmp_path)
        .ok_or_else(|| anyhow!("tmp path does not have a suffix: {tmp_path:?}"))?;
    std::fs::rename(tmp_path, &path).with_context(|| anyhow!("renaming {tmp_path:?} to {path:?}"))
}