mago-reporting 1.20.1

Structured error and diagnostic reporting utilities.
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
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
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! Issue reporting and formatting for Mago.
//!
//! This crate provides functionality for reporting code issues identified by the linter and analyzer.
//! It includes support for multiple output formats, baseline filtering, and rich terminal output.
//!
//! # Core Types
//!
//! - [`Issue`]: Represents a single code issue with severity level, annotations, and optional fixes
//! - [`IssueCollection`]: A collection of issues with filtering and sorting capabilities
//! - [`reporter::Reporter`]: Handles formatting and outputting issues in various formats
//! - [`baseline::Baseline`]: Manages baseline files to filter out known issues

use std::cmp::Ordering;
use std::iter::Once;
use std::str::FromStr;

use foldhash::HashMap;
use foldhash::HashMapExt;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use strum::Display;
use strum::VariantNames;

use mago_database::GlobSettings;
use mago_database::file::FileId;
use mago_database::matcher::ExclusionMatcher;
use mago_span::Span;
use mago_text_edit::TextEdit;

/// Represents an entry in the analyzer's `ignore` configuration.
///
/// Can be either a plain code string (ignored everywhere) or a scoped entry
/// that only ignores a code in specific paths. Scoped paths accept both
/// plain directory/file prefixes (e.g. `"tests/"`, `"src/Legacy.php"`) and
/// glob patterns (e.g. `"src/**/*.php"`); entries
/// containing any of `*`, `?`, `[`, `{` are matched with [`ExclusionMatcher`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum IgnoreEntry {
    /// Ignore a code everywhere: `"code1"`
    Code(String),
    /// Ignore a code in specific paths or glob patterns:
    /// `{ code = "code2", in = ["tests/", "src/**/*.php"] }`
    Scoped {
        code: String,
        #[serde(rename = "in", deserialize_with = "one_or_many")]
        paths: Vec<String>,
    },
}

fn one_or_many<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMany {
        One(String),
        Many(Vec<String>),
    }

    match OneOrMany::deserialize(deserializer)? {
        OneOrMany::One(s) => Ok(vec![s]),
        OneOrMany::Many(v) => Ok(v),
    }
}

mod formatter;
mod internal;

pub mod baseline;
pub mod color;
pub mod error;
pub mod output;
pub mod reporter;

pub use color::ColorChoice;
pub use formatter::ReportingFormat;
pub use output::ReportingTarget;

/// Represents the kind of annotation associated with an issue.
#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Deserialize, Serialize)]
pub enum AnnotationKind {
    /// A primary annotation, typically highlighting the main source of the issue.
    Primary,
    /// A secondary annotation, providing additional context or related information.
    Secondary,
}

/// An annotation associated with an issue, providing additional context or highlighting specific code spans.
#[derive(Debug, PartialEq, Eq, Ord, Clone, Hash, PartialOrd, Deserialize, Serialize)]
pub struct Annotation {
    /// An optional message associated with the annotation.
    pub message: Option<String>,
    /// The kind of annotation.
    pub kind: AnnotationKind,
    /// The code span that the annotation refers to.
    pub span: Span,
}

/// Represents the severity level of an issue.
#[derive(
    Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Deserialize, Serialize, Display, VariantNames, JsonSchema,
)]
#[strum(serialize_all = "lowercase")]
pub enum Level {
    /// A note, providing additional information or context.
    #[serde(alias = "note")]
    Note,
    /// A help message, suggesting possible solutions or further actions.
    #[serde(alias = "help")]
    Help,
    /// A warning, indicating a potential problem that may need attention.
    #[serde(alias = "warning", alias = "warn")]
    Warning,
    /// An error, indicating a problem that prevents the code from functioning correctly.
    #[serde(alias = "error", alias = "err")]
    Error,
}

impl FromStr for Level {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "note" => Ok(Self::Note),
            "help" => Ok(Self::Help),
            "warning" => Ok(Self::Warning),
            "error" => Ok(Self::Error),
            _ => Err(()),
        }
    }
}

type IssueEdits = Vec<TextEdit>;
type IssueEditBatches = Vec<(Option<String>, IssueEdits)>;

/// Represents an issue identified in the code.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Issue {
    /// The severity level of the issue.
    pub level: Level,
    /// An optional code associated with the issue.
    pub code: Option<String>,
    /// The main message describing the issue.
    pub message: String,
    /// Additional notes related to the issue.
    pub notes: Vec<String>,
    /// An optional help message suggesting possible solutions or further actions.
    pub help: Option<String>,
    /// An optional link to external resources for more information about the issue.
    pub link: Option<String>,
    /// Annotations associated with the issue, providing additional context or highlighting specific code spans.
    pub annotations: Vec<Annotation>,
    /// Text edits that can be applied to fix the issue, grouped by file.
    pub edits: HashMap<FileId, IssueEdits>,
}

