1#![allow(clippy::pub_use, clippy::exhaustive_enums)]
2
3use std::borrow::Cow;
16use std::cmp::Ordering;
17use std::collections::hash_map::Entry;
18use std::iter::Once;
19use std::str::FromStr;
20
21use foldhash::HashMap;
22use foldhash::HashMapExt;
23use regex::Regex;
24use schemars::JsonSchema;
25use strum::Display;
26use strum::VariantNames;
27
28use mago_database::GlobSettings;
29use mago_database::file::FileId;
30use mago_database::matcher::ExclusionMatcher;
31use mago_span::Span;
32use mago_text_edit::TextEdit;
33
34mod formatter;
35#[cfg(feature = "serde")]
36mod internal;
37
38pub mod baseline;
39pub mod color;
40pub mod error;
41pub mod output;
42pub mod reporter;
43
44pub use color::ColorChoice;
45pub use formatter::ReportingFormat;
46pub use formatter::utils::osc8_file_hyperlink;
47pub use formatter::utils::osc8_hyperlink;
48pub use output::ReportingTarget;
49
50#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
69#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
70#[cfg_attr(feature = "serde", serde(untagged))]
71pub enum IgnoreEntry {
72 Code(String),
74 Pattern {
77 pattern: String,
83 #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
86 code: Option<String>,
87 #[cfg_attr(
89 feature = "serde",
90 serde(
91 rename = "in",
92 default,
93 skip_serializing_if = "Option::is_none",
94 deserialize_with = "opt_one_or_many"
95 )
96 )]
97 paths: Option<Vec<String>>,
98 },
99 Scoped {
102 code: String,
103 #[cfg_attr(feature = "serde", serde(rename = "in", deserialize_with = "one_or_many"))]
104 paths: Vec<String>,
105 },
106}
107
108#[cfg(feature = "serde")]
109fn one_or_many<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
110where
111 D: serde::Deserializer<'de>,
112{
113 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
114 #[cfg_attr(feature = "serde", serde(untagged))]
115 enum OneOrMany {
116 One(String),
117 Many(Vec<String>),
118 }
119
120 match <OneOrMany as serde::Deserialize>::deserialize(deserializer)? {
121 OneOrMany::One(s) => Ok(vec![s]),
122 OneOrMany::Many(v) => Ok(v),
123 }
124}
125
126#[cfg(feature = "serde")]
127fn opt_one_or_many<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
128where
129 D: serde::Deserializer<'de>,
130{
131 Ok(Some(one_or_many(deserializer)?))
132}
133
134#[derive(Debug, Default)]
141pub struct CompiledIgnoreSet {
142 entries: Vec<CompiledIgnoreEntry>,
143}
144
145#[derive(Debug)]
146enum CompiledIgnoreEntry {
147 Code(String),
148 Scoped { code: String, matcher: ExclusionMatcher<String> },
149 Pattern { regex: Regex, code: Option<String>, matcher: Option<ExclusionMatcher<String>> },
150}
151
152#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd)]
154#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
155pub enum AnnotationKind {
156 Primary,
158 Secondary,
160}
161
162#[derive(Debug, PartialEq, Eq, Ord, Clone, Hash, PartialOrd)]
164#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
165pub struct Annotation {
166 pub message: Option<Cow<'static, str>>,
168 pub kind: AnnotationKind,
170 pub span: Span,
172}
173
174#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Display, VariantNames, JsonSchema)]
176#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
177#[strum(serialize_all = "lowercase")]
178pub enum Level {
179 #[cfg_attr(feature = "serde", serde(alias = "note"))]
181 Note,
182 #[cfg_attr(feature = "serde", serde(alias = "help"))]
184 Help,
185 #[cfg_attr(feature = "serde", serde(alias = "warning", alias = "warn"))]
187 Warning,
188 #[cfg_attr(feature = "serde", serde(alias = "error", alias = "err"))]
190 Error,
191}
192
193impl FromStr for Level {
194 type Err = ();
195
196 fn from_str(s: &str) -> Result<Self, Self::Err> {
197 match s.to_lowercase().as_str() {
198 "note" => Ok(Self::Note),
199 "help" => Ok(Self::Help),
200 "warning" => Ok(Self::Warning),
201 "error" => Ok(Self::Error),
202 _ => Err(()),
203 }
204 }
205}
206
207type IssueEdits = Vec<TextEdit>;
208type IssueEditBatches = Vec<(Option<String>, IssueEdits)>;
209
210#[derive(Debug, Clone, Eq, PartialEq)]
212#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
213pub struct Issue {
214 pub level: Level,
216 pub code: Option<String>,
218 pub message: Cow<'static, str>,
220 pub notes: Vec<Cow<'static, str>>,
222 pub help: Option<Cow<'static, str>>,
224 pub link: Option<String>,
226 pub annotations: Vec<Annotation>,
228 pub edits: HashMap<FileId, IssueEdits>,
230}
231
232#[derive(Debug, Clone, Eq, PartialEq)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235pub struct IssueCollection {
236 issues: Vec<Issue>,
237}
238
239impl AnnotationKind {
240 #[inline]
242 #[must_use]
243 pub const fn is_primary(&self) -> bool {
244 matches!(self, AnnotationKind::Primary)
245 }
246
247 #[inline]
249 #[must_use]
250 pub const fn is_secondary(&self) -> bool {
251 matches!(self, AnnotationKind::Secondary)
252 }
253}
254
255impl CompiledIgnoreSet {
256 #[must_use]
261 pub fn compile(entries: &[IgnoreEntry], glob: GlobSettings) -> Self {
262 let mut compiled = Vec::with_capacity(entries.len());
263 for entry in entries {
264 match entry {
265 IgnoreEntry::Code(code) => compiled.push(CompiledIgnoreEntry::Code(code.clone())),
266 IgnoreEntry::Scoped { code, paths } => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
267 Ok(matcher) => compiled.push(CompiledIgnoreEntry::Scoped { code: code.clone(), matcher }),
268 Err(err) => {
269 tracing::error!("Failed to compile ignore patterns for `{code}`: {err}. Entry will be skipped.")
270 }
271 },
272 IgnoreEntry::Pattern { pattern, code, paths } => {
273 let regex = match Regex::new(pattern) {
274 Ok(regex) => regex,
275 Err(err) => {
276 tracing::error!(
277 "Failed to compile ignore regex `{pattern}`: {err}. Entry will be skipped."
278 );
279
280 continue;
281 }
282 };
283
284 let matcher = match paths {
285 Some(paths) => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
286 Ok(matcher) => Some(matcher),
287 Err(err) => {
288 tracing::error!(
289 "Failed to compile ignore paths for regex `{pattern}`: {err}. Entry will be skipped."
290 );
291
292 continue;
293 }
294 },
295 None => None,
296 };
297
298 compiled.push(CompiledIgnoreEntry::Pattern { regex, code: code.clone(), matcher });
299 }
300 }
301 }
302
303 Self { entries: compiled }
304 }
305
306 #[must_use]
307 pub fn is_empty(&self) -> bool {
308 self.entries.is_empty()
309 }
310
311 #[must_use]
312 pub fn len(&self) -> usize {
313 self.entries.len()
314 }
315}
316
317impl Annotation {
318 #[must_use]
335 pub fn new(kind: AnnotationKind, span: Span) -> Self {
336 Self { message: None, kind, span }
337 }
338
339 #[must_use]
356 pub fn primary(span: Span) -> Self {
357 Self::new(AnnotationKind::Primary, span)
358 }
359
360 #[must_use]
377 pub fn secondary(span: Span) -> Self {
378 Self::new(AnnotationKind::Secondary, span)
379 }
380
381 #[must_use]
398 pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
399 self.message = Some(message.into());
400
401 self
402 }
403
404 #[must_use]
406 pub fn is_primary(&self) -> bool {
407 self.kind == AnnotationKind::Primary
408 }
409}
410
411impl Level {
412 #[must_use]
439 pub fn downgrade(&self) -> Self {
440 match self {
441 Level::Error => Level::Warning,
442 Level::Warning => Level::Help,
443 Level::Help | Level::Note => Level::Note,
444 }
445 }
446}
447
448impl Issue {
449 pub fn new(level: Level, message: impl Into<Cow<'static, str>>) -> Self {
459 Self {
460 level,
461 code: None,
462 message: message.into(),
463 annotations: Vec::new(),
464 notes: Vec::new(),
465 help: None,
466 link: None,
467 edits: HashMap::default(),
468 }
469 }
470
471 pub fn error(message: impl Into<Cow<'static, str>>) -> Self {
481 Self::new(Level::Error, message)
482 }
483
484 pub fn warning(message: impl Into<Cow<'static, str>>) -> Self {
494 Self::new(Level::Warning, message)
495 }
496
497 pub fn help(message: impl Into<Cow<'static, str>>) -> Self {
507 Self::new(Level::Help, message)
508 }
509
510 pub fn note(message: impl Into<Cow<'static, str>>) -> Self {
520 Self::new(Level::Note, message)
521 }
522
523 #[must_use]
533 pub fn with_code(mut self, code: impl Into<String>) -> Self {
534 self.code = Some(code.into());
535
536 self
537 }
538
539 #[must_use]
557 pub fn with_annotation(mut self, annotation: Annotation) -> Self {
558 self.annotations.push(annotation);
559
560 self
561 }
562
563 #[must_use]
564 pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
565 self.annotations.extend(annotation);
566
567 self
568 }
569
570 #[must_use]
574 pub fn primary_annotation(&self) -> Option<&Annotation> {
575 self.annotations.iter().filter(|annotation| annotation.is_primary()).min_by_key(|annotation| annotation.span)
576 }
577
578 #[must_use]
580 pub fn primary_span(&self) -> Option<Span> {
581 self.primary_annotation().map(|annotation| annotation.span)
582 }
583
584 #[must_use]
594 pub fn with_note(mut self, note: impl Into<Cow<'static, str>>) -> Self {
595 self.notes.push(note.into());
596
597 self
598 }
599
600 #[must_use]
612 pub fn with_help(mut self, help: impl Into<Cow<'static, str>>) -> Self {
613 self.help = Some(help.into());
614
615 self
616 }
617
618 #[must_use]
628 pub fn with_link(mut self, link: impl Into<String>) -> Self {
629 self.link = Some(link.into());
630
631 self
632 }
633
634 #[must_use]
636 pub fn with_edit(mut self, file_id: FileId, edit: TextEdit) -> Self {
637 self.edits.entry(file_id).or_default().push(edit);
638
639 self
640 }
641
642 #[must_use]
644 pub fn with_file_edits(mut self, file_id: FileId, edits: IssueEdits) -> Self {
645 if !edits.is_empty() {
646 match self.edits.entry(file_id) {
647 Entry::Vacant(entry) => {
648 entry.insert(edits);
649 }
650 Entry::Occupied(mut entry) => entry.get_mut().extend(edits),
651 }
652 }
653
654 self
655 }
656
657 #[must_use]
659 pub fn take_edits(&mut self) -> HashMap<FileId, IssueEdits> {
660 std::mem::replace(&mut self.edits, HashMap::new())
661 }
662}
663
664impl IssueCollection {
665 #[must_use]
666 pub fn new() -> Self {
667 Self { issues: Vec::new() }
668 }
669
670 pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
671 Self { issues: issues.into_iter().collect() }
672 }
673
674 pub fn push(&mut self, issue: Issue) {
675 self.issues.push(issue);
676 }
677
678 pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
679 self.issues.extend(issues);
680 }
681
682 pub fn reserve(&mut self, additional: usize) {
683 self.issues.reserve(additional);
684 }
685
686 pub fn shrink_to_fit(&mut self) {
687 self.issues.shrink_to_fit();
688 }
689
690 #[must_use]
691 pub fn is_empty(&self) -> bool {
692 self.issues.is_empty()
693 }
694
695 #[must_use]
696 pub fn len(&self) -> usize {
697 self.issues.len()
698 }
699
700 #[must_use]
703 pub fn with_maximum_level(self, level: Level) -> Self {
704 Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
705 }
706
707 #[must_use]
710 pub fn with_minimum_level(self, level: Level) -> Self {
711 Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
712 }
713
714 #[must_use]
717 pub fn has_minimum_level(&self, level: Level) -> bool {
718 self.issues.iter().any(|issue| issue.level >= level)
719 }
720
721 #[must_use]
723 pub fn get_level_count(&self, level: Level) -> usize {
724 self.issues.iter().filter(|issue| issue.level == level).count()
725 }
726
727 #[must_use]
729 pub fn get_highest_level(&self) -> Option<Level> {
730 self.issues.iter().map(|issue| issue.level).max()
731 }
732
733 #[must_use]
735 pub fn get_lowest_level(&self) -> Option<Level> {
736 self.issues.iter().map(|issue| issue.level).min()
737 }
738
739 pub fn filter_out_ignored<F>(&mut self, set: &CompiledIgnoreSet, resolve_file_name: F)
740 where
741 F: Fn(FileId) -> Option<String>,
742 {
743 if set.is_empty() {
744 return;
745 }
746
747 self.issues.retain(|issue| {
748 let mut cached_path: Option<Option<String>> = None;
749 let mut resolve_path = |issue: &Issue| -> Option<String> {
750 cached_path
751 .get_or_insert_with(|| issue.primary_span().and_then(|span| resolve_file_name(span.file_id)))
752 .clone()
753 };
754
755 for entry in &set.entries {
756 match entry {
757 CompiledIgnoreEntry::Code(ignored_code) => {
758 if let Some(code) = &issue.code
759 && ignored_code == code
760 {
761 return false;
762 }
763 }
764 CompiledIgnoreEntry::Scoped { code: ignored_code, matcher } => {
765 let Some(code) = &issue.code else {
766 continue;
767 };
768
769 if ignored_code != code {
770 continue;
771 }
772
773 if let Some(name) = resolve_path(issue)
774 && matcher.is_match(&name)
775 {
776 return false;
777 }
778 }
779 CompiledIgnoreEntry::Pattern { regex, code: ignored_code, matcher } => {
780 if let Some(ignored_code) = ignored_code {
781 let Some(code) = &issue.code else {
782 continue;
783 };
784
785 if ignored_code != code {
786 continue;
787 }
788 }
789
790 if let Some(matcher) = matcher {
791 let Some(name) = resolve_path(issue) else {
792 continue;
793 };
794
795 if !matcher.is_match(&name) {
796 continue;
797 }
798 }
799
800 if issue_text_matches(issue, regex) {
801 return false;
802 }
803 }
804 }
805 }
806
807 true
808 });
809 }
810
811 pub fn filter_retain_codes(&mut self, retain_codes: &[String]) {
812 self.issues.retain(|issue| if let Some(code) = &issue.code { retain_codes.contains(code) } else { false });
813 }
814
815 pub fn take_edits(&mut self) -> impl Iterator<Item = (FileId, IssueEdits)> + '_ {
816 self.issues.iter_mut().flat_map(|issue| issue.take_edits().into_iter())
817 }
818
819 #[must_use]
821 pub fn with_edits(self) -> Self {
822 Self { issues: self.issues.into_iter().filter(|issue| !issue.edits.is_empty()).collect() }
823 }
824
825 #[must_use]
830 pub fn sorted(self) -> Self {
831 let mut issues = self.issues;
832
833 issues.sort_by(|a, b| match a.level.cmp(&b.level) {
834 Ordering::Greater => Ordering::Greater,
835 Ordering::Less => Ordering::Less,
836 Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
837 Ordering::Less => Ordering::Less,
838 Ordering::Greater => Ordering::Greater,
839 Ordering::Equal => {
840 let a_span = a.primary_span();
841 let b_span = b.primary_span();
842
843 match (a_span, b_span) {
844 (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
845 (Some(_), None) => Ordering::Less,
846 (None, Some(_)) => Ordering::Greater,
847 (None, None) => Ordering::Equal,
848 }
849 }
850 },
851 });
852
853 Self { issues }
854 }
855
856 pub fn iter(&self) -> impl Iterator<Item = &Issue> {
857 self.issues.iter()
858 }
859
860 #[must_use]
868 pub fn to_edit_batches(self) -> HashMap<FileId, IssueEditBatches> {
869 let mut result: HashMap<FileId, Vec<(Option<String>, IssueEdits)>> = HashMap::default();
870 for issue in self.issues.into_iter().filter(|issue| !issue.edits.is_empty()) {
871 let code = issue.code;
872 for (file_id, edit_list) in issue.edits {
873 result.entry(file_id).or_default().push((code.clone(), edit_list));
874 }
875 }
876
877 result
878 }
879}
880
881fn issue_text_matches(issue: &Issue, regex: &Regex) -> bool {
887 if regex.is_match(&issue.message) {
888 return true;
889 }
890
891 if issue
892 .annotations
893 .iter()
894 .any(|annotation| annotation.message.as_ref().is_some_and(|message| regex.is_match(message)))
895 {
896 return true;
897 }
898
899 if issue.notes.iter().any(|note| regex.is_match(note)) {
900 return true;
901 }
902
903 issue.help.as_ref().is_some_and(|help| regex.is_match(help))
904}
905
906impl IntoIterator for IssueCollection {
907 type Item = Issue;
908
909 type IntoIter = std::vec::IntoIter<Issue>;
910
911 fn into_iter(self) -> Self::IntoIter {
912 self.issues.into_iter()
913 }
914}
915
916impl<'collection> IntoIterator for &'collection IssueCollection {
917 type Item = &'collection Issue;
918
919 type IntoIter = std::slice::Iter<'collection, Issue>;
920
921 fn into_iter(self) -> Self::IntoIter {
922 self.issues.iter()
923 }
924}
925
926impl Default for IssueCollection {
927 fn default() -> Self {
928 Self::new()
929 }
930}
931
932impl IntoIterator for Issue {
933 type Item = Issue;
934 type IntoIter = Once<Issue>;
935
936 fn into_iter(self) -> Self::IntoIter {
937 std::iter::once(self)
938 }
939}
940
941impl FromIterator<Issue> for IssueCollection {
942 fn from_iter<T>(iter: T) -> Self
943 where
944 T: IntoIterator<Item = Issue>,
945 {
946 Self { issues: iter.into_iter().collect() }
947 }
948}
949
950#[cfg(test)]
951mod tests {
952 use std::collections::HashMap;
953
954 use super::*;
955
956 #[test]
957 pub fn test_highest_collection_level() {
958 let mut collection = IssueCollection::from(vec![]);
959 assert_eq!(collection.get_highest_level(), None);
960
961 collection.push(Issue::note("note"));
962 assert_eq!(collection.get_highest_level(), Some(Level::Note));
963
964 collection.push(Issue::help("help"));
965 assert_eq!(collection.get_highest_level(), Some(Level::Help));
966
967 collection.push(Issue::warning("warning"));
968 assert_eq!(collection.get_highest_level(), Some(Level::Warning));
969
970 collection.push(Issue::error("error"));
971 assert_eq!(collection.get_highest_level(), Some(Level::Error));
972 }
973
974 #[test]
975 pub fn test_level_downgrade() {
976 assert_eq!(Level::Error.downgrade(), Level::Warning);
977 assert_eq!(Level::Warning.downgrade(), Level::Help);
978 assert_eq!(Level::Help.downgrade(), Level::Note);
979 assert_eq!(Level::Note.downgrade(), Level::Note);
980 }
981
982 #[test]
983 pub fn test_issue_collection_with_maximum_level() {
984 let mut collection = IssueCollection::from(vec![
985 Issue::error("error"),
986 Issue::warning("warning"),
987 Issue::help("help"),
988 Issue::note("note"),
989 ]);
990
991 collection = collection.with_maximum_level(Level::Warning);
992 assert_eq!(collection.len(), 3);
993 assert_eq!(
994 collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
995 vec![Level::Warning, Level::Help, Level::Note]
996 );
997 }
998
999 #[test]
1000 pub fn test_issue_collection_with_minimum_level() {
1001 let mut collection = IssueCollection::from(vec![
1002 Issue::error("error"),
1003 Issue::warning("warning"),
1004 Issue::help("help"),
1005 Issue::note("note"),
1006 ]);
1007
1008 collection = collection.with_minimum_level(Level::Warning);
1009 assert_eq!(collection.len(), 2);
1010 assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
1011 }
1012
1013 #[test]
1014 pub fn test_issue_collection_has_minimum_level() {
1015 let mut collection = IssueCollection::from(vec![]);
1016
1017 assert!(!collection.has_minimum_level(Level::Error));
1018 assert!(!collection.has_minimum_level(Level::Warning));
1019 assert!(!collection.has_minimum_level(Level::Help));
1020 assert!(!collection.has_minimum_level(Level::Note));
1021
1022 collection.push(Issue::note("note"));
1023
1024 assert!(!collection.has_minimum_level(Level::Error));
1025 assert!(!collection.has_minimum_level(Level::Warning));
1026 assert!(!collection.has_minimum_level(Level::Help));
1027 assert!(collection.has_minimum_level(Level::Note));
1028
1029 collection.push(Issue::help("help"));
1030
1031 assert!(!collection.has_minimum_level(Level::Error));
1032 assert!(!collection.has_minimum_level(Level::Warning));
1033 assert!(collection.has_minimum_level(Level::Help));
1034 assert!(collection.has_minimum_level(Level::Note));
1035
1036 collection.push(Issue::warning("warning"));
1037
1038 assert!(!collection.has_minimum_level(Level::Error));
1039 assert!(collection.has_minimum_level(Level::Warning));
1040 assert!(collection.has_minimum_level(Level::Help));
1041 assert!(collection.has_minimum_level(Level::Note));
1042
1043 collection.push(Issue::error("error"));
1044
1045 assert!(collection.has_minimum_level(Level::Error));
1046 assert!(collection.has_minimum_level(Level::Warning));
1047 assert!(collection.has_minimum_level(Level::Help));
1048 assert!(collection.has_minimum_level(Level::Note));
1049 }
1050
1051 #[test]
1052 pub fn test_issue_collection_level_count() {
1053 let mut collection = IssueCollection::from(vec![]);
1054
1055 assert_eq!(collection.get_level_count(Level::Error), 0);
1056 assert_eq!(collection.get_level_count(Level::Warning), 0);
1057 assert_eq!(collection.get_level_count(Level::Help), 0);
1058 assert_eq!(collection.get_level_count(Level::Note), 0);
1059
1060 collection.push(Issue::error("error"));
1061
1062 assert_eq!(collection.get_level_count(Level::Error), 1);
1063 assert_eq!(collection.get_level_count(Level::Warning), 0);
1064 assert_eq!(collection.get_level_count(Level::Help), 0);
1065 assert_eq!(collection.get_level_count(Level::Note), 0);
1066
1067 collection.push(Issue::warning("warning"));
1068
1069 assert_eq!(collection.get_level_count(Level::Error), 1);
1070 assert_eq!(collection.get_level_count(Level::Warning), 1);
1071 assert_eq!(collection.get_level_count(Level::Help), 0);
1072 assert_eq!(collection.get_level_count(Level::Note), 0);
1073
1074 collection.push(Issue::help("help"));
1075
1076 assert_eq!(collection.get_level_count(Level::Error), 1);
1077 assert_eq!(collection.get_level_count(Level::Warning), 1);
1078 assert_eq!(collection.get_level_count(Level::Help), 1);
1079 assert_eq!(collection.get_level_count(Level::Note), 0);
1080
1081 collection.push(Issue::note("note"));
1082
1083 assert_eq!(collection.get_level_count(Level::Error), 1);
1084 assert_eq!(collection.get_level_count(Level::Warning), 1);
1085 assert_eq!(collection.get_level_count(Level::Help), 1);
1086 assert_eq!(collection.get_level_count(Level::Note), 1);
1087 }
1088
1089 #[test]
1090 pub fn test_primary_span_is_deterministic() {
1091 let file = FileId::zero();
1092 let span_later = Span::new(file, 20u32.into(), 25u32.into());
1093 let span_earlier = Span::new(file, 5u32.into(), 10u32.into());
1094
1095 let issue = Issue::error("x")
1096 .with_annotation(Annotation::primary(span_later))
1097 .with_annotation(Annotation::primary(span_earlier));
1098
1099 assert_eq!(issue.primary_span(), Some(span_earlier));
1100 }
1101
1102 fn ignore_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1103 let file_id = |name: &[u8]| FileId::new(name);
1104
1105 let paths: [&[u8]; 4] =
1106 [b"src/App.php", b"tests/Unit/FooTest.php", b"modules/auth/views/login.tpl", b"types/user/form.tpl"];
1107
1108 let mut mapping = HashMap::new();
1109 let issues: Vec<Issue> = paths
1110 .iter()
1111 .map(|p| {
1112 let id = file_id(p);
1113 mapping.insert(id, *p);
1114 Issue::error("oops").with_code("invalid-global").with_annotation(Annotation::primary(Span::new(
1115 id,
1116 0u32.into(),
1117 1u32.into(),
1118 )))
1119 })
1120 .collect();
1121
1122 (IssueCollection::from(issues), mapping)
1123 }
1124
1125 fn resolve<'mapping>(
1126 mapping: &'mapping HashMap<FileId, &'static [u8]>,
1127 ) -> impl Fn(FileId) -> Option<String> + 'mapping {
1128 move |id| mapping.get(&id).map(|s| String::from_utf8_lossy(s).into_owned())
1129 }
1130
1131 fn remaining_paths(collection: &IssueCollection, mapping: &HashMap<FileId, &'static [u8]>) -> Vec<String> {
1132 collection
1133 .iter()
1134 .filter_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
1135 .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
1136 .collect()
1137 }
1138
1139 #[test]
1140 pub fn test_filter_out_ignored_with_plain_prefix() {
1141 let (mut collection, mapping) = ignore_fixture();
1142 let entries =
1143 vec![IgnoreEntry::Scoped { code: "invalid-global".to_string(), paths: vec!["tests/".to_string()] }];
1144 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1145
1146 collection.filter_out_ignored(&set, resolve(&mapping));
1147
1148 assert_eq!(
1149 remaining_paths(&collection, &mapping),
1150 vec![
1151 "src/App.php".to_string(),
1152 "modules/auth/views/login.tpl".to_string(),
1153 "types/user/form.tpl".to_string(),
1154 ]
1155 );
1156 }
1157
1158 #[test]
1159 pub fn test_filter_out_ignored_with_glob_pattern() {
1160 let (mut collection, mapping) = ignore_fixture();
1161 let entries = vec![IgnoreEntry::Scoped {
1162 code: "invalid-global".to_string(),
1163 paths: vec!["modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1164 }];
1165 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1166
1167 collection.filter_out_ignored(&set, resolve(&mapping));
1168
1169 assert_eq!(
1170 remaining_paths(&collection, &mapping),
1171 vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1172 );
1173 }
1174
1175 #[test]
1176 pub fn test_filter_out_ignored_mixes_plain_and_glob() {
1177 let (mut collection, mapping) = ignore_fixture();
1178 let entries = vec![IgnoreEntry::Scoped {
1179 code: "invalid-global".to_string(),
1180 paths: vec!["tests/".to_string(), "modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1181 }];
1182 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1183
1184 collection.filter_out_ignored(&set, resolve(&mapping));
1185
1186 assert_eq!(remaining_paths(&collection, &mapping), vec!["src/App.php".to_string()]);
1187 }
1188
1189 #[test]
1190 pub fn test_filter_out_ignored_respects_code_scope() {
1191 let (mut collection, mapping) = ignore_fixture();
1192 let entries = vec![IgnoreEntry::Scoped { code: "different-code".to_string(), paths: vec!["**/*".to_string()] }];
1193 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1194
1195 collection.filter_out_ignored(&set, resolve(&mapping));
1196
1197 assert_eq!(collection.len(), 4);
1198 }
1199
1200 fn pattern_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1201 let paths: [&[u8]; 3] = [b"src/App.php", b"src/Bridge/Symfony.php", b"tests/Unit/FooTest.php"];
1202 let mut mapping = HashMap::new();
1203 let mut issues: Vec<Issue> = Vec::new();
1204
1205 let id0 = FileId::new(blake3::hash(paths[0]).as_bytes());
1206 mapping.insert(id0, paths[0]);
1207 issues.push(
1208 Issue::error("Saw type `mixed` in Symfony bridge.")
1209 .with_code("mixed-assignment")
1210 .with_annotation(Annotation::primary(Span::new(id0, 0u32.into(), 1u32.into()))),
1211 );
1212
1213 let id1 = FileId::new(blake3::hash(paths[1]).as_bytes());
1214 mapping.insert(id1, paths[1]);
1215 issues.push(
1216 Issue::error("Could not infer a precise return type.")
1217 .with_code("mixed-assignment")
1218 .with_note("Originates from Symfony vendor stubs.")
1219 .with_annotation(Annotation::primary(Span::new(id1, 0u32.into(), 1u32.into()))),
1220 );
1221
1222 let id2 = FileId::new(blake3::hash(paths[2]).as_bytes());
1223 mapping.insert(id2, paths[2]);
1224 issues.push(
1225 Issue::error("Unused variable.")
1226 .with_code("unused-variable")
1227 .with_annotation(Annotation::primary(Span::new(id2, 0u32.into(), 1u32.into()))),
1228 );
1229
1230 (IssueCollection::from(issues), mapping)
1231 }
1232
1233 #[test]
1234 pub fn test_pattern_matches_title_and_note() {
1235 let (mut collection, mapping) = pattern_fixture();
1236 let entries = vec![IgnoreEntry::Pattern {
1237 pattern: "Symfony".to_string(),
1238 code: Some("mixed-assignment".to_string()),
1239 paths: None,
1240 }];
1241 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1242
1243 collection.filter_out_ignored(&set, resolve(&mapping));
1244
1245 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1246 }
1247
1248 #[test]
1249 pub fn test_pattern_without_code_matches_across_codes() {
1250 let (mut collection, mapping) = pattern_fixture();
1251 let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1252 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1253
1254 collection.filter_out_ignored(&set, resolve(&mapping));
1255
1256 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1257 }
1258
1259 #[test]
1260 pub fn test_pattern_with_path_scope() {
1261 let (mut collection, mapping) = pattern_fixture();
1262 let entries = vec![IgnoreEntry::Pattern {
1263 pattern: "Symfony".to_string(),
1264 code: None,
1265 paths: Some(vec!["src/Bridge/".to_string()]),
1266 }];
1267 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1268
1269 collection.filter_out_ignored(&set, resolve(&mapping));
1270
1271 assert_eq!(
1272 remaining_paths(&collection, &mapping),
1273 vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1274 );
1275 }
1276
1277 #[test]
1278 pub fn test_pattern_case_insensitive_with_flag() {
1279 let (mut collection, mapping) = pattern_fixture();
1280 let entries = vec![IgnoreEntry::Pattern { pattern: "(?i)symfony".to_string(), code: None, paths: None }];
1281 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1282
1283 collection.filter_out_ignored(&set, resolve(&mapping));
1284
1285 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1286 }
1287
1288 #[test]
1289 pub fn test_pattern_invalid_regex_is_skipped() {
1290 let (mut collection, mapping) = pattern_fixture();
1291 let entries = vec![
1292 IgnoreEntry::Pattern { pattern: "[unterminated".to_string(), code: None, paths: None },
1293 IgnoreEntry::Code("unused-variable".to_string()),
1294 ];
1295 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1296
1297 assert_eq!(set.len(), 1);
1298
1299 collection.filter_out_ignored(&set, resolve(&mapping));
1300
1301 assert_eq!(
1302 remaining_paths(&collection, &mapping),
1303 vec!["src/App.php".to_string(), "src/Bridge/Symfony.php".to_string()]
1304 );
1305 }
1306
1307 #[test]
1308 pub fn test_pattern_matches_help_message() {
1309 let id = FileId::new(blake3::hash(b"src/foo.php").as_bytes());
1310 let mut mapping: HashMap<FileId, &'static [u8]> = HashMap::new();
1311 mapping.insert(id, &b"src/foo.php"[..]);
1312 let mut collection = IssueCollection::from(vec![
1313 Issue::error("Title.")
1314 .with_code("some-code")
1315 .with_help("Consider migrating off legacy Symfony bridge.")
1316 .with_annotation(Annotation::primary(Span::new(id, 0u32.into(), 1u32.into()))),
1317 ]);
1318
1319 let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1320 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1321
1322 collection.filter_out_ignored(&set, resolve(&mapping));
1323
1324 assert!(collection.is_empty());
1325 }
1326}