nextdeck 0.1.0

A TUI wrapper for cargo-nextest, Clap-powered xtasks, and more.
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
use std::{
    path::{Component, PathBuf},
    time::{Duration, Instant},
};

use serde::Serialize;

use crate::{
    config::TreeDurationMode,
    output::{TestOutput, append_bounded_text, bounded_output_section, bounded_text},
    state::StatusCounts,
};

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct TestKey {
    pub binary_id: Option<String>,
    pub event_prefix: Option<String>,
    pub name: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct DiscoveredTest {
    pub key: TestKey,
    pub package: String,
    pub binary: String,
    pub binary_kind: String,
    pub binary_path: PathBuf,
    pub cwd: PathBuf,
    pub source_path: Option<PathBuf>,
    pub module: Option<String>,
    pub name: String,
    pub full_name: String,
    pub status: TestStatus,
    pub ignored: bool,
    pub ignore_reason: Option<String>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TestStatus {
    Pending,
    Running,
    Passed,
    Failed,
    Ignored,
    Skipped,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TestViewFilter {
    pub show_success: bool,
    pub show_failed: bool,
    pub show_ignored: bool,
    pub show_skipped: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SelectionChange {
    Unchanged,
    Changed,
}

impl SelectionChange {
    pub fn changed(self) -> bool {
        self == Self::Changed
    }
}

impl Default for TestViewFilter {
    fn default() -> Self {
        Self {
            show_success: true,
            show_failed: true,
            show_ignored: true,
            show_skipped: true,
        }
    }
}

impl TestViewFilter {
    fn allows(self, status: TestStatus) -> bool {
        match status {
            TestStatus::Passed => self.show_success,
            TestStatus::Failed => self.show_failed,
            TestStatus::Ignored => self.show_ignored,
            TestStatus::Skipped => self.show_skipped,
            TestStatus::Pending | TestStatus::Running => true,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum NodeKind {
    Workspace,
    Package {
        name: String,
    },
    Binary {
        package: String,
        name: String,
        kind: String,
    },
    Module {
        path: String,
    },
    Test(Box<DiscoveredTest>),
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum NodeId {
    Workspace,
    Package {
        name: String,
    },
    Binary {
        package: String,
        name: String,
        kind: String,
    },
    Module {
        package: String,
        binary: String,
        kind: String,
        path: String,
    },
    Test {
        key: TestKey,
    },
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TestNode {
    pub id: NodeId,
    pub label: String,
    pub kind: NodeKind,
    pub status: TestStatus,
    pub output: TestOutput,
    pub has_events: bool,
    pub started_at: Option<Instant>,
    pub run_started_at: Option<Instant>,
    pub finished_at: Option<Instant>,
    pub expanded: bool,
    pub children: Vec<TestNode>,
}

impl TestNode {
    fn new(id: NodeId, label: impl Into<String>, kind: NodeKind) -> Self {
        Self {
            id,
            label: label.into(),
            kind,
            status: TestStatus::Pending,
            output: TestOutput::default(),
            has_events: false,
            started_at: None,
            run_started_at: None,
            finished_at: None,
            expanded: false,
            children: Vec::new(),
        }
    }

    pub fn display_duration(&self, mode: TreeDurationMode) -> Option<Duration> {
        self.display_duration_at(mode, Instant::now())
    }

    fn display_duration_at(&self, mode: TreeDurationMode, now: Instant) -> Option<Duration> {
        if matches!(self.kind, NodeKind::Test(_)) {
            return self.test_display_duration_at(now);
        }

        match mode {
            TreeDurationMode::Wall => self
                .duration_span_at(now)
                .map(|(started_at, finished_at)| finished_at.duration_since(started_at))
                .or_else(|| self.aggregate_duration_at(now)),
            TreeDurationMode::Aggregate => self.aggregate_duration_at(now),
        }
    }

    fn test_display_duration_at(&self, now: Instant) -> Option<Duration> {
        self.output.duration.or_else(|| {
            (self.status == TestStatus::Running)
                .then(|| {
                    self.started_at
                        .map(|started_at| now.duration_since(started_at))
                })
                .flatten()
        })
    }

    fn aggregate_duration_at(&self, now: Instant) -> Option<Duration> {
        let mut total = Duration::ZERO;
        let mut has_duration = false;
        for child in &self.children {
            if let Some(duration) = child.display_duration_at(TreeDurationMode::Aggregate, now) {
                total += duration;
                has_duration = true;
            }
        }
        has_duration.then_some(total)
    }

    fn duration_span_at(&self, now: Instant) -> Option<(Instant, Instant)> {
        if matches!(self.kind, NodeKind::Test(_)) {
            if self.status == TestStatus::Running {
                return self.started_at.map(|started_at| (started_at, now));
            }
            let finished_at = self.finished_at?;
            let started_at = self.run_started_at.or_else(|| {
                self.output
                    .duration
                    .and_then(|duration| finished_at.checked_sub(duration))
            })?;
            return Some((started_at, finished_at));
        }

        let mut started_at = None;
        let mut finished_at = None;
        for child in &self.children {
            let Some((child_started, child_finished)) = child.duration_span_at(now) else {
                continue;
            };
            started_at = Some(
                started_at.map_or(child_started, |current: Instant| current.min(child_started)),
            );
            finished_at = Some(finished_at.map_or(child_finished, |current: Instant| {
                current.max(child_finished)
            }));
        }
        started_at.zip(finished_at)
    }
}

#[derive(Clone, Copy)]
pub struct TreeRow<'a> {
    pub depth: usize,
    pub node: &'a TestNode,
}

pub struct VisibleTreeRows<'a> {
    pub rows: Vec<TreeRow<'a>>,
    pub selected_index: usize,
}

pub struct Tree {
    pub root: TestNode,
    pub view_filter: TestViewFilter,
    selected: NodeId,
    runner_output: Vec<String>,
}

impl Tree {
    pub fn from_tests(tests: Vec<DiscoveredTest>) -> Self {
        let mut root = TestNode::new(
            NodeId::Workspace,
            workspace_label(&tests),
            NodeKind::Workspace,
        );
        root.expanded = true;
        let mut tree = Self {
            root,
            view_filter: TestViewFilter::default(),
            selected: NodeId::Workspace,
            runner_output: Vec::new(),
        };
        for test in tests {
            tree.insert_test(test);
        }
        tree.recompute_statuses();
        tree
    }

    pub fn visible_rows(&self) -> Vec<TreeRow<'_>> {
        let mut rows = Vec::new();
        collect_visible(&self.root, 0, self.view_filter, true, &mut rows);
        rows
    }

    pub fn visible_rows_with_selection(&self) -> VisibleTreeRows<'_> {
        let rows = self.visible_rows();
        let selected_index = rows
            .iter()
            .position(|row| row.node.id == self.selected)
            .unwrap_or(0);
        VisibleTreeRows {
            rows,
            selected_index,
        }
    }

    pub fn set_view_filter(&mut self, filter: TestViewFilter) {
        self.set_view_filter_preserving_selection(filter);
    }

    pub fn set_view_filter_preserving_selection(
        &mut self,
        filter: TestViewFilter,
    ) -> SelectionChange {
        let before = self.selected.clone();
        self.view_filter = filter;
        if !self.is_selected_visible() {
            self.clamp_selection();
        }
        if self.selected == before {
            SelectionChange::Unchanged
        } else {
            SelectionChange::Changed
        }
    }

    pub fn selected_index(&self) -> usize {
        self.visible_rows_with_selection().selected_index
    }

    pub fn selected_node(&self) -> Option<&TestNode> {
        self.node(&self.selected)
    }

    pub fn selected_id(&self) -> &NodeId {
        &self.selected
    }

    pub fn select_next(&mut self) {
        let visible = self.visible_rows_with_selection();
        let rows = visible.rows;
        if !rows.is_empty() {
            let index = visible.selected_index.saturating_add(1).min(rows.len() - 1);
            self.selected = rows[index].node.id.clone();
        }
    }

    pub fn select_previous(&mut self) {
        let visible = self.visible_rows_with_selection();
        let rows = visible.rows;
        if !rows.is_empty() {
            let index = visible.selected_index.saturating_sub(1);
            self.selected = rows[index].node.id.clone();
        }
    }

    pub fn select_first(&mut self) {
        if let Some(row) = self.visible_rows().first() {
            self.selected = row.node.id.clone();
        }
    }

    pub fn select_last(&mut self) {
        if let Some(row) = self.visible_rows().last() {
            self.selected = row.node.id.clone();
        }
    }

    pub fn select_next_page(&mut self, page_size: usize) {
        let visible = self.visible_rows_with_selection();
        let rows = visible.rows;
        if !rows.is_empty() {
            let index = visible
                .selected_index
                .saturating_add(page_size.max(1))
                .min(rows.len().saturating_sub(1));
            self.selected = rows[index].node.id.clone();
        }
    }

    pub fn select_previous_page(&mut self, page_size: usize) {
        let visible = self.visible_rows_with_selection();
        let rows = visible.rows;
        if !rows.is_empty() {
            let index = visible.selected_index.saturating_sub(page_size.max(1));
            self.selected = rows[index].node.id.clone();
        }
    }

    pub fn toggle_selected(&mut self) {
        self.with_selected_mut(|node| {
            if !node.children.is_empty() {
                node.expanded = !node.expanded;
            }
        });
        self.clamp_selection();
    }

    pub fn expand_selected(&mut self) {
        self.with_selected_mut(|node| {
            if !node.children.is_empty() {
                node.expanded = true;
            }
        });
        self.clamp_selection();
    }

    pub fn collapse_selected_or_parent(&mut self) {
        let target = {
            let rows = self.visible_rows();
            let selected = self.selected_index();
            let Some(selected_row) = rows.get(selected) else {
                return;
            };
            let selected_depth = selected_row.depth;
            let selected_node = selected_row.node;

            if !selected_node.children.is_empty() && selected_node.expanded {
                Some(selected_node.id.clone())
            } else {
                rows[..selected]
                    .iter()
                    .rev()
                    .find_map(|row| (row.depth < selected_depth).then_some(row.node.id.clone()))
            }
        };

        let Some(target) = target else {
            return;
        };

        self.with_id_mut(&target, |node| node.expanded = false);
        self.selected = target;
        self.clamp_selection();
    }

    pub fn prepare_for_run(&mut self, scope: &crate::nextest::RunScope) {
        self.clear_runner_output();
        visit_mut(&mut self.root, &mut |node| {
            if let NodeKind::Test(test) = &node.kind {
                node.output = TestOutput::default();
                node.started_at = None;
                node.run_started_at = None;
                node.finished_at = None;
                if test.ignored {
                    node.status = TestStatus::Ignored;
                } else if scope.matches_test(test) {
                    node.status = TestStatus::Pending;
                } else {
                    node.status = TestStatus::Skipped;
                }
            }
        });
        self.recompute_statuses();
    }

    pub fn start_test(&mut self, key: &TestKey) {
        visit_mut(&mut self.root, &mut |node| {
            if node_matches(node, key)
                && let NodeKind::Test(test) = &node.kind
                && !test.ignored
            {
                let now = Instant::now();
                node.status = TestStatus::Running;
                node.started_at = Some(now);
                node.run_started_at = Some(now);
                node.finished_at = None;
            }
        });
        self.recompute_statuses();
    }

    pub fn finish_test(
        &mut self,
        key: &TestKey,
        status: TestStatus,
        output: String,
        duration: Option<Duration>,
    ) {
        visit_mut(&mut self.root, &mut |node| {
            if node_matches(node, key) {
                node.status = status;
                node.started_at = None;
                node.finished_at = Some(Instant::now());
                node.output.append_text(&output);
                node.output.duration = duration;
                if status == TestStatus::Failed {
                    node.output.append_nextest_failure(duration);
                }
            }
        });
        self.recompute_statuses();
    }

    pub fn append_test_output(&mut self, key: &TestKey, output: String) {
        visit_mut(&mut self.root, &mut |node| {
            if node_matches(node, key) {
                node.output.append_text(&output);
            }
        });
    }

    pub fn append_test_event(
        &mut self,
        key: &TestKey,
        event: &nextdeck_helper::TestEvent,
        line: &str,
    ) -> bool {
        let mut appended = false;
        visit_mut(&mut self.root, &mut |node| {
            if node_matches(node, key) {
                node.output.append_event(event.level, line);
                appended = true;
            }
        });
        if appended {
            self.recompute_statuses();
        }
        appended
    }

    pub fn stop_running_tests(&mut self) {
        visit_mut(&mut self.root, &mut |node| {
            if node.status == TestStatus::Running {
                node.status = TestStatus::Pending;
                node.started_at = None;
                node.run_started_at = None;
                node.finished_at = None;
            }
        });
        self.recompute_statuses();
    }

    pub fn append_runner_output(&mut self, line: String) {
        self.runner_output.push(bounded_text(line));
        if self.runner_output.len() > 500 {
            self.runner_output.drain(0..100);
        }
    }

    pub fn runner_output_tail(&self, max_lines: usize) -> String {
        let start = self.runner_output.len().saturating_sub(max_lines);
        self.runner_output[start..].join("\n")
    }

    fn clear_runner_output(&mut self) {
        self.runner_output.clear();
    }

    pub fn refresh_from_tests(&mut self, tests: Vec<DiscoveredTest>) {
        let filter = self.view_filter;
        *self = Self::from_tests(tests);
        self.set_view_filter(filter);
    }

    pub fn selected_output(&self) -> String {
        if let Some(node) = self.selected_node() {
            if matches!(node.kind, NodeKind::Test(_)) {
                return node.output.captured_text();
            }
            return descendant_outputs(node);
        }

        if self.runner_output.is_empty() {
            "Select a test to inspect captured output. Press r to run, R to rerun failures, q to quit."
                .to_owned()
        } else {
            self.runner_output.join("\n")
        }
    }

    pub fn failed_test_selectors(&self) -> Vec<crate::nextest::TestSelector> {
        let mut tests = Vec::new();
        visit(&self.root, &mut |node| {
            if node.status == TestStatus::Failed
                && let NodeKind::Test(test) = &node.kind
            {
                tests.push(crate::nextest::TestSelector::from_test(test));
            }
        });
        tests
    }

    pub fn select_next_failed(&mut self) -> bool {
        let visible = self.visible_rows_with_selection();
        let rows = visible.rows;
        if rows.is_empty() {
            return false;
        }
        let start = visible.selected_index.saturating_add(1);
        if let Some(index) = rows
            .iter()
            .enumerate()
            .skip(start)
            .chain(rows.iter().enumerate().take(start))
            .find_map(|(index, row)| (row.node.status == TestStatus::Failed).then_some(index))
        {
            self.selected = rows[index].node.id.clone();
            true
        } else {
            false
        }
    }

    pub fn select_previous_failed(&mut self) -> bool {
        let visible = self.visible_rows_with_selection();
        let rows = visible.rows;
        if rows.is_empty() {
            return false;
        }
        let start = visible.selected_index;
        let mut indices = (0..start).rev().chain((start + 1..rows.len()).rev());
        if let Some(index) = indices.find(|index| rows[*index].node.status == TestStatus::Failed) {
            self.selected = rows[index].node.id.clone();
            true
        } else {
            false
        }
    }

    pub fn selected_path(&self) -> String {
        let Some(node) = self.selected_node() else {
            return "workspace".to_owned();
        };

        match &node.kind {
            NodeKind::Workspace => "workspace".to_owned(),
            NodeKind::Package { name } => name.clone(),
            NodeKind::Binary { package, name, .. } => format!("{package}::{name}"),
            NodeKind::Module { path } => path.clone(),
            NodeKind::Test(test) => format!("{}::{}", test.package, test.full_name),
        }
    }

    pub fn status_counts_for_scope(&self, scope: &crate::nextest::RunScope) -> StatusCounts {
        let mut counts = StatusCounts::default();
        visit(&self.root, &mut |node| {
            if let NodeKind::Test(test) = &node.kind
                && scope.matches_test(test)
            {
                add_status_count(&mut counts, node.status);
            }
        });
        counts
    }

    pub fn progress_for_scope(&self, scope: &crate::nextest::RunScope) -> (usize, usize) {
        let mut finished = 0;
        let mut total = 0;
        visit(&self.root, &mut |node| {
            if let NodeKind::Test(test) = &node.kind
                && scope.matches_test(test)
                && !test.ignored
            {
                total += 1;
                if matches!(
                    node.status,
                    TestStatus::Passed | TestStatus::Failed | TestStatus::Skipped
                ) {
                    finished += 1;
                }
            }
        });
        (finished, total)
    }

    fn insert_test(&mut self, test: DiscoveredTest) {
        let package_index = child_position(&self.root, &test.package).unwrap_or_else(|| {
            self.root.children.push(TestNode::new(
                NodeId::Package {
                    name: test.package.clone(),
                },
                &test.package,
                NodeKind::Package {
                    name: test.package.clone(),
                },
            ));
            self.root.children.len() - 1
        });

        let mut parent = &mut self.root.children[package_index];
        if test.binary_kind == "test" {
            let index = child_position(parent, &test.binary).unwrap_or_else(|| {
                parent.children.push(TestNode::new(
                    NodeId::Binary {
                        package: test.package.clone(),
                        name: test.binary.clone(),
                        kind: test.binary_kind.clone(),
                    },
                    &test.binary,
                    NodeKind::Binary {
                        package: test.package.clone(),
                        name: test.binary.clone(),
                        kind: test.binary_kind.clone(),
                    },
                ));
                parent.children.len() - 1
            });
            parent = &mut parent.children[index];
        }

        let mut module_path = String::new();
        if let Some(module) = &test.module {
            for part in module.split("::") {
                if !module_path.is_empty() {
                    module_path.push_str("::");
                }
                module_path.push_str(part);
                let index = child_position(parent, part).unwrap_or_else(|| {
                    parent.children.push(TestNode::new(
                        NodeId::Module {
                            package: test.package.clone(),
                            binary: test.binary.clone(),
                            kind: test.binary_kind.clone(),
                            path: module_path.clone(),
                        },
                        part,
                        NodeKind::Module {
                            path: module_path.clone(),
                        },
                    ));
                    parent.children.len() - 1
                });
                parent = &mut parent.children[index];
            }
        }

        let mut node = TestNode::new(
            NodeId::Test {
                key: test.key.clone(),
            },
            test.name.clone(),
            NodeKind::Test(Box::new(test.clone())),
        );
        node.status = test.status;
        node.expanded = false;
        parent.children.push(node);
    }

    fn recompute_statuses(&mut self) {
        recompute_node_state(&mut self.root);
    }

    fn clamp_selection(&mut self) {
        if !self.is_selected_visible() {
            self.selected = self
                .visible_rows()
                .first()
                .map(|row| row.node.id.clone())
                .unwrap_or(NodeId::Workspace);
        }
    }

    fn with_selected_mut(&mut self, f: impl FnMut(&mut TestNode)) {
        let target = self.selected.clone();
        self.with_id_mut(&target, f);
    }

    fn with_id_mut(&mut self, target: &NodeId, mut f: impl FnMut(&mut TestNode)) {
        let _ = with_id_mut(&mut self.root, target, &mut f);
    }

    fn node(&self, id: &NodeId) -> Option<&TestNode> {
        node(&self.root, id)
    }

    fn is_selected_visible(&self) -> bool {
        self.visible_rows()
            .iter()
            .any(|row| row.node.id == self.selected)
    }
}

fn add_status_count(counts: &mut StatusCounts, status: TestStatus) {
    match status {
        TestStatus::Pending => counts.pending += 1,
        TestStatus::Running => counts.running += 1,
        TestStatus::Passed => counts.passed += 1,
        TestStatus::Failed => counts.failed += 1,
        TestStatus::Ignored => counts.ignored += 1,
        TestStatus::Skipped => counts.skipped += 1,
    }
}

fn child_position(parent: &TestNode, label: &str) -> Option<usize> {
    parent
        .children
        .iter()
        .position(|child| child.label == label)
}

fn collect_visible<'a>(
    node: &'a TestNode,
    depth: usize,
    filter: TestViewFilter,
    force_include: bool,
    rows: &mut Vec<TreeRow<'a>>,
) {
    if !force_include && !node_has_visible_tests(node, filter) {
        return;
    }

    rows.push(TreeRow { depth, node });
    if node.expanded {
        for child in &node.children {
            collect_visible(child, depth + 1, filter, false, rows);
        }
    }
}

fn node_has_visible_tests(node: &TestNode, filter: TestViewFilter) -> bool {
    match &node.kind {
        NodeKind::Test(_) => filter.allows(node.status),
        NodeKind::Workspace
        | NodeKind::Package { .. }
        | NodeKind::Binary { .. }
        | NodeKind::Module { .. } => node
            .children
            .iter()
            .any(|child| node_has_visible_tests(child, filter)),
    }
}

fn node<'a>(current: &'a TestNode, target: &NodeId) -> Option<&'a TestNode> {
    if current.id == *target {
        return Some(current);
    }

    current
        .children
        .iter()
        .find_map(|child| node(child, target))
}

fn with_id_mut(node: &mut TestNode, target: &NodeId, f: &mut impl FnMut(&mut TestNode)) -> bool {
    if node.id == *target {
        f(node);
        return true;
    }

    for child in &mut node.children {
        if with_id_mut(child, target, f) {
            return true;
        }
    }
    false
}

fn visit(node: &TestNode, f: &mut impl FnMut(&TestNode)) {
    f(node);
    for child in &node.children {
        visit(child, f);
    }
}

fn visit_mut(node: &mut TestNode, f: &mut impl FnMut(&mut TestNode)) {
    f(node);
    for child in &mut node.children {
        visit_mut(child, f);
    }
}

fn recompute_node_state(node: &mut TestNode) -> (TestStatus, bool) {
    if matches!(node.kind, NodeKind::Test(_)) {
        node.has_events = node.output.has_events();
        return (node.status, node.has_events);
    }

    let mut aggregate = None;
    let mut has_events = node.output.has_events();
    for child in &mut node.children {
        let (status, child_has_events) = recompute_node_state(child);
        has_events |= child_has_events;
        aggregate = Some(match aggregate {
            Some(current) => merge_status(current, status),
            None => status,
        });
    }
    let aggregate = aggregate.unwrap_or(TestStatus::Pending);
    node.status = aggregate;
    node.has_events = has_events;
    (aggregate, has_events)
}

fn merge_status(current: TestStatus, next: TestStatus) -> TestStatus {
    use TestStatus::{Failed, Ignored, Passed, Pending, Running, Skipped};
    match (current, next) {
        (Running, _) | (_, Running) => Running,
        (Failed, _) | (_, Failed) => Failed,
        (Pending, _) | (_, Pending) => Pending,
        (Skipped, _) | (_, Skipped) => Skipped,
        (Ignored, Passed) | (Passed, Ignored) | (Ignored, Ignored) => Ignored,
        (Passed, Passed) => Passed,
    }
}

fn node_matches(node: &TestNode, key: &TestKey) -> bool {
    let NodeKind::Test(test) = &node.kind else {
        return false;
    };

    if let Some(binary_id) = &key.binary_id {
        test.key.binary_id.as_deref() == Some(binary_id.as_str()) && test.key.name == key.name
    } else if let Some(event_prefix) = &key.event_prefix {
        test.key.event_prefix.as_deref() == Some(event_prefix.as_str()) && test.key.name == key.name
    } else {
        test.key.name == key.name
    }
}

fn descendant_outputs(node: &TestNode) -> String {
    let mut output = String::new();
    let mut has_output = false;
    visit(node, &mut |child| {
        if let NodeKind::Test(test) = &child.kind
            && has_observable_output(child)
        {
            let prefix = format!(
                "{}{}::{} [{}]\n",
                if has_output { "\n\n" } else { "" },
                test.package,
                test.full_name,
                status_label(child.status)
            );
            let section = bounded_output_section(&prefix, child.output.display_text());
            append_bounded_text(&mut output, &section);
            has_output = true;
        }
    });

    if !has_output {
        if descendant_test_count(node) == 0 {
            "No tests under this selection".to_owned()
        } else {
            "No captured output for tests under this selection yet".to_owned()
        }
    } else {
        output
    }
}

fn has_observable_output(node: &TestNode) -> bool {
    node.status != TestStatus::Pending
        || node.output.duration.is_some()
        || node.output.has_entries()
}

fn descendant_test_count(node: &TestNode) -> usize {
    let mut count = 0;
    visit(node, &mut |child| {
        if matches!(child.kind, NodeKind::Test(_)) {
            count += 1;
        }
    });
    count
}

fn status_label(status: TestStatus) -> &'static str {
    match status {
        TestStatus::Pending => "pending",
        TestStatus::Running => "running",
        TestStatus::Passed => "passed",
        TestStatus::Failed => "failed",
        TestStatus::Ignored => "ignored",
        TestStatus::Skipped => "skipped",
    }
}

fn workspace_label(tests: &[DiscoveredTest]) -> String {
    let Some(path) = common_cwd(tests) else {
        return "workspace".to_owned();
    };
    if path.as_os_str().is_empty() {
        "workspace".to_owned()
    } else {
        path.display().to_string()
    }
}

fn common_cwd(tests: &[DiscoveredTest]) -> Option<PathBuf> {
    let mut iter = tests.iter();
    let first = iter.next()?.cwd.clone();
    let mut common = first.components().collect::<Vec<_>>();

    for test in iter {
        let other = test.cwd.components().collect::<Vec<_>>();
        let shared_len = common
            .iter()
            .zip(other.iter())
            .take_while(|(left, right)| left == right)
            .count();
        common.truncate(shared_len);
    }

    Some(components_to_path(&common))
}

fn components_to_path(components: &[Component<'_>]) -> PathBuf {
    let mut path = PathBuf::new();
    for component in components {
        path.push(component.as_os_str());
    }
    path
}

#[cfg(test)]
mod tests;