destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
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
//! Tree rendering for dcg.
//!
//! Provides tree visualization for hierarchical data like pack structures,
//! decision traces, and command transformation pipelines.
//!
//! # Feature Flags
//!
//! When the `rich-output` feature is enabled, trees are rendered using `rich_rust`
//! for premium terminal output. Otherwise, a fallback ASCII tree renderer is used.

#[cfg(feature = "rich-output")]
use rich_rust::renderables::tree::{Tree as RichTree, TreeGuides, TreeNode as RichTreeNode};
#[cfg(feature = "rich-output")]
use rich_rust::style::Style;

use super::theme::{BorderStyle, Theme};

/// Guide style for tree rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DcgTreeGuides {
    /// ASCII guides using `|`, `+`, and `-` characters.
    Ascii,
    /// Unicode box-drawing characters (default).
    #[default]
    Unicode,
    /// Bold Unicode box-drawing characters.
    Bold,
    /// Rounded Unicode characters for softer appearance.
    Rounded,
}

impl DcgTreeGuides {
    /// Create guides based on the current theme's border style.
    #[must_use]
    pub fn from_theme(theme: &Theme) -> Self {
        match theme.border_style {
            BorderStyle::Ascii => Self::Ascii,
            BorderStyle::Unicode => Self::Unicode,
            BorderStyle::None => Self::Ascii,
        }
    }

    /// Get the branch character for items with siblings below.
    #[must_use]
    pub const fn branch(&self) -> &str {
        match self {
            Self::Ascii => "+-- ",
            Self::Unicode => "├── ",
            Self::Bold => "┣━━ ",
            Self::Rounded => "├── ",
        }
    }

    /// Get the last item character for items without siblings below.
    #[must_use]
    pub const fn last(&self) -> &str {
        match self {
            Self::Ascii => "`-- ",
            Self::Unicode => "└── ",
            Self::Bold => "┗━━ ",
            Self::Rounded => "╰── ",
        }
    }

    /// Get the vertical continuation character.
    #[must_use]
    pub const fn vertical(&self) -> &str {
        match self {
            Self::Ascii => "|   ",
            Self::Unicode | Self::Rounded => "",
            Self::Bold => "",
        }
    }

    /// Get the space for indentation.
    #[must_use]
    pub const fn space(&self) -> &'static str {
        "    "
    }
}

/// A node in a dcg tree structure.
#[derive(Debug, Clone)]
pub struct TreeNode {
    /// The label text for this node.
    pub label: String,
    /// Optional icon (emoji or character).
    pub icon: Option<String>,
    /// Optional style markup (e.g., "[bold cyan]").
    pub style: Option<String>,
    /// Child nodes.
    pub children: Vec<TreeNode>,
}

impl TreeNode {
    /// Create a new tree node with a plain label.
    #[must_use]
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            icon: None,
            style: None,
            children: Vec::new(),
        }
    }

    /// Create a new tree node with an icon.
    #[must_use]
    pub fn with_icon(icon: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            icon: Some(icon.into()),
            style: None,
            children: Vec::new(),
        }
    }

    /// Add a style to this node.
    #[must_use]
    pub fn styled(mut self, style: impl Into<String>) -> Self {
        self.style = Some(style.into());
        self
    }

    /// Add a child node.
    #[must_use]
    pub fn child(mut self, node: TreeNode) -> Self {
        self.children.push(node);
        self
    }

    /// Add multiple children.
    #[must_use]
    pub fn children(mut self, nodes: impl IntoIterator<Item = TreeNode>) -> Self {
        self.children.extend(nodes);
        self
    }

    /// Check if this node has children.
    #[must_use]
    pub fn has_children(&self) -> bool {
        !self.children.is_empty()
    }

    /// Convert to rich_rust TreeNode (when feature enabled).
    #[cfg(feature = "rich-output")]
    fn to_rich_node(&self) -> RichTreeNode {
        let label = if let Some(ref style) = self.style {
            format!("{style}{}{style_end}", self.label, style_end = "[/]")
        } else {
            self.label.clone()
        };

        let mut node = if let Some(ref icon) = self.icon {
            RichTreeNode::with_icon(icon.clone(), label)
        } else {
            RichTreeNode::new(label)
        };

        for child in &self.children {
            node = node.child(child.to_rich_node());
        }

        node
    }
}

