cj_path_util/
path_util.rs1use std::path::{Path, PathBuf};
2
3use anyhow::{anyhow, Context, Result};
4
5pub trait AppendToPath {
7 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(""), None);
46 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 assert_eq!(t("foo"), "foo");
60 assert_eq!(t("foo/bar"), "foo/bar");
61 assert_eq!(t("foo/"), "foo");
62}
63
64pub 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}