/// A collection of issues.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct IssueCollection {
    issues: Vec<Issue>,
}

impl AnnotationKind {
    /// Returns `true` if this annotation kind is primary.
    #[inline]
    #[must_use]
    pub const fn is_primary(&self) -> bool {
        matches!(self, AnnotationKind::Primary)
    }

    /// Returns `true` if this annotation kind is secondary.
    #[inline]
    #[must_use]
    pub const fn is_secondary(&self) -> bool {
        matches!(self, AnnotationKind::Secondary)
    }
}

impl Annotation {
    /// Creates a new annotation with the given kind and span.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_database::file::FileId;
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let file = FileId::zero();
    /// let start = Position::new(0);
    /// let end = Position::new(5);
    /// let span = Span::new(file, start, end);
    /// let annotation = Annotation::new(AnnotationKind::Primary, span);
    /// ```
    #[must_use]
    pub fn new(kind: AnnotationKind, span: Span) -> Self {
        Self { message: None, kind, span }
    }

    /// Creates a new primary annotation with the given span.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_database::file::FileId;
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let file = FileId::zero();
    /// let start = Position::new(0);
    /// let end = Position::new(5);
    /// let span = Span::new(file, start, end);
    /// let annotation = Annotation::primary(span);
    /// ```
    #[must_use]
    pub fn primary(span: Span) -> Self {
        Self::new(AnnotationKind::Primary, span)
    }

    /// Creates a new secondary annotation with the given span.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_database::file::FileId;
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let file = FileId::zero();
    /// let start = Position::new(0);
    /// let end = Position::new(5);
    /// let span = Span::new(file, start, end);
    /// let annotation = Annotation::secondary(span);
    /// ```
    #[must_use]
    pub fn secondary(span: Span) -> Self {
        Self::new(AnnotationKind::Secondary, span)
    }

    /// Sets the message of this annotation.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Annotation, AnnotationKind};
    /// use mago_database::file::FileId;
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let file = FileId::zero();
    /// let start = Position::new(0);
    /// let end = Position::new(5);
    /// let span = Span::new(file, start, end);
    /// let annotation = Annotation::primary(span).with_message("This is a primary annotation");
    /// ```
    #[must_use]
    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.message = Some(message.into());

        self
    }

    /// Returns `true` if this annotation is a primary annotation.
    #[must_use]
    pub fn is_primary(&self) -> bool {
        self.kind == AnnotationKind::Primary
    }
}

impl Level {
    /// Downgrades the level to the next lower severity.
    ///
    /// This function maps levels to their less severe counterparts:
    ///
    /// - `Error` becomes `Warning`
    /// - `Warning` becomes `Help`
    /// - `Help` becomes `Note`
    /// - `Note` remains as `Note`
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Level;
    ///
    /// let level = Level::Error;
    /// assert_eq!(level.downgrade(), Level::Warning);
    ///
    /// let level = Level::Warning;
    /// assert_eq!(level.downgrade(), Level::Help);
    ///
    /// let level = Level::Help;
    /// assert_eq!(level.downgrade(), Level::Note);
    ///
    /// let level = Level::Note;
    /// assert_eq!(level.downgrade(), Level::Note);
    /// ```
    #[must_use]
    pub fn downgrade(&self) -> Self {
        match self {
            Level::Error => Level::Warning,
            Level::Warning => Level::Help,
            Level::Help | Level::Note => Level::Note,
        }
    }
}

impl Issue {
    /// Creates a new issue with the given level and message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Issue, Level};
    ///
    /// let issue = Issue::new(Level::Error, "This is an error");
    /// ```
    pub fn new(level: Level, message: impl Into<String>) -> Self {
        Self {
            level,
            code: None,
            message: message.into(),
            annotations: Vec::new(),
            notes: Vec::new(),
            help: None,
            link: None,
            edits: HashMap::default(),
        }
    }

    /// Creates a new error issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error");
    /// ```
    pub fn error(message: impl Into<String>) -> Self {
        Self::new(Level::Error, message)
    }

    /// Creates a new warning issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::warning("This is a warning");
    /// ```
    pub fn warning(message: impl Into<String>) -> Self {
        Self::new(Level::Warning, message)
    }