/// A tree structure for rendering hierarchical data.
#[derive(Debug, Clone)]
pub struct DcgTree {
    /// Root node of the tree.
    root: TreeNode,
    /// Guide style to use.
    guides: DcgTreeGuides,
    /// Whether to show the root node.
    show_root: bool,
    /// Optional title/header.
    title: Option<String>,
}

impl DcgTree {
    /// Create a new tree with a root node.
    #[must_use]
    pub fn new(root: TreeNode) -> Self {
        Self {
            root,
            guides: DcgTreeGuides::default(),
            show_root: true,
            title: None,
        }
    }

    /// Create a tree with just a label for the root.
    #[must_use]
    pub fn with_label(label: impl Into<String>) -> Self {
        Self::new(TreeNode::new(label))
    }

    /// Set the guide style.
    #[must_use]
    pub fn guides(mut self, guides: DcgTreeGuides) -> Self {
        self.guides = guides;
        self
    }

    /// Configure guides from a theme.
    #[must_use]
    pub fn with_theme(mut self, theme: &Theme) -> Self {
        self.guides = DcgTreeGuides::from_theme(theme);
        self
    }

    /// Set whether to show the root node.
    #[must_use]
    pub fn show_root(mut self, show: bool) -> Self {
        self.show_root = show;
        self
    }

    /// Hide the root node.
    #[must_use]
    pub fn hide_root(self) -> Self {
        self.show_root(false)
    }

    /// Set a title for the tree.
    #[must_use]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Add a child to the root node.
    #[must_use]
    pub fn child(mut self, node: TreeNode) -> Self {
        self.root.children.push(node);
        self
    }

    /// Add multiple children to the root.
    #[must_use]
    pub fn children(mut self, nodes: impl IntoIterator<Item = TreeNode>) -> Self {
        self.root.children.extend(nodes);
        self
    }

    /// Render the tree using rich_rust (when feature enabled).
    #[cfg(feature = "rich-output")]
    pub fn render_rich(&self) {
        use super::console::console;

        let con = console();

        // Print title if set
        if let Some(ref title) = self.title {
            con.print(title);
        }

        // Convert to rich_rust tree
        let rich_guides = match self.guides {
            DcgTreeGuides::Ascii => TreeGuides::Ascii,
            DcgTreeGuides::Unicode => TreeGuides::Unicode,
            DcgTreeGuides::Bold => TreeGuides::Bold,
            DcgTreeGuides::Rounded => TreeGuides::Rounded,
        };

        let tree = RichTree::new(self.root.to_rich_node())
            .guides(rich_guides)
            .guide_style(Style::new().color_str("bright_black").unwrap_or_default())
            .show_root(self.show_root);

        con.print_renderable(&tree);
    }

    /// Render the tree as plain text lines.
    #[must_use]
    pub fn render_plain(&self) -> Vec<String> {
        let mut lines = Vec::new();

        if let Some(ref title) = self.title {
            lines.push(title.clone());
        }

        if self.show_root {
            self.render_node_plain(&self.root, &mut lines, &[], true);
        } else {
            let children = &self.root.children;
            for (i, child) in children.iter().enumerate() {
                let is_last = i == children.len() - 1;
                self.render_node_plain(child, &mut lines, &[], is_last);
            }
        }

        lines
    }

