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 rayon::prelude::*;
24use regex::Regex;
25use schemars::JsonSchema;
26use strum::Display;
27use strum::VariantNames;
28
29use mago_database::GlobSettings;
30use mago_database::file::FileId;
31use mago_database::matcher::ExclusionMatcher;
32use mago_span::Span;
33use mago_text_edit::TextEdit;
34
35mod formatter;
36#[cfg(feature = "serde")]
37mod internal;
38
39pub mod baseline;
40pub mod color;
41pub mod error;
42pub mod output;
43pub mod reporter;
44
45pub use color::ColorChoice;
46pub use formatter::ReportingFormat;
47pub use formatter::utils::osc8_file_hyperlink;
48pub use formatter::utils::osc8_hyperlink;
49pub use output::ReportingTarget;
50
51#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
70#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
71#[cfg_attr(feature = "serde", serde(untagged))]
72pub enum IgnoreEntry {
73 Code(String),
75 Pattern {
78 pattern: String,
84 #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
87 code: Option<String>,
88 #[cfg_attr(
90 feature = "serde",
91 serde(
92 rename = "in",
93 default,
94 skip_serializing_if = "Option::is_none",
95 deserialize_with = "opt_one_or_many"
96 )
97 )]
98 paths: Option<Vec<String>>,
99 },
100 Scoped {
103 code: String,
104 #[cfg_attr(feature = "serde", serde(rename = "in", deserialize_with = "one_or_many"))]
105 paths: Vec<String>,
106 },
107}
108
109#[cfg(feature = "serde")]
110fn one_or_many<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
111where
112 D: serde::Deserializer<'de>,
113{
114 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
115 #[cfg_attr(feature = "serde", serde(untagged))]
116 enum OneOrMany {
117 One(String),
118 Many(Vec<String>),
119 }
120
121 match <OneOrMany as serde::Deserialize>::deserialize(deserializer)? {
122 OneOrMany::One(s) => Ok(vec![s]),
123 OneOrMany::Many(v) => Ok(v),
124 }
125}
126
127#[cfg(feature = "serde")]
128fn opt_one_or_many<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
129where
130 D: serde::Deserializer<'de>,
131{
132 Ok(Some(one_or_many(deserializer)?))
133}
134
135#[derive(Debug, Default)]
142pub struct CompiledIgnoreSet {
143 entries: Vec<CompiledIgnoreEntry>,
144}
145
146#[derive(Debug)]
147enum CompiledIgnoreEntry {
148 Code(String),
149 Scoped { code: String, matcher: ExclusionMatcher<String> },
150 Pattern { regex: Regex, code: Option<String>, matcher: Option<ExclusionMatcher<String>> },
151}
152
153#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd)]
155#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
156pub enum AnnotationKind {
157 Primary,
159 Secondary,
161}
162
163#[derive(Debug, PartialEq, Eq, Ord, Clone, Hash, PartialOrd)]
165#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
166pub struct Annotation {
167 pub message: Option<Cow<'static, str>>,
169 pub kind: AnnotationKind,
171 pub span: Span,
173}
174
175#[derive(Debug, PartialEq, Eq, Ord, Copy, Clone, Hash, PartialOrd, Display, VariantNames, JsonSchema)]
177#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
178#[strum(serialize_all = "lowercase")]
179pub enum Level {
180 #[cfg_attr(feature = "serde", serde(alias = "note"))]
182 Note,
183 #[cfg_attr(feature = "serde", serde(alias = "help"))]
185 Help,
186 #[cfg_attr(feature = "serde", serde(alias = "warning", alias = "warn"))]
188 Warning,
189 #[cfg_attr(feature = "serde", serde(alias = "error", alias = "err"))]
191 Error,
192}
193
194impl FromStr for Level {
195 type Err = ();
196
197 fn from_str(s: &str) -> Result<Self, Self::Err> {
198 match s.to_lowercase().as_str() {
199 "note" => Ok(Self::Note),
200 "help" => Ok(Self::Help),
201 "warning" => Ok(Self::Warning),
202 "error" => Ok(Self::Error),
203 _ => Err(()),
204 }
205 }
206}
207
208type IssueEdits = Vec<TextEdit>;
209type IssueEditBatches = Vec<(Option<String>, IssueEdits)>;
210
211#[derive(Debug, Clone, Eq, PartialEq)]
213#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
214pub struct Issue {
215 pub level: Level,
217 pub code: Option<String>,
219 pub message: Cow<'static, str>,
221 pub notes: Vec<Cow<'static, str>>,
223 pub help: Option<Cow<'static, str>>,
225 pub link: Option<String>,
227 pub annotations: Vec<Annotation>,
229 pub edits: HashMap<FileId, IssueEdits>,
231}
232
233#[derive(Debug, Clone, Eq, PartialEq)]
235#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
236#[allow(clippy::unsafe_derive_deserialize)]
237pub struct IssueCollection {
238 issues: Vec<Issue>,
239}
240
241impl AnnotationKind {
242 #[inline]
244 #[must_use]
245 pub const fn is_primary(&self) -> bool {
246 matches!(self, AnnotationKind::Primary)
247 }
248
249 #[inline]
251 #[must_use]
252 pub const fn is_secondary(&self) -> bool {
253 matches!(self, AnnotationKind::Secondary)
254 }
255}
256
257impl CompiledIgnoreSet {
258 #[must_use]
260 pub fn is_ignored<F>(&self, issue: &Issue, resolve_file_name: F) -> bool
261 where
262 F: Fn(FileId) -> Option<String>,
263 {
264 let mut cached_path: Option<Option<String>> = None;
265 let mut resolve_path = |issue: &Issue| -> Option<String> {
266 cached_path
267 .get_or_insert_with(|| issue.primary_span().and_then(|span| resolve_file_name(span.file_id)))
268 .clone()
269 };
270
271 for entry in &self.entries {
272 match entry {
273 CompiledIgnoreEntry::Code(ignored_code) => {
274 if let Some(code) = &issue.code
275 && ignored_code == code
276 {
277 return true;
278 }
279 }
280 CompiledIgnoreEntry::Scoped { code: ignored_code, matcher } => {
281 let Some(code) = &issue.code else {
282 continue;
283 };
284
285 if ignored_code != code {
286 continue;
287 }
288
289 if let Some(name) = resolve_path(issue)
290 && matcher.is_match(&name)
291 {
292 return true;
293 }
294 }
295 CompiledIgnoreEntry::Pattern { regex, code: ignored_code, matcher } => {
296 if let Some(ignored_code) = ignored_code {
297 let Some(code) = &issue.code else {
298 continue;
299 };
300
301 if ignored_code != code {
302 continue;
303 }
304 }
305
306 if let Some(matcher) = matcher {
307 let Some(name) = resolve_path(issue) else {
308 continue;
309 };
310
311 if !matcher.is_match(&name) {
312 continue;
313 }
314 }
315
316 if issue_text_matches(issue, regex) {
317 return true;
318 }
319 }
320 }
321 }
322 false
323 }
324
325 #[must_use]
330 pub fn compile(entries: &[IgnoreEntry], glob: GlobSettings) -> Self {
331 let mut compiled = Vec::with_capacity(entries.len());
332 for entry in entries {
333 match entry {
334 IgnoreEntry::Code(code) => compiled.push(CompiledIgnoreEntry::Code(code.clone())),
335 IgnoreEntry::Scoped { code, paths } => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
336 Ok(matcher) => compiled.push(CompiledIgnoreEntry::Scoped { code: code.clone(), matcher }),
337 Err(err) => {
338 tracing::error!("Failed to compile ignore patterns for `{code}`: {err}. Entry will be skipped.")
339 }
340 },
341 IgnoreEntry::Pattern { pattern, code, paths } => {
342 let regex = match Regex::new(pattern) {
343 Ok(regex) => regex,
344 Err(err) => {
345 tracing::error!(
346 "Failed to compile ignore regex `{pattern}`: {err}. Entry will be skipped."
347 );
348
349 continue;
350 }
351 };
352
353 let matcher = match paths {
354 Some(paths) => match ExclusionMatcher::compile(paths.iter().cloned(), glob) {
355 Ok(matcher) => Some(matcher),
356 Err(err) => {
357 tracing::error!(
358 "Failed to compile ignore paths for regex `{pattern}`: {err}. Entry will be skipped."
359 );
360
361 continue;
362 }
363 },
364 None => None,
365 };
366
367 compiled.push(CompiledIgnoreEntry::Pattern { regex, code: code.clone(), matcher });
368 }
369 }
370 }
371
372 Self { entries: compiled }
373 }
374
375 #[must_use]
376 pub fn is_empty(&self) -> bool {
377 self.entries.is_empty()
378 }
379
380 #[must_use]
381 pub fn len(&self) -> usize {
382 self.entries.len()
383 }
384}
385
386impl Annotation {
387 #[must_use]
404 pub fn new(kind: AnnotationKind, span: Span) -> Self {
405 Self { message: None, kind, span }
406 }
407
408 #[must_use]
425 pub fn primary(span: Span) -> Self {
426 Self::new(AnnotationKind::Primary, span)
427 }
428
429 #[must_use]
446 pub fn secondary(span: Span) -> Self {
447 Self::new(AnnotationKind::Secondary, span)
448 }
449
450 #[must_use]
467 pub fn with_message(mut self, message: impl Into<Cow<'static, str>>) -> Self {
468 self.message = Some(message.into());
469
470 self
471 }
472
473 #[must_use]
475 pub fn is_primary(&self) -> bool {
476 self.kind == AnnotationKind::Primary
477 }
478}
479
480impl Level {
481 #[must_use]
508 pub fn downgrade(&self) -> Self {
509 match self {
510 Level::Error => Level::Warning,
511 Level::Warning => Level::Help,
512 Level::Help | Level::Note => Level::Note,
513 }
514 }
515}
516
517impl Issue {
518 pub fn new(level: Level, message: impl Into<Cow<'static, str>>) -> Self {
528 Self {
529 level,
530 code: None,
531 message: message.into(),
532 annotations: Vec::new(),
533 notes: Vec::new(),
534 help: None,
535 link: None,
536 edits: HashMap::default(),
537 }
538 }
539
540 pub fn error(message: impl Into<Cow<'static, str>>) -> Self {
550 Self::new(Level::Error, message)
551 }
552
553 pub fn warning(message: impl Into<Cow<'static, str>>) -> Self {
563 Self::new(Level::Warning, message)
564 }
565
566 pub fn help(message: impl Into<Cow<'static, str>>) -> Self {
576 Self::new(Level::Help, message)
577 }
578
579 pub fn note(message: impl Into<Cow<'static, str>>) -> Self {
589 Self::new(Level::Note, message)
590 }
591
592 #[must_use]
602 pub fn with_code(mut self, code: impl Into<String>) -> Self {
603 self.code = Some(code.into());
604
605 self
606 }
607
608 #[must_use]
626 pub fn with_annotation(mut self, annotation: Annotation) -> Self {
627 if self.annotations.is_empty() {
628 self.annotations.reserve_exact(2);
629 }
630
631 self.annotations.push(annotation);
632
633 self
634 }
635
636 #[must_use]
637 pub fn with_annotations(mut self, annotation: impl IntoIterator<Item = Annotation>) -> Self {
638 self.annotations.extend(annotation);
639
640 self
641 }
642
643 #[must_use]
647 pub fn primary_annotation(&self) -> Option<&Annotation> {
648 self.annotations.iter().filter(|annotation| annotation.is_primary()).min_by_key(|annotation| annotation.span)
649 }
650
651 #[must_use]
653 pub fn primary_span(&self) -> Option<Span> {
654 self.primary_annotation().map(|annotation| annotation.span)
655 }
656
657 #[must_use]
667 pub fn with_note(mut self, note: impl Into<Cow<'static, str>>) -> Self {
668 if self.notes.is_empty() {
669 self.notes.reserve_exact(1);
670 }
671
672 self.notes.push(note.into());
673
674 self
675 }
676
677 #[must_use]
689 pub fn with_help(mut self, help: impl Into<Cow<'static, str>>) -> Self {
690 self.help = Some(help.into());
691
692 self
693 }
694
695 #[must_use]
705 pub fn with_link(mut self, link: impl Into<String>) -> Self {
706 self.link = Some(link.into());
707
708 self
709 }
710
711 #[must_use]
713 pub fn with_edit(mut self, file_id: FileId, edit: TextEdit) -> Self {
714 self.edits.entry(file_id).or_default().push(edit);
715
716 self
717 }
718
719 #[must_use]
721 pub fn with_file_edits(mut self, file_id: FileId, edits: IssueEdits) -> Self {
722 if !edits.is_empty() {
723 match self.edits.entry(file_id) {
724 Entry::Vacant(entry) => {
725 entry.insert(edits);
726 }
727 Entry::Occupied(mut entry) => entry.get_mut().extend(edits),
728 }
729 }
730
731 self
732 }
733
734 #[must_use]
736 pub fn take_edits(&mut self) -> HashMap<FileId, IssueEdits> {
737 std::mem::replace(&mut self.edits, HashMap::new())
738 }
739}
740
741impl IssueCollection {
742 #[must_use]
743 pub fn new() -> Self {
744 Self { issues: Vec::new() }
745 }
746
747 pub fn from(issues: impl IntoIterator<Item = Issue>) -> Self {
748 Self { issues: issues.into_iter().collect() }
749 }
750
751 #[must_use]
753 pub fn concat(collections: Vec<IssueCollection>) -> Self {
754 let total = collections.iter().map(IssueCollection::len).sum();
755 let mut issues = Vec::with_capacity(total);
756 let mut slots = issues.spare_capacity_mut();
757 let mut parts = Vec::with_capacity(collections.len());
758 for collection in collections {
759 let (head, tail) = slots.split_at_mut(collection.len());
760 parts.push((head, collection.issues));
761 slots = tail;
762 }
763
764 parts.into_par_iter().for_each(|(slots, source)| {
765 for (slot, issue) in slots.iter_mut().zip(source) {
766 slot.write(issue);
767 }
768 });
769
770 unsafe { issues.set_len(total) };
772
773 Self { issues }
774 }
775
776 pub fn push(&mut self, issue: Issue) {
777 self.issues.push(issue);
778 }
779
780 pub fn extend(&mut self, issues: impl IntoIterator<Item = Issue>) {
781 self.issues.extend(issues);
782 }
783
784 pub fn reserve(&mut self, additional: usize) {
785 self.issues.reserve(additional);
786 }
787
788 pub fn shrink_to_fit(&mut self) {
789 self.issues.shrink_to_fit();
790 }
791
792 #[must_use]
793 pub fn is_empty(&self) -> bool {
794 self.issues.is_empty()
795 }
796
797 #[must_use]
798 pub fn len(&self) -> usize {
799 self.issues.len()
800 }
801
802 #[must_use]
805 pub fn with_maximum_level(self, level: Level) -> Self {
806 Self { issues: self.issues.into_iter().filter(|issue| issue.level <= level).collect() }
807 }
808
809 #[must_use]
812 pub fn with_minimum_level(self, level: Level) -> Self {
813 Self { issues: self.issues.into_iter().filter(|issue| issue.level >= level).collect() }
814 }
815
816 #[must_use]
819 pub fn has_minimum_level(&self, level: Level) -> bool {
820 self.issues.iter().any(|issue| issue.level >= level)
821 }
822
823 #[must_use]
825 pub fn get_level_count(&self, level: Level) -> usize {
826 self.issues.iter().filter(|issue| issue.level == level).count()
827 }
828
829 #[must_use]
831 pub fn get_highest_level(&self) -> Option<Level> {
832 self.issues.iter().map(|issue| issue.level).max()
833 }
834
835 #[must_use]
837 pub fn get_lowest_level(&self) -> Option<Level> {
838 self.issues.iter().map(|issue| issue.level).min()
839 }
840
841 pub fn filter_out_ignored<F>(&mut self, set: &CompiledIgnoreSet, resolve_file_name: F)
842 where
843 F: Fn(FileId) -> Option<String>,
844 {
845 if !set.is_empty() {
846 self.issues.retain(|issue| !set.is_ignored(issue, &resolve_file_name));
847 }
848 }
849
850 pub fn filter_retain_codes(&mut self, retain_codes: &[String]) {
851 self.issues.retain(|issue| if let Some(code) = &issue.code { retain_codes.contains(code) } else { false });
852 }
853
854 pub fn take_edits(&mut self) -> impl Iterator<Item = (FileId, IssueEdits)> + '_ {
855 self.issues.iter_mut().flat_map(|issue| issue.take_edits().into_iter())
856 }
857
858 #[must_use]
860 pub fn with_edits(self) -> Self {
861 Self { issues: self.issues.into_iter().filter(|issue| !issue.edits.is_empty()).collect() }
862 }
863
864 #[must_use]
869 pub fn sorted(self) -> Self {
870 let mut issues = self.issues;
871
872 issues.sort_by(|a, b| match a.level.cmp(&b.level) {
873 Ordering::Greater => Ordering::Greater,
874 Ordering::Less => Ordering::Less,
875 Ordering::Equal => match a.code.as_deref().cmp(&b.code.as_deref()) {
876 Ordering::Less => Ordering::Less,
877 Ordering::Greater => Ordering::Greater,
878 Ordering::Equal => {
879 let a_span = a.primary_span();
880 let b_span = b.primary_span();
881
882 match (a_span, b_span) {
883 (Some(a_span), Some(b_span)) => a_span.cmp(&b_span),
884 (Some(_), None) => Ordering::Less,
885 (None, Some(_)) => Ordering::Greater,
886 (None, None) => Ordering::Equal,
887 }
888 }
889 },
890 });
891
892 Self { issues }
893 }
894
895 pub fn iter(&self) -> impl Iterator<Item = &Issue> {
896 self.issues.iter()
897 }
898
899 #[must_use]
907 pub fn to_edit_batches(self) -> HashMap<FileId, IssueEditBatches> {
908 let mut result: HashMap<FileId, Vec<(Option<String>, IssueEdits)>> = HashMap::default();
909 for issue in self.issues.into_iter().filter(|issue| !issue.edits.is_empty()) {
910 let code = issue.code;
911 for (file_id, edit_list) in issue.edits {
912 result.entry(file_id).or_default().push((code.clone(), edit_list));
913 }
914 }
915
916 result
917 }
918}
919
920fn issue_text_matches(issue: &Issue, regex: &Regex) -> bool {
926 if regex.is_match(&issue.message) {
927 return true;
928 }
929
930 if issue
931 .annotations
932 .iter()
933 .any(|annotation| annotation.message.as_ref().is_some_and(|message| regex.is_match(message)))
934 {
935 return true;
936 }
937
938 if issue.notes.iter().any(|note| regex.is_match(note)) {
939 return true;
940 }
941
942 issue.help.as_ref().is_some_and(|help| regex.is_match(help))
943}
944
945impl IntoIterator for IssueCollection {
946 type Item = Issue;
947
948 type IntoIter = std::vec::IntoIter<Issue>;
949
950 fn into_iter(self) -> Self::IntoIter {
951 self.issues.into_iter()
952 }
953}
954
955impl<'collection> IntoIterator for &'collection IssueCollection {
956 type Item = &'collection Issue;
957
958 type IntoIter = std::slice::Iter<'collection, Issue>;
959
960 fn into_iter(self) -> Self::IntoIter {
961 self.issues.iter()
962 }
963}
964
965impl Default for IssueCollection {
966 fn default() -> Self {
967 Self::new()
968 }
969}
970
971impl IntoIterator for Issue {
972 type Item = Issue;
973 type IntoIter = Once<Issue>;
974
975 fn into_iter(self) -> Self::IntoIter {
976 std::iter::once(self)
977 }
978}
979
980impl FromIterator<Issue> for IssueCollection {
981 fn from_iter<T>(iter: T) -> Self
982 where
983 T: IntoIterator<Item = Issue>,
984 {
985 Self { issues: iter.into_iter().collect() }
986 }
987}
988
989#[cfg(test)]
990mod tests {
991 use std::collections::HashMap;
992
993 use super::*;
994
995 #[test]
996 pub fn test_highest_collection_level() {
997 let mut collection = IssueCollection::from(vec![]);
998 assert_eq!(collection.get_highest_level(), None);
999
1000 collection.push(Issue::note("note"));
1001 assert_eq!(collection.get_highest_level(), Some(Level::Note));
1002
1003 collection.push(Issue::help("help"));
1004 assert_eq!(collection.get_highest_level(), Some(Level::Help));
1005
1006 collection.push(Issue::warning("warning"));
1007 assert_eq!(collection.get_highest_level(), Some(Level::Warning));
1008
1009 collection.push(Issue::error("error"));
1010 assert_eq!(collection.get_highest_level(), Some(Level::Error));
1011 }
1012
1013 #[test]
1014 pub fn test_level_downgrade() {
1015 assert_eq!(Level::Error.downgrade(), Level::Warning);
1016 assert_eq!(Level::Warning.downgrade(), Level::Help);
1017 assert_eq!(Level::Help.downgrade(), Level::Note);
1018 assert_eq!(Level::Note.downgrade(), Level::Note);
1019 }
1020
1021 #[test]
1022 pub fn test_issue_collection_concat_keeps_order() {
1023 let collections: Vec<IssueCollection> = (0..300usize)
1024 .map(|part| IssueCollection::from((0..part % 7).map(|index| Issue::error(format!("{part}:{index}")))))
1025 .collect();
1026 let expected: Vec<Issue> = collections.iter().flat_map(IssueCollection::iter).cloned().collect();
1027
1028 assert_eq!(IssueCollection::concat(collections).into_iter().collect::<Vec<_>>(), expected);
1029 assert!(IssueCollection::concat(Vec::new()).is_empty());
1030 }
1031
1032 #[test]
1033 pub fn test_issue_collection_with_maximum_level() {
1034 let mut collection = IssueCollection::from(vec![
1035 Issue::error("error"),
1036 Issue::warning("warning"),
1037 Issue::help("help"),
1038 Issue::note("note"),
1039 ]);
1040
1041 collection = collection.with_maximum_level(Level::Warning);
1042 assert_eq!(collection.len(), 3);
1043 assert_eq!(
1044 collection.iter().map(|issue| issue.level).collect::<Vec<_>>(),
1045 vec![Level::Warning, Level::Help, Level::Note]
1046 );
1047 }
1048
1049 #[test]
1050 pub fn test_issue_collection_with_minimum_level() {
1051 let mut collection = IssueCollection::from(vec![
1052 Issue::error("error"),
1053 Issue::warning("warning"),
1054 Issue::help("help"),
1055 Issue::note("note"),
1056 ]);
1057
1058 collection = collection.with_minimum_level(Level::Warning);
1059 assert_eq!(collection.len(), 2);
1060 assert_eq!(collection.iter().map(|issue| issue.level).collect::<Vec<_>>(), vec![Level::Error, Level::Warning,]);
1061 }
1062
1063 #[test]
1064 pub fn test_issue_collection_has_minimum_level() {
1065 let mut collection = IssueCollection::from(vec![]);
1066
1067 assert!(!collection.has_minimum_level(Level::Error));
1068 assert!(!collection.has_minimum_level(Level::Warning));
1069 assert!(!collection.has_minimum_level(Level::Help));
1070 assert!(!collection.has_minimum_level(Level::Note));
1071
1072 collection.push(Issue::note("note"));
1073
1074 assert!(!collection.has_minimum_level(Level::Error));
1075 assert!(!collection.has_minimum_level(Level::Warning));
1076 assert!(!collection.has_minimum_level(Level::Help));
1077 assert!(collection.has_minimum_level(Level::Note));
1078
1079 collection.push(Issue::help("help"));
1080
1081 assert!(!collection.has_minimum_level(Level::Error));
1082 assert!(!collection.has_minimum_level(Level::Warning));
1083 assert!(collection.has_minimum_level(Level::Help));
1084 assert!(collection.has_minimum_level(Level::Note));
1085
1086 collection.push(Issue::warning("warning"));
1087
1088 assert!(!collection.has_minimum_level(Level::Error));
1089 assert!(collection.has_minimum_level(Level::Warning));
1090 assert!(collection.has_minimum_level(Level::Help));
1091 assert!(collection.has_minimum_level(Level::Note));
1092
1093 collection.push(Issue::error("error"));
1094
1095 assert!(collection.has_minimum_level(Level::Error));
1096 assert!(collection.has_minimum_level(Level::Warning));
1097 assert!(collection.has_minimum_level(Level::Help));
1098 assert!(collection.has_minimum_level(Level::Note));
1099 }
1100
1101 #[test]
1102 pub fn test_issue_collection_level_count() {
1103 let mut collection = IssueCollection::from(vec![]);
1104
1105 assert_eq!(collection.get_level_count(Level::Error), 0);
1106 assert_eq!(collection.get_level_count(Level::Warning), 0);
1107 assert_eq!(collection.get_level_count(Level::Help), 0);
1108 assert_eq!(collection.get_level_count(Level::Note), 0);
1109
1110 collection.push(Issue::error("error"));
1111
1112 assert_eq!(collection.get_level_count(Level::Error), 1);
1113 assert_eq!(collection.get_level_count(Level::Warning), 0);
1114 assert_eq!(collection.get_level_count(Level::Help), 0);
1115 assert_eq!(collection.get_level_count(Level::Note), 0);
1116
1117 collection.push(Issue::warning("warning"));
1118
1119 assert_eq!(collection.get_level_count(Level::Error), 1);
1120 assert_eq!(collection.get_level_count(Level::Warning), 1);
1121 assert_eq!(collection.get_level_count(Level::Help), 0);
1122 assert_eq!(collection.get_level_count(Level::Note), 0);
1123
1124 collection.push(Issue::help("help"));
1125
1126 assert_eq!(collection.get_level_count(Level::Error), 1);
1127 assert_eq!(collection.get_level_count(Level::Warning), 1);
1128 assert_eq!(collection.get_level_count(Level::Help), 1);
1129 assert_eq!(collection.get_level_count(Level::Note), 0);
1130
1131 collection.push(Issue::note("note"));
1132
1133 assert_eq!(collection.get_level_count(Level::Error), 1);
1134 assert_eq!(collection.get_level_count(Level::Warning), 1);
1135 assert_eq!(collection.get_level_count(Level::Help), 1);
1136 assert_eq!(collection.get_level_count(Level::Note), 1);
1137 }
1138
1139 #[test]
1140 pub fn test_primary_span_is_deterministic() {
1141 let file = FileId::zero();
1142 let span_later = Span::new(file, 20u32.into(), 25u32.into());
1143 let span_earlier = Span::new(file, 5u32.into(), 10u32.into());
1144
1145 let issue = Issue::error("x")
1146 .with_annotation(Annotation::primary(span_later))
1147 .with_annotation(Annotation::primary(span_earlier));
1148
1149 assert_eq!(issue.primary_span(), Some(span_earlier));
1150 }
1151
1152 fn ignore_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1153 let file_id = |name: &[u8]| FileId::new(name);
1154
1155 let paths: [&[u8]; 4] =
1156 [b"src/App.php", b"tests/Unit/FooTest.php", b"modules/auth/views/login.tpl", b"types/user/form.tpl"];
1157
1158 let mut mapping = HashMap::new();
1159 let issues: Vec<Issue> = paths
1160 .iter()
1161 .map(|p| {
1162 let id = file_id(p);
1163 mapping.insert(id, *p);
1164 Issue::error("oops").with_code("invalid-global").with_annotation(Annotation::primary(Span::new(
1165 id,
1166 0u32.into(),
1167 1u32.into(),
1168 )))
1169 })
1170 .collect();
1171
1172 (IssueCollection::from(issues), mapping)
1173 }
1174
1175 fn resolve<'mapping>(
1176 mapping: &'mapping HashMap<FileId, &'static [u8]>,
1177 ) -> impl Fn(FileId) -> Option<String> + 'mapping {
1178 move |id| mapping.get(&id).map(|s| String::from_utf8_lossy(s).into_owned())
1179 }
1180
1181 fn remaining_paths(collection: &IssueCollection, mapping: &HashMap<FileId, &'static [u8]>) -> Vec<String> {
1182 collection
1183 .iter()
1184 .filter_map(|issue| issue.primary_span().and_then(|s| mapping.get(&s.file_id)).copied())
1185 .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
1186 .collect()
1187 }
1188
1189 #[test]
1190 pub fn test_filter_out_ignored_with_plain_prefix() {
1191 let (mut collection, mapping) = ignore_fixture();
1192 let entries =
1193 vec![IgnoreEntry::Scoped { code: "invalid-global".to_string(), paths: vec!["tests/".to_string()] }];
1194 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1195
1196 collection.filter_out_ignored(&set, resolve(&mapping));
1197
1198 assert_eq!(
1199 remaining_paths(&collection, &mapping),
1200 vec![
1201 "src/App.php".to_string(),
1202 "modules/auth/views/login.tpl".to_string(),
1203 "types/user/form.tpl".to_string(),
1204 ]
1205 );
1206 }
1207
1208 #[test]
1209 pub fn test_filter_out_ignored_with_glob_pattern() {
1210 let (mut collection, mapping) = ignore_fixture();
1211 let entries = vec![IgnoreEntry::Scoped {
1212 code: "invalid-global".to_string(),
1213 paths: vec!["modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1214 }];
1215 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1216
1217 collection.filter_out_ignored(&set, resolve(&mapping));
1218
1219 assert_eq!(
1220 remaining_paths(&collection, &mapping),
1221 vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1222 );
1223 }
1224
1225 #[test]
1226 pub fn test_filter_out_ignored_mixes_plain_and_glob() {
1227 let (mut collection, mapping) = ignore_fixture();
1228 let entries = vec![IgnoreEntry::Scoped {
1229 code: "invalid-global".to_string(),
1230 paths: vec!["tests/".to_string(), "modules/*/*/*.tpl".to_string(), "types/*/*.tpl".to_string()],
1231 }];
1232 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1233
1234 collection.filter_out_ignored(&set, resolve(&mapping));
1235
1236 assert_eq!(remaining_paths(&collection, &mapping), vec!["src/App.php".to_string()]);
1237 }
1238
1239 #[test]
1240 pub fn test_filter_out_ignored_respects_code_scope() {
1241 let (mut collection, mapping) = ignore_fixture();
1242 let entries = vec![IgnoreEntry::Scoped { code: "different-code".to_string(), paths: vec!["**/*".to_string()] }];
1243 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1244
1245 collection.filter_out_ignored(&set, resolve(&mapping));
1246
1247 assert_eq!(collection.len(), 4);
1248 }
1249
1250 fn pattern_fixture() -> (IssueCollection, HashMap<FileId, &'static [u8]>) {
1251 let paths: [&[u8]; 3] = [b"src/App.php", b"src/Bridge/Symfony.php", b"tests/Unit/FooTest.php"];
1252 let mut mapping = HashMap::new();
1253 let mut issues: Vec<Issue> = Vec::new();
1254
1255 let id0 = FileId::new(blake3::hash(paths[0]).as_bytes());
1256 mapping.insert(id0, paths[0]);
1257 issues.push(
1258 Issue::error("Saw type `mixed` in Symfony bridge.")
1259 .with_code("mixed-assignment")
1260 .with_annotation(Annotation::primary(Span::new(id0, 0u32.into(), 1u32.into()))),
1261 );
1262
1263 let id1 = FileId::new(blake3::hash(paths[1]).as_bytes());
1264 mapping.insert(id1, paths[1]);
1265 issues.push(
1266 Issue::error("Could not infer a precise return type.")
1267 .with_code("mixed-assignment")
1268 .with_note("Originates from Symfony vendor stubs.")
1269 .with_annotation(Annotation::primary(Span::new(id1, 0u32.into(), 1u32.into()))),
1270 );
1271
1272 let id2 = FileId::new(blake3::hash(paths[2]).as_bytes());
1273 mapping.insert(id2, paths[2]);
1274 issues.push(
1275 Issue::error("Unused variable.")
1276 .with_code("unused-variable")
1277 .with_annotation(Annotation::primary(Span::new(id2, 0u32.into(), 1u32.into()))),
1278 );
1279
1280 (IssueCollection::from(issues), mapping)
1281 }
1282
1283 #[test]
1284 pub fn test_pattern_matches_title_and_note() {
1285 let (mut collection, mapping) = pattern_fixture();
1286 let entries = vec![IgnoreEntry::Pattern {
1287 pattern: "Symfony".to_string(),
1288 code: Some("mixed-assignment".to_string()),
1289 paths: None,
1290 }];
1291 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1292
1293 collection.filter_out_ignored(&set, resolve(&mapping));
1294
1295 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1296 }
1297
1298 #[test]
1299 pub fn test_pattern_without_code_matches_across_codes() {
1300 let (mut collection, mapping) = pattern_fixture();
1301 let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1302 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1303
1304 collection.filter_out_ignored(&set, resolve(&mapping));
1305
1306 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1307 }
1308
1309 #[test]
1310 pub fn test_pattern_with_path_scope() {
1311 let (mut collection, mapping) = pattern_fixture();
1312 let entries = vec![IgnoreEntry::Pattern {
1313 pattern: "Symfony".to_string(),
1314 code: None,
1315 paths: Some(vec!["src/Bridge/".to_string()]),
1316 }];
1317 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1318
1319 collection.filter_out_ignored(&set, resolve(&mapping));
1320
1321 assert_eq!(
1322 remaining_paths(&collection, &mapping),
1323 vec!["src/App.php".to_string(), "tests/Unit/FooTest.php".to_string()]
1324 );
1325 }
1326
1327 #[test]
1328 pub fn test_pattern_case_insensitive_with_flag() {
1329 let (mut collection, mapping) = pattern_fixture();
1330 let entries = vec![IgnoreEntry::Pattern { pattern: "(?i)symfony".to_string(), code: None, paths: None }];
1331 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1332
1333 collection.filter_out_ignored(&set, resolve(&mapping));
1334
1335 assert_eq!(remaining_paths(&collection, &mapping), vec!["tests/Unit/FooTest.php".to_string()]);
1336 }
1337
1338 #[test]
1339 pub fn test_pattern_invalid_regex_is_skipped() {
1340 let (mut collection, mapping) = pattern_fixture();
1341 let entries = vec![
1342 IgnoreEntry::Pattern { pattern: "[unterminated".to_string(), code: None, paths: None },
1343 IgnoreEntry::Code("unused-variable".to_string()),
1344 ];
1345 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1346
1347 assert_eq!(set.len(), 1);
1348
1349 collection.filter_out_ignored(&set, resolve(&mapping));
1350
1351 assert_eq!(
1352 remaining_paths(&collection, &mapping),
1353 vec!["src/App.php".to_string(), "src/Bridge/Symfony.php".to_string()]
1354 );
1355 }
1356
1357 #[test]
1358 pub fn test_pattern_matches_help_message() {
1359 let id = FileId::new(blake3::hash(b"src/foo.php").as_bytes());
1360 let mut mapping: HashMap<FileId, &'static [u8]> = HashMap::new();
1361 mapping.insert(id, &b"src/foo.php"[..]);
1362 let mut collection = IssueCollection::from(vec![
1363 Issue::error("Title.")
1364 .with_code("some-code")
1365 .with_help("Consider migrating off legacy Symfony bridge.")
1366 .with_annotation(Annotation::primary(Span::new(id, 0u32.into(), 1u32.into()))),
1367 ]);
1368
1369 let entries = vec![IgnoreEntry::Pattern { pattern: "Symfony".to_string(), code: None, paths: None }];
1370 let set = CompiledIgnoreSet::compile(&entries, GlobSettings::default());
1371
1372 collection.filter_out_ignored(&set, resolve(&mapping));
1373
1374 assert!(collection.is_empty());
1375 }
1376}