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    tools::inspection::Query,
7};
8use serde::{Deserialize, Serialize};
9use sha2::{Digest, Sha256};
10use std::{
11    collections::BTreeMap,
12    os::unix::ffi::OsStrExt,
13    path::{Path, PathBuf},
14};
15
16pub mod registry_edit;
17
18fn schema_one() -> u32 {
19    1
20}
21
22/// Bind the file's full identity but only parent identities: unrelated sibling
23/// creation changes a parent clock without making this read unsafe.
24fn same_read(before: &crate::observation::Entry, after: &crate::observation::Entry) -> bool {
25    before.path == after.path
26        && before.kind == after.kind
27        && before.fingerprint == after.fingerprint
28        && before.link_target == after.link_target
29        && before.parents.len() == after.parents.len()
30        && before.parents.iter().zip(&after.parents).all(|(a, b)| {
31            a.path == b.path && crate::adoption::parent_identity(&a.fingerprint, &b.fingerprint)
32        })
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct RepositoryRecord {
38    pub root: PathBuf,
39}
40
41#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(deny_unknown_fields)]
43pub struct ToolSettingsScope {
44    pub query: Query,
45    pub id: String,
46}
47
48#[derive(Clone, Serialize, Deserialize)]
49#[serde(deny_unknown_fields)]
50pub struct ToolSettings {
51    pub scope: ToolSettingsScope,
52    pub program: PathBuf,
53    pub search_dirs: Vec<PathBuf>,
54    pub npm_cli: Option<PathBuf>,
55    pub prefix: Option<PathBuf>,
56}
57
58#[derive(Clone, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct LocalConfig {
61    #[serde(default = "schema_one")]
62    pub schema: u32,
63    #[serde(default)]
64    pub active_profiles: Vec<String>,
65    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
66    profile_choices: BTreeMap<String, BTreeMap<String, crate::profiles::Choice>>,
67    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
68    tool_settings: BTreeMap<PathBuf, Vec<ToolSettings>>,
69    #[serde(default)]
70    pub variables: BTreeMap<String, toml::Value>,
71    pub active_repository: Option<String>,
72    #[serde(default)]
73    pub repositories: BTreeMap<String, RepositoryRecord>,
74}
75
76impl Default for LocalConfig {
77    fn default() -> Self {
78        Self {
79            schema: 1,
80            active_profiles: vec![],
81            profile_choices: BTreeMap::new(),
82            tool_settings: BTreeMap::new(),
83            variables: BTreeMap::new(),
84            active_repository: None,
85            repositories: BTreeMap::new(),
86        }
87    }
88}
89
90impl LocalConfig {
91    /// No Debug implementation: variable values must not leak through debug logging.
92    pub fn load(host: &HostContext) -> Result<Self> {
93        let Some(directory) = PrivateDir::open(&host.config_dir, false)? else {
94            return Ok(Self::default());
95        };
96        let Some(text) = directory.read("local.toml")? else {
97            return Ok(Self::default());
98        };
99        let config: Self = toml::from_str(&text)
100            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
101        config.validate()?;
102        Ok(config)
103    }
104
105    /// Bounded, stable private configuration read for source-bound Tools writes.
106    /// Only the fingerprint/hash escapes; variable values remain private.
107    pub(crate) fn load_bound(host: &HostContext) -> Result<(Self, crate::observation::Entry)> {
108        let directory = PrivateDir::open(&host.config_dir, false)?
109            .ok_or_else(|| Error::Invalid("registered local configuration required".into()))?;
110        let before = crate::observation::inspect(&host.local_config_path(), false)?;
111        let bytes = crate::journal::read_bytes(&directory, "local.toml")?;
112        let text = std::str::from_utf8(&bytes)
113            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
114        let config: Self = toml::from_str(text)
115            .map_err(|_| Error::Invalid("invalid local configuration (values redacted)".into()))?;
116        config.validate()?;
117        let mut after = crate::observation::inspect(&host.local_config_path(), false)?;
118        if !same_read(&before, &after) {
119            return Err(Error::Invalid(
120                "local configuration changed during read".into(),
121            ));
122        }
123        after.sha256 = Some(crate::journal::digest(&bytes));
124        Ok((config, after))
125    }
126
127    fn validate(&self) -> Result<()> {
128        if self.schema != 1 {
129            return Err(Error::Invalid(
130                "unsupported local configuration schema".into(),
131            ));
132        }
133        for (id, record) in &self.repositories {
134            validate_repository_id(id)?;
135            crate::context::validate_absolute(&record.root)?;
136        }
137        if self
138            .active_repository
139            .as_ref()
140            .is_some_and(|id| !self.repositories.contains_key(id))
141        {
142            return Err(Error::Invalid("active repository is not registered".into()));
143        }
144        let roots: std::collections::BTreeSet<_> =
145            self.repositories.values().map(|r| &r.root).collect();
146        if roots.len() != self.repositories.len() {
147            return Err(Error::Invalid(
148                "repository root is registered more than once".into(),
149            ));
150        }
151        Ok(())
152    }
153
154    fn save(&self, host: &HostContext, lock: &WriterLock) -> Result<()> {
155        lock.check_context(host)?;
156        self.validate()?;
157        let text = toml::to_string(self).map_err(|_| {
158            Error::Invalid("could not encode local configuration (values redacted)".into())
159        })?;
160        let directory =
161            PrivateDir::open(&host.config_dir, true)?.expect("created config directory");
162        directory.replace("local.toml", &text)
163    }
164
165    pub fn tool_settings(&self, manifest: &Path) -> &[ToolSettings] {
166        self.tool_settings.get(manifest).map_or(&[], Vec::as_slice)
167    }
168
169    pub fn save_tool_settings(
170        host: &HostContext,
171        lock: &WriterLock,
172        manifest: PathBuf,
173        settings: ToolSettings,
174    ) -> Result<()> {
175        lock.check_context(host)?;
176        crate::context::validate_absolute(&manifest)?;
177        for path in std::iter::once(&settings.program)
178            .chain(&settings.search_dirs)
179            .chain(&settings.npm_cli)
180            .chain(&settings.prefix)
181        {
182            crate::context::validate_absolute(path)?;
183        }
184        let mut local = Self::load(host)?;
185        let rows = local.tool_settings.entry(manifest).or_default();
186        rows.retain(|row| row.scope != settings.scope);
187        rows.push(settings);
188        local.save(host, lock)
189    }
190
191    pub fn profile_rows(
192        &self,
193        profiles: &crate::profiles::Profiles,
194        platform: crate::platform::Platform,
195        repository: Option<&Path>,
196        temporary: &[String],
197    ) -> Result<Vec<crate::profiles::Row>> {
198        let saved = repository
199            .and_then(|root| {
200                self.repositories
201                    .iter()
202                    .find(|(_, record)| record.root == root)
203            })
204            .and_then(|(id, _)| self.profile_choices.get(id));
205        profiles.rows(
206            platform,
207            &self.active_profiles,
208            saved.unwrap_or(&BTreeMap::new()),
209            temporary,
210        )
211    }
212
213    pub fn select_repository(&self, explicit: Option<&Path>) -> Result<PathBuf> {
214        if let Some(path) = explicit {
215            return path
216                .canonicalize()
217                .map_err(|e| io_error("resolve explicit repository", path, e));
218        }
219        self.active_repository
220            .as_ref()
221            .and_then(|id| self.repositories.get(id))
222            .map(|r| r.root.clone())
223            .ok_or(Error::NoRepository)
224    }
225}
226
227#[derive(Serialize)]
228pub struct ProfilePreview {
229    repository: PathBuf,
230    name: String,
231    choice: crate::profiles::Choice,
232    #[serde(skip)]
233    manifest: crate::observation::Entry,
234    #[serde(skip)]
235    config: crate::observation::Entry,
236}
237
238impl ProfilePreview {
239    pub fn prepare(
240        host: &HostContext,
241        repository: &Path,
242        name: &str,
243        choice: crate::profiles::Choice,
244    ) -> Result<Self> {
245        let (local, config) = LocalConfig::load_bound(host)?;
246        if !local.repositories.values().any(|r| r.root == repository) {
247            return Err(Error::Invalid(
248                "Profile choices need a registered repository".into(),
249            ));
250        }
251        let (manifest, entry) = crate::observation::read_manifest(&repository.join("dort.toml"))?;
252        if name == "base" || !manifest.profiles.known().contains(name) {
253            return Err(Error::Invalid(
254                "Choose a known profile other than base".into(),
255            ));
256        }
257        Ok(Self {
258            repository: repository.to_owned(),
259            name: name.into(),
260            choice,
261            manifest: entry,
262            config,
263        })
264    }
265
266    pub fn human(&self) -> String {
267        format!(
268            "Repository: {:?}\nProfile: {}\nSave: {}\n\nChanges the local profile choice only. Files and tools stay in place.",
269            self.repository,
270            self.name,
271            self.choice.label()
272        )
273    }
274
275    pub fn approve(self) -> ProfileApproval {
276        ProfileApproval(self)
277    }
278}
279
280pub struct ProfileApproval(ProfilePreview);
281
282impl ProfileApproval {
283    pub fn execute(self, host: &HostContext) -> Result<()> {
284        let lock = WriterLock::acquire(host)?;
285        let p = self.0;
286        let fresh = ProfilePreview::prepare(host, &p.repository, &p.name, p.choice)?;
287        if !crate::adoption::same(&p.manifest, &fresh.manifest, true)
288            || !crate::adoption::same(&p.config, &fresh.config, true)
289        {
290            return Err(Error::Invalid(
291                "Manifest or profile choices changed. Review again.".into(),
292            ));
293        }
294        let (mut local, config) = LocalConfig::load_bound(host)?;
295        if !same_read(&fresh.config, &config) || fresh.config.sha256 != config.sha256 {
296            return Err(Error::Invalid(
297                "Profile choices changed. Review again.".into(),
298            ));
299        }
300        let id = local
301            .repositories
302            .iter()
303            .find(|(_, r)| r.root == p.repository)
304            .map(|(id, _)| id.clone())
305            .ok_or(Error::NoRepository)?;
306        local
307            .profile_choices
308            .entry(id)
309            .or_default()
310            .insert(p.name, p.choice);
311        local.save(host, &lock)
312    }
313}
314
315/// Foundation APIs only: callers must hold the application lock.
316/// These operations register metadata, never initialise Git or touch live dotfiles.
317pub struct RepositoryRegistry;
318
319impl RepositoryRegistry {
320    pub fn register(host: &HostContext, lock: &WriterLock, root: &Path) -> Result<String> {
321        lock.check_context(host)?;
322        crate::journal::ensure_writable(host)?;
323        let root = inspect_repository(host, root)?;
324        let mut config = LocalConfig::load(host)?;
325        let id = config
326            .repositories
327            .iter()
328            .find(|(_, r)| r.root == root)
329            .map(|(id, _)| id.clone())
330            .unwrap_or_else(|| format!("{:x}", Sha256::digest(root.as_os_str().as_bytes())));
331        config
332            .repositories
333            .insert(id.clone(), RepositoryRecord { root });
334        config.active_repository = Some(id.clone());
335        config.save(host, lock)?;
336        Ok(id)
337    }
338
339    /// Preserve the state ID after a deliberate move. Refuse forks or missing manifests.
340    pub fn relocate(host: &HostContext, lock: &WriterLock, id: &str, root: &Path) -> Result<()> {
341        lock.check_context(host)?;
342        crate::journal::ensure_writable(host)?;
343        let mut config = LocalConfig::load(host)?;
344        let old = config
345            .repositories
346            .get(id)
347            .ok_or_else(|| Error::Invalid("unknown repository ID".into()))?;
348        if old
349            .root
350            .try_exists()
351            .map_err(|e| io_error("inspect previous repository", &old.root, e))?
352        {
353            return Err(Error::Invalid(
354                "old repository still exists; refusing ambiguous relocation".into(),
355            ));
356        }
357        let root = inspect_repository(host, root)?;
358        if config.repositories.values().any(|r| r.root == root) {
359            return Err(Error::Invalid(
360                "new repository root is already registered".into(),
361            ));
362        }
363        config
364            .repositories
365            .insert(id.into(), RepositoryRecord { root });
366        config.save(host, lock)
367    }
368}
369
370pub fn repository_state_path(host: &HostContext, id: &str) -> Result<PathBuf> {
371    validate_repository_id(id)?;
372    Ok(host.state_dir.join("repositories").join(id))
373}
374
375fn validate_repository_id(id: &str) -> Result<()> {
376    if id.len() != 64
377        || !id
378            .bytes()
379            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
380    {
381        return Err(Error::Invalid("invalid local repository ID".into()));
382    }
383    Ok(())
384}
385
386pub(crate) fn registration_text(host: &HostContext, root: &Path) -> Result<(String, String)> {
387    let mut config = LocalConfig::load(host)?;
388    let id = config
389        .repositories
390        .iter()
391        .find(|(_, r)| r.root == root)
392        .map(|(id, _)| id.clone())
393        .unwrap_or_else(|| format!("{:x}", Sha256::digest(root.as_os_str().as_bytes())));
394    config.repositories.insert(
395        id.clone(),
396        RepositoryRecord {
397            root: root.to_owned(),
398        },
399    );
400    config.active_repository = Some(id.clone());
401    config.validate()?;
402    let text = toml::to_string(&config)
403        .map_err(|_| Error::Invalid("cannot encode registration (values redacted)".into()))?;
404    Ok((id, text))
405}
406
407fn inspect_repository(host: &HostContext, root: &Path) -> Result<PathBuf> {
408    let root = root
409        .canonicalize()
410        .map_err(|e| io_error("resolve repository", root, e))?;
411    if root.to_str().is_none() {
412        return Err(Error::Invalid(
413            "non-UTF-8 repository paths cannot be stored in TOML yet".into(),
414        ));
415    }
416    if root == host.home
417        || root.parent().is_none()
418        || root.starts_with(&host.config_dir)
419        || host.config_dir.starts_with(&root)
420        || root.starts_with(&host.state_dir)
421        || host.state_dir.starts_with(&root)
422    {
423        return Err(Error::Invalid(
424            "repository cannot be HOME or filesystem root, or overlap Dort metadata".into(),
425        ));
426    }
427    if !root
428        .join(".git")
429        .try_exists()
430        .map_err(|e| io_error("inspect Git metadata", &root, e))?
431    {
432        return Err(Error::Invalid(
433            "registry requires existing Git metadata; use bootstrap to create a repository".into(),
434        ));
435    }
436    let path = root.join("dort.toml");
437    let text = std::fs::read_to_string(&path)
438        .map_err(|e| io_error("read repository manifest", &path, e))?;
439    Manifest::parse(&text)?;
440    Ok(root)
441}
442
443#[cfg(test)]
444mod tests {
445    use super::same_read;
446    use crate::observation::{Entry, Fingerprint, Kind, Parent};
447
448    fn fingerprint(inode: u64, modified: i64) -> Fingerprint {
449        Fingerprint {
450            device: 1,
451            inode,
452            links: 1,
453            mode: 0o100600,
454            uid: 501,
455            gid: 20,
456            size: 10,
457            modified: (modified, 0),
458            changed: (modified, 0),
459        }
460    }
461
462    fn entry(parent_modified: i64, parent_inode: u64) -> Entry {
463        Entry {
464            path: "/h/.config/dort/local.toml".into(),
465            kind: Kind::Regular,
466            fingerprint: Some(fingerprint(7, 100)),
467            parents: vec![Parent {
468                path: "/h/.config/dort".into(),
469                fingerprint: fingerprint(parent_inode, parent_modified),
470            }],
471            link_target: None,
472            sha256: None,
473            sensitive: true,
474        }
475    }
476
477    #[test]
478    fn unrelated_parent_clock_changes_do_not_invalidate_a_config_read() {
479        assert!(same_read(&entry(100, 3), &entry(999, 3)));
480        assert!(!same_read(&entry(100, 3), &entry(100, 4)));
481        let mut replaced = entry(100, 3);
482        replaced.fingerprint = Some(fingerprint(8, 100));
483        assert!(!same_read(&entry(100, 3), &replaced));
484    }
485}