use std::path::{Path, PathBuf};
use anyhow::{anyhow, Context, Result};
pub trait AppendToPath {
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(""), 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");
assert_eq!(t("foo"), "foo");
assert_eq!(t("foo/bar"), "foo/bar");
assert_eq!(t("foo/"), "foo");
}
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:?}"))
}