treeboot-core 0.6.0

Reusable worktree bootstrap engine for the treeboot CLI.
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
use std::path::{Path, PathBuf};

use crate::FileOperationKind;

/// Counts produced by one top-level file operation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FileOperationSummary {
    /// Number of created, updated, or replaced paths.
    pub changed: usize,
    /// Number of skipped paths.
    pub skipped: usize,
    /// Number of deleted target-only paths.
    pub deleted: usize,
    /// Number of warnings emitted.
    pub warnings: usize,
    /// Number of metadata-only sync repairs.
    pub metadata_changed: usize,
    /// Whether the summary represents expanded directory work.
    pub expanded: bool,
    /// Reason for a single skipped top-level operation.
    pub skip_reason: Option<String>,
}

impl FileOperationSummary {
    /// Returns the number of visible action decisions in the summary.
    #[must_use]
    pub const fn decision_count(&self) -> usize {
        self.changed + self.skipped + self.deleted
    }

    /// Formats the summary as a user-facing file-operation line.
    #[must_use]
    pub fn message(
        &self,
        operation: FileOperationKind,
        source: &Path,
        target: &Path,
        dry_run: bool,
    ) -> String {
        format_file_operation_summary(operation, source, target, self, dry_run)
    }

    fn count_details(&self, dry_run: bool) -> Vec<String> {
        let mut details = Vec::new();
        if self.changed > 0 {
            details.push(count_detail(
                self.changed,
                if dry_run { "change" } else { "changed" },
                if dry_run { "changes" } else { "changed" },
            ));
        }
        if self.skipped > 0 {
            details.push(count_detail(
                self.skipped,
                if dry_run { "skip" } else { "skipped" },
                if dry_run { "skips" } else { "skipped" },
            ));
        }
        if self.deleted > 0 {
            details.push(count_detail(
                self.deleted,
                if dry_run { "delete" } else { "deleted" },
                if dry_run { "deletes" } else { "deleted" },
            ));
        }
        details
    }
}

fn count_detail(count: usize, singular: &str, plural: &str) -> String {
    let noun = if count == 1 { singular } else { plural };
    format!("{count} {noun}")
}

/// A structured message produced during a treeboot operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutputEvent {
    /// A non-executable script candidate was ignored.
    IgnoredInitScript {
        /// Script candidate path.
        path: PathBuf,
    },

    /// A dry run would execute the given init script.
    WouldRunInitScript {
        /// Script path.
        path: PathBuf,
        /// Root checkout path passed as the script argument.
        root_path: PathBuf,
    },

    /// An init script is about to run.
    RunInitScript {
        /// Script path.
        path: PathBuf,
    },

    /// No script or config was found.
    NoConfigDetected,

    /// The run started from the root checkout instead of a separate worktree.
    RootWorktreeDetected,

    /// A config file was found.
    ConfigDetected {
        /// Config file path.
        path: PathBuf,
    },

    /// A file operation was applied.
    FileApplied {
        /// File operation kind.
        operation: FileOperationKind,
        /// Display source path.
        source: PathBuf,
        /// Display target path.
        target: PathBuf,
    },

    /// A dry run would apply a file operation.
    FileWouldApply {
        /// File operation kind.
        operation: FileOperationKind,
        /// Display source path.
        source: PathBuf,
        /// Display target path.
        target: PathBuf,
    },

    /// A sync operation applied metadata-only changes.
    FileMetadataApplied {
        /// Display source path.
        source: PathBuf,
        /// Display target path.
        target: PathBuf,
    },

    /// A dry run would apply metadata-only sync changes.
    FileMetadataWouldApply {
        /// Display source path.
        source: PathBuf,
        /// Display target path.
        target: PathBuf,
    },

    /// A file operation was skipped.
    FileSkipped {
        /// File operation kind.
        operation: FileOperationKind,
        /// Display target path.
        target: PathBuf,
        /// Reason the operation was skipped.
        reason: String,
    },

    /// A dry run would skip a file operation.
    FileWouldSkip {
        /// File operation kind.
        operation: FileOperationKind,
        /// Display target path.
        target: PathBuf,
        /// Reason the operation would be skipped.
        reason: String,
    },

    /// A sync operation deleted a target-only path.
    FileDeleted {
        /// Deleted path.
        path: PathBuf,
    },

    /// A dry-run sync operation would delete a target-only path.
    FileWouldDelete {
        /// Path that would be deleted.
        path: PathBuf,
    },

    /// A file operation warning was produced.
    FileWarning {
        /// Warning path.
        path: PathBuf,
        /// Human-readable warning detail.
        reason: String,
    },

    /// Ownership metadata could not be preserved.
    OwnershipWarning {
        /// Warning path.
        path: PathBuf,
        /// Human-readable warning detail.
        reason: String,
    },

    /// A command is about to run.
    CommandStarted {
        /// Human-readable command label.
        label: String,
    },

    /// A dry run would execute a command.
    CommandWouldRun {
        /// Human-readable command label.
        label: String,
    },

    /// A command failure was allowed and execution will continue.
    CommandAllowedFailure {
        /// Human-readable command label.
        label: String,
        /// Failure detail.
        reason: String,
    },

    /// An init file was created.
    InitCreated {
        /// Created file path.
        path: PathBuf,
    },
}

