dort-core 0.3.0

UI-independent planning and guarded filesystem services for Dort
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use crate::{
    Error, Manifest, Result,
    adoption::{parent_identity, same, transaction_id},
    context::HostContext,
    error::io_error,
    journal,
    local::{LocalConfig, repository_state_path},
    model::{FileMode, ManagedFile},
    observation::{self, Entry},
    platform::Platform,
    state::{PrivateDir, WriterLock},
};
use rustix::{fs, process};
use std::{
    collections::BTreeSet,
    path::{Path, PathBuf},
};
use toml_edit::{Array, DocumentMut, Item, Table, Value, value};
mod repair;
use repair::verify_repair_scope;
pub use repair::{RepairDraft, RepairPreview};

#[derive(Debug, Clone)]
pub struct Profile {
    pub name: String,
    pub default: bool,
    pub macos: bool,
    pub linux: bool,
}

impl Profile {
    pub fn from_declaration(profiles: &crate::profiles::Profiles, name: String) -> Self {
        let platform_default = |platform| {
            profiles
                .platform
                .get(&platform)
                .is_some_and(|names| names.contains(&name))
        };
        Self {
            default: profiles.default.contains(&name),
            macos: platform_default(Platform::Macos),
            linux: platform_default(Platform::Linux),
            name,
        }
    }
}

#[derive(Debug, Clone)]
pub enum Change {
    Profile {
        old: Option<String>,
        new: Option<Profile>,
    },
    RenameProfile {
        old: String,
        new: String,
    },
    File(Box<FileChange>),
}

#[derive(Debug, Clone)]
pub struct FileChange {
    pub mapping: ManagedFile,
    pub before: Option<ManagedFile>,
}

pub struct Preview {
    repository: PathBuf,
    backup_root: PathBuf,
    repair_git: Option<Entry>,
    config: Entry,
    manifest: Entry,
    watched_target: Option<Entry>,
    original: Vec<u8>,
    replacement: String,
    description: String,
}

pub struct Approval(Preview);

fn invalid(reason: impl Into<String>) -> Error {
    Error::Invalid(reason.into())
}

fn list(table: &mut Table, key: &str, old: Option<&str>, new: Option<&str>) {
    if let Some(array) = table.get_mut(key).and_then(Item::as_array_mut) {
        if let Some(old) = old {
            array.retain(|item| item.as_str() != Some(old));
        }
        if let Some(new) = new
            && !array.iter().any(|item| item.as_str() == Some(new))
        {
            array.push(new);
        }
    } else if let Some(new) = new {
        let mut array = Array::new();
        array.push(new);
        table.insert(key, value(array));
    }
}