    /// Recursively render a node and its children.
    fn render_node_plain(
        &self,
        node: &TreeNode,
        lines: &mut Vec<String>,
        prefix_stack: &[bool],
        is_last: bool,
    ) {
        let mut line = String::new();

        // Build prefix from ancestors
        for &has_more_siblings in prefix_stack {
            if has_more_siblings {
                line.push_str(self.guides.vertical());
            } else {
                line.push_str(self.guides.space());
            }
        }

        // Add branch guide
        if !prefix_stack.is_empty() || !self.show_root {
            if is_last {
                line.push_str(self.guides.last());
            } else {
                line.push_str(self.guides.branch());
            }
        }

        // Add icon if present
        if let Some(ref icon) = node.icon {
            line.push_str(icon);
            line.push(' ');
        }

        // Add label
        line.push_str(&node.label);

        lines.push(line);

        // Render children
        let mut new_prefix_stack = prefix_stack.to_vec();
        new_prefix_stack.push(!is_last);

        for (i, child) in node.children.iter().enumerate() {
            let child_is_last = i == node.children.len() - 1;
            self.render_node_plain(child, lines, &new_prefix_stack, child_is_last);
        }
    }

    /// Render the tree to the console (uses rich output if available).
    pub fn render(&self) {
        #[cfg(feature = "rich-output")]
        {
            if super::should_use_rich_output() {
                self.render_rich();
                return;
            }
        }

        // Fallback to plain text
        for line in self.render_plain() {
            eprintln!("{line}");
        }
    }
}

/// Builder for creating explain trace trees.
///
/// Provides a convenient API for building the tree visualization
/// of command evaluation traces.
#[derive(Debug, Default)]
pub struct ExplainTreeBuilder {
    command_node: Option<TreeNode>,
    match_node: Option<TreeNode>,
    allowlist_node: Option<TreeNode>,
    pack_node: Option<TreeNode>,
    pipeline_node: Option<TreeNode>,
    suggestions_node: Option<TreeNode>,
}

impl ExplainTreeBuilder {
    /// Create a new explain tree builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the command section.
    #[must_use]
    pub fn command(mut self, node: TreeNode) -> Self {
        self.command_node = Some(node);
        self
    }

    /// Set the match section.
    #[must_use]
    pub fn match_info(mut self, node: TreeNode) -> Self {
        self.match_node = Some(node);
        self
    }

    /// Set the allowlist section.
    #[must_use]
    pub fn allowlist(mut self, node: TreeNode) -> Self {
        self.allowlist_node = Some(node);
        self
    }

    /// Set the packs section.
    #[must_use]
    pub fn packs(mut self, node: TreeNode) -> Self {
        self.pack_node = Some(node);
        self
    }

    /// Set the pipeline section.
    #[must_use]
    pub fn pipeline(mut self, node: TreeNode) -> Self {
        self.pipeline_node = Some(node);
        self
    }

    /// Set the suggestions section.
    #[must_use]
    pub fn suggestions(mut self, node: TreeNode) -> Self {
        self.suggestions_node = Some(node);
        self
    }

