d2-rs 0.1.7

The d2-rs command-line tool, a Rust port of D2's d2cli package.
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
// SPDX-License-Identifier: MPL-2.0
//! d2cli/board_output_publish.go: prepare all backups, apply, then roll back
//! the applied journal in reverse on any failure. The manifest is installed last.
use super::*;
use d2_rs_core::stable_sort::StableSort;
use root::Info;
use root::Root;

struct Change {
    rel: PathBuf,
    source: Option<PathBuf>,
    expected_digest: Option<String>,
    original: Option<Info>,
    backup: Option<PathBuf>,
    skip: bool,
    installed: Option<Info>,
}
impl Change {
    fn new(rel: PathBuf, source: Option<PathBuf>, expected_digest: Option<String>) -> Self {
        Self {
            rel,
            source,
            expected_digest,
            original: None,
            backup: None,
            skip: false,
            installed: None,
        }
    }
}

pub(super) struct Transaction<'a> {
    workspace: &'a mut BoardOutputWorkspace,
    root: Root,
    changes: Vec<Change>,
    applied: Vec<usize>,
    created_dirs: Vec<PathBuf>,
    removed_dirs: Vec<(PathBuf, u32)>,
}

fn digest(bytes: &[u8]) -> String {
    hex(ring::digest::digest(&ring::digest::SHA256, bytes).as_ref())
}
pub(super) fn same_file(first: &Info, second: &Info) -> bool {
    first.same_file(second)
}