    /// Creates a new help issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::help("This is a help message");
    /// ```
    pub fn help(message: impl Into<String>) -> Self {
        Self::new(Level::Help, message)
    }

    /// Creates a new note issue with the given message.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::note("This is a note");
    /// ```
    pub fn note(message: impl Into<String>) -> Self {
        Self::new(Level::Note, message)
    }

    /// Adds a code to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Issue, Level};
    ///
    /// let issue = Issue::error("This is an error").with_code("E0001");
    /// ```
    #[must_use]
    pub fn with_code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());

        self
    }

    /// Add an annotation to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::{Issue, Annotation, AnnotationKind};
    /// use mago_database::file::FileId;
    /// use mago_span::Span;
    /// use mago_span::Position;
    ///
    /// let file = FileId::zero();
    /// let start = Position::new(0);
    /// let end = Position::new(5);
    /// let span = Span::new(file, start, end);
    ///
    /// let issue = Issue::error("This is an error").with_annotation(Annotation::primary(span));
    /// ```
    #[must_use]
    pub fn with_annotation(mut self, annotation: Annotation) -> Self {
        self.annotations.push(annotation);

        self
    }

    #[must_use]
    pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
        self.annotations.extend(annotation);

        self
    }

    /// Returns the deterministic primary annotation for this issue.
    ///
    /// If multiple primary annotations exist, the one with the smallest span is returned.
    #[must_use]
    pub fn primary_annotation(&self) -> Option<&Annotation> {
        self.annotations.iter().filter(|annotation| annotation.is_primary()).min_by_key(|annotation| annotation.span)
    }

    /// Returns the deterministic primary span for this issue.
    #[must_use]
    pub fn primary_span(&self) -> Option<Span> {
        self.primary_annotation().map(|annotation| annotation.span)
    }

    /// Add a note to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error").with_note("This is a note");
    /// ```
    #[must_use]
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());

        self
    }

    /// Add a help message to this issue.
    ///
    /// This is useful for providing additional context to the user on how to resolve the issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error").with_help("This is a help message");
    /// ```
    #[must_use]
    pub fn with_help(mut self, help: impl Into<String>) -> Self {
        self.help = Some(help.into());

        self
    }

    /// Add a link to this issue.
    ///
    /// # Examples
    ///
    /// ```
    /// use mago_reporting::Issue;
    ///
    /// let issue = Issue::error("This is an error").with_link("https://example.com");
    /// ```
    #[must_use]
    pub fn with_link(mut self, link: impl Into<String>) -> Self {
        self.link = Some(link.into());

        self
    }

    /// Add a single edit to this issue.
    #[must_use]
    pub fn with_edit(mut self, file_id: FileId, edit: TextEdit) -> Self {
        self.edits.entry(file_id).or_default().push(edit);

        self
    }

    /// Add multiple edits to this issue.
    #[must_use]
    pub fn with_file_edits(mut self, file_id: FileId, edits: IssueEdits) -> Self {
        if !edits.is_empty() {
            self.edits.entry(file_id).or_default().extend(edits);
        }

        self
    }

    /// Take the edits from this issue.
    #[must_use]
    pub fn take_edits(&mut self) -> HashMap<FileId, IssueEdits> {
        std::mem::replace(&mut self.edits, HashMap::with_capacity(0))
    }
}

impl IssueCollection {
    #[must_use]
    pub fn new() -> Self {
        Self { issues: Vec::new() }
    }

    pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
        Self { issues: issues.into_iter().collect() }
    }

    pub fn push(&mut self, issue: Issue) {
        self.issues.push(issue);
    }

    pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
        self.issues.extend(issues);
    }

    pub fn reserve(&mut self, additional: usize) {
        self.issues.reserve(additional);
    }

    pub fn shrink_to_fit(&mut self) {
        self.issues.shrink_to_fit();
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.issues.is_empty()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.issues.len()
    }

    /// Filters the issues in the collection to only include those with a severity level
    /// lower than or equal to the given level.
    #[must_use]
    pub fn with_maximum_level(self, level: Level) -> Self {
        Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
    }

    /// Filters the issues in the collection to only include those with a severity level
    ///  higher than or equal to the given level.
    #[must_use]
    pub fn with_minimum_level(self, level: Level) -> Self {
        Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
    }

    /// Returns `true` if the collection contains any issues with a severity level
    ///  higher than or equal to the given level.
    #[must_use]
    pub fn has_minimum_level(&self, level: Level) -> bool {
        self.issues.iter().any(|issue| issue.level >= level)
    }

    /// Returns the number of issues in the collection with the given severity level.
    #[must_use]
    pub fn get_level_count(&self, level: Level) -> usize {
        self.issues.iter().filter(|issue| issue.level == level).count()
    }

    /// Returns the highest severity level of the issues in the collection.
    #[must_use]
    pub fn get_highest_level(&self) -> Option<Level> {
        self.issues.iter().map(|issue| issue.level).max()
    }

    /// Returns the lowest severity level of the issues in the collection.
    #[must_use]
    pub fn get_lowest_level(&self) -> Option<Level> {
        self.issues.iter().map(|issue| issue.level).min()
    }

    pub fn filter_out_ignored<F>(&mut self, ignore: &[IgnoreEntry], glob: GlobSettings, resolve_file_name: F)
    where
        F: Fn(FileId) -> Option<String>,
    {
        if ignore.is_empty() {
            return;
        }

        enum CompiledEntry<'a> {
            Code(&'a str),
            Scoped { code: &'a str, matcher: ExclusionMatcher<&'a str> },
        }

        let compiled: Vec<CompiledEntry<'_>> = ignore
            .iter()
            .filter_map(|entry| match entry {
                IgnoreEntry::Code(code) => Some(CompiledEntry::Code(code.as_str())),
                IgnoreEntry::Scoped { code, paths } => {
                    match ExclusionMatcher::compile(paths.iter().map(String::as_str), glob) {
                        Ok(matcher) => Some(CompiledEntry::Scoped { code: code.as_str(), matcher }),
                        Err(err) => {
                            tracing::error!(
                                "Failed to compile ignore patterns for `{code}`: {err}. Entry will be skipped."
                            );
                            None
                        }
                    }
                }
            })
            .collect();

        self.issues.retain(|issue| {
            let Some(code) = &issue.code else {
                return true;
            };

            let mut resolved_file_name: Option<Option<String>> = None;

            for entry in &compiled {
                match entry {
                    CompiledEntry::Code(ignored) if *ignored == code => return false,
                    CompiledEntry::Scoped { code: ignored, matcher } if *ignored == code => {
                        let file_name = resolved_file_name
                            .get_or_insert_with(|| {
                                issue.primary_span().and_then(|span| resolve_file_name(span.file_id))
                            })
                            .as_deref();

                        if let Some(name) = file_name
                            && matcher.is_match(name)
                        {
                            return false;
                        }
                    }
                    _ => {}
                }
            }

            true
        });
    }

    pub fn filter_retain_codes(&mut self, retain_codes: &[String]) {
        self.issues.retain(|issue| if let Some(code) = &issue.code { retain_codes.contains(code) } else { false });
    }

    pub fn take_edits(&mut self) -> impl Iterator<Item = (FileId, IssueEdits)> + '_ {
        self.issues.iter_mut().flat_map(|issue| issue.take_edits().into_iter())
    }

    /// Filters the issues in the collection to only include those that have associated edits.
    #[must_use]
    pub fn with_edits(self) -> Self {
        Self { issues: self.issues.into_iter().filter(|issue| !issue.edits.is_empty()).collect() }
    }

    /// Sorts the issues in the collection.
    ///
    /// The issues are sorted by severity level in ascending order,
    /// then by code in ascending order, and finally by the primary annotation span.
    #[must_use]
    pub fn sorted(self) -> Self {
        let mut issues = self.issues;

        issues.sort_by(|a, b| match a.level.cmp(&b.level) {
            Ordering::Greater => Ordering::Greater,
            Ordering::Less => Ordering::Less,
            Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
                Ordering::Less => Ordering::Less,
                Ordering::Greater => Ordering::Greater,
                Ordering::Equal => {
                    let a_span = a.primary_span();
                    let b_span = b.primary_span();

                    match (a_span, b_span) {
                        (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
                        (Some(_), None) => Ordering::Less,
                        (None, Some(_)) => Ordering::Greater,
                        (None, None) => Ordering::Equal,
                    }
                }
            },
        });

        Self { issues }
    }

    pub fn iter(&self) -> impl Iterator<Item = &Issue> {
        self.issues.iter()
    }

    /// Converts the collection into a map of edit batches grouped by file.
    ///
    /// Each batch contains all edits from a single issue along with the rule code.
    /// All edits from an issue must be applied together as a batch to maintain code validity.
    ///
    /// Returns `HashMap<FileId, Vec<(Option<String>, IssueEdits)>>` where each tuple
    /// is (rule_code, edits_for_that_issue).
    #[must_use]
    pub fn to_edit_batches(self) -> HashMap<FileId, IssueEditBatches> {
        let mut result: HashMap<FileId, Vec<(Option<String>, IssueEdits)>> = HashMap::default();
        for issue in self.issues.into_iter().filter(|issue| !issue.edits.is_empty()) {
            let code = issue.code;
            for (file_id, edit_list) in issue.edits {
                result.entry(file_id).or_default().push((code.clone(), edit_list));
            }
        }

        result
    }
}

