Skip to main content

dort_core/
context.rs

1use crate::{
2    Error, Result,
3    platform::{Architecture, Platform},
4};
5use serde::Serialize;
6use std::{
7    ffi::OsString,
8    path::{Component, Path, PathBuf},
9};
10
11/// All machine-specific paths are explicit; core services never discover HOME themselves.
12#[derive(Debug, Clone, Serialize)]
13pub struct HostContext {
14    pub home: PathBuf,
15    pub config_dir: PathBuf,
16    pub state_dir: PathBuf,
17    pub platform: Platform,
18    pub architecture: Architecture,
19}
20
21impl HostContext {
22    pub fn new(
23        home: PathBuf,
24        xdg_config_home: Option<PathBuf>,
25        xdg_state_home: Option<PathBuf>,
26        platform: Platform,
27        architecture: Architecture,
28    ) -> Result<Self> {
29        validate_absolute(&home)?;
30        if home.parent().is_none() {
31            return Err(Error::Invalid("HOME cannot be the filesystem root".into()));
32        }
33        let config_base = xdg_config_home.unwrap_or_else(|| home.join(".config"));
34        let state_base = xdg_state_home.unwrap_or_else(|| home.join(".local/state"));
35        validate_absolute(&config_base)?;
36        validate_absolute(&state_base)?;
37        let config_dir = config_base.join("dort");
38        let state_dir = state_base.join("dort");
39        if config_dir == state_dir
40            || config_dir.starts_with(&state_dir)
41            || state_dir.starts_with(&config_dir)
42        {
43            return Err(Error::Invalid(
44                "Dort config and state directories must be separate".into(),
45            ));
46        }
47        Ok(Self {
48            home,
49            config_dir,
50            state_dir,
51            platform,
52            architecture,
53        })
54    }
55
56    /// Called at the application boundary only. Empty XDG values mean unset.
57    pub fn from_env() -> Result<Self> {
58        fn env_path(name: &str) -> Option<PathBuf> {
59            std::env::var_os(name)
60                .filter(|s: &OsString| !s.is_empty())
61                .map(PathBuf::from)
62        }
63        let home = env_path("HOME").ok_or_else(|| Error::Invalid("HOME must be set".into()))?;
64        Self::new(
65            home,
66            env_path("XDG_CONFIG_HOME"),
67            env_path("XDG_STATE_HOME"),
68            Platform::detect()?,
69            Architecture::detect()?,
70        )
71    }
72
73    pub fn local_config_path(&self) -> PathBuf {
74        self.config_dir.join("local.toml")
75    }
76
77    /// Lexical validation only; live reads must also use `observation`'s no-follow boundary.
78    pub fn target_path(&self, target: &Path, repository: Option<&Path>) -> Result<PathBuf> {
79        let path = if let Ok(suffix) = target.strip_prefix("~") {
80            self.home.join(suffix)
81        } else {
82            target.to_path_buf()
83        };
84        validate_absolute(&path)?;
85        if path == self.home || !path.starts_with(&self.home) {
86            return Err(Error::Invalid("managed targets must be below HOME".into()));
87        }
88        if path.starts_with(&self.config_dir)
89            || self.config_dir.starts_with(&path)
90            || path.starts_with(&self.state_dir)
91            || self.state_dir.starts_with(&path)
92            || repository.is_some_and(|repo| path.starts_with(repo) || repo.starts_with(&path))
93        {
94            return Err(Error::Invalid(
95                "managed targets cannot overlap Dort state or its repository".into(),
96            ));
97        }
98        Ok(path)
99    }
100}
101
102pub(crate) fn validate_absolute(path: &Path) -> Result<()> {
103    if !path.is_absolute()
104        || path
105            .components()
106            .any(|c| matches!(c, Component::ParentDir | Component::CurDir))
107        || path
108            .as_os_str()
109            .as_encoded_bytes()
110            .iter()
111            .any(|b| b.is_ascii_control())
112        || path
113            .as_os_str()
114            .as_encoded_bytes()
115            .split(|b| *b == b'/')
116            .any(|part| part == b"." || part == b"..")
117    {
118        return Err(Error::Invalid(format!(
119            "expected an absolute path without traversal: {}",
120            path.display()
121        )));
122    }
123    Ok(())
124}