impl<'a> Transaction<'a> {
    pub(super) fn new(workspace: &'a mut BoardOutputWorkspace, root: Root) -> Self {
        Self {
            workspace,
            root,
            changes: Vec::new(),
            applied: Vec::new(),
            created_dirs: Vec::new(),
            removed_dirs: Vec::new(),
        }
    }
    pub(super) fn publish(
        mut self,
        directories: &[PathBuf],
        files: &[PathBuf],
        previous: &Manifest,
        current: &Manifest,
    ) -> Result<bool, String> {
        if let Err(error) = self.apply(directories, files, previous, current) {
            return match self.rollback() {
                Ok(()) => {
                    self.workspace.visible_mutation = false;
                    Err(error)
                }
                Err(rollback_error) => Err(format!("{error}\n{rollback_error}")),
            };
        }
        Ok(self.workspace.visible_mutation)
    }
    fn equivalent(&self, previous: &str, current: &str) -> bool {
        previous == current
            || matches!((self.root.metadata(Path::new(previous)), self.root.metadata(Path::new(current))), (Ok(first), Ok(second)) if same_file(&first, &second))
    }
    fn apply(
        &mut self,
        directories: &[PathBuf],
        files: &[PathBuf],
        previous: &Manifest,
        current: &Manifest,
    ) -> Result<(), String> {
        let stage = self.workspace.stage_root().to_path_buf();
        self.changes.extend(
            files
                .iter()
                .map(|rel| Change::new(rel.clone(), Some(stage.join(rel)), None)),
        );
        let current_files = current
            .files
            .iter()
            .map(|(path, _)| (collision_key(Path::new(path)), path.as_str()))
            .collect::<BTreeMap<_, _>>();
        for (path, expected) in &previous.files {
            if current_files
                .get(&collision_key(Path::new(path)))
                .is_some_and(|new| self.equivalent(path, new))
            {
                continue;
            }
            let rel = Path::new(path);
            match self.root.kind(rel) {
                Ok(0x8000) => {}
                Ok(_) => continue,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error.to_string()),
            }
            let info = self.root.metadata(rel).map_err(|error| error.to_string())?;
            let bytes = self
                .root
                .read(rel, &info)
                .map_err(|error| format!("hash prior board output {}: {error}", quote(rel)))?;
            if digest(&bytes) == expected.to_lowercase() {
                self.changes.push(Change::new(
                    rel.to_owned(),
                    None,
                    Some(expected.to_lowercase()),
                ));
            }
        }
        self.changes.push(Change::new(
            PathBuf::from(BOARD_OUTPUT_MANIFEST_NAME),
            Some(stage.join(BOARD_OUTPUT_MANIFEST_NAME)),
            None,
        ));
        self.prepare_backups()?;
        for rel in directories {
            match self.root.kind(rel) {
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                    self.workspace.before_mutation(rel)?;
                    let permissions = mode(
                        &std::fs::metadata(stage.join(rel)).map_err(|error| error.to_string())?,
                    );
                    self.root.mkdir(rel, permissions).map_err(|error| {
                        format!(
                            "create board output directory {}: mkdirat {}: {}",
                            self.root.display(rel),
                            rel.display(),
                            go_io_error(&error)
                        )
                    })?;
                    self.created_dirs.push(rel.clone());
                    self.workspace.visible_mutation = true;
                }
                Err(error) => return Err(error.to_string()),
                Ok(0x4000) => {}
                Ok(_) => {
                    return Err(format!(
                        "board output directory {} is not a real directory",
                        self.root.display(rel)
                    ));
                }
            }
        }
        let manifest_index = self.changes.len() - 1;
        for index in 0..manifest_index {
            self.apply_change(index)?;
        }
        self.remove_stale_directories(previous, current)?;
        self.apply_change(manifest_index)
    }
    fn prepare_backups(&mut self) -> Result<(), String> {
        let mut random = [0u8; 16];
        ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut random)
            .map_err(|_| "generate board output rollback directory name".to_owned())?;
        let backup_root = self
            .workspace
            .stage_root()
            .join(format!(".d2-board-rollback-{}", hex(&random)));
        let mut backup_created = false;
        for (index, change) in self.changes.iter_mut().enumerate() {
            match self.root.kind(&change.rel) {
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error.to_string()),
                Ok(0x8000) => {}
                Ok(_) => {
                    return Err(format!(
                        "board output path {} is not a regular file",
                        self.root.display(&change.rel)
                    ));
                }
            }
            let info = self
                .root
                .metadata(&change.rel)
                .map_err(|error| error.to_string())?;
            if !backup_created {
                create_private_dir(&backup_root)
                    .map_err(|error| format!("create board output rollback directory: {error}"))?;
                backup_created = true;
            }
            let backup = backup_root.join(format!("{index:06}"));
            let bytes = self.root.read(&change.rel, &info).map_err(|error| {
                format!(
                    "back up board output {}: {error}",
                    self.root.display(&change.rel)
                )
            })?;
            // Exclusive backup with original permissions, never a hard link.
            let mut backup_file = std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&backup)
                .map_err(|error| error.to_string())?;
            use std::io::Write;
            backup_file
                .write_all(&bytes)
                .map_err(|error| error.to_string())?;
            set_file_mode(&backup_file, mode(&info)).map_err(|error| error.to_string())?;
            if change
                .expected_digest
                .as_ref()
                .is_some_and(|expected| digest(&bytes) != *expected)
            {
                change.skip = true;
            }
            change.backup = Some(backup);
            change.original = Some(info);
        }
        Ok(())
    }
    fn apply_change(&mut self, index: usize) -> Result<(), String> {
        let change = &mut self.changes[index];
        if change.skip || (change.source.is_none() && change.original.is_none()) {
            return Ok(());
        }
        self.workspace.before_mutation(&change.rel)?;
        let current = self.root.metadata(&change.rel);
        match (&change.original, &current) {
            (None, Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
            (None, Ok(_)) => {
                return Err(format!(
                    "board output path {} appeared during publication",
                    self.root.display(&change.rel)
                ));
            }
            (None, Err(error)) => return Err(error.to_string()),
            (Some(original), Ok(info)) if info.is_file() && same_file(original, info) => {}
            (Some(_), Err(error)) => {
                return Err(format!(
                    "inspect board output {} before publication: {error}",
                    self.root.display(&change.rel)
                ));
            }
            _ => {
                return Err(format!(
                    "board output path {} changed during publication",
                    self.root.display(&change.rel)
                ));
            }
        }
        if let Some(source) = &change.source {
            let (applied, installed, result) =
                self.root
                    .install(source, &change.rel, change.original.is_some());
            change.installed = installed;
            if applied {
                self.applied.push(index);
                self.workspace.visible_mutation = true;
            }
            return result;
        } else {
            // A stale file can be edited after the backup without changing its
            // identity. Re-read it immediately before retiring it.
            let bytes = self
                .root
                .read(&change.rel, change.original.as_ref().unwrap())
                .map_err(|error| {
                    format!(
                        "verify stale board output {}: {error}",
                        self.root.display(&change.rel)
                    )
                })?;
            if change.expected_digest.as_deref() != Some(digest(&bytes).as_str()) {
                change.skip = true;
                return Ok(());
            }
            self.root.remove(&change.rel, false).map_err(|error| {
                format!(
                    "remove stale board output {}: {error}",
                    self.root.display(&change.rel)
                )
            })?;
        }
        self.applied.push(index);
        self.workspace.visible_mutation = true;
        Ok(())
    }
    fn remove_stale_directories(
        &mut self,
        previous: &Manifest,
        current: &Manifest,
    ) -> Result<(), String> {
        let current_dirs = current
            .directories
            .iter()
            .map(|path| (collision_key(Path::new(path)), path.as_str()))
            .collect::<BTreeMap<_, _>>();
        let mut stale = previous
            .directories
            .iter()
            .filter(|path| {
                !current_dirs
                    .get(&collision_key(Path::new(path)))
                    .is_some_and(|new| self.equivalent(path, new))
            })
            .collect::<Vec<_>>();
        stale.stable_sort_by_key(|path| std::cmp::Reverse(path.matches('/').count()));
        for path in stale {
            let rel = Path::new(path);
            match self.root.kind(rel) {
                Ok(0x4000) => {}
                Ok(_) => continue,
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error.to_string()),
            }
            let original = self.root.metadata(rel).map_err(|error| error.to_string())?;
            if !self
                .root
                .entries(rel)
                .map_err(|error| error.to_string())?
                .is_empty()
            {
                continue;
            }
            self.workspace.before_mutation(rel)?;
            if !self
                .root
                .metadata(rel)
                .is_ok_and(|now| same_file(&original, &now))
            {
                return Err(format!(
                    "board output directory {} changed during publication",
                    self.root.display(rel)
                ));
            }
            if let Err(error) = self.root.remove(rel, true) {
                if self
                    .root
                    .entries(rel)
                    .is_ok_and(|children| !children.is_empty())
                {
                    continue;
                }
                return Err(format!(
                    "remove stale board output directory {}: {error}",
                    self.root.display(rel)
                ));
            }
            self.removed_dirs.push((rel.to_owned(), mode(&original)));
            self.workspace.visible_mutation = true;
        }
        Ok(())
    }
    fn rollback(&mut self) -> Result<(), String> {
        let mut errors = Vec::new();
        for (rel, mode) in self.removed_dirs.iter().rev() {
            if let Err(error) = self.root.mkdir(rel, *mode) {
                if error.kind() != std::io::ErrorKind::AlreadyExists {
                    errors.push(format!(
                        "restore board output directory {}: {error}",
                        self.root.display(rel)
                    ));
                }
            }
        }
        for &index in self.applied.iter().rev() {
            let change = &self.changes[index];
            let current = self.root.metadata(&change.rel);
            if let Some(installed) = &change.installed {
                if !current
                    .as_ref()
                    .is_ok_and(|info| same_file(installed, info))
                {
                    errors.push(format!(
                        "refusing to roll back changed board output {}",
                        self.root.display(&change.rel)
                    ));
                    continue;
                }
            } else {
                match current {
                    Ok(_) => {
                        errors.push(format!(
                            "refusing to roll back recreated board output {}",
                            self.root.display(&change.rel)
                        ));
                        continue;
                    }
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(error) => {
                        errors.push(error.to_string());
                        continue;
                    }
                }
            }
            if let Some(backup) = &change.backup {
                if let Err(error) = self
                    .root
                    .install(backup, &change.rel, change.installed.is_some())
                    .2
                {
                    errors.push(format!(
                        "restore board output {}: {error}",
                        self.root.display(&change.rel)
                    ));
                }
            } else if change.installed.is_some() {
                if let Err(error) = self.root.remove(&change.rel, false) {
                    errors.push(format!(
                        "remove newly published board output {}: {error}",
                        self.root.display(&change.rel)
                    ));
                }
            }
        }
        for rel in self.created_dirs.iter().rev() {
            if let Err(error) = self.root.remove(rel, true) {
                if error.kind() == std::io::ErrorKind::NotFound {
                    continue;
                }
                if self
                    .root
                    .entries(rel)
                    .is_ok_and(|children| !children.is_empty())
                {
                    errors.push(format!(
                        "refusing to remove non-empty transaction directory {}",
                        self.root.display(rel)
                    ));
                } else {
                    errors.push(format!(
                        "remove transaction directory {}: {error}",
                        self.root.display(rel)
                    ));
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors.join("\n"))
        }
    }
}

// Go's PathError prints strerror without Rust's "(os error N)" suffix.
fn go_io_error(error: &std::io::Error) -> String {
    let text = error.to_string();
    #[cfg(unix)]
    if let Some(code) = error.raw_os_error() {
        let suffix = format!(" (os error {code})");
        return text.strip_suffix(&suffix).unwrap_or(&text).to_lowercase();
    }
    text
}