impl OutputEvent {
    /// Formats the event as a user-facing line.
    #[must_use]
    pub fn message(&self) -> String {
        match self {
            Self::IgnoredInitScript { path } => {
                format!("treeboot: ignore {}; not executable", path.display())
            }
            Self::WouldRunInitScript { path, root_path } => format!(
                "treeboot: would run {} {}",
                path.display(),
                root_path.display()
            ),
            Self::RunInitScript { path } => {
                format!("treeboot: run {}", path.display())
            }
            Self::NoConfigDetected => "treeboot: no config detected".to_owned(),
            Self::RootWorktreeDetected => "treeboot: This is not a work tree".to_owned(),
            Self::ConfigDetected { path } => {
                format!("treeboot: config detected {}", path.display())
            }
            Self::FileApplied {
                operation,
                source,
                target,
            } => format!(
                "treeboot: {} {} -> {}",
                operation.as_str(),
                source.display(),
                target.display()
            ),
            Self::FileWouldApply {
                operation,
                source,
                target,
            } => format!(
                "treeboot: would {} {} -> {}",
                operation.as_str(),
                source.display(),
                target.display()
            ),
            Self::FileMetadataApplied { source, target } => format!(
                "treeboot: sync metadata {} -> {}",
                source.display(),
                target.display()
            ),
            Self::FileMetadataWouldApply { source, target } => format!(
                "treeboot: would sync metadata {} -> {}",
                source.display(),
                target.display()
            ),
            Self::FileSkipped {
                operation,
                target,
                reason,
            } => format!(
                "treeboot: skip {} {}; {}",
                operation.as_str(),
                target.display(),
                reason
            ),
            Self::FileWouldSkip {
                operation,
                target,
                reason,
            } => format!(
                "treeboot: would skip {} {}; {}",
                operation.as_str(),
                target.display(),
                reason
            ),
            Self::FileDeleted { path } => {
                format!("treeboot: delete {}", path.display())
            }
            Self::FileWouldDelete { path } => {
                format!("treeboot: would delete {}", path.display())
            }
            Self::FileWarning { path, reason } => {
                format!("treeboot: warning: {} {}", path.display(), reason)
            }
            Self::OwnershipWarning { path, reason } => format!(
                "treeboot: warning: could not preserve ownership {}: {}",
                path.display(),
                reason
            ),
            Self::CommandStarted { label } => {
                format!("treeboot: run {label}")
            }
            Self::CommandWouldRun { label } => {
                format!("treeboot: would run {label}")
            }
            Self::CommandAllowedFailure { label, reason } => {
                format!("treeboot: warning: command {label} {reason}")
            }
            Self::InitCreated { path } => {
                format!("treeboot: created {}", path.display())
            }
        }
    }
}

fn format_file_operation_summary(
    operation: FileOperationKind,
    source: &Path,
    target: &Path,
    summary: &FileOperationSummary,
    dry_run: bool,
) -> String {
    if summary.decision_count() == 1 {
        if summary.changed == 1 {
            if summary.metadata_changed == 1 {
                if dry_run {
                    return format!(
                        "treeboot: would sync metadata {} -> {}",
                        source.display(),
                        target.display()
                    );
                }

                return format!(
                    "treeboot: sync metadata {} -> {}",
                    source.display(),
                    target.display()
                );
            }

            if !summary.expanded && dry_run {
                return format!(
                    "treeboot: would {} {} -> {}",
                    operation.as_str(),
                    source.display(),
                    target.display()
                );
            }

            if !summary.expanded {
                return format!(
                    "treeboot: {} {} -> {}",
                    operation.as_str(),
                    source.display(),
                    target.display()
                );
            }
        }

        if summary.skipped == 1 {
            let reason = summary.skip_reason.as_deref().unwrap_or("skipped");
            if dry_run {
                return format!(
                    "treeboot: would skip {} {}; {}",
                    operation.as_str(),
                    target.display(),
                    reason
                );
            }

            return format!(
                "treeboot: skip {} {}; {}",
                operation.as_str(),
                target.display(),
                reason
            );
        }
    }

    let details = summary.count_details(dry_run).join(", ");
    let suffix = if details.is_empty() {
        String::new()
    } else {
        format!(" ({details})")
    };
    if dry_run {
        format!(
            "treeboot: would {} {} -> {}{suffix}",
            operation.as_str(),
            source.display(),
            target.display()
        )
    } else {
        format!(
            "treeboot: {} {} -> {}{suffix}",
            operation.as_str(),
            source.display(),
            target.display()
        )
    }
}

