Skip to main content

dort_core/
manifest_edit.rs

1use crate::{
2    Error, Manifest, Result,
3    adoption::{parent_identity, same, transaction_id},
4    context::HostContext,
5    error::io_error,
6    journal,
7    local::{LocalConfig, repository_state_path},
8    model::{FileMode, ManagedFile},
9    observation::{self, Entry},
10    platform::Platform,
11    state::{PrivateDir, WriterLock},
12};
13use rustix::{fs, process};
14use std::{
15    collections::BTreeSet,
16    path::{Path, PathBuf},
17};
18use toml_edit::{Array, DocumentMut, Item, Table, Value, value};
19mod repair;
20use repair::verify_repair_scope;
21pub use repair::{RepairDraft, RepairPreview};
22
23#[derive(Debug, Clone)]
24pub struct Profile {
25    pub name: String,
26    pub default: bool,
27    pub macos: bool,
28    pub linux: bool,
29}
30
31impl Profile {
32    pub fn from_declaration(profiles: &crate::profiles::Profiles, name: String) -> Self {
33        let platform_default = |platform| {
34            profiles
35                .platform
36                .get(&platform)
37                .is_some_and(|names| names.contains(&name))
38        };
39        Self {
40            default: profiles.default.contains(&name),
41            macos: platform_default(Platform::Macos),
42            linux: platform_default(Platform::Linux),
43            name,
44        }
45    }
46}
47
48#[derive(Debug, Clone)]
49pub enum Change {
50    Profile {
51        old: Option<String>,
52        new: Option<Profile>,
53    },
54    RenameProfile {
55        old: String,
56        new: String,
57    },
58    File(Box<FileChange>),
59}
60
61#[derive(Debug, Clone)]
62pub struct FileChange {
63    pub mapping: ManagedFile,
64    pub before: Option<ManagedFile>,
65}
66
67pub struct Preview {
68    repository: PathBuf,
69    backup_root: PathBuf,
70    repair_git: Option<Entry>,
71    config: Entry,
72    manifest: Entry,
73    watched_target: Option<Entry>,
74    original: Vec<u8>,
75    replacement: String,
76    description: String,
77}
78
79pub struct Approval(Preview);
80
81fn invalid(reason: impl Into<String>) -> Error {
82    Error::Invalid(reason.into())
83}
84
85fn list(table: &mut Table, key: &str, old: Option<&str>, new: Option<&str>) {
86    if let Some(array) = table.get_mut(key).and_then(Item::as_array_mut) {
87        if let Some(old) = old {
88            array.retain(|item| item.as_str() != Some(old));
89        }
90        if let Some(new) = new
91            && !array.iter().any(|item| item.as_str() == Some(new))
92        {
93            array.push(new);
94        }
95    } else if let Some(new) = new {
96        let mut array = Array::new();
97        array.push(new);
98        table.insert(key, value(array));
99    }
100}
101
102fn edit_profile(doc: &mut DocumentMut, old: Option<&str>, new: Option<&Profile>) -> Result<()> {
103    if !doc.contains_key("profiles") {
104        doc["profiles"] = Item::Table(Table::new());
105    }
106    let profiles = &mut doc["profiles"];
107    let profiles = profiles
108        .as_table_like_mut()
109        .ok_or_else(|| invalid("Read the profile list again."))?;
110    let name = new.map(|profile| profile.name.as_str());
111    let mut defs = Table::new();
112    for key in ["available", "default"] {
113        if let Some(item) = profiles.remove(key) {
114            defs.insert(key, item);
115        }
116    }
117    list(&mut defs, "available", old, name);
118    list(
119        &mut defs,
120        "default",
121        old,
122        new.filter(|p| p.default).map(|p| p.name.as_str()),
123    );
124    for (key, item) in defs {
125        profiles.insert(&key, item);
126    }
127    let mut platform = Table::new();
128    if let Some(item) = profiles.remove("platform") {
129        match item {
130            Item::Table(table) => platform = table,
131            Item::Value(Value::InlineTable(table)) => platform = table.into_table(),
132            _ => return Err(invalid("Read the platform profile list again.")),
133        }
134    }
135    list(
136        &mut platform,
137        "macos",
138        old,
139        new.filter(|p| p.macos).map(|p| p.name.as_str()),
140    );
141    list(
142        &mut platform,
143        "linux",
144        old,
145        new.filter(|p| p.linux).map(|p| p.name.as_str()),
146    );
147    if !platform.is_empty() {
148        profiles.insert("platform", Item::Table(platform));
149    }
150    if let (Some(old), Some(name)) = (old, name)
151        && old != name
152    {
153        for section in ["files", "tools"] {
154            if let Some(tables) = doc.get_mut(section).and_then(Item::as_array_of_tables_mut) {
155                for table in tables.iter_mut() {
156                    if let Some(names) = table.get_mut("profiles").and_then(Item::as_array_mut) {
157                        for item in names.iter_mut().filter(|item| item.as_str() == Some(old)) {
158                            let decor = item.decor().clone();
159                            *item = Value::from(name);
160                            *item.decor_mut() = decor;
161                        }
162                    }
163                }
164            }
165        }
166    }
167    Ok(())
168}
169
170fn edit_file(doc: &mut DocumentMut, manifest: &Manifest, file: &ManagedFile) -> Result<()> {
171    let fields: DocumentMut = toml::to_string(file)
172        .map_err(|_| invalid("Cannot encode this file mapping."))?
173        .parse()
174        .map_err(|_| invalid("Cannot save this file mapping."))?;
175    if let Some((index, before)) = manifest
176        .files
177        .iter()
178        .enumerate()
179        .find(|(_, entry)| entry.id == file.id)
180    {
181        let existing = doc["files"]
182            .as_array_of_tables_mut()
183            .and_then(|files| files.get_mut(index))
184            .ok_or_else(|| invalid("Use an array of file tables to edit this mapping."))?;
185        for (key, changed) in [
186            ("source", before.source != file.source),
187            ("target", before.target != file.target),
188            ("profiles", before.profiles != file.profiles),
189            ("requires", before.requires != file.requires),
190            ("overrides", before.overrides != file.overrides),
191        ] {
192            if changed && let Some(field) = fields.get(key) {
193                let field = field
194                    .clone()
195                    .into_value()
196                    .map_err(|_| invalid("Could not prepare the file mapping."))?;
197                existing.insert(key, Item::Value(field));
198            } else if changed {
199                existing.remove(key);
200            }
201        }
202    } else {
203        if !doc.contains_key("files") {
204            doc["files"] = Item::ArrayOfTables(toml_edit::ArrayOfTables::new());
205        }
206        doc["files"]
207            .as_array_of_tables_mut()
208            .ok_or_else(|| invalid("Use an array of file tables to add a mapping."))?
209            .push(fields.into_table());
210    }
211    Ok(())
212}
213
214fn same_entry(before: &Entry, after: &Entry) -> bool {
215    same(before, after, true)
216        && before.parents.len() == after.parents.len()
217        && before
218            .parents
219            .iter()
220            .zip(&after.parents)
221            .all(|(a, b)| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
222}
223
224impl Preview {
225    pub fn prepare(host: &HostContext, repository: &Path, change: &Change) -> Result<Self> {
226        let (local, config) = LocalConfig::load_bound(host)?;
227        let repository_id = local
228            .repositories
229            .iter()
230            .find(|(_, r)| r.root == repository)
231            .map(|(id, _)| id.clone())
232            .ok_or_else(|| invalid("Choose a registered repository."))?;
233        let path = repository.join("dort.toml");
234        let (manifest, entry) = observation::read_manifest(&path)?;
235        let original = crate::adoption::checked_bytes(&entry)?;
236        let text =
237            std::str::from_utf8(&original).map_err(|_| invalid("Manifest must be UTF-8."))?;
238        let mut doc: DocumentMut = text
239            .parse()
240            .map_err(|_| invalid("Invalid manifest. Contents withheld."))?;
241        let mut watched_target = None;
242        let description = match change {
243            Change::Profile { .. } | Change::RenameProfile { .. } => {
244                let renamed;
245                let (old, new) = match change {
246                    Change::Profile { old, new } => (old.as_deref(), new.as_ref()),
247                    Change::RenameProfile { old, new } => {
248                        if old == new {
249                            return Err(invalid("Enter a different profile name."));
250                        }
251                        renamed = Profile {
252                            name: new.clone(),
253                            ..Profile::from_declaration(&manifest.profiles, old.clone())
254                        };
255                        (Some(old.as_str()), Some(&renamed))
256                    }
257                    _ => unreachable!(),
258                };
259                let names = manifest.profiles.known();
260                if old.is_none() && new.is_none()
261                    || old == Some("base")
262                    || new.is_some_and(|p| p.name == "base")
263                {
264                    return Err(invalid("Base is always on and cannot be changed."));
265                }
266                if old.is_some_and(|name| !names.contains(name)) {
267                    return Err(invalid("Select an existing profile."));
268                }
269                if new.is_some_and(|p| Some(p.name.as_str()) != old && names.contains(&p.name)) {
270                    return Err(invalid("That profile already exists."));
271                }
272                if let Some(name) = old.filter(|name| new.is_none_or(|next| next.name != *name)) {
273                    if local.active_profiles.iter().any(|p| p == name) {
274                        return Err(invalid(
275                            "Clear the old profile from legacy local settings first.",
276                        ));
277                    }
278                    if new.is_none() {
279                        let used_by: BTreeSet<_> = manifest
280                            .files
281                            .iter()
282                            .map(|f| (&f.id, &f.profiles))
283                            .chain(manifest.tools.iter().map(|t| (&t.id, &t.profiles)))
284                            .filter(|(_, profiles)| profiles.iter().any(|p| p == name))
285                            .map(|(id, _)| id.as_str())
286                            .collect();
287                        if !used_by.is_empty() {
288                            return Err(invalid(format!(
289                                "Change the profile on these files and tools first: {}.",
290                                used_by.into_iter().collect::<Vec<_>>().join(", ")
291                            )));
292                        }
293                    }
294                }
295                edit_profile(&mut doc, old, new)?;
296                (match (old, new) {
297                    (None, Some(p)) => format!("Create profile {:?}.", p.name),
298                    (Some(old), Some(p)) if old != p.name => format!(
299                        "Rename {old:?} to {:?} in the manifest and its files and tools. Set the saved choice for the new name separately.",
300                        p.name
301                    ),
302                    (Some(old), Some(_)) => {
303                        format!("Change the repository and OS defaults for {old:?}.")
304                    }
305                    (Some(old), None) => format!("Delete profile {old:?}."),
306                    _ => unreachable!(),
307                }) + &new
308                    .map(|p| {
309                        format!(
310                            "\nRepository default: {}\nmacOS default: {}\nLinux default: {}",
311                            p.default, p.macos, p.linux
312                        )
313                    })
314                    .unwrap_or_default()
315            }
316            Change::File(change) => {
317                let FileChange {
318                    mapping: file,
319                    before,
320                } = change.as_ref();
321                if file.mode != FileMode::Link {
322                    return Err(invalid("Only link mappings can be edited here."));
323                }
324                let previous = manifest
325                    .files
326                    .iter()
327                    .find(|existing| existing.id == file.id);
328                match (before.is_some(), previous) {
329                    (false, Some(_)) => {
330                        return Err(invalid(
331                            "That mapping ID already exists. Select it and choose Edit file mapping.",
332                        ));
333                    }
334                    (true, None) => {
335                        return Err(invalid(
336                            "That mapping no longer exists. Refresh and select it again.",
337                        ));
338                    }
339                    _ => (),
340                }
341                if before.as_ref() != previous {
342                    return Err(invalid("That mapping changed. Refresh and edit it again."));
343                }
344                if let Some(previous) = previous {
345                    if previous.mode != FileMode::Link {
346                        return Err(invalid("Only link mappings can be edited here."));
347                    }
348                    let source = |m: &ManagedFile| {
349                        repository.join(m.overrides.get(&host.platform).unwrap_or(&m.source))
350                    };
351                    let target = host.target_path(&previous.target, Some(repository))?;
352                    if previous.target != file.target || source(previous) != source(file) {
353                        let before = observation::inspect(&target, false)?;
354                        if observation::link_path(&before).as_ref() == Some(&source(previous)) {
355                            return Err(invalid(
356                                "Keep the current managed file before changing its source or destination. Then add the mapping again.",
357                            ));
358                        }
359                        watched_target = Some(before);
360                    }
361                }
362                if previous != Some(file) {
363                    edit_file(&mut doc, &manifest, file)?;
364                }
365                let override_path = |p: Platform| {
366                    file.overrides
367                        .get(&p)
368                        .map_or_else(|| "Use source".into(), |p| format!("{p:?}"))
369                };
370                format!(
371                    "Save file mapping {:?}.\nSource: {:?}\nHome destination: {:?}\nProfiles: {}\nRequires: {}\nmacOS source: {}\nLinux source: {}",
372                    file.id,
373                    file.source,
374                    file.target,
375                    file.profiles.join(", "),
376                    if file.requires.is_empty() {
377                        "None".into()
378                    } else {
379                        file.requires.join(", ")
380                    },
381                    override_path(Platform::Macos),
382                    override_path(Platform::Linux)
383                )
384            }
385        };
386        let replacement = if matches!(change, Change::File(change) if change.before.as_ref() == Some(&change.mapping))
387        {
388            text.to_owned()
389        } else {
390            doc.to_string()
391        };
392        let parsed = Manifest::parse(&replacement).map_err(|error| match error {
393            Error::Parse(_) => invalid("Cannot save an invalid manifest."),
394            error => error,
395        })?;
396        parsed.validate_file_targets(host, &parsed.profiles.known(), Some(repository), None)?;
397        Ok(Self {
398            repository: repository.to_owned(),
399            backup_root: repository_state_path(host, &repository_id)?.join("manifest-edits"),
400            repair_git: None,
401            config,
402            manifest: entry,
403            watched_target,
404            original,
405            replacement,
406            description,
407        })
408    }
409
410    pub fn unchanged(&self) -> bool {
411        self.original == self.replacement.as_bytes()
412    }
413
414    pub fn human(&self) -> String {
415        format!(
416            "Repository: {:?}\n\n{}\n\nUpdate dort.toml only. Home files and packages stay in place. The previous manifest is backed up privately.",
417            self.repository, self.description
418        )
419    }
420
421    pub fn approve(self) -> Approval {
422        Approval(self)
423    }
424}
425
426impl Approval {
427    pub fn execute(self, host: &HostContext) -> Result<Option<PathBuf>> {
428        let p = self.0;
429        let lock = WriterLock::acquire(host)?;
430        lock.check_context(host)?;
431        journal::ensure_writable(host)?;
432        let path = &p.manifest.path;
433        let compare = || -> Result<()> {
434            let config = match &p.repair_git {
435                Some(git) => verify_repair_scope(host, &p.repository, git)?,
436                None => LocalConfig::load_bound(host)?.1,
437            };
438            if !same_entry(&p.config, &config) {
439                return Err(invalid("Repository settings changed. Review again."));
440            }
441            let (_, current) = observation::read_manifest_bytes(path)?;
442            if !same_entry(&p.manifest, &current) {
443                return Err(invalid("Manifest changed. Review again."));
444            }
445            if let Some(before) = &p.watched_target
446                && !same_entry(before, &observation::inspect(&before.path, false)?)
447            {
448                return Err(invalid("The Home destination changed. Review again."));
449            }
450            Ok(())
451        };
452        compare()?;
453        if p.original == p.replacement.as_bytes() {
454            return Ok(None);
455        }
456        let handle = observation::parent_handle(path)?;
457        let fingerprint = p.manifest.fingerprint.as_ref().filter(|f| f.links == 1 && f.uid == process::geteuid().as_raw() && f.mode & 0o7000 == 0)
458            .ok_or_else(|| invalid("The manifest must be an owned regular file without hard links or special permissions."))?;
459        let parent = fs::fstat(&handle.directory)
460            .map_err(|e| io_error("inspect manifest parent", path, e))?;
461        if parent.st_uid != process::geteuid().as_raw() || parent.st_mode & 0o022 != 0 {
462            return Err(invalid(
463                "The repository folder must be owned and not group/world writable.",
464            ));
465        }
466        let backup_path = p.backup_root.join(transaction_id());
467        let backup = PrivateDir::open(&backup_path, true)?.expect("created backup directory");
468        let device = fs::fstat(&backup.file)
469            .map_err(|e| io_error("inspect backup device", &backup_path, e))?
470            .st_dev;
471        if fingerprint.device != device as u64 {
472            return Err(invalid(
473                "Manifest and Dort state must be on the same filesystem.",
474            ));
475        }
476        backup.create("before.toml", &p.original)?;
477        backup.create("replacement.toml", p.replacement.as_bytes())?;
478        let file = std::fs::File::from(
479            fs::openat(
480                &backup.file,
481                "replacement.toml",
482                fs::OFlags::RDONLY | fs::OFlags::NOFOLLOW,
483                fs::Mode::empty(),
484            )
485            .map_err(|e| io_error("open replacement", &backup_path, e))?,
486        );
487        fs::fchown(&file, None, Some(process::Gid::from_raw(fingerprint.gid)))
488            .map_err(|e| io_error("preserve manifest group", path, e))?;
489        fs::fchmod(
490            &file,
491            fs::Mode::from_bits_truncate((fingerprint.mode & 0o777) as _),
492        )
493        .map_err(|e| io_error("preserve manifest permissions", path, e))?;
494        file.sync_all()
495            .map_err(|e| io_error("sync replacement", path, e))?;
496        compare()?;
497        if handle.parents.len() != p.manifest.parents.len()
498            || !handle
499                .parents
500                .iter()
501                .zip(&p.manifest.parents)
502                .all(|(a, b)| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
503        {
504            return Err(invalid("Repository folder changed. Review again."));
505        }
506        fs::renameat_with(
507            &backup.file,
508            "replacement.toml",
509            &handle.directory,
510            &handle.name,
511            fs::RenameFlags::EXCHANGE,
512        )
513        .map_err(|e| io_error("replace manifest", path, e))?;
514        fs::renameat(
515            &backup.file,
516            "replacement.toml",
517            &backup.file,
518            "previous-entry.toml",
519        )
520        .map_err(|e| io_error("keep previous manifest", &backup_path, e))?;
521        handle
522            .directory
523            .sync_all()
524            .map_err(|e| io_error("sync manifest folder", path, e))?;
525        backup.sync()?;
526        Ok(Some(backup_path.join("before.toml")))
527    }
528}