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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use crate::{
    config::{
        CompiledOverride, CustomTestGroup, EarlyProfile, EvaluatableProfile, FinalConfig,
        MaybeTargetSpec, OverrideId, SettingSource, TestGroup, TestGroupConfig,
    },
    errors::ShowTestGroupsError,
    helpers::QuotedDisplay,
    indenter::indented,
    list::{TestInstance, TestList, TestListDisplayFilter},
    write_str::WriteStr,
};
use indexmap::IndexMap;
use owo_colors::{OwoColorize, Style};
use std::{
    collections::{BTreeMap, BTreeSet},
    io,
};

/// Shows sets of tests that are in various groups.
#[derive(Debug)]
pub struct ShowTestGroups<'a> {
    test_list: &'a TestList<'a>,
    indexed_overrides: BTreeMap<TestGroup, IndexMap<OverrideId, ShowTestGroupsData<'a>>>,
    test_group_config: &'a BTreeMap<CustomTestGroup, TestGroupConfig>,
    // This is Some iff settings.show_default is true.
    non_overrides: Option<TestListDisplayFilter<'a>>,
}

impl<'a> ShowTestGroups<'a> {
    /// Validates that the given groups are known to this profile.
    pub fn validate_groups(
        profile: &EarlyProfile<'_>,
        groups: impl IntoIterator<Item = TestGroup>,
    ) -> Result<ValidatedTestGroups, ShowTestGroupsError> {
        let groups = groups.into_iter().collect();
        let known_groups: BTreeSet<_> =
            TestGroup::make_all_groups(profile.test_group_config().keys().cloned()).collect();
        let unknown_groups = &groups - &known_groups;
        if !unknown_groups.is_empty() {
            return Err(ShowTestGroupsError::UnknownGroups {
                unknown_groups,
                known_groups,
            });
        }
        Ok(ValidatedTestGroups(groups))
    }

    /// Creates a new `ShowTestGroups` from the given profile and test list.
    pub fn new(
        profile: &'a EvaluatableProfile<'a>,
        test_list: &'a TestList<'a>,
        settings: &ShowTestGroupSettings,
    ) -> Self {
        let mut indexed_overrides: BTreeMap<_, _> =
            TestGroup::make_all_groups(profile.test_group_config().keys().cloned())
                .filter_map(|group| {
                    settings
                        .mode
                        .matches_group(&group)
                        .then(|| (group, IndexMap::new()))
                })
                .collect();
        let mut non_overrides = settings.show_default.then(TestListDisplayFilter::new);

        for suite in test_list.iter() {
            for (test_name, test_case) in suite.status.test_cases() {
                let test_instance = TestInstance::new(test_name, suite, test_case);
                let query = test_instance.to_test_query();
                let test_settings = profile.settings_with_source_for(&query);
                let (test_group, source) = test_settings.test_group_with_source();

                match source {
                    SettingSource::Override(source) => {
                        let override_map = match indexed_overrides.get_mut(test_group) {
                            Some(override_map) => override_map,
                            None => continue,
                        };
                        let data = override_map
                            .entry(source.id().clone())
                            .or_insert_with(|| ShowTestGroupsData::new(source));
                        data.matching_tests.insert(&suite.binary_id, test_name);
                    }
                    SettingSource::Profile => {
                        if let Some(non_overrides) = non_overrides.as_mut() {
                            if settings.mode.matches_group(&TestGroup::Global) {
                                non_overrides.insert(&suite.binary_id, test_name);
                            }
                        }
                    }
                }
            }
        }

        Self {
            test_list,
            indexed_overrides,
            test_group_config: profile.test_group_config(),
            non_overrides,
        }
    }

    fn should_show_group(&self, group: &TestGroup) -> bool {
        // So this is a bit tricky. We want to show a group if it matches the filter.
        //
        //     group     filter    show-default   |   show?
        //    -------   --------   -------------  |  -------
        //    @global    matches       true       |   always
        //    @global    matches      false       |   only if any overrides set @global
        //    @global   no match         *        |   false  [1]
        //     custom    matches         *        |   always
        //     custom   no match         *        |   false  [1]
        //
        // [1]: filtered out by the constructor above, so not handled below

        match (group, self.non_overrides.is_some()) {
            (TestGroup::Global, true) => true,
            (TestGroup::Global, false) => self
                .indexed_overrides
                .get(group)
                .map(|override_map| !override_map.values().all(|data| data.is_empty()))
                .unwrap_or(false),
            _ => true,
        }
    }

