Skip to main content

dort_core/
local.rs

1use crate::{
2    Error, Manifest, Result,
3    context::HostContext,
4    error::io_error,
5    state::{PrivateDir, WriterLock},
6};
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use std::{
10    collections::BTreeMap,
11    os::unix::ffi::OsStrExt,
12    path::{Path, PathBuf},
13};
14
15fn schema_one() -> u32 {
16    1
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct RepositoryRecord {
22    pub root: PathBuf,
23}
24
25#[derive(Clone, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct LocalConfig {
28    #[serde(default = "schema_one")]
29    pub schema: u32,
30    #[serde(default)]
31    pub active_profiles: Vec<String>,
32    #[serde(default)]
33    pub variables: BTreeMap<String, toml::Value>,
34    pub active_repository: Option<String>,
35    #[serde(default)]
36    pub repositories: BTreeMap<String, RepositoryRecord>,
37}
38
39impl Default for LocalConfig {
40    fn default() -> Self {
41        Self {
42            schema: 1,
43            active_profiles: vec![],
44            variables: BTreeMap::new(),
45            active_repository: None,
46            repositories: BTreeMap::new(),
47        }
48    }
49}
50
51impl LocalConfig {
52    /// No Debug implementation: variable values must not leak through debug logging.
53    pub fn load(host: &HostContext) -> Result<Self> {
54        let Some(directory) = PrivateDir::open(&host.config_dir, false)? else {
55            return Ok(Self::default());
56        };
57        let Some(text) = directory.read("local.toml")? else {
58            return Ok(Self::default());
59        };
60        let config: Self = toml::from_str(&text)
61            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
62        config.validate()?;
63        Ok(config)
64    }
65
66    fn validate(&self) -> Result<()> {
67        if self.schema != 1 {
68            return Err(Error::Invalid(
69                "unsupported local configuration schema".into(),
70            ));
71        }
72        for (id, record) in &self.repositories {
73            validate_repository_id(id)?;
74            crate::context::validate_absolute(&record.root)?;
75        }
76        if self
77            .active_repository
78            .as_ref()
79            .is_some_and(|id| !self.repositories.contains_key(id))
80        {
81            return Err(Error::Invalid("active repository is not registered".into()));
82        }
83        let roots: std::collections::BTreeSet<_> =
84            self.repositories.values().map(|r| &r.root).collect();
85        if roots.len() != self.repositories.len() {
86            return Err(Error::Invalid(
87                "repository root is registered more than once".into(),
88            ));
89        }
90        Ok(())
91    }
92
93    fn save(&self, host: &HostContext, lock: &WriterLock) -> Result<()> {
94        lock.check_context(host)?;
95        self.validate()?;
96        let text = toml::to_string(self).map_err(|_| {
97            Error::Invalid("could not encode local configuration (values redacted)".into())
98        })?;
99        let directory =
100            PrivateDir::open(&host.config_dir, true)?.expect("created config directory");
101        directory.replace("local.toml", &text)
102    }
103
104    pub fn select_repository(&self, explicit: Option<&Path>) -> Result<PathBuf> {
105        if let Some(path) = explicit {
106            return path
107                .canonicalize()
108                .map_err(|e| io_error("resolve explicit repository", path, e));
109        }
110        self.active_repository
111            .as_ref()
112            .and_then(|id| self.repositories.get(id))
113            .map(|r| r.root.clone())
114            .ok_or(Error::NoRepository)
115    }
116}
117
118/// Foundation APIs only: callers must hold the application lock.
119/// These operations register metadata, never initialise Git or touch live dotfiles.
120pub struct RepositoryRegistry;
121
122impl RepositoryRegistry {
123    pub fn register(host: &HostContext, lock: &WriterLock, root: &Path) -> Result<String> {
124        lock.check_context(host)?;
125        crate::journal::ensure_writable(host)?;
126        let root = inspect_repository(host, root)?;
127        let mut config = LocalConfig::load(host)?;
128        let id = config
129            .repositories
130            .iter()
131            .find(|(_, r)| r.root == root)
132            .map(|(id, _)| id.clone())
133            .unwrap_or_else(|| format!("{:x}", Sha256::digest(root.as_os_str().as_bytes())));
134        config
135            .repositories
136            .insert(id.clone(), RepositoryRecord { root });
137        config.active_repository = Some(id.clone());
138        config.save(host, lock)?;
139        Ok(id)
140    }
141
142    /// Preserve the state ID after a deliberate move. Refuse forks or missing manifests.
143    pub fn relocate(host: &HostContext, lock: &WriterLock, id: &str, root: &Path) -> Result<()> {
144        lock.check_context(host)?;
145        crate::journal::ensure_writable(host)?;
146        let mut config = LocalConfig::load(host)?;
147        let old = config
148            .repositories
149            .get(id)
150            .ok_or_else(|| Error::Invalid("unknown repository ID".into()))?;
151        if old
152            .root
153            .try_exists()
154            .map_err(|e| io_error("inspect previous repository", &old.root, e))?
155        {
156            return Err(Error::Invalid(
157                "old repository still exists; refusing ambiguous relocation".into(),
158            ));
159        }
160        let root = inspect_repository(host, root)?;
161        if config.repositories.values().any(|r| r.root == root) {
162            return Err(Error::Invalid(
163                "new repository root is already registered".into(),
164            ));
165        }
166        config
167            .repositories
168            .insert(id.into(), RepositoryRecord { root });
169        config.save(host, lock)
170    }
171}
172
173pub fn repository_state_path(host: &HostContext, id: &str) -> Result<PathBuf> {
174    validate_repository_id(id)?;
175    Ok(host.state_dir.join("repositories").join(id))
176}
177
178fn validate_repository_id(id: &str) -> Result<()> {
179    if id.len() != 64
180        || !id
181            .bytes()
182            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
183    {
184        return Err(Error::Invalid("invalid local repository ID".into()));
185    }
186    Ok(())
187}
188
189pub(crate) fn registration_text(host: &HostContext, root: &Path) -> Result<(String, String)> {
190    let mut config = LocalConfig::load(host)?;
191    let id = config
192        .repositories
193        .iter()
194        .find(|(_, r)| r.root == root)
195        .map(|(id, _)| id.clone())
196        .unwrap_or_else(|| format!("{:x}", Sha256::digest(root.as_os_str().as_bytes())));
197    config.repositories.insert(
198        id.clone(),
199        RepositoryRecord {
200            root: root.to_owned(),
201        },
202    );
203    config.active_repository = Some(id.clone());
204    config.validate()?;
205    let text = toml::to_string(&config)
206        .map_err(|_| Error::Invalid("cannot encode registration (values redacted)".into()))?;
207    Ok((id, text))
208}
209
210fn inspect_repository(host: &HostContext, root: &Path) -> Result<PathBuf> {
211    let root = root
212        .canonicalize()
213        .map_err(|e| io_error("resolve repository", root, e))?;
214    if root.to_str().is_none() {
215        return Err(Error::Invalid(
216            "non-UTF-8 repository paths cannot be stored in TOML yet".into(),
217        ));
218    }
219    if root == host.home
220        || root.parent().is_none()
221        || root.starts_with(&host.config_dir)
222        || host.config_dir.starts_with(&root)
223        || root.starts_with(&host.state_dir)
224        || host.state_dir.starts_with(&root)
225    {
226        return Err(Error::Invalid(
227            "repository cannot be HOME or filesystem root, or overlap Dort metadata".into(),
228        ));
229    }
230    if !root
231        .join(".git")
232        .try_exists()
233        .map_err(|e| io_error("inspect Git metadata", &root, e))?
234    {
235        return Err(Error::Invalid(
236            "registry requires existing Git metadata; use bootstrap to create a repository".into(),
237        ));
238    }
239    let path = root.join("dort.toml");
240    let text = std::fs::read_to_string(&path)
241        .map_err(|e| io_error("read repository manifest", &path, e))?;
242    Manifest::parse(&text)?;
243    Ok(root)
244}