1use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6use anyhow::{Context, Result};
7
8use crate::report::Finding;
9
10pub fn fingerprint(finding: &Finding) -> String {
13 let kind = match finding {
15 Finding::InputGap { .. } => "input_gap",
16 Finding::AssertionGap { .. } | Finding::Survivor { .. } => "assertion_gap",
17 };
18 let (at, survivors) = (finding.at(), finding.survivors());
19 format!(
20 "{kind}\t{}\t{}\t{}",
21 at.file,
22 at.code,
23 survivors.join(" | ")
24 )
25}
26
27#[derive(Debug, PartialEq)]
29pub enum Baseline {
30 Fingerprints(BTreeSet<String>),
32 Ids {
34 file_package: Option<String>,
36 scoped: BTreeMap<String, BTreeSet<String>>,
38 unscoped: BTreeSet<String>,
40 },
41}
42
43impl Baseline {
44 pub fn validate_for_package(&self, package: &str, path: &Path) -> Result<()> {
46 if let Baseline::Ids {
47 file_package: Some(expected),
48 ..
49 } = self
50 && !package.is_empty()
51 && expected != package
52 {
53 anyhow::bail!(
54 "baseline {} is for package `{expected}`, not `{package}`",
55 path.display()
56 );
57 }
58 Ok(())
59 }
60
61 pub fn knows_in_package(&self, package: &str, finding: &Finding) -> bool {
63 let at = finding.at();
64 match self {
65 Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
66 Baseline::Ids {
67 scoped, unscoped, ..
68 } => {
69 !at.id.is_empty()
70 && (unscoped.contains(&at.id)
71 || (!package.is_empty()
72 && scoped.get(package).is_some_and(|ids| ids.contains(&at.id))))
73 }
74 }
75 }
76
77 pub fn knows(&self, finding: &Finding) -> bool {
78 let at = finding.at();
79 match self {
80 Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
81 Baseline::Ids {
82 scoped, unscoped, ..
83 } => {
84 !at.id.is_empty()
85 && (unscoped.contains(&at.id)
86 || scoped.values().any(|ids| ids.contains(&at.id)))
87 }
88 }
89 }
90}
91
92const VERSION: u64 = 3;
94const LEGACY_V2: u64 = 2;
96const MAX_BASELINE_BYTES: u64 = 16 * 1024 * 1024;
98
99#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
101#[serde(deny_unknown_fields)]
102pub struct BaselineEntry {
103 pub id: String,
104 #[serde(default, skip_serializing_if = "String::is_empty")]
105 pub package: String,
106 #[serde(default, skip_serializing_if = "String::is_empty")]
107 pub workspace_file: String,
108 #[serde(default, skip_serializing_if = "String::is_empty")]
109 pub kind: String,
110 #[serde(default, skip_serializing_if = "String::is_empty")]
111 pub file: String,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub line: Option<usize>,
114 #[serde(default, skip_serializing_if = "String::is_empty")]
115 pub item: String,
116 #[serde(default, skip_serializing_if = "String::is_empty")]
117 pub code: String,
118 #[serde(default, skip_serializing_if = "Vec::is_empty")]
119 pub survivors: Vec<String>,
120 #[serde(default)]
121 pub reason: String,
122}
123
124pub struct PartialScope<'a> {
126 pub scope: Option<&'a crate::scope::Scope>,
128 pub exclude_files: &'a [String],
130 pub preserve_all_existing: bool,
132}
133
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
136pub struct WriteSummary {
137 pub written: usize,
138 pub preserved: usize,
139 pub removed: usize,
140}
141
142#[derive(serde::Deserialize)]
143#[serde(untagged)]
144enum RawBaselineEntry {
145 Id(String),
146 Detailed(Box<BaselineEntry>),
147}
148
149struct ParsedBaseline {
150 baseline: Baseline,
151 is_legacy_fingerprints: bool,
152 entries: Vec<BaselineEntry>,
153 reasons: BTreeMap<(String, String), String>,
154 legacy_reasons: BTreeMap<String, String>,
155}
156
157fn read_regular_baseline(path: &Path) -> Result<String> {
158 use std::io::Read as _;
159
160 let metadata = std::fs::symlink_metadata(path)
161 .with_context(|| format!("inspecting {}", path.display()))?;
162 if !metadata.is_file() {
163 anyhow::bail!("{} is not a regular file", path.display());
164 }
165 let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
166 let mut text = String::new();
167 file.take(MAX_BASELINE_BYTES + 1)
168 .read_to_string(&mut text)
169 .with_context(|| format!("reading {}", path.display()))?;
170 let text_len = text.len() as u64;
171 if text_len > MAX_BASELINE_BYTES {
172 anyhow::bail!(
173 "{} exceeds maximum baseline size of {MAX_BASELINE_BYTES} bytes",
174 path.display()
175 );
176 }
177 Ok(text)
178}
179
180pub fn load(path: &Path) -> Result<Baseline> {
183 let text = read_regular_baseline(path)?;
184 parse(&text).with_context(|| format!("{} is not a tmt baseline", path.display()))
185}
186
187fn parse(text: &str) -> Result<Baseline> {
188 parse_full(text).map(|parsed| parsed.baseline)
189}
190
191fn parse_full(text: &str) -> Result<ParsedBaseline> {
192 let mut value: serde_json::Value = serde_json::from_str(text)?;
193 if value.is_array() {
194 return Ok(ParsedBaseline {
195 baseline: Baseline::Fingerprints(serde_json::from_value(value)?),
196 is_legacy_fingerprints: true,
197 entries: vec![],
198 reasons: BTreeMap::new(),
199 legacy_reasons: BTreeMap::new(),
200 });
201 }
202 let file_package = match value.get("package") {
203 None | Some(serde_json::Value::Null) => None,
204 Some(serde_json::Value::String(pkg)) if !pkg.is_empty() => Some(pkg.clone()),
205 Some(serde_json::Value::String(_)) => None,
206 Some(_) => anyhow::bail!("baseline `package` field must be a string"),
207 };
208 match value["version"].as_u64() {
209 Some(LEGACY_V2) => {
210 let ids: BTreeSet<String> = serde_json::from_value(value["findings"].take())?;
211 let entries = ids
212 .iter()
213 .map(|id| BaselineEntry {
214 id: id.clone(),
215 package: file_package.clone().unwrap_or_default(),
216 workspace_file: String::new(),
217 kind: String::new(),
218 file: String::new(),
219 line: None,
220 item: String::new(),
221 code: String::new(),
222 survivors: vec![],
223 reason: String::new(),
224 })
225 .collect();
226 let mut scoped = BTreeMap::new();
227 let mut unscoped = BTreeSet::new();
228 if let Some(pkg) = &file_package {
229 scoped.insert(pkg.clone(), ids);
230 } else {
231 unscoped = ids;
232 }
233 Ok(ParsedBaseline {
234 baseline: Baseline::Ids {
235 file_package,
236 scoped,
237 unscoped,
238 },
239 is_legacy_fingerprints: false,
240 entries,
241 reasons: BTreeMap::new(),
242 legacy_reasons: BTreeMap::new(),
243 })
244 }
245 Some(VERSION) => {
246 let raw_entries: Vec<RawBaselineEntry> =
247 serde_json::from_value(value["findings"].take())?;
248 let mut scoped: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
249 let mut unscoped = BTreeSet::new();
250 let mut entries = Vec::with_capacity(raw_entries.len());
251 let mut reasons = BTreeMap::new();
252 let mut legacy_reasons = BTreeMap::new();
253 for raw in raw_entries {
254 match raw {
255 RawBaselineEntry::Id(id) => {
256 if let Some(pkg) = &file_package {
257 scoped.entry(pkg.clone()).or_default().insert(id.clone());
258 } else {
259 unscoped.insert(id.clone());
260 }
261 entries.push(BaselineEntry {
262 id,
263 package: file_package.clone().unwrap_or_default(),
264 workspace_file: String::new(),
265 kind: String::new(),
266 file: String::new(),
267 line: None,
268 item: String::new(),
269 code: String::new(),
270 survivors: vec![],
271 reason: String::new(),
272 });
273 }
274 RawBaselineEntry::Detailed(entry) => {
275 let mut entry = *entry;
276 if entry.package.is_empty()
277 && let Some(pkg) = &file_package
278 {
279 entry.package = pkg.clone();
280 }
281 if !entry.reason.is_empty() {
282 if !entry.package.is_empty() {
283 reasons.insert(
284 (entry.package.clone(), entry.id.clone()),
285 entry.reason.clone(),
286 );
287 } else {
288 legacy_reasons
289 .entry(entry.id.clone())
290 .or_insert_with(|| entry.reason.clone());
291 }
292 }
293 if entry.package.is_empty() {
294 unscoped.insert(entry.id.clone());
295 } else {
296 scoped
297 .entry(entry.package.clone())
298 .or_default()
299 .insert(entry.id.clone());
300 }
301 entries.push(entry);
302 }
303 }
304 }
305 Ok(ParsedBaseline {
306 baseline: Baseline::Ids {
307 file_package,
308 scoped,
309 unscoped,
310 },
311 is_legacy_fingerprints: false,
312 entries,
313 reasons,
314 legacy_reasons,
315 })
316 }
317 Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
318 None => anyhow::bail!("neither a list nor an object with a version"),
319 }
320}
321
322fn read_existing(path: &Path) -> Result<Option<ParsedBaseline>> {
323 match std::fs::symlink_metadata(path) {
324 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
325 Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
326 Ok(meta) if !meta.is_file() => {
327 anyhow::bail!(
328 "refusing to overwrite non-regular baseline path {}",
329 path.display()
330 );
331 }
332 Ok(_) => {}
333 }
334 let text = read_regular_baseline(path)?;
335 let parsed = parse_full(&text).with_context(|| {
336 format!(
337 "cannot preserve reasons from existing baseline {} (fix or remove it before rewriting)",
338 path.display()
339 )
340 })?;
341 Ok(Some(parsed))
342}
343
344fn normalize_workspace_file(package_prefix: &str, file: &str) -> String {
345 let combined = if package_prefix.is_empty() {
346 Path::new(file).to_path_buf()
347 } else {
348 Path::new(package_prefix).join(file)
349 };
350 let mut parts: Vec<String> = Vec::new();
351 for component in combined.components() {
352 match component {
353 std::path::Component::Normal(name) => {
354 parts.push(name.to_string_lossy().into_owned());
355 }
356 std::path::Component::ParentDir => {
357 if parts.pop().is_none() {
358 parts.push("..".to_string());
359 }
360 }
361 std::path::Component::CurDir => {}
362 std::path::Component::RootDir | std::path::Component::Prefix(_) => {}
363 }
364 }
365 parts.join("/")
366}
367
368struct BaselineWriteLock {
371 _file: std::fs::File,
372}
373
374impl BaselineWriteLock {
375 fn acquire(path: &Path) -> Result<Self> {
376 let parent = path
377 .parent()
378 .filter(|p| !p.as_os_str().is_empty())
379 .unwrap_or_else(|| Path::new("."));
380 let file_name = path
381 .file_name()
382 .and_then(|n| n.to_str())
383 .unwrap_or("baseline");
384 let lock_path = parent.join(format!(".{file_name}.tmt-lock"));
385 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
386 loop {
387 match crate::work_lock::acquire(&lock_path) {
388 Ok(file) => return Ok(Self { _file: file }),
389 Err(err) if crate::work_lock::contended(&err) => {
390 if std::time::Instant::now() >= deadline {
391 anyhow::bail!(
392 "timed out waiting for baseline write lock {}",
393 lock_path.display()
394 );
395 }
396 std::thread::sleep(std::time::Duration::from_millis(10));
397 }
398 Err(err) => {
399 return Err(err).with_context(|| {
400 format!("acquiring baseline lock {}", lock_path.display())
401 });
402 }
403 }
404 }
405 }
406}
407
408fn entry_in_evaluated_scope(
409 entry: &BaselineEntry,
410 package: &str,
411 workspace_package_prefix: &str,
412 partial: Option<&PartialScope<'_>>,
413) -> bool {
414 if !package.is_empty() && !entry.package.is_empty() && entry.package != package {
416 return false;
417 }
418 let Some(partial) = partial else {
419 return true;
421 };
422 if partial.preserve_all_existing {
423 return false;
424 }
425 if (!package.is_empty() && entry.package.is_empty()) || entry.file.is_empty() {
427 return false;
428 }
429 if crate::scope::matches_any_glob(partial.exclude_files, &entry.file) {
430 return false;
431 }
432 if let Some(scope) = partial.scope {
433 let ws_file = if !entry.workspace_file.is_empty() {
434 entry.workspace_file.clone()
435 } else {
436 normalize_workspace_file(workspace_package_prefix, &entry.file)
437 };
438 if !scope.covers_whole_file(&ws_file) {
441 return false;
442 }
443 }
444 true
445}
446
447pub fn write_scoped(
457 path: &Path,
458 package: &str,
459 workspace_package_prefix: &str,
460 findings: &[Finding],
461 partial: Option<&PartialScope<'_>>,
462 single_package: Option<&str>,
463) -> Result<WriteSummary> {
464 let _lock = BaselineWriteLock::acquire(path)?;
465 let existing = read_existing(path)?;
466 if let Some(parsed) = &existing
467 && parsed.is_legacy_fingerprints
468 && partial.is_some()
469 {
470 anyhow::bail!(
471 "cannot partially update legacy v1 fingerprint baseline {} (run a full package analysis without scope filters to migrate it to v3)",
472 path.display()
473 );
474 }
475 let (existing_entries, reasons, legacy_reasons) = match existing {
476 Some(parsed) => (parsed.entries, parsed.reasons, parsed.legacy_reasons),
477 None => (vec![], BTreeMap::new(), BTreeMap::new()),
478 };
479
480 let mut by_key: BTreeMap<(String, String), BaselineEntry> = BTreeMap::new();
481 let mut preserved = 0usize;
482 let mut in_scope_existing = 0usize;
483 for entry in existing_entries {
484 if entry_in_evaluated_scope(&entry, package, workspace_package_prefix, partial) {
485 in_scope_existing += 1;
486 } else {
487 by_key
488 .entry((entry.package.clone(), entry.id.clone()))
489 .or_insert(entry);
490 preserved += 1;
491 }
492 }
493
494 let mut new_keys = BTreeSet::new();
495 for finding in findings {
496 let at = finding.at();
497 let pkg = package.to_string();
498 let key = (pkg.clone(), at.id.clone());
499 new_keys.insert(key.clone());
500 let workspace_file = normalize_workspace_file(workspace_package_prefix, &at.file);
501 let reason = reasons
502 .get(&key)
503 .or_else(|| legacy_reasons.get(&at.id))
504 .cloned()
505 .unwrap_or_default();
506 by_key.insert(
507 key,
508 BaselineEntry {
509 id: at.id.clone(),
510 package: pkg,
511 workspace_file,
512 kind: finding.kind().to_string(),
513 file: at.file.clone(),
514 line: Some(at.line),
515 item: at.item.clone(),
516 code: at.code.clone(),
517 survivors: finding.survivors().to_vec(),
518 reason,
519 },
520 );
521 }
522
523 let removed = in_scope_existing.saturating_sub(new_keys.len());
524 let entries: Vec<BaselineEntry> = by_key.into_values().collect();
525 let written = entries.len();
526
527 let top_level_package = single_package.and_then(|pkg| {
528 if pkg.is_empty() {
529 return None;
530 }
531 let has_other_or_unscoped = entries
532 .iter()
533 .any(|e| e.package.is_empty() || e.package != pkg);
534 (!has_other_or_unscoped).then(|| pkg.to_string())
535 });
536
537 let mut text = render_entries(&entries, top_level_package.as_deref());
538 text.push('\n');
539 let text_len = text.len() as u64;
540 if text_len > MAX_BASELINE_BYTES {
541 anyhow::bail!(
542 "baseline {} would exceed maximum size of {MAX_BASELINE_BYTES} bytes",
543 path.display()
544 );
545 }
546 let parent = path
547 .parent()
548 .filter(|p| !p.as_os_str().is_empty())
549 .unwrap_or_else(|| Path::new("."));
550 let file_name = path
551 .file_name()
552 .and_then(|n| n.to_str())
553 .unwrap_or("baseline");
554 let tmp = parent.join(format!(
555 ".{file_name}.tmt-tmp-{}-{}",
556 std::process::id(),
557 std::time::SystemTime::now()
558 .duration_since(std::time::UNIX_EPOCH)
559 .map_or(0, |d| d.as_nanos())
560 ));
561 if let Err(err) = std::fs::write(&tmp, &text) {
562 let _ = std::fs::remove_file(&tmp);
563 return Err(err).with_context(|| format!("writing {}", path.display()));
564 }
565 if let Err(err) = std::fs::rename(&tmp, path) {
566 let _ = std::fs::remove_file(&tmp);
567 return Err(err).with_context(|| format!("replacing {}", path.display()));
568 }
569 Ok(WriteSummary {
570 written,
571 preserved,
572 removed,
573 })
574}
575
576pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
577 write_scoped(path, "", "", findings, None, None).map(|_| ())
578}
579
580#[cfg(test)]
581fn render(findings: &[Finding]) -> String {
582 let entries: Vec<BaselineEntry> = findings
583 .iter()
584 .map(|finding| {
585 let at = finding.at();
586 BaselineEntry {
587 id: at.id.clone(),
588 package: String::new(),
589 workspace_file: at.file.clone(),
590 kind: finding.kind().to_string(),
591 file: at.file.clone(),
592 line: Some(at.line),
593 item: at.item.clone(),
594 code: at.code.clone(),
595 survivors: finding.survivors().to_vec(),
596 reason: String::new(),
597 }
598 })
599 .collect();
600 render_entries(&entries, None)
601}
602
603fn render_entries(entries: &[BaselineEntry], package: Option<&str>) -> String {
604 #[derive(serde::Serialize)]
605 struct BaselineFile<'a> {
606 #[serde(skip_serializing_if = "Option::is_none")]
607 package: Option<&'a str>,
608 findings: &'a [BaselineEntry],
609 version: u64,
610 }
611
612 serde_json::to_string_pretty(&BaselineFile {
613 package,
614 findings: entries,
615 version: VERSION,
616 })
617 .expect("baseline entries serialise")
618}
619
620#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
623pub struct IgnoreFilter {
624 pub kind: Option<String>,
626 pub column: Option<usize>,
628}
629
630impl IgnoreFilter {
631 pub fn matches(&self, kind: &str, column: usize) -> bool {
632 self.kind.as_deref().is_none_or(|k| k == kind) && self.column.is_none_or(|c| c == column)
633 }
634}
635
636#[derive(Clone, Debug, PartialEq, Eq)]
638pub enum IgnoreScope {
639 All,
641 Filters(BTreeSet<IgnoreFilter>),
643}
644
645#[derive(Clone, Debug, PartialEq, Eq)]
647pub struct LineIgnore {
648 pub scope: IgnoreScope,
649 pub reason: String,
650}
651
652impl LineIgnore {
653 pub fn matches_kind(&self, kind: &str) -> bool {
656 match &self.scope {
657 IgnoreScope::All => true,
658 IgnoreScope::Filters(filters) => filters
659 .iter()
660 .any(|f| f.column.is_none() && f.kind.as_deref().is_none_or(|k| k == kind)),
661 }
662 }
663
664 pub fn matches(&self, kind: &str, column: usize) -> bool {
666 match &self.scope {
667 IgnoreScope::All => true,
668 IgnoreScope::Filters(filters) => filters.iter().any(|f| f.matches(kind, column)),
669 }
670 }
671
672 fn merge(&mut self, other: LineIgnore) {
673 match (&mut self.scope, other.scope) {
674 (IgnoreScope::All, IgnoreScope::All) => {
675 self.reason = other.reason;
677 }
678 (IgnoreScope::All, IgnoreScope::Filters(_)) => {}
679 (slot, IgnoreScope::All) => {
680 *slot = IgnoreScope::All;
681 self.reason = other.reason;
683 }
684 (IgnoreScope::Filters(existing), IgnoreScope::Filters(extra)) => {
685 existing.extend(extra);
686 if !other.reason.is_empty() {
687 self.reason = other.reason;
688 }
689 }
690 }
691 }
692}
693
694#[derive(Clone, Debug, PartialEq, Eq)]
696pub enum IgnoreWarning {
697 EmptyScope { line: usize },
699 InvalidToken { line: usize, token: String },
701}
702
703#[derive(Clone, Debug, PartialEq, Eq)]
705pub struct IgnoreDirectiveEntry {
706 pub comment_line: usize,
707 pub target_lines: Vec<usize>,
708 pub scope: IgnoreScope,
709}
710
711impl IgnoreDirectiveEntry {
712 pub fn is_active(&self) -> bool {
713 match &self.scope {
714 IgnoreScope::All => true,
715 IgnoreScope::Filters(filters) => !filters.is_empty(),
716 }
717 }
718
719 pub fn matches(&self, line: usize, kind: &str, column: usize) -> bool {
720 if !self.target_lines.contains(&line) {
721 return false;
722 }
723 match &self.scope {
724 IgnoreScope::All => true,
725 IgnoreScope::Filters(filters) => filters.iter().any(|f| f.matches(kind, column)),
726 }
727 }
728}
729
730#[derive(Clone, Debug, Default, PartialEq, Eq)]
732pub struct ParsedLineIgnores {
733 pub directives: BTreeMap<usize, LineIgnore>,
734 pub entries: Vec<IgnoreDirectiveEntry>,
735 pub warnings: Vec<IgnoreWarning>,
736}
737
738fn parse_ignore_filter(raw: &str) -> Option<IgnoreFilter> {
739 let token = raw.trim();
740 if token.is_empty() {
741 return None;
742 }
743 let (kind_part, col_part) = match token.split_once('@') {
744 Some((k, c)) => (k.trim(), Some(c.trim())),
745 None => (token, None),
746 };
747 let column = match col_part {
748 Some(c) => {
749 let parsed = c.parse::<usize>().ok()?;
750 if parsed == 0 {
751 return None;
752 }
753 Some(parsed)
754 }
755 None => None,
756 };
757 let kind = if kind_part.is_empty() {
758 column?;
759 None
760 } else {
761 let normalized = kind_part.replace('-', "_");
762 if matches!(
763 normalized.as_str(),
764 "input_gap" | "assertion_gap" | "survivor"
765 ) {
766 Some(normalized)
767 } else {
768 return None;
769 }
770 };
771 Some(IgnoreFilter { kind, column })
772}
773
774fn parse_ignore_comment(
775 comment: &str,
776 line: usize,
777 warnings: &mut Vec<IgnoreWarning>,
778) -> Option<LineIgnore> {
779 let rest = comment.trim_start().strip_prefix("tmt:ignore")?;
780 if let Some(bracketed) = rest.strip_prefix('[') {
781 let close = bracketed.find(']')?;
782 let inside = &bracketed[..close];
783 let after = &bracketed[close + 1..];
784 if !(after.is_empty() || after.starts_with(|c: char| c.is_whitespace() || c == ':')) {
785 return None;
786 }
787 let mut filters = BTreeSet::new();
788 if inside.trim().is_empty() {
789 warnings.push(IgnoreWarning::EmptyScope { line });
790 } else {
791 for token in inside.split(',') {
792 if let Some(filter) = parse_ignore_filter(token) {
793 filters.insert(filter);
794 } else {
795 warnings.push(IgnoreWarning::InvalidToken {
796 line,
797 token: token.trim().to_string(),
798 });
799 }
800 }
801 }
802 let reason = after.trim_start_matches(':').trim().to_string();
803 return Some(LineIgnore {
804 scope: IgnoreScope::Filters(filters),
805 reason,
806 });
807 }
808 if rest.is_empty() || rest.starts_with(|c: char| c.is_whitespace() || c == ':') {
809 let reason = rest.trim_start_matches(':').trim().to_string();
810 return Some(LineIgnore {
811 scope: IgnoreScope::All,
812 reason,
813 });
814 }
815 None
816}
817
818pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
823 line_ignores(source)
824 .into_iter()
825 .filter(|(_, ignore)| matches!(ignore.scope, IgnoreScope::All))
826 .map(|(line, ignore)| (line, ignore.reason))
827 .collect()
828}
829
830pub fn line_ignores(source: &str) -> BTreeMap<usize, LineIgnore> {
834 parse_line_ignores(source).directives
835}
836
837pub fn parse_line_ignores(source: &str) -> ParsedLineIgnores {
840 let mut parsed = ParsedLineIgnores::default();
841 let bytes = source.as_bytes();
842 let mut i = 0;
843 let mut line = 1usize;
844 let mut line_start = 0usize;
845 let mut block_depth = 0usize;
846 while i < bytes.len() {
847 if block_depth > 0 {
848 if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
849 block_depth += 1;
850 i += 2;
851 } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
852 block_depth -= 1;
853 i += 2;
854 } else {
855 if bytes[i] == b'\n' {
856 line += 1;
857 line_start = i + 1;
858 }
859 i += 1;
860 }
861 continue;
862 }
863 match bytes[i] {
864 b'\n' => {
865 line += 1;
866 line_start = i + 1;
867 i += 1;
868 }
869 b'/' if bytes.get(i + 1) == Some(&b'/') => {
870 let comment_start = i + 2;
871 let mut end = comment_start;
872 while end < bytes.len() && bytes[end] != b'\n' {
873 end += 1;
874 }
875 let comment = &source[comment_start..end];
876 if let Some(directive) = parse_ignore_comment(comment, line, &mut parsed.warnings) {
877 let standalone = source[line_start..i].trim().is_empty();
878 let target_lines = if standalone {
879 vec![line, line + 1]
880 } else {
881 vec![line]
882 };
883 parsed.entries.push(IgnoreDirectiveEntry {
884 comment_line: line,
885 target_lines,
886 scope: directive.scope.clone(),
887 });
888 parsed
889 .directives
890 .entry(line)
891 .and_modify(|existing| existing.merge(directive.clone()))
892 .or_insert_with(|| directive.clone());
893 if standalone {
894 parsed
895 .directives
896 .entry(line + 1)
897 .and_modify(|existing| existing.merge(directive.clone()))
898 .or_insert(directive);
899 }
900 }
901 i = end;
902 }
903 b'/' if bytes.get(i + 1) == Some(&b'*') => {
904 block_depth = 1;
905 i += 2;
906 }
907 b'r' if raw_string_hashes(bytes, i).is_some() => {
909 let hashes = raw_string_hashes(bytes, i).unwrap();
910 i += 1 + hashes + 1;
911 while i < bytes.len() {
912 if bytes[i] == b'\n' {
913 line += 1;
914 line_start = i + 1;
915 }
916 if bytes[i] == b'"'
917 && bytes
918 .get(i + 1..i + 1 + hashes)
919 .is_some_and(|s| s.iter().all(|b| *b == b'#'))
920 {
921 i += 1 + hashes;
922 break;
923 }
924 i += 1;
925 }
926 }
927 b'"' => {
928 i += 1;
929 while i < bytes.len() {
930 if bytes[i] == b'\\' {
931 if bytes.get(i + 1) == Some(&b'\n') {
932 line += 1;
933 line_start = i + 2;
934 }
935 i = (i + 2).min(bytes.len());
936 continue;
937 }
938 if bytes[i] == b'\n' {
939 line += 1;
940 line_start = i + 1;
941 }
942 if bytes[i] == b'"' {
943 i += 1;
944 break;
945 }
946 i += 1;
947 }
948 }
949 b'\'' => {
951 if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 2).is_some_and(|&b| b != b'\n')
952 {
953 let mut j = i + 3;
956 while j < bytes.len() && bytes[j] != b'\n' && bytes[j] != b'\'' {
957 j += 1;
958 }
959 if bytes.get(j) == Some(&b'\'') {
960 i = j + 1;
961 } else {
962 i += 1;
963 }
964 } else if let Some(ch) = source[i + 1..].chars().next()
965 && bytes.get(i + 1 + ch.len_utf8()) == Some(&b'\'')
966 {
967 i += 1 + ch.len_utf8() + 1;
968 } else {
969 i += 1;
970 }
971 }
972 _ => i += 1,
973 }
974 }
975 parsed
976}
977
978fn raw_string_hashes(bytes: &[u8], r_pos: usize) -> Option<usize> {
979 if r_pos > 0 {
981 let prev = bytes[r_pos - 1];
982 let is_prefix =
983 (prev == b'b' || prev == b'c') && (r_pos == 1 || !is_ident_byte(bytes[r_pos - 2]));
984 if is_ident_byte(prev) && !is_prefix {
985 return None;
986 }
987 }
988 let mut hashes = 0;
989 while bytes.get(r_pos + 1 + hashes) == Some(&b'#') {
990 hashes += 1;
991 }
992 (bytes.get(r_pos + 1 + hashes) == Some(&b'"')).then_some(hashes)
993}
994
995fn is_ident_byte(b: u8) -> bool {
996 b.is_ascii_alphanumeric() || b == b'_'
997}
998
999#[cfg(test)]
1000mod tests {
1001 use super::*;
1002 use crate::report::Location;
1003
1004 fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
1005 Finding::AssertionGap {
1006 at: Location {
1007 file: "src/lib.rs".into(),
1008 line,
1009 column: 5,
1010 code: code.into(),
1011 ..Location::default()
1012 },
1013 survivors: survivors.iter().map(|s| s.to_string()).collect(),
1014 tests: vec!["tests::t".into()],
1015 effects: vec![],
1016 effects_of: None,
1017 witness: None,
1018 }
1019 }
1020
1021 #[test]
1022 fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
1023 let named = |id: &str, survivors: &[&str]| {
1024 let mut finding = gap(10, "a > b", survivors);
1025 let Finding::AssertionGap { at, .. } = &mut finding else {
1026 unreachable!()
1027 };
1028 at.id = id.to_string();
1029 finding
1030 };
1031 let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
1032 let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
1033 let written = render(std::slice::from_ref(&one));
1034 let baseline = parse(&written).unwrap();
1035 assert!(baseline.knows(&one));
1036 assert!(!baseline.knows(&other));
1038 assert!(baseline.knows(&named(
1040 "assertion_gap|src/lib.rs|f|a > b|0",
1041 &["`a >= b`", "the negation"]
1042 )));
1043 assert!(
1045 !parse(&render(&[gap(1, "x", &[])]))
1046 .unwrap()
1047 .knows(&gap(2, "y", &[]))
1048 );
1049 let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
1051 let baseline = parse(&old).unwrap();
1052 assert!(matches!(baseline, Baseline::Fingerprints(_)));
1053 assert!(baseline.knows(&one) && baseline.knows(&other));
1054 assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
1055 let later = parse(r#"{"version": 4, "findings": []}"#).unwrap_err();
1057 assert!(later.to_string().contains("version 4"), "{later}");
1058 for bad in [
1059 "{}",
1060 "3",
1061 r#"{"version": 2}"#,
1062 r#"{"version": 2, "findings": null}"#,
1063 r#"{"version": 2, "findings": [1]}"#,
1064 r#"{"version": 3, "findings": [1]}"#,
1065 r#"["a", 1]"#,
1066 ] {
1067 assert!(parse(bad).is_err(), "{bad}");
1068 }
1069 }
1070
1071 #[test]
1072 fn fingerprints_ignore_position_but_not_content() {
1073 let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
1074 assert_eq!(
1075 base,
1076 fingerprint(&gap(99, "a > b", &["`a >= b`"])),
1077 "moved code"
1078 );
1079 assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
1080 assert_ne!(
1081 base,
1082 fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
1083 "a new survivor"
1084 );
1085 let input = Finding::InputGap {
1086 at: Location {
1087 file: "src/lib.rs".into(),
1088 line: 10,
1089 column: 5,
1090 code: "a > b".into(),
1091 ..Location::default()
1092 },
1093 survivors: vec!["`a >= b`".into()],
1094 survivor_count: 1,
1095 add_tests: vec![],
1096 observed: None,
1097 verified: true,
1098 };
1099 assert_ne!(base, fingerprint(&input), "another kind of finding");
1100 }
1101
1102 #[test]
1103 fn baseline_round_trip() {
1104 let path =
1105 std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
1106 let _ = std::fs::remove_file(&path);
1107 let mut findings = vec![
1108 gap(1, "a > b", &["`a >= b`"]),
1109 gap(2, "x();", &["delete `x();`"]),
1110 ];
1111 for (index, finding) in findings.iter_mut().enumerate() {
1112 let Finding::AssertionGap { at, .. } = finding else {
1113 unreachable!()
1114 };
1115 at.id = format!("id-{index}-é\n");
1116 at.item = format!("fn_{index}");
1117 }
1118 findings.reverse();
1119 findings.push(findings[0].clone());
1120 write(&path, &findings).unwrap();
1121 let written: serde_json::Value =
1122 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1123 assert_eq!(written["version"], 3);
1124 let entries = written["findings"].as_array().unwrap();
1125 assert_eq!(entries.len(), 2);
1126 assert_eq!(entries[0]["id"], "id-0-é\n");
1127 assert_eq!(entries[0]["kind"], "assertion_gap");
1128 assert_eq!(entries[0]["file"], "src/lib.rs");
1129 assert_eq!(entries[0]["item"], "fn_0");
1130 assert_eq!(entries[0]["code"], "a > b");
1131 assert_eq!(entries[0]["survivors"], serde_json::json!(["`a >= b`"]));
1132 assert_eq!(entries[0]["reason"], "");
1133 assert_eq!(entries[1]["id"], "id-1-é\n");
1134
1135 let mut edited = written.clone();
1137 edited["findings"][0]["reason"] = serde_json::json!("equivalent in domain");
1138 std::fs::write(&path, serde_json::to_string_pretty(&edited).unwrap()).unwrap();
1139 write(&path, &findings).unwrap();
1140 let rewritten: serde_json::Value =
1141 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1142 assert_eq!(rewritten["findings"][0]["reason"], "equivalent in domain");
1143 assert_eq!(rewritten["findings"][1]["reason"], "");
1144
1145 let loaded = load(&path).unwrap();
1146 let ids: BTreeSet<String> = ["id-0-é\n", "id-1-é\n"].map(str::to_string).into();
1147 assert_eq!(
1148 loaded,
1149 Baseline::Ids {
1150 file_package: None,
1151 scoped: BTreeMap::new(),
1152 unscoped: ids,
1153 }
1154 );
1155 assert!(findings.iter().all(|f| loaded.knows(f)));
1156
1157 let broken = r#"{"version": 3, "findings": [{"id": "id-0", "reasons": "typo"}]}"#;
1159 std::fs::write(&path, broken).unwrap();
1160 assert!(write(&path, &findings).is_err());
1161 assert_eq!(std::fs::read_to_string(&path).unwrap(), broken);
1162
1163 std::fs::write(&path, "not json").unwrap();
1164 assert!(load(&path).is_err());
1165 assert!(write(&path, &findings).is_err());
1166 assert_eq!(std::fs::read_to_string(&path).unwrap(), "not json");
1167 std::fs::remove_file(&path).unwrap();
1168 assert!(load(&path).is_err());
1169 }
1170
1171 #[test]
1172 fn baseline_accepts_legacy_strings_and_structured_entries_mixed() {
1173 let v2 = r#"{"version": 2, "findings": ["v2-id"]}"#;
1174 assert_eq!(
1175 parse(v2).unwrap(),
1176 Baseline::Ids {
1177 file_package: None,
1178 scoped: BTreeMap::new(),
1179 unscoped: ["v2-id"].map(str::to_string).into(),
1180 }
1181 );
1182
1183 let mixed = r#"{
1184 "version": 3,
1185 "findings": [
1186 "legacy-id",
1187 {
1188 "id": "structured-id",
1189 "kind": "input_gap",
1190 "file": "src/lib.rs",
1191 "code": "x > 0",
1192 "survivors": ["`x >= 0`"],
1193 "reason": "zero is unreachable"
1194 }
1195 ]
1196}"#;
1197 let parsed = parse_full(mixed).unwrap();
1198 assert_eq!(
1199 parsed.baseline,
1200 Baseline::Ids {
1201 file_package: None,
1202 scoped: BTreeMap::new(),
1203 unscoped: ["legacy-id", "structured-id"].map(str::to_string).into(),
1204 }
1205 );
1206 assert_eq!(
1207 parsed
1208 .legacy_reasons
1209 .get("structured-id")
1210 .map(String::as_str),
1211 Some("zero is unreachable")
1212 );
1213 assert!(!parsed.legacy_reasons.contains_key("legacy-id"));
1214
1215 let typo = r#"{"version": 3, "findings": [{"id": "x", "reasons": "typo"}]}"#;
1217 assert!(parse(typo).is_err());
1218 let missing_id = r#"{"version": 3, "findings": [{"reason": "no id"}]}"#;
1219 assert!(parse(missing_id).is_err());
1220 }
1221
1222 #[test]
1223 fn selective_ignore_comments() {
1224 let source = "\
1225fn f() {
1226 // tmt:ignore[input_gap] boundary is equivalent
1227 if a >= b { a } else { b }
1228 let x = 1; // tmt:ignore[assertion-gap, survivor]: intentional
1229 // tmt:ignore[input_gap] above
1230 let y = 2; // tmt:ignore[assertion_gap] inline
1231 // tmt:ignore[unknown_kind] should not suppress anything
1232 let z = 3;
1233 let empty = 4; // tmt:ignore[] empty list
1234 let unclosed = 5; // tmt:ignore[input_gap missing bracket
1235 let attached = 6; // tmt:ignore[input_gap]extra
1236}
1237";
1238 let ignores = line_ignores(source);
1239 assert!(ignores[&3].matches_kind("input_gap"));
1241 assert!(!ignores[&3].matches_kind("assertion_gap"));
1242 assert!(!ignores[&3].matches_kind("survivor"));
1243 assert_eq!(ignores[&3].reason, "boundary is equivalent");
1244
1245 assert!(!ignores[&4].matches_kind("input_gap"));
1247 assert!(ignores[&4].matches_kind("assertion_gap"));
1248 assert!(ignores[&4].matches_kind("survivor"));
1249 assert_eq!(ignores[&4].reason, "intentional");
1250
1251 assert!(ignores[&6].matches_kind("input_gap"));
1253 assert!(ignores[&6].matches_kind("assertion_gap"));
1254 assert!(!ignores[&6].matches_kind("survivor"));
1255
1256 assert!(!ignores[&8].matches_kind("input_gap"));
1258 assert!(!ignores[&8].matches_kind("assertion_gap"));
1259 assert!(!ignores[&8].matches_kind("survivor"));
1260
1261 assert!(!ignores[&9].matches_kind("input_gap"));
1263
1264 assert!(!ignores.contains_key(&10));
1266 assert!(!ignores.contains_key(&11));
1267
1268 assert!(ignored_lines(source).is_empty());
1270
1271 let overlap = "\
1273fn g() {
1274 // tmt:ignore above
1275 let a = 1; // tmt:ignore inline
1276 // tmt:ignore[input_gap] scoped above
1277 let b = 2; // tmt:ignore unscoped inline
1278}
1279";
1280 let legacy = ignored_lines(overlap);
1281 assert_eq!(legacy.get(&3).map(String::as_str), Some("inline"));
1282 assert_eq!(legacy.get(&5).map(String::as_str), Some("unscoped inline"));
1283 }
1284
1285 #[test]
1286 fn ignore_comments() {
1287 let source = "\
1288fn f() {
1289 // tmt:ignore equivalent: both branches return the same
1290 if a >= b { a } else { b }
1291 let x = 1; // tmt:ignore
1292 let y = 2;
1293 let z = 3;
1294 let w = 4; // tmt:ignore: with a colon
1295 // tmt:ignored is another word
1296 // not tmt:ignore here? it is: tmt:ignore must start the comment
1297 let url = \"http://tmt:ignore reason\";
1298 let ok = \"https://example.com\"; // tmt:ignore after url
1299 let raw = r#\"// tmt:ignore inside raw string\"#;
1300 /* // tmt:ignore inside block comment */
1301 let ch = '\"'; // tmt:ignore after quote char
1302 let quotes = ['\\'', '\"'];
1303 let fake = \"// tmt:ignore fake after escaped quote\";
1304 let real = 5; // tmt:ignore after escaped quote
1305}
1306";
1307 let ignored = ignored_lines(source);
1308 assert_eq!(
1309 ignored.keys().copied().collect::<Vec<_>>(),
1310 [2, 3, 4, 7, 11, 14, 17]
1311 );
1312 assert_eq!(ignored[&7], "with a colon");
1313 assert_eq!(ignored[&2], "equivalent: both branches return the same");
1314 assert_eq!(ignored[&3], "equivalent: both branches return the same");
1315 assert_eq!(ignored[&4], "");
1316 assert_eq!(ignored[&11], "after url");
1317 assert_eq!(ignored[&14], "after quote char");
1318 assert_eq!(ignored[&17], "after escaped quote");
1319 assert!(ignored_lines("").is_empty());
1320 }
1321}