asimov_directory/fs/
program_directory.rs1use super::StateDirectory;
4use alloc::format;
5use camino::{Utf8Path, Utf8PathBuf};
6use derive_more::Display;
7use std::{
8 io::{Error, ErrorKind, Result},
9 path::Path,
10};
11
12#[derive(Debug, Display)]
14#[display("ProgramDirectory({:?})", path)]
15pub struct ProgramDirectory {
16 path: Utf8PathBuf,
17}
18
19impl AsRef<Utf8PathBuf> for ProgramDirectory {
20 fn as_ref(&self) -> &Utf8PathBuf {
21 &self.path
22 }
23}
24
25impl ProgramDirectory {
26 pub fn home() -> Result<Self> {
30 StateDirectory::home().map(|base_dir| base_dir.programs())?
31 }
32
33 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
35 let path = path.as_ref();
36 if !path.exists() {
37 std::fs::create_dir_all(path)?;
38 }
39 let path = Utf8PathBuf::from_path_buf(path.to_path_buf()).map_err(|e| {
40 Error::new(
41 ErrorKind::InvalidFilename,
42 format!("failed to open non-UTF-8 path: {}", e.display()),
43 )
44 })?;
45 Ok(ProgramDirectory { path })
46 }
47
48 pub fn join(&self, path: impl AsRef<Utf8Path>) -> Utf8PathBuf {
49 self.path.join(path.as_ref())
50 }
51
52 pub fn as_str(&self) -> &str {
53 self.path.as_str()
54 }
55}
56
57impl AsRef<str> for ProgramDirectory {
58 fn as_ref(&self) -> &str {
59 self.path.as_str()
60 }
61}
62
63impl AsRef<Path> for ProgramDirectory {
64 fn as_ref(&self) -> &Path {
65 self.path.as_std_path()
66 }
67}
68
69#[cfg(feature = "camino")]
70impl AsRef<Utf8Path> for ProgramDirectory {
71 fn as_ref(&self) -> &Utf8Path {
72 self.path.as_path()
73 }
74}
75
76impl crate::ProgramDirectory for ProgramDirectory {}