    /// Writes the test groups to the given writer in a human-friendly format.
    pub fn write_human(&self, mut writer: &mut dyn WriteStr, colorize: bool) -> io::Result<()> {
        static INDENT: &str = "      ";

        let mut styles = Styles::default();
        if colorize {
            styles.colorize();
        }

        for (test_group, override_map) in &self.indexed_overrides {
            if !self.should_show_group(test_group) {
                continue;
            }

            write!(writer, "group: {}", test_group.style(styles.group))?;
            if let TestGroup::Custom(group) = test_group {
                write!(
                    writer,
                    " (max threads = {})",
                    self.test_group_config[group]
                        .max_threads
                        .style(styles.max_threads)
                )?;
            }
            writeln!(writer)?;

            let mut any_printed = false;

            for (override_id, data) in override_map {
                any_printed = true;
                write!(
                    writer,
                    "  * override for {} profile",
                    override_id.profile_name.style(styles.profile),
                )?;

                if let Some(expr) = data.override_.filter() {
                    write!(
                        writer,
                        " with filter {}",
                        QuotedDisplay(&expr.parsed).style(styles.filter)
                    )?;
                }
                if let MaybeTargetSpec::Provided(target_spec) = data.override_.target_spec() {
                    write!(
                        writer,
                        " on platform {}",
                        QuotedDisplay(target_spec).style(styles.platform)
                    )?;
                }

                writeln!(writer, ":")?;

                let mut inner_writer = indented(writer).with_str(INDENT);
                self.test_list.write_human_with_filter(
                    &data.matching_tests,
                    &mut inner_writer,
                    false,
                    colorize,
                )?;
                inner_writer.write_str_flush()?;
                writer = inner_writer.into_inner();
            }

            // Also show tests that don't match an override if they match the global config below.
            if test_group == &TestGroup::Global {
                if let Some(non_overrides) = &self.non_overrides {
                    any_printed = true;
                    writeln!(writer, "  * from default settings:")?;
                    let mut inner_writer = indented(writer).with_str(INDENT);
                    self.test_list.write_human_with_filter(
                        non_overrides,
                        &mut inner_writer,
                        false,
                        colorize,
                    )?;
                    inner_writer.write_str_flush()?;
                    writer = inner_writer.into_inner();
                }
            }

            if !any_printed {
                writeln!(writer, "    (no matches)")?;
            }
        }

        Ok(())
    }
}

/// Settings for showing test groups.
#[derive(Clone, Debug)]
pub struct ShowTestGroupSettings {
    /// Whether to show tests that have default settings and don't match any overrides.
    pub show_default: bool,

    /// Which groups of tests to show.
    pub mode: ShowTestGroupsMode,
}

/// Which groups of tests to show.
#[derive(Clone, Debug)]
pub enum ShowTestGroupsMode {
    /// Show all groups.
    All,
    /// Show only the named groups.
    Only(ValidatedTestGroups),
}

impl ShowTestGroupsMode {
    fn matches_group(&self, group: &TestGroup) -> bool {
        match self {
            Self::All => true,
            Self::Only(groups) => groups.0.contains(group),
        }
    }
}

/// Validated test groups, part of [`ShowTestGroupsMode`].
#[derive(Clone, Debug)]
pub struct ValidatedTestGroups(BTreeSet<TestGroup>);

impl ValidatedTestGroups {
    /// Returns the set of test groups.
    pub fn into_inner(self) -> BTreeSet<TestGroup> {
        self.0
    }
}

#[derive(Debug)]
struct ShowTestGroupsData<'a> {
    override_: &'a CompiledOverride<FinalConfig>,
    matching_tests: TestListDisplayFilter<'a>,
}

impl<'a> ShowTestGroupsData<'a> {
    fn new(override_: &'a CompiledOverride<FinalConfig>) -> Self {
        Self {
            override_,
            matching_tests: TestListDisplayFilter::new(),
        }
    }

    fn is_empty(&self) -> bool {
        self.matching_tests.test_count() == 0
    }
}

#[derive(Clone, Debug, Default)]
struct Styles {
    group: Style,
    max_threads: Style,
    profile: Style,
    filter: Style,
    platform: Style,
}

impl Styles {
    fn colorize(&mut self) {
        self.group = Style::new().bold().underline();
        self.max_threads = Style::new().bold();
        self.profile = Style::new().bold();
        self.filter = Style::new().yellow();
        self.platform = Style::new().yellow();
    }
}