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]
258 pub fn is_ignored<F>(&self, issue: &Issue, resolve_file_name: F) -> bool
259 where
260 F: Fn(FileId) -> Option<String>,
261 {
262 let mut cached_path: Option<Option<String>> = None;
263 let mut resolve_path = |issue: &Issue| -> Option<String> {
264 cached_path
265 .get_or_insert_with(|| issue.primary_span().and_then(|span| resolve_file_name(span.file_id)))
266 .clone()
267 };
268
269 for entry in &self.entries {
270 match entry {
271 CompiledIgnoreEntry::Code(ignored_code) => {
272 if let Some(code) = &issue.code
273 && ignored_code == code
274 {
275 return true;
276 }
277 }
278 CompiledIgnoreEntry::Scoped { code: ignored_code, matcher } => {
279 let Some(code) = &issue.code else {
280 continue;
281 };
282
283 if ignored_code != code {
284 continue;
285 }
286
287 if let Some(name) = resolve_path(issue)
288 && matcher.is_match(&name)
289 {
290 return true;
291 }
292 }
293 CompiledIgnoreEntry::Pattern { regex, code: ignored_code, matcher } => {
294 if let Some(ignored_code) = ignored_code {
295 let Some(code) = &issue.code else {
296 continue;
297 };
298
299 if ignored_code != code {
300 continue;
301 }
302 }
303
304 if let Some(matcher) = matcher {
305 let Some(name) = resolve_path(issue) else {
306 continue;
307 };
308
309 if !matcher.is_match(&name) {
310 continue;
311 }
312 }
313
314 if issue_text_matches(issue, regex) {
315 return true;
316 }
317 }
318 }
319 }
320 false
321 }
322
323 #[must_use]
328 pub fn compile(entries: &[IgnoreEntry], glob: GlobSettings) -> Self {
329 let mut compiled = Vec::with_capacity(entries.len());
330 for entry in entries {
331 match entry {
332 IgnoreEntry::Code(code) => compiled.push(CompiledIgnoreEntry::Code(code.clone())),
333 IgnoreEntry::Scoped { code, paths } => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
334 Ok(matcher) => compiled.push(CompiledIgnoreEntry::Scoped { code: code.clone(), matcher }),
335 Err(err) => {
336 tracing::error!("Failed to compile ignore patterns for `{code}`: {err}. Entry will be skipped.")
337 }
338 },
339 IgnoreEntry::Pattern { pattern, code, paths } => {
340 let regex = match Regex::new(pattern) {
341 Ok(regex) => regex,
342 Err(err) => {
343 tracing::error!(
344 "Failed to compile ignore regex `{pattern}`: {err}. Entry will be skipped."
345 );
346
347 continue;
348 }
349 };
350
351 let matcher = match paths {
352 Some(paths) => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
353 Ok(matcher) => Some(matcher),
354 Err(err) => {
355 tracing::error!(
356 "Failed to compile ignore paths for regex `{pattern}`: {err}. Entry will be skipped."
357 );
358
359 continue;
360 }
361 },
362 None => None,
363 };
364
365 compiled.push(CompiledIgnoreEntry::Pattern { regex, code: code.clone(), matcher });
366 }
367 }
368 }
369
370 Self { entries: compiled }
371 }
372
373 #[must_use]
374 pub fn is_empty(&self) -> bool {
375 self.entries.is_empty()
376 }
377
378 #[must_use]
379 pub fn len(&self) -> usize {
380 self.entries.len()
381 }
382}
383
384impl Annotation {
385 #[must_use]
402 pub fn new(kind: AnnotationKind, span: Span) -> Self {
403 Self { message: None, kind, span }
404 }
405
406 #[must_use]
423 pub fn primary(span: Span) -> Self {
424 Self::new(AnnotationKind::Primary, span)
425 }
426
427 #[must_use]
444 pub fn secondary(span: Span) -> Self {
445 Self::new(AnnotationKind::Secondary, span)
446 }
447
448 #[must_use]
465 pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
466 self.message = Some(message.into());
467
468 self
469 }
470
471 #[must_use]
473 pub fn is_primary(&self) -> bool {
474 self.kind == AnnotationKind::Primary
475 }
476}
477
478impl Level {
479 #[must_use]
506 pub fn downgrade(&self) -> Self {
507 match self {
508 Level::Error => Level::Warning,
509 Level::Warning => Level::Help,
510 Level::Help | Level::Note => Level::Note,
511 }
512 }
513}
514
515impl Issue {
516 pub fn new(level: Level, message: impl Into<Cow<'static, str>>) -> Self {
526 Self {
527 level,
528 code: None,
529 message: message.into(),
530 annotations: Vec::new(),
531 notes: Vec::new(),
532 help: None,
533 link: None,
534 edits: HashMap::default(),
535 }
536 }
537
538 pub fn error(message: impl Into<Cow<'static, str>>) -> Self {
548 Self::new(Level::Error, message)
549 }
550
551 pub fn warning(message: impl Into<Cow<'static, str>>) -> Self {
561 Self::new(Level::Warning, message)
562 }
563
564 pub fn help(message: impl Into<Cow<'static, str>>) -> Self {
574 Self::new(Level::Help, message)
575 }
576
577 pub fn note(message: impl Into<Cow<'static, str>>) -> Self {
587 Self::new(Level::Note, message)
588 }
589
590 #[must_use]
600 pub fn with_code(mut self, code: impl Into<String>) -> Self {
601 self.code = Some(code.into());
602
603 self
604 }
605
606 #[must_use]
624 pub fn with_annotation(mut self, annotation: Annotation) -> Self {
625 if self.annotations.is_empty() {
626 self.annotations.reserve_exact(2);
627 }
628
629 self.annotations.push(annotation);
630
631 self
632 }
633
634 #[must_use]
635 pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
636 self.annotations.extend(annotation);
637
638 self
639 }
640
641 #[must_use]
645 pub fn primary_annotation(&self) -> Option<&Annotation> {
646 self.annotations.iter().filter(|annotation| annotation.is_primary()).min_by_key(|annotation| annotation.span)
647 }
648
649 #[must_use]
651 pub fn primary_span(&self) -> Option<Span> {
652 self.primary_annotation().map(|annotation| annotation.span)
653 }
654
655 #[must_use]
665 pub fn with_note(mut self, note: impl Into<Cow<'static, str>>) -> Self {
666 if self.notes.is_empty() {
667 self.notes.reserve_exact(1);
668 }
669
670 self.notes.push(note.into());
671
672 self
673 }
674
675 #[must_use]
687 pub fn with_help(mut self, help: impl Into<Cow<'static, str>>) -> Self {
688 self.help = Some(help.into());
689
690 self
691 }
692
693 #[must_use]
703 pub fn with_link(mut self, link: impl Into<String>) -> Self {
704 self.link = Some(link.into());
705
706 self
707 }
708
709 #[must_use]
711 pub fn with_edit(mut self, file_id: FileId, edit: TextEdit) -> Self {
712 self.edits.entry(file_id).or_default().push(edit);
713
714 self
715 }
716
717 #[must_use]
719 pub fn with_file_edits(mut self, file_id: FileId, edits: IssueEdits) -> Self {
720 if !edits.is_empty() {
721 match self.edits.entry(file_id) {
722 Entry::Vacant(entry) => {
723 entry.insert(edits);
724 }
725 Entry::Occupied(mut entry) => entry.get_mut().extend(edits),
726 }
727 }
728
729 self
730 }
731
732 #[must_use]
734 pub fn take_edits(&mut self) -> HashMap<FileId, IssueEdits> {
735 std::mem::replace(&mut self.edits, HashMap::new())
736 }
737}
738
739impl IssueCollection {
740 #[must_use]
741 pub fn new() -> Self {
742 Self { issues: Vec::new() }
743 }
744
745 pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
746 Self { issues: issues.into_iter().collect() }
747 }
748
749 pub fn push(&mut self, issue: Issue) {
750 self.issues.push(issue);
751 }
752
753 pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
754 self.issues.extend(issues);
755 }
756
757 pub fn reserve(&mut self, additional: usize) {
758 self.issues.reserve(additional);
759 }
760
761 pub fn shrink_to_fit(&mut self) {
762 self.issues.shrink_to_fit();
763 }
764
765 #[must_use]
766 pub fn is_empty(&self) -> bool {
767 self.issues.is_empty()
768 }
769
770 #[must_use]
771 pub fn len(&self) -> usize {
772 self.issues.len()
773 }
774
775 #[must_use]
778 pub fn with_maximum_level(self, level: Level) -> Self {
779 Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
780 }
781
782 #[must_use]
785 pub fn with_minimum_level(self, level: Level) -> Self {
786 Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
787 }
788
789 #[must_use]
792 pub fn has_minimum_level(&self, level: Level) -> bool {
793 self.issues.iter().any(|issue| issue.level >= level)
794 }
795
796 #[must_use]
798 pub fn get_level_count(&self, level: Level) -> usize {
799 self.issues.iter().filter(|issue| issue.level == level).count()
800 }
801
802 #[must_use]
804 pub fn get_highest_level(&self) -> Option<Level> {
805 self.issues.iter().map(|issue| issue.level).max()
806 }
807
808 #[must_use]
810 pub fn get_lowest_level(&self) -> Option<Level> {
811 self.issues.iter().map(|issue| issue.level).min()
812 }
813
814 pub fn filter_out_ignored<F>(&mut self, set: &CompiledIgnoreSet, resolve_file_name: F)
815 where
816 F: Fn(FileId) -> Option<String>,
817 {
818 if !set.is_empty() {
819 self.issues.retain(|issue| !set.is_ignored(issue, &resolve_file_name));
820 }
821 }
822
823 pub fn filter_retain_codes(&mut self, retain_codes: &[String]) {
824 self.issues.retain(|issue| if let Some(code) = &issue.code { retain_codes.contains(code) } else { false });
825 }
826
827 pub fn take_edits(&mut self) -> impl Iterator<Item = (FileId, IssueEdits)> + '_ {
828 self.issues.iter_mut().flat_map(|issue| issue.take_edits().into_iter())
829 }
830
831 #[must_use]
833 pub fn with_edits(self) -> Self {
834 Self { issues: self.issues.into_iter().filter(|issue| !issue.edits.is_empty()).collect() }
835 }
836
837 #[must_use]
842 pub fn sorted(self) -> Self {
843 let mut issues = self.issues;
844
845 issues.sort_by(|a, b| match a.level.cmp(&b.level) {
846 Ordering::Greater => Ordering::Greater,
847 Ordering::Less => Ordering::Less,
848 Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
849 Ordering::Less => Ordering::Less,
850 Ordering::Greater => Ordering::Greater,
851 Ordering::Equal => {
852 let a_span = a.primary_span();
853 let b_span = b.primary_span();
854
855 match (a_span, b_span) {
856 (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
857 (Some(_), None) => Ordering::Less,
858 (None, Some(_)) => Ordering::Greater,
859 (None, None) => Ordering::Equal,
860 }
861 }
862 },
863 });
864
865 Self { issues }
866 }
867
868 pub fn iter(&self) -> impl Iterator<Item = &Issue> {
869 self.issues.iter()
870 }
871
872 #[must_use]
880 pub fn to_edit_batches(self) -> HashMap<FileId, IssueEditBatches> {
881 let mut result: HashMap<FileId, Vec<(Option<String>, IssueEdits)>> = HashMap::default();
882 for issue in self.issues.into_iter().filter(|issue| !issue.edits.is_empty()) {
883 let code = issue.code;
884 for (file_id, edit_list) in issue.edits {
885 result.entry(file_id).or_default().push((code.clone(), edit_list));
886 }
887 }
888
889 result
890 }
891}
892
893fn issue_text_matches(issue: &Issue, regex: &Regex) -> bool {
899 if regex.is_match(&issue.message) {
900 return true;
901 }
902
903 if issue
904 .annotations
905 .iter()
906 .any(|annotation| annotation.message.as_ref().is_some_and(|message| regex.is_match(message)))
907 {
908 return true;
909 }
910
911 if issue.notes.iter().any(|note| regex.is_match(note)) {
912 return true;
913 }
914
915 issue.help.as_ref().is_some_and(|help| regex.is_match(help))
916}
917
918impl IntoIterator for IssueCollection {
919 type Item = Issue;
920
921 type IntoIter = std::vec::IntoIter<Issue>;
922
923 fn into_iter(self) -> Self::IntoIter {
924 self.issues.into_iter()
925 }
926}
927
928impl<'collection> IntoIterator for &'collection IssueCollection {
929 type Item = &'collection Issue;
930
931 type IntoIter = std::slice::Iter<'collection, Issue>;
932
933 fn into_iter(self) -> Self::IntoIter {
934 self.issues.iter()
935 }
936}
937
938impl Default for IssueCollection {
939 fn default() -> Self {
940 Self::new()
941 }
942}
943
944impl IntoIterator for Issue {
945 type Item = Issue;
946 type IntoIter = Once<Issue>;
947
948 fn into_iter(self) -> Self::IntoIter {
949 std::iter::once(self)
950 }
951}
952
953impl FromIterator<Issue> for IssueCollection {
954 fn from_iter<T>(iter: T) -> Self
955 where
956 T: IntoIterator<Item = Issue>,
957 {
958 Self { issues: iter.into_iter().collect() }
959 }
960}
961
962#[cfg(test)]
963mod tests {
964 use std::collections::HashMap;
965
966 use super::*;
967
968 #[test]
969 pub fn test_highest_collection_level() {
970 let mut collection = IssueCollection::from(vec![]);
971 assert_eq!(collection.get_highest_level(), None);
972
973 collection.push(Issue::note("note"));
974 assert_eq!(collection.get_highest_level(), Some(Level::Note));
975
976 collection.push(Issue::help("help"));
977 assert_eq!(collection.get_highest_level(), Some(Level::Help));
978
979 collection.push(Issue::warning("warning"));
980 assert_eq!(collection.get_highest_level(), Some(Level::Warning));
981
982 collection.push(Issue::error("error"));
983 assert_eq!(collection.get_highest_level(), Some(Level::Error));
984 }
985
986 #[test]
987 pub fn test_level_downgrade() {
988 assert_eq!(Level::Error.downgrade(), Level::Warning);
989 assert_eq!(Level::Warning.downgrade(), Level::Help);
990 assert_eq!(Level::Help.downgrade(), Level::Note);
991 assert_eq!(Level::Note.downgrade(), Level::Note);
992 }
993
994 #[test]
995 pub fn test_issue_collection_with_maximum_level() {
996 let mut collection = IssueCollection::from(vec![
997 Issue::error("error"),
998 Issue::warning("warning"),
999 Issue::help("help"),
1000 Issue::note("note"),
1001 ]);
1002
1003 collection = collection.with_maximum_level(Level::Warning);
1004 assert_eq!(collection.len(), 3);
1005 assert_eq!(
1006 collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
1007 vec![Level::Warning, Level::Help, Level::Note]
1008 );
1009 }
1010
1011 #[test]
1012 pub fn test_issue_collection_with_minimum_level() {
1013 let mut collection = IssueCollection::from(vec![
1014 Issue::error("error"),
1015 Issue::warning("warning"),
1016 Issue::help("help"),
1017 Issue::note("note"),
1018 ]);
1019
1020 collection = collection.with_minimum_level(Level::Warning);
1021 assert_eq!(collection.len(), 2);
1022 assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
1023 }
1024
1025 #[test]
1026 pub fn test_issue_collection_has_minimum_level() {
1027 let mut collection = IssueCollection::from(vec![]);
1028
1029 assert!(!collection.has_minimum_level(Level::Error));
1030 assert!(!collection.has_minimum_level(Level::Warning));
1031 assert!(!collection.has_minimum_level(Level::Help));
1032 assert!(!collection.has_minimum_level(Level::Note));
1033
1034 collection.push(Issue::note("note"));
1035
1036 assert!(!collection.has_minimum_level(Level::Error));
1037 assert!(!collection.has_minimum_level(Level::Warning));
1038 assert!(!collection.has_minimum_level(Level::Help));
1039 assert!(collection.has_minimum_level(Level::Note));
1040
1041 collection.push(Issue::help("help"));
1042
1043 assert!(!collection.has_minimum_level(Level::Error));
1044 assert!(!collection.has_minimum_level(Level::Warning));
1045 assert!(collection.has_minimum_level(Level::Help));
1046 assert!(collection.has_minimum_level(Level::Note));
1047
1048 collection.push(Issue::warning("warning"));
1049
1050 assert!(!collection.has_minimum_level(Level::Error));
1051 assert!(collection.has_minimum_level(Level::Warning));
1052 assert!(collection.has_minimum_level(Level::Help));
1053 assert!(collection.has_minimum_level(Level::Note));
1054
1055 collection.push(Issue::error("error"));
1056
1057 assert!(collection.has_minimum_level(Level::Error));
1058 assert!(collection.has_minimum_level(Level::Warning));
1059 assert!(collection.has_minimum_level(Level::Help));
1060 assert!(collection.has_minimum_level(Level::Note));
1061 }
1062
1063 #[test]
1064 pub fn test_issue_collection_level_count() {
1065 let mut collection = IssueCollection::from(vec![]);
1066
1067 assert_eq!(collection.get_level_count(Level::Error), 0);
1068 assert_eq!(collection.get_level_count(Level::Warning), 0);
1069 assert_eq!(collection.get_level_count(Level::Help), 0);
1070 assert_eq!(collection.get_level_count(Level::Note), 0);
1071
1072 collection.push(Issue::error("error"));
1073
1074 assert_eq!(collection.get_level_count(Level::Error), 1);
1075 assert_eq!(collection.get_level_count(Level::Warning), 0);
1076 assert_eq!(collection.get_level_count(Level::Help), 0);
1077 assert_eq!(collection.get_level_count(Level::Note), 0);
1078
1079 collection.push(Issue::warning("warning"));
1080
1081 assert_eq!(collection.get_level_count(Level::Error), 1);
1082 assert_eq!(collection.get_level_count(Level::Warning), 1);
1083 assert_eq!(collection.get_level_count(Level::Help), 0);
1084 assert_eq!(collection.get_level_count(Level::Note), 0);
1085
1086 collection.push(Issue::help("help"));
1087
1088 assert_eq!(collection.get_level_count(Level::Error), 1);
1089 assert_eq!(collection.get_level_count(Level::Warning), 1);
1090 assert_eq!(collection.get_level_count(Level::Help), 1);
1091 assert_eq!(collection.get_level_count(Level::Note), 0);
1092
1093 collection.push(Issue::note("note"));
1094
1095 assert_eq!(collection.get_level_count(Level::Error), 1);
1096 assert_eq!(collection.get_level_count(Level::Warning), 1);
1097 assert_eq!(collection.get_level_count(Level::Help), 1);
1098 assert_eq!(collection.get_level_count(Level::Note), 1);
1099 }
1100
1101 #[test]
1102 pub fn test_primary_span_is_deterministic() {
1103 let file = FileId::zero();
1104 let span_later = Span::new(file, 20u32.into(), 25u32.into());
1105 let span_earlier = Span::new(file, 5u32.into(), 10u32.into());
1106
1107 let issue = Issue::error("x")
1108 .with_annotation(Annotation::primary(span_later))
1109 .with_annotation(Annotation::primary(span_earlier));
1110
1111 assert_eq!(issue.primary_span(), Some(span_earlier));
1112 }
1113
1114 fn ignore_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1115 let file_id = |name: &[u8]| FileId::new(name);
1116
1117 let paths: [&[u8]; 4] =
1118 [b"src/App.php", b"tests/Unit/FooTest.php", b"modules/auth/views/login.tpl", b"types/user/form.tpl"];
1119
1120 let mut mapping = HashMap::new();
1121 let issues: Vec<Issue> = paths
1122 .iter()
1123 .map(|p| {
1124 let id = file_id(p);
1125 mapping.insert(id, *p);
1126 Issue::error("oops").with_code("invalid-global").with_annotation(Annotation::primary(Span::new(
1127 id,
1128 0u32.into(),
1129 1u32.into(),
1130 )))
1131 })
1132 .collect();
1133
1134 (IssueCollection::from(issues), mapping)
1135 }
1136
1137 fn resolve<'mapping>(
1138 mapping: &'mapping HashMap<FileId, &'static [u8]>,
1139 ) -> impl Fn(FileId) -> Option<String> + 'mapping {
1140 move |id| mapping.get(&id).map(|s| String::from_utf8_lossy(s).into_owned())
1141 }
1142
1143 fn remaining_paths(collection: &IssueCollection, mapping: &HashMap<FileId, &'static [u8]>) -> Vec<String> {
1144 collection
1145 .iter()
1146 .filter_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
1147 .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
1148 .collect()
1149 }
1150
1151 #[test]
1152 pub fn test_filter_out_ignored_with_plain_prefix() {
1153 let (mut collection, mapping) = ignore_fixture();
1154 let entries =
1155 vec![IgnoreEntry::Scoped { code: "invalid-global".to_string(), paths: vec!["tests/".to_string()] }];
1156 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1157
1158 collection.filter_out_ignored(&set, resolve(&mapping));
1159
1160 assert_eq!(
1161 remaining_paths(&collection, &mapping),
1162 vec![
1163 "src/App.php".to_string(),
1164 "modules/auth/views/login.tpl".to_string(),
1165 "types/user/form.tpl".to_string(),
1166 ]
1167 );
1168 }
1169
1170 #[test]
1171 pub fn test_filter_out_ignored_with_glob_pattern() {
1172 let (mut collection, mapping) = ignore_fixture();
1173 let entries = vec![IgnoreEntry::Scoped {
1174 code: "invalid-global".to_string(),
1175 paths: vec!["modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1176 }];
1177 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1178
1179 collection.filter_out_ignored(&set, resolve(&mapping));
1180
1181 assert_eq!(
1182 remaining_paths(&collection, &mapping),
1183 vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1184 );
1185 }
1186
1187 #[test]
1188 pub fn test_filter_out_ignored_mixes_plain_and_glob() {
1189 let (mut collection, mapping) = ignore_fixture();
1190 let entries = vec![IgnoreEntry::Scoped {
1191 code: "invalid-global".to_string(),
1192 paths: vec!["tests/".to_string(), "modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1193 }];
1194 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1195
1196 collection.filter_out_ignored(&set, resolve(&mapping));
1197
1198 assert_eq!(remaining_paths(&collection, &mapping), vec!["src/App.php".to_string()]);
1199 }
1200
1201 #[test]
1202 pub fn test_filter_out_ignored_respects_code_scope() {
1203 let (mut collection, mapping) = ignore_fixture();
1204 let entries = vec![IgnoreEntry::Scoped { code: "different-code".to_string(), paths: vec!["**/*".to_string()] }];
1205 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1206
1207 collection.filter_out_ignored(&set, resolve(&mapping));
1208
1209 assert_eq!(collection.len(), 4);
1210 }
1211
1212 fn pattern_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1213 let paths: [&[u8]; 3] = [b"src/App.php", b"src/Bridge/Symfony.php", b"tests/Unit/FooTest.php"];
1214 let mut mapping = HashMap::new();
1215 let mut issues: Vec<Issue> = Vec::new();
1216
1217 let id0 = FileId::new(blake3::hash(paths[0]).as_bytes());
1218 mapping.insert(id0, paths[0]);
1219 issues.push(
1220 Issue::error("Saw type `mixed` in Symfony bridge.")
1221 .with_code("mixed-assignment")
1222 .with_annotation(Annotation::primary(Span::new(id0, 0u32.into(), 1u32.into()))),
1223 );
1224
1225 let id1 = FileId::new(blake3::hash(paths[1]).as_bytes());
1226 mapping.insert(id1, paths[1]);
1227 issues.push(
1228 Issue::error("Could not infer a precise return type.")
1229 .with_code("mixed-assignment")
1230 .with_note("Originates from Symfony vendor stubs.")
1231 .with_annotation(Annotation::primary(Span::new(id1, 0u32.into(), 1u32.into()))),
1232 );
1233
1234 let id2 = FileId::new(blake3::hash(paths[2]).as_bytes());
1235 mapping.insert(id2, paths[2]);
1236 issues.push(
1237 Issue::error("Unused variable.")
1238 .with_code("unused-variable")
1239 .with_annotation(Annotation::primary(Span::new(id2, 0u32.into(), 1u32.into()))),
1240 );
1241
1242 (IssueCollection::from(issues), mapping)
1243 }
1244
1245 #[test]
1246 pub fn test_pattern_matches_title_and_note() {
1247 let (mut collection, mapping) = pattern_fixture();
1248 let entries = vec![IgnoreEntry::Pattern {
1249 pattern: "Symfony".to_string(),
1250 code: Some("mixed-assignment".to_string()),
1251 paths: None,
1252 }];
1253 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1254
1255 collection.filter_out_ignored(&set, resolve(&mapping));
1256
1257 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1258 }
1259
1260 #[test]
1261 pub fn test_pattern_without_code_matches_across_codes() {
1262 let (mut collection, mapping) = pattern_fixture();
1263 let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1264 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1265
1266 collection.filter_out_ignored(&set, resolve(&mapping));
1267
1268 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1269 }
1270
1271 #[test]
1272 pub fn test_pattern_with_path_scope() {
1273 let (mut collection, mapping) = pattern_fixture();
1274 let entries = vec![IgnoreEntry::Pattern {
1275 pattern: "Symfony".to_string(),
1276 code: None,
1277 paths: Some(vec!["src/Bridge/".to_string()]),
1278 }];
1279 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1280
1281 collection.filter_out_ignored(&set, resolve(&mapping));
1282
1283 assert_eq!(
1284 remaining_paths(&collection, &mapping),
1285 vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1286 );
1287 }
1288
1289 #[test]
1290 pub fn test_pattern_case_insensitive_with_flag() {
1291 let (mut collection, mapping) = pattern_fixture();
1292 let entries = vec![IgnoreEntry::Pattern { pattern: "(?i)symfony".to_string(), code: None, paths: None }];
1293 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1294
1295 collection.filter_out_ignored(&set, resolve(&mapping));
1296
1297 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1298 }
1299
1300 #[test]
1301 pub fn test_pattern_invalid_regex_is_skipped() {
1302 let (mut collection, mapping) = pattern_fixture();
1303 let entries = vec![
1304 IgnoreEntry::Pattern { pattern: "[unterminated".to_string(), code: None, paths: None },
1305 IgnoreEntry::Code("unused-variable".to_string()),
1306 ];
1307 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1308
1309 assert_eq!(set.len(), 1);
1310
1311 collection.filter_out_ignored(&set, resolve(&mapping));
1312
1313 assert_eq!(
1314 remaining_paths(&collection, &mapping),
1315 vec!["src/App.php".to_string(), "src/Bridge/Symfony.php".to_string()]
1316 );
1317 }
1318
1319 #[test]
1320 pub fn test_pattern_matches_help_message() {
1321 let id = FileId::new(blake3::hash(b"src/foo.php").as_bytes());
1322 let mut mapping: HashMap<FileId, &'static [u8]> = HashMap::new();
1323 mapping.insert(id, &b"src/foo.php"[..]);
1324 let mut collection = IssueCollection::from(vec![
1325 Issue::error("Title.")
1326 .with_code("some-code")
1327 .with_help("Consider migrating off legacy Symfony bridge.")
1328 .with_annotation(Annotation::primary(Span::new(id, 0u32.into(), 1u32.into()))),
1329 ]);
1330
1331 let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1332 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1333
1334 collection.filter_out_ignored(&set, resolve(&mapping));
1335
1336 assert!(collection.is_empty());
1337 }
1338}