git_prole/
utf8tempdir.rs

1use std::ops::Deref;
2use std::path::Path;
3
4use camino::Utf8Path;
5use camino::Utf8PathBuf;
6use miette::IntoDiagnostic;
7use tempfile::TempDir;
8
9#[derive(Debug)]
10pub struct Utf8TempDir {
11    #[allow(dead_code)]
12    inner: Option<TempDir>,
13    path: Utf8PathBuf,
14}
15
16impl Utf8TempDir {
17    pub fn new(parent_dir: &Utf8PathBuf) -> miette::Result<Self> {
18        let inner = tempfile::tempdir_in(parent_dir).into_diagnostic()?;
19        let path = inner.path().to_owned().try_into().into_diagnostic()?;
20        Ok(Self {
21            inner: Some(inner),
22            path,
23        })
24    }
25
26    /// Keep this directory when it goes out of scope, without changing its type.
27    pub fn persist(&mut self) {
28        let inner = self.inner.take();
29        if let Some(tempdir) = inner {
30            let _ = tempdir.into_path();
31        }
32    }
33
34    /// Keep this directory when it goes out of scope.
35    pub fn into_path(mut self) -> Utf8PathBuf {
36        self.persist();
37        self.path
38    }
39
40    #[expect(dead_code)]
41    pub(crate) fn as_path(&self) -> &Utf8Path {
42        &self.path
43    }
44}
45
46impl Deref for Utf8TempDir {
47    type Target = Utf8Path;
48
49    fn deref(&self) -> &Self::Target {
50        &self.path
51    }
52}
53
54impl AsRef<Path> for Utf8TempDir {
55    fn as_ref(&self) -> &Path {
56        self.as_std_path()
57    }
58}