/// Receives structured output events from core operations.
pub trait Reporter {
    /// Handles one output event.
    fn report(&mut self, event: OutputEvent) -> std::io::Result<()>;

    /// Handles the start of planning for one top-level file operation.
    fn file_operation_planning_started(
        &mut self,
        operation: FileOperationKind,
        source: &Path,
        target: &Path,
    ) -> std::io::Result<()> {
        let _ = (operation, source, target);
        Ok(())
    }

    /// Handles completion of planning for one top-level file operation.
    fn file_operation_planning_finished(
        &mut self,
        operation: FileOperationKind,
        source: &Path,
        target: &Path,
        action_count: usize,
    ) -> std::io::Result<()> {
        let _ = (operation, source, target, action_count);
        Ok(())
    }

    /// Handles the start of execution for one top-level file operation.
    fn file_operation_execution_started(
        &mut self,
        operation: FileOperationKind,
        source: &Path,
        target: &Path,
        action_count: usize,
    ) -> std::io::Result<()> {
        let _ = (operation, source, target, action_count);
        Ok(())
    }

    /// Handles completion of one concrete file-operation action.
    fn file_operation_action_advanced(
        &mut self,
        operation: FileOperationKind,
        source: &Path,
        target: &Path,
    ) -> std::io::Result<()> {
        let _ = (operation, source, target);
        Ok(())
    }