impl IntoIterator for IssueCollection {
    type Item = Issue;

    type IntoIter = std::vec::IntoIter<Issue>;

    fn into_iter(self) -> Self::IntoIter {
        self.issues.into_iter()
    }
}

impl<'a> IntoIterator for &'a IssueCollection {
    type Item = &'a Issue;

    type IntoIter = std::slice::Iter<'a, Issue>;

    fn into_iter(self) -> Self::IntoIter {
        self.issues.iter()
    }
}

impl Default for IssueCollection {
    fn default() -> Self {
        Self::new()
    }
}

impl IntoIterator for Issue {
    type Item = Issue;
    type IntoIter = Once<Issue>;

    fn into_iter(self) -> Self::IntoIter {
        std::iter::once(self)
    }
}

impl FromIterator<Issue> for IssueCollection {
    fn from_iter<T: IntoIterator<Item = Issue>>(iter: T) -> Self {
        Self { issues: iter.into_iter().collect() }
    }
}

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

    #[test]
    pub fn test_highest_collection_level() {
        let mut collection = IssueCollection::from(vec![]);
        assert_eq!(collection.get_highest_level(), None);

        collection.push(Issue::note("note"));
        assert_eq!(collection.get_highest_level(), Some(Level::Note));

        collection.push(Issue::help("help"));
        assert_eq!(collection.get_highest_level(), Some(Level::Help));

        collection.push(Issue::warning("warning"));
        assert_eq!(collection.get_highest_level(), Some(Level::Warning));

        collection.push(Issue::error("error"));
        assert_eq!(collection.get_highest_level(), Some(Level::Error));
    }

    #[test]
    pub fn test_level_downgrade() {
        assert_eq!(Level::Error.downgrade(), Level::Warning);
        assert_eq!(Level::Warning.downgrade(), Level::Help);
        assert_eq!(Level::Help.downgrade(), Level::Note);
        assert_eq!(Level::Note.downgrade(), Level::Note);
    }

    #[test]
    pub fn test_issue_collection_with_maximum_level() {
        let mut collection = IssueCollection::from(vec![
            Issue::error("error"),
            Issue::warning("warning"),
            Issue::help("help"),
            Issue::note("note"),
        ]);

        collection = collection.with_maximum_level(Level::Warning);
        assert_eq!(collection.len(), 3);
        assert_eq!(
            collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
            vec![Level::Warning, Level::Help, Level::Note]
        );
    }

    #[test]
    pub fn test_issue_collection_with_minimum_level() {
        let mut collection = IssueCollection::from(vec![
            Issue::error("error"),
            Issue::warning("warning"),
            Issue::help("help"),
            Issue::note("note"),
        ]);

        collection = collection.with_minimum_level(Level::Warning);
        assert_eq!(collection.len(), 2);
        assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
    }

    #[test]
    pub fn test_issue_collection_has_minimum_level() {
        let mut collection = IssueCollection::from(vec![]);

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(!collection.has_minimum_level(Level::Warning));
        assert!(!collection.has_minimum_level(Level::Help));
        assert!(!collection.has_minimum_level(Level::Note));

        collection.push(Issue::note("note"));

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(!collection.has_minimum_level(Level::Warning));
        assert!(!collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));

        collection.push(Issue::help("help"));

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(!collection.has_minimum_level(Level::Warning));
        assert!(collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));

        collection.push(Issue::warning("warning"));

        assert!(!collection.has_minimum_level(Level::Error));
        assert!(collection.has_minimum_level(Level::Warning));
        assert!(collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));

        collection.push(Issue::error("error"));

        assert!(collection.has_minimum_level(Level::Error));
        assert!(collection.has_minimum_level(Level::Warning));
        assert!(collection.has_minimum_level(Level::Help));
        assert!(collection.has_minimum_level(Level::Note));
    }

    #[test]
    pub fn test_issue_collection_level_count() {
        let mut collection = IssueCollection::from(vec![]);

        assert_eq!(collection.get_level_count(Level::Error), 0);
        assert_eq!(collection.get_level_count(Level::Warning), 0);
        assert_eq!(collection.get_level_count(Level::Help), 0);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::error("error"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 0);
        assert_eq!(collection.get_level_count(Level::Help), 0);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::warning("warning"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 1);
        assert_eq!(collection.get_level_count(Level::Help), 0);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::help("help"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 1);
        assert_eq!(collection.get_level_count(Level::Help), 1);
        assert_eq!(collection.get_level_count(Level::Note), 0);

        collection.push(Issue::note("note"));

        assert_eq!(collection.get_level_count(Level::Error), 1);
        assert_eq!(collection.get_level_count(Level::Warning), 1);
        assert_eq!(collection.get_level_count(Level::Help), 1);
        assert_eq!(collection.get_level_count(Level::Note), 1);
    }

    #[test]
    pub fn test_primary_span_is_deterministic() {
        let file = FileId::zero();
        let span_later = Span::new(file, 20_u32.into(), 25_u32.into());
        let span_earlier = Span::new(file, 5_u32.into(), 10_u32.into());

        let issue = Issue::error("x")
            .with_annotation(Annotation::primary(span_later))
            .with_annotation(Annotation::primary(span_earlier));

        assert_eq!(issue.primary_span(), Some(span_earlier));
    }

    fn ignore_fixture() -> (IssueCollection, std::collections::HashMap<FileId, &'static str>) {
        let file_id = |name: &str| FileId::new(name);

        let paths = ["src/App.php", "tests/Unit/FooTest.php", "modules/auth/views/login.tpl", "types/user/form.tpl"];

        let mut mapping = std::collections::HashMap::new();
        let issues: Vec<Issue> = paths
            .iter()
            .map(|p| {
                let id = file_id(p);
                mapping.insert(id, *p);
                Issue::error("oops").with_code("invalid-global").with_annotation(Annotation::primary(Span::new(
                    id,
                    0_u32.into(),
                    1_u32.into(),
                )))
            })
            .collect();

        (IssueCollection::from(issues), mapping)
    }

    #[test]
    pub fn test_filter_out_ignored_with_plain_prefix() {
        let (mut collection, mapping) = ignore_fixture();
        let ignore =
            vec![IgnoreEntry::Scoped { code: "invalid-global".to_string(), paths: vec!["tests/".to_string()] }];

        collection.filter_out_ignored(&ignore, GlobSettings::default(), |id| mapping.get(&id).map(|s| s.to_string()));

        let remaining: Vec<String> = collection
            .iter()
            .flat_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
            .map(String::from)
            .collect();

        assert_eq!(
            remaining,
            vec![
                "src/App.php".to_string(),
                "modules/auth/views/login.tpl".to_string(),
                "types/user/form.tpl".to_string(),
            ]
        );
    }

    #[test]
    pub fn test_filter_out_ignored_with_glob_pattern() {
        let (mut collection, mapping) = ignore_fixture();
        let ignore = vec![IgnoreEntry::Scoped {
            code: "invalid-global".to_string(),
            paths: vec!["modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
        }];

        collection.filter_out_ignored(&ignore, GlobSettings::default(), |id| mapping.get(&id).map(|s| s.to_string()));

        let remaining: Vec<String> = collection
            .iter()
            .flat_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
            .map(String::from)
            .collect();

        assert_eq!(remaining, vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string(),]);
    }

    #[test]
    pub fn test_filter_out_ignored_mixes_plain_and_glob() {
        let (mut collection, mapping) = ignore_fixture();
        let ignore = vec![IgnoreEntry::Scoped {
            code: "invalid-global".to_string(),
            paths: vec!["tests/".to_string(), "modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
        }];

        collection.filter_out_ignored(&ignore, GlobSettings::default(), |id| mapping.get(&id).map(|s| s.to_string()));

        let remaining: Vec<String> = collection
            .iter()
            .flat_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
            .map(String::from)
            .collect();

        assert_eq!(remaining, vec!["src/App.php".to_string()]);
    }

    #[test]
    pub fn test_filter_out_ignored_respects_code_scope() {
        let (mut collection, mapping) = ignore_fixture();
        let ignore = vec![IgnoreEntry::Scoped { code: "different-code".to_string(), paths: vec!["**/*".to_string()] }];

        collection.filter_out_ignored(&ignore, GlobSettings::default(), |id| mapping.get(&id).map(|s| s.to_string()));

        assert_eq!(collection.len(), 4);
    }
}