Skip to main content

dhttp_home/
lib.rs

1pub mod identity;
2
3use std::path::{Path, PathBuf};
4
5#[cfg(any(unix, windows))]
6use snafu::OptionExt;
7use snafu::Snafu;
8
9/// A handle to the user's dhttp home directory (e.g. `~/.dhttp/`).
10///
11/// `DhttpHome` describes a directory that contains per-identity profiles and
12/// a global settings file. It does not own any in-memory configuration data;
13/// it is purely a typed path with helpers for resolving the layout inside.
14#[derive(Debug, Clone)]
15pub struct DhttpHome {
16    path: PathBuf,
17}
18
19#[derive(Debug, Snafu)]
20#[snafu(module)]
21pub enum LocateDhttpHomeError {
22    #[cfg(any(unix, windows))]
23    #[snafu(display("cannot locate user home directory"))]
24    NoUserHome {},
25    #[snafu(display(
26        "dhttp home cannot be automatically located on this platform, try setting DHTTP_HOME environment variable"
27    ))]
28    UnsupportedPlatform {},
29}
30
31impl DhttpHome {
32    pub const DIR_NAME: &str = ".dhttp";
33
34    pub fn new(pathbuf: PathBuf) -> Self {
35        Self { path: pathbuf }
36    }
37
38    pub fn for_user_home_dir(home_dir: impl Into<PathBuf>) -> Self {
39        Self::new(home_dir.into().join(Self::DIR_NAME))
40    }
41
42    pub fn load_from_environment() -> Result<Self, LocateDhttpHomeError> {
43        if let Some(path) = std::env::var_os("DHTTP_HOME") {
44            return Ok(Self::new(PathBuf::from(path)));
45        }
46
47        #[cfg(any(unix, windows))]
48        return Ok(Self::for_user_home_dir(
49            dirs::home_dir().context(locate_dhttp_home_error::NoUserHomeSnafu)?,
50        ));
51
52        #[allow(unreachable_code)]
53        locate_dhttp_home_error::UnsupportedPlatformSnafu.fail()
54    }
55
56    pub fn as_path(&self) -> &Path {
57        self.path.as_path()
58    }
59
60    pub fn join(&self, path: impl AsRef<Path>) -> PathBuf {
61        self.path.join(path)
62    }
63}
64
65impl AsRef<Path> for DhttpHome {
66    fn as_ref(&self) -> &Path {
67        self.as_path()
68    }
69}