fn edit_profile(doc: &mut DocumentMut, old: Option<&str>, new: Option<&Profile>) -> Result<()> {
    if !doc.contains_key("profiles") {
        doc["profiles"] = Item::Table(Table::new());
    }
    let profiles = &mut doc["profiles"];
    let profiles = profiles
        .as_table_like_mut()
        .ok_or_else(|| invalid("Read the profile list again."))?;
    let name = new.map(|profile| profile.name.as_str());
    let mut defs = Table::new();
    for key in ["available", "default"] {
        if let Some(item) = profiles.remove(key) {
            defs.insert(key, item);
        }
    }
    list(&mut defs, "available", old, name);
    list(
        &mut defs,
        "default",
        old,
        new.filter(|p| p.default).map(|p| p.name.as_str()),
    );
    for (key, item) in defs {
        profiles.insert(&key, item);
    }
    let mut platform = Table::new();
    if let Some(item) = profiles.remove("platform") {
        match item {
            Item::Table(table) => platform = table,
            Item::Value(Value::InlineTable(table)) => platform = table.into_table(),
            _ => return Err(invalid("Read the platform profile list again.")),
        }
    }
    list(
        &mut platform,
        "macos",
        old,
        new.filter(|p| p.macos).map(|p| p.name.as_str()),
    );
    list(
        &mut platform,
        "linux",
        old,
        new.filter(|p| p.linux).map(|p| p.name.as_str()),
    );
    if !platform.is_empty() {
        profiles.insert("platform", Item::Table(platform));
    }
    if let (Some(old), Some(name)) = (old, name)
        && old != name
    {
        for section in ["files", "tools"] {
            if let Some(tables) = doc.get_mut(section).and_then(Item::as_array_of_tables_mut) {
                for table in tables.iter_mut() {
                    if let Some(names) = table.get_mut("profiles").and_then(Item::as_array_mut) {
                        for item in names.iter_mut().filter(|item| item.as_str() == Some(old)) {
                            let decor = item.decor().clone();
                            *item = Value::from(name);
                            *item.decor_mut() = decor;
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

fn edit_file(doc: &mut DocumentMut, manifest: &Manifest, file: &ManagedFile) -> Result<()> {
    let fields: DocumentMut = toml::to_string(file)
        .map_err(|_| invalid("Cannot encode this file mapping."))?
        .parse()
        .map_err(|_| invalid("Cannot save this file mapping."))?;
    if let Some((index, before)) = manifest
        .files
        .iter()
        .enumerate()
        .find(|(_, entry)| entry.id == file.id)
    {
        let existing = doc["files"]
            .as_array_of_tables_mut()
            .and_then(|files| files.get_mut(index))
            .ok_or_else(|| invalid("Use an array of file tables to edit this mapping."))?;
        for (key, changed) in [
            ("source", before.source != file.source),
            ("target", before.target != file.target),
            ("profiles", before.profiles != file.profiles),
            ("requires", before.requires != file.requires),
            ("overrides", before.overrides != file.overrides),
        ] {
            if changed && let Some(field) = fields.get(key) {
                let field = field
                    .clone()
                    .into_value()
                    .map_err(|_| invalid("Could not prepare the file mapping."))?;
                existing.insert(key, Item::Value(field));
            } else if changed {
                existing.remove(key);
            }
        }
    } else {
        if !doc.contains_key("files") {
            doc["files"] = Item::ArrayOfTables(toml_edit::ArrayOfTables::new());
        }
        doc["files"]
            .as_array_of_tables_mut()
            .ok_or_else(|| invalid("Use an array of file tables to add a mapping."))?
            .push(fields.into_table());
    }
    Ok(())
}

fn same_entry(before: &Entry, after: &Entry) -> bool {
    same(before, after, true)
        && before.parents.len() == after.parents.len()
        && before
            .parents
            .iter()
            .zip(&after.parents)
            .all(|(a, b)| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
}

impl Preview {
    pub fn prepare(host: &HostContext, repository: &Path, change: &Change) -> Result<Self> {
        let (local, config) = LocalConfig::load_bound(host)?;
        let repository_id = local
            .repositories
            .iter()
            .find(|(_, r)| r.root == repository)
            .map(|(id, _)| id.clone())
            .ok_or_else(|| invalid("Choose a registered repository."))?;
        let path = repository.join("dort.toml");
        let (manifest, entry) = observation::read_manifest(&path)?;
        let original = crate::adoption::checked_bytes(&entry)?;
        let text =
            std::str::from_utf8(&original).map_err(|_| invalid("Manifest must be UTF-8."))?;
        let mut doc: DocumentMut = text
            .parse()
            .map_err(|_| invalid("Invalid manifest. Contents withheld."))?;
        let mut watched_target = None;
        let description = match change {
            Change::Profile { .. } | Change::RenameProfile { .. } => {
                let renamed;
                let (old, new) = match change {
                    Change::Profile { old, new } => (old.as_deref(), new.as_ref()),
                    Change::RenameProfile { old, new } => {
                        if old == new {
                            return Err(invalid("Enter a different profile name."));
                        }
                        renamed = Profile {
                            name: new.clone(),
                            ..Profile::from_declaration(&manifest.profiles, old.clone())
                        };
                        (Some(old.as_str()), Some(&renamed))
                    }
                    _ => unreachable!(),
                };
                let names = manifest.profiles.known();
                if old.is_none() && new.is_none()
                    || old == Some("base")
                    || new.is_some_and(|p| p.name == "base")
                {
                    return Err(invalid("Base is always on and cannot be changed."));
                }
                if old.is_some_and(|name| !names.contains(name)) {
                    return Err(invalid("Select an existing profile."));
                }
                if new.is_some_and(|p| Some(p.name.as_str()) != old && names.contains(&p.name)) {
                    return Err(invalid("That profile already exists."));
                }
                if let Some(name) = old.filter(|name| new.is_none_or(|next| next.name != *name)) {
                    if local.active_profiles.iter().any(|p| p == name) {
                        return Err(invalid(
                            "Clear the old profile from legacy local settings first.",
                        ));
                    }
                    if new.is_none() {
                        let used_by: BTreeSet<_> = manifest
                            .files
                            .iter()
                            .map(|f| (&f.id, &f.profiles))
                            .chain(manifest.tools.iter().map(|t| (&t.id, &t.profiles)))
                            .filter(|(_, profiles)| profiles.iter().any(|p| p == name))
                            .map(|(id, _)| id.as_str())
                            .collect();
                        if !used_by.is_empty() {
                            return Err(invalid(format!(
                                "Change the profile on these files and tools first: {}.",
                                used_by.into_iter().collect::<Vec<_>>().join(", ")
                            )));
                        }
                    }
                }
                edit_profile(&mut doc, old, new)?;
                (match (old, new) {
                    (None, Some(p)) => format!("Create profile {:?}.", p.name),
                    (Some(old), Some(p)) if old != p.name => format!(
                        "Rename {old:?} to {:?} in the manifest and its files and tools. Set the saved choice for the new name separately.",
                        p.name
                    ),
                    (Some(old), Some(_)) => {
                        format!("Change the repository and OS defaults for {old:?}.")
                    }
                    (Some(old), None) => format!("Delete profile {old:?}."),
                    _ => unreachable!(),
                }) + &new
                    .map(|p| {
                        format!(
                            "\nRepository default: {}\nmacOS default: {}\nLinux default: {}",
                            p.default, p.macos, p.linux
                        )
                    })
                    .unwrap_or_default()
            }
            Change::File(change) => {
                let FileChange {
                    mapping: file,
                    before,
                } = change.as_ref();
                if file.mode != FileMode::Link {
                    return Err(invalid("Only link mappings can be edited here."));
                }
                let previous = manifest
                    .files
                    .iter()
                    .find(|existing| existing.id == file.id);
                match (before.is_some(), previous) {
                    (false, Some(_)) => {
                        return Err(invalid(
                            "That mapping ID already exists. Select it and choose Edit file mapping.",
                        ));
                    }
                    (true, None) => {
                        return Err(invalid(
                            "That mapping no longer exists. Refresh and select it again.",
                        ));
                    }
                    _ => (),
                }
                if before.as_ref() != previous {
                    return Err(invalid("That mapping changed. Refresh and edit it again."));
                }
                if let Some(previous) = previous {
                    if previous.mode != FileMode::Link {
                        return Err(invalid("Only link mappings can be edited here."));
                    }
                    let source = |m: &ManagedFile| {
                        repository.join(m.overrides.get(&host.platform).unwrap_or(&m.source))
                    };
                    let target = host.target_path(&previous.target, Some(repository))?;
                    if previous.target != file.target || source(previous) != source(file) {
                        let before = observation::inspect(&target, false)?;
                        if observation::link_path(&before).as_ref() == Some(&source(previous)) {
                            return Err(invalid(
                                "Keep the current managed file before changing its source or destination. Then add the mapping again.",
                            ));
                        }
                        watched_target = Some(before);
                    }
                }
                if previous != Some(file) {
                    edit_file(&mut doc, &manifest, file)?;
                }
                let override_path = |p: Platform| {
                    file.overrides
                        .get(&p)
                        .map_or_else(|| "Use source".into(), |p| format!("{p:?}"))
                };
                format!(
                    "Save file mapping {:?}.\nSource: {:?}\nHome destination: {:?}\nProfiles: {}\nRequires: {}\nmacOS source: {}\nLinux source: {}",
                    file.id,
                    file.source,
                    file.target,
                    file.profiles.join(", "),
                    if file.requires.is_empty() {
                        "None".into()
                    } else {
                        file.requires.join(", ")
                    },
                    override_path(Platform::Macos),
                    override_path(Platform::Linux)
                )
            }
        };
        let replacement = if matches!(change, Change::File(change) if change.before.as_ref() == Some(&change.mapping))
        {
            text.to_owned()
        } else {
            doc.to_string()
        };
        let parsed = Manifest::parse(&replacement).map_err(|error| match error {
            Error::Parse(_) => invalid("Cannot save an invalid manifest."),
            error => error,
        })?;
        parsed.validate_file_targets(host, &parsed.profiles.known(), Some(repository), None)?;
        Ok(Self {
            repository: repository.to_owned(),
            backup_root: repository_state_path(host, &repository_id)?.join("manifest-edits"),
            repair_git: None,
            config,
            manifest: entry,
            watched_target,
            original,
            replacement,
            description,
        })
    }

    pub fn unchanged(&self) -> bool {
        self.original == self.replacement.as_bytes()
    }

    pub fn human(&self) -> String {
        format!(
            "Repository: {:?}\n\n{}\n\nUpdate dort.toml only. Home files and packages stay in place. The previous manifest is backed up privately.",
            self.repository, self.description
        )
    }

    pub fn approve(self) -> Approval {
        Approval(self)
    }
}

impl Approval {
    pub fn execute(self, host: &HostContext) -> Result<Option<PathBuf>> {
        let p = self.0;
        let lock = WriterLock::acquire(host)?;
        lock.check_context(host)?;
        journal::ensure_writable(host)?;
        let path = &p.manifest.path;
        let compare = || -> Result<()> {
            let config = match &p.repair_git {
                Some(git) => verify_repair_scope(host, &p.repository, git)?,
                None => LocalConfig::load_bound(host)?.1,
            };
            if !same_entry(&p.config, &config) {
                return Err(invalid("Repository settings changed. Review again."));
            }
            let (_, current) = observation::read_manifest_bytes(path)?;
            if !same_entry(&p.manifest, &current) {
                return Err(invalid("Manifest changed. Review again."));
            }
            if let Some(before) = &p.watched_target
                && !same_entry(before, &observation::inspect(&before.path, false)?)
            {
                return Err(invalid("The Home destination changed. Review again."));
            }
            Ok(())
        };
        compare()?;
        if p.original == p.replacement.as_bytes() {
            return Ok(None);
        }
        let handle = observation::parent_handle(path)?;
        let fingerprint = p.manifest.fingerprint.as_ref().filter(|f| f.links == 1 && f.uid == process::geteuid().as_raw() && f.mode & 0o7000 == 0)
            .ok_or_else(|| invalid("The manifest must be an owned regular file without hard links or special permissions."))?;
        let parent = fs::fstat(&handle.directory)
            .map_err(|e| io_error("inspect manifest parent", path, e))?;
        if parent.st_uid != process::geteuid().as_raw() || parent.st_mode & 0o022 != 0 {
            return Err(invalid(
                "The repository folder must be owned and not group/world writable.",
            ));
        }
        let backup_path = p.backup_root.join(transaction_id());
        let backup = PrivateDir::open(&backup_path, true)?.expect("created backup directory");
        let device = fs::fstat(&backup.file)
            .map_err(|e| io_error("inspect backup device", &backup_path, e))?
            .st_dev;
        if fingerprint.device != device as u64 {
            return Err(invalid(
                "Manifest and Dort state must be on the same filesystem.",
            ));
        }
        backup.create("before.toml", &p.original)?;
        backup.create("replacement.toml", p.replacement.as_bytes())?;
        let file = std::fs::File::from(
            fs::openat(
                &backup.file,
                "replacement.toml",
                fs::OFlags::RDONLY | fs::OFlags::NOFOLLOW,
                fs::Mode::empty(),
            )
            .map_err(|e| io_error("open replacement", &backup_path, e))?,
        );
        fs::fchown(&file, None, Some(process::Gid::from_raw(fingerprint.gid)))
            .map_err(|e| io_error("preserve manifest group", path, e))?;
        fs::fchmod(
            &file,
            fs::Mode::from_bits_truncate((fingerprint.mode & 0o777) as _),
        )
        .map_err(|e| io_error("preserve manifest permissions", path, e))?;
        file.sync_all()
            .map_err(|e| io_error("sync replacement", path, e))?;
        compare()?;
        if handle.parents.len() != p.manifest.parents.len()
            || !handle
                .parents
                .iter()
                .zip(&p.manifest.parents)
                .all(|(a, b)| a.path == b.path && parent_identity(&a.fingerprint, &b.fingerprint))
        {
            return Err(invalid("Repository folder changed. Review again."));
        }
        fs::renameat_with(
            &backup.file,
            "replacement.toml",
            &handle.directory,
            &handle.name,
            fs::RenameFlags::EXCHANGE,
        )
        .map_err(|e| io_error("replace manifest", path, e))?;
        fs::renameat(
            &backup.file,
            "replacement.toml",
            &backup.file,
            "previous-entry.toml",
        )
        .map_err(|e| io_error("keep previous manifest", &backup_path, e))?;
        handle
            .directory
            .sync_all()
            .map_err(|e| io_error("sync manifest folder", path, e))?;
        backup.sync()?;
        Ok(Some(backup_path.join("before.toml")))
    }
}