    /// Build the final tree.
    #[must_use]
    pub fn build(self) -> DcgTree {
        let mut root = TreeNode::new("DCG EXPLAIN");

        if let Some(node) = self.command_node {
            root = root.child(node);
        }
        if let Some(node) = self.match_node {
            root = root.child(node);
        }
        if let Some(node) = self.allowlist_node {
            root = root.child(node);
        }
        if let Some(node) = self.pack_node {
            root = root.child(node);
        }
        if let Some(node) = self.pipeline_node {
            root = root.child(node);
        }
        if let Some(node) = self.suggestions_node {
            root = root.child(node);
        }

        DcgTree::new(root).hide_root()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tree_node_creation() {
        let node = TreeNode::new("test label");
        assert_eq!(node.label, "test label");
        assert!(node.icon.is_none());
        assert!(node.children.is_empty());
    }

    #[test]
    fn test_tree_node_with_icon() {
        let node = TreeNode::with_icon("📁", "folder");
        assert_eq!(node.label, "folder");
        assert_eq!(node.icon.as_deref(), Some("📁"));
    }

    #[test]
    fn test_tree_node_children() {
        let node = TreeNode::new("parent")
            .child(TreeNode::new("child1"))
            .child(TreeNode::new("child2"));
        assert_eq!(node.children.len(), 2);
        assert!(node.has_children());
    }

    #[test]
    fn test_dcg_tree_render_plain() {
        let tree = DcgTree::with_label("Root")
            .child(TreeNode::new("Child 1"))
            .child(TreeNode::new("Child 2").child(TreeNode::new("Grandchild")));

        let lines = tree.render_plain();
        assert!(!lines.is_empty());
        assert_eq!(lines[0], "Root");
    }

    #[test]
    fn test_dcg_tree_guides() {
        let guides = DcgTreeGuides::Unicode;
        assert_eq!(guides.branch(), "├── ");
        assert_eq!(guides.last(), "└── ");
        assert_eq!(guides.vertical(), "");

        let ascii = DcgTreeGuides::Ascii;
        assert_eq!(ascii.branch(), "+-- ");
        assert_eq!(ascii.last(), "`-- ");
    }

    #[test]
    fn test_explain_tree_builder() {
        let tree = ExplainTreeBuilder::new()
            .command(TreeNode::new("Command").child(TreeNode::new("rm -rf /")))
            .match_info(TreeNode::new("Match").child(TreeNode::new("rule: rm_rf")))
            .build();

        let lines = tree.render_plain();
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_tree_node_no_children() {
        let node = TreeNode::new("leaf");
        assert!(!node.has_children());
    }

    #[test]
    fn test_tree_node_styled() {
        let node = TreeNode::new("styled").styled("[bold red]");
        assert_eq!(node.style.as_deref(), Some("[bold red]"));
    }

    #[test]
    fn test_tree_node_children_batch() {
        let children = vec![TreeNode::new("a"), TreeNode::new("b"), TreeNode::new("c")];
        let node = TreeNode::new("root").children(children);
        assert_eq!(node.children.len(), 3);
    }

    #[test]
    fn test_bold_guides() {
        let guides = DcgTreeGuides::Bold;
        assert_eq!(guides.branch(), "┣━━ ");
        assert_eq!(guides.last(), "┗━━ ");
        assert_eq!(guides.vertical(), "");
    }

    #[test]
    fn test_rounded_guides() {
        let guides = DcgTreeGuides::Rounded;
        assert_eq!(guides.branch(), "├── ");
        assert_eq!(guides.last(), "╰── ");
        assert_eq!(guides.vertical(), "");
    }

    #[test]
    fn test_guides_space() {
        // All guide styles should have the same space indent
        assert_eq!(DcgTreeGuides::Ascii.space(), "    ");
        assert_eq!(DcgTreeGuides::Unicode.space(), "    ");
        assert_eq!(DcgTreeGuides::Bold.space(), "    ");
        assert_eq!(DcgTreeGuides::Rounded.space(), "    ");
    }

    #[test]
    fn test_guides_from_theme() {
        let theme = Theme::default();
        let guides = DcgTreeGuides::from_theme(&theme);
        assert_eq!(guides, DcgTreeGuides::Unicode);

        let no_color = Theme::no_color();
        let guides = DcgTreeGuides::from_theme(&no_color);
        assert_eq!(guides, DcgTreeGuides::Ascii);

        let minimal = Theme::minimal();
        let guides = DcgTreeGuides::from_theme(&minimal);
        assert_eq!(guides, DcgTreeGuides::Ascii);
    }

    #[test]
    fn test_tree_render_plain_with_title() {
        let tree = DcgTree::with_label("Root")
            .title("My Tree Title")
            .child(TreeNode::new("Item 1"));

        let lines = tree.render_plain();
        assert_eq!(lines[0], "My Tree Title");
        assert!(lines.len() >= 3); // title + root + child
    }

    #[test]
    fn test_tree_render_plain_hidden_root() {
        let tree = DcgTree::with_label("Hidden Root")
            .hide_root()
            .child(TreeNode::new("Child A"))
            .child(TreeNode::new("Child B"));

        let lines = tree.render_plain();
        // Root should not appear in output
        assert!(!lines.iter().any(|l| l.contains("Hidden Root")));
        // Children should appear
        assert!(lines.iter().any(|l| l.contains("Child A")));
        assert!(lines.iter().any(|l| l.contains("Child B")));
    }

    #[test]
    fn test_tree_render_plain_ascii_guides() {
        let tree = DcgTree::with_label("Root")
            .guides(DcgTreeGuides::Ascii)
            .child(TreeNode::new("A"))
            .child(TreeNode::new("B"));

        let lines = tree.render_plain();
        // Should use ASCII branch characters
        assert!(lines.iter().any(|l| l.contains("+-- ")));
        assert!(lines.iter().any(|l| l.contains("`-- ")));
    }

    #[test]
    fn test_tree_render_plain_unicode_guides() {
        let tree = DcgTree::with_label("Root")
            .guides(DcgTreeGuides::Unicode)
            .child(TreeNode::new("A"))
            .child(TreeNode::new("B"));

        let lines = tree.render_plain();
        assert!(lines.iter().any(|l| l.contains("├── ")));
        assert!(lines.iter().any(|l| l.contains("└── ")));
    }

    #[test]
    fn test_tree_render_plain_deeply_nested() {
        let tree =
            DcgTree::with_label("L0").child(TreeNode::new("L1").child(
                TreeNode::new("L2").child(TreeNode::new("L3").child(TreeNode::new("L4 leaf"))),
            ));

        let lines = tree.render_plain();
        assert_eq!(lines.len(), 5); // L0, L1, L2, L3, L4
        assert!(lines[4].contains("L4 leaf"));
    }

    #[test]
    fn test_tree_render_plain_with_icons() {
        let tree = DcgTree::with_label("Packages")
            .child(TreeNode::with_icon("📦", "core.git"))
            .child(TreeNode::with_icon("📦", "core.filesystem"));

        let lines = tree.render_plain();
        assert!(lines.iter().any(|l| l.contains("📦 core.git")));
        assert!(lines.iter().any(|l| l.contains("📦 core.filesystem")));
    }

    #[test]
    fn test_tree_with_theme() {
        let theme = Theme::no_color();
        let tree = DcgTree::with_label("Root")
            .with_theme(&theme)
            .child(TreeNode::new("child"));

        let lines = tree.render_plain();
        // ASCII guides from no_color theme
        assert!(lines.iter().any(|l| l.contains("`-- ")));
    }

    #[test]
    fn test_explain_tree_builder_all_sections() {
        let tree = ExplainTreeBuilder::new()
            .command(TreeNode::new("Command"))
            .match_info(TreeNode::new("Match"))
            .allowlist(TreeNode::new("Allowlist"))
            .packs(TreeNode::new("Packs"))
            .pipeline(TreeNode::new("Pipeline"))
            .suggestions(TreeNode::new("Suggestions"))
            .build();

        let lines = tree.render_plain();
        // All sections should appear (root is hidden)
        assert!(lines.iter().any(|l| l.contains("Command")));
        assert!(lines.iter().any(|l| l.contains("Match")));
        assert!(lines.iter().any(|l| l.contains("Allowlist")));
        assert!(lines.iter().any(|l| l.contains("Packs")));
        assert!(lines.iter().any(|l| l.contains("Pipeline")));
        assert!(lines.iter().any(|l| l.contains("Suggestions")));
    }

    #[test]
    fn test_explain_tree_builder_empty() {
        let tree = ExplainTreeBuilder::new().build();
        let lines = tree.render_plain();
        // Empty builder with hidden root should produce no output
        assert!(lines.is_empty());
    }

    #[test]
    fn test_default_guides() {
        let guides = DcgTreeGuides::default();
        assert_eq!(guides, DcgTreeGuides::Unicode);
    }

    #[test]
    fn test_tree_render_does_not_panic() {
        // render() goes to stderr, just verify no panic
        let tree = DcgTree::with_label("Test").child(TreeNode::new("child"));
        tree.render();
    }
}