    /// Handles completion of one top-level compact file operation.
    fn file_operation_finished(
        &mut self,
        operation: FileOperationKind,
        source: &Path,
        target: &Path,
        summary: &FileOperationSummary,
        dry_run: bool,
    ) -> std::io::Result<()> {
        let _ = (operation, source, target, summary, dry_run);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;
    use crate::FileOperationKind;

    #[test]
    fn message_should_format_ignored_init_script() {
        let event = OutputEvent::IgnoredInitScript {
            path: PathBuf::from(".treeboot.sh"),
        };

        assert_eq!(
            event.message(),
            "treeboot: ignore .treeboot.sh; not executable"
        );
    }

    #[test]
    fn message_should_format_dry_run_init_script() {
        let event = OutputEvent::WouldRunInitScript {
            path: PathBuf::from(".treeboot.sh"),
            root_path: PathBuf::from("/repo"),
        };

        assert_eq!(event.message(), "treeboot: would run .treeboot.sh /repo");
    }

    #[test]
    fn message_should_format_config_detected() {
        let event = OutputEvent::ConfigDetected {
            path: PathBuf::from(".treeboot.toml"),
        };

        assert_eq!(event.message(), "treeboot: config detected .treeboot.toml");
    }

    #[test]
    fn message_should_format_file_applied() {
        let event = OutputEvent::FileApplied {
            operation: FileOperationKind::Copy,
            source: PathBuf::from(".env"),
            target: PathBuf::from(".env"),
        };

        assert_eq!(event.message(), "treeboot: copy .env -> .env");
    }

    #[test]
    fn message_should_format_file_would_apply() {
        let event = OutputEvent::FileWouldApply {
            operation: FileOperationKind::Symlink,
            source: PathBuf::from("tool"),
            target: PathBuf::from(".tool"),
        };

        assert_eq!(event.message(), "treeboot: would symlink tool -> .tool");
    }

    #[test]
    fn message_should_format_file_metadata_applied() {
        let event = OutputEvent::FileMetadataApplied {
            source: PathBuf::from("shared/config"),
            target: PathBuf::from(".config"),
        };

        assert_eq!(
            event.message(),
            "treeboot: sync metadata shared/config -> .config"
        );
    }

    #[test]
    fn message_should_format_file_metadata_would_apply() {
        let event = OutputEvent::FileMetadataWouldApply {
            source: PathBuf::from("shared/config"),
            target: PathBuf::from(".config"),
        };

        assert_eq!(
            event.message(),
            "treeboot: would sync metadata shared/config -> .config"
        );
    }

    #[test]
    fn message_should_format_file_skipped() {
        let event = OutputEvent::FileSkipped {
            operation: FileOperationKind::Copy,
            target: PathBuf::from(".env"),
            reason: "target exists".to_owned(),
        };

        assert_eq!(event.message(), "treeboot: skip copy .env; target exists");
    }

    #[test]
    fn message_should_format_file_would_skip() {
        let event = OutputEvent::FileWouldSkip {
            operation: FileOperationKind::Sync,
            target: PathBuf::from("shared"),
            reason: "missing source".to_owned(),
        };

        assert_eq!(
            event.message(),
            "treeboot: would skip sync shared; missing source"
        );
    }

    #[test]
    fn message_should_format_file_deleted() {
        let event = OutputEvent::FileDeleted {
            path: PathBuf::from(".config/old.toml"),
        };

        assert_eq!(event.message(), "treeboot: delete .config/old.toml");
    }

    #[test]
    fn message_should_format_file_would_delete() {
        let event = OutputEvent::FileWouldDelete {
            path: PathBuf::from(".config/old.toml"),
        };

        assert_eq!(event.message(), "treeboot: would delete .config/old.toml");
    }

    #[test]
    fn message_should_format_file_warning() {
        let event = OutputEvent::FileWarning {
            path: PathBuf::from("shared/link"),
            reason: "symlink target does not exist".to_owned(),
        };

        assert_eq!(
            event.message(),
            "treeboot: warning: shared/link symlink target does not exist"
        );
    }

    #[test]
    fn message_should_format_ownership_warning() {
        let event = OutputEvent::OwnershipWarning {
            path: PathBuf::from("shared/config"),
            reason: "operation not permitted".to_owned(),
        };

        assert_eq!(
            event.message(),
            "treeboot: warning: could not preserve ownership shared/config: operation not permitted"
        );
    }

    #[test]
    fn message_should_format_single_file_operation_summary_without_counts() {
        let summary = FileOperationSummary {
            changed: 1,
            ..FileOperationSummary::default()
        };

        assert_eq!(
            summary.message(
                FileOperationKind::Copy,
                Path::new(".env"),
                Path::new(".env"),
                false
            ),
            "treeboot: copy .env -> .env"
        );
    }

    #[test]
    fn message_should_format_expanded_file_operation_summary_with_counts() {
        let summary = FileOperationSummary {
            changed: 4,
            deleted: 1,
            expanded: true,
            ..FileOperationSummary::default()
        };

        assert_eq!(
            summary.message(
                FileOperationKind::Sync,
                Path::new("shared"),
                Path::new("shared"),
                false
            ),
            "treeboot: sync shared -> shared (4 changed, 1 deleted)"
        );
    }

    #[test]
    fn message_should_omit_empty_file_operation_summary_counts() {
        let summary = FileOperationSummary {
            warnings: 1,
            ..FileOperationSummary::default()
        };

        assert_eq!(
            summary.message(
                FileOperationKind::Copy,
                Path::new("shared/link"),
                Path::new("shared/link"),
                false
            ),
            "treeboot: copy shared/link -> shared/link"
        );
    }

    #[test]
    fn message_should_format_single_dry_run_skip_summary() {
        let summary = FileOperationSummary {
            skipped: 1,
            skip_reason: Some("target exists".to_owned()),
            ..FileOperationSummary::default()
        };

        assert_eq!(
            summary.message(
                FileOperationKind::Copy,
                Path::new(".env"),
                Path::new(".env"),
                true
            ),
            "treeboot: would skip copy .env; target exists"
        );
    }

    #[test]
    fn message_should_format_root_worktree_detected() {
        let event = OutputEvent::RootWorktreeDetected;

        assert_eq!(event.message(), "treeboot: This is not a work tree");
    }

    #[test]
    fn message_should_format_command_started() {
        let event = OutputEvent::CommandStarted {
            label: "Install packages: npm install".to_owned(),
        };

        assert_eq!(
            event.message(),
            "treeboot: run Install packages: npm install"
        );
    }

    #[test]
    fn message_should_format_command_allowed_failure() {
        let event = OutputEvent::CommandAllowedFailure {
            label: "lint".to_owned(),
            reason: "failed with exit status: 1".to_owned(),
        };

        assert_eq!(
            event.message(),
            "treeboot: warning: command lint failed with exit status: 1"
        );
    }
}