1use std::collections::HashSet;
5use std::ffi::{OsStr, OsString};
6use std::path::{Path, PathBuf};
7use std::sync::Mutex;
8use std::sync::atomic::{AtomicUsize, Ordering};
9
10use cuno_core::Env;
11use cuno_manifest::{Lint, LintPreset};
12use cuno_toolchain::Runner;
13
14pub const FILE: &str = ".clang-tidy";
16
17pub const MARKER: &str =
21 "# Generated by cuno from [lint] in Cuno.toml, and overwritten: edit Cuno.toml instead.";
22
23const RECOMMENDED: &[&str] = &[
25 "bugprone-*",
26 "-bugprone-easily-swappable-parameters",
27 "-bugprone-throwing-static-initialization",
30 "-bugprone-exception-escape",
35 "clang-analyzer-*",
36 "performance-*",
37 "modernize-use-nullptr",
38 "modernize-use-override",
39 "modernize-make-unique",
40 "modernize-use-emplace",
41 "readability-isolate-declaration",
42];
43
44const STRICT: &[&str] = &[
46 "readability-*",
47 "cppcoreguidelines-*",
48 "modernize-*",
49 "-modernize-use-trailing-return-type",
50 "-readability-identifier-length",
51];
52
53#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct TidyConfig {
57 pub checks: Vec<String>,
59 pub warnings_as_errors: Vec<String>,
61}
62
63pub fn clang_tidy_config(lint: &Lint) -> TidyConfig {
71 let preset: Vec<&str> = match lint.preset {
72 LintPreset::None => Vec::new(),
73 LintPreset::Recommended => RECOMMENDED.to_vec(),
74 LintPreset::Strict => RECOMMENDED.iter().chain(STRICT).copied().collect(),
75 };
76 let (excluded, enabled): (Vec<&str>, Vec<&str>) =
77 preset.into_iter().partition(|g| g.starts_with('-'));
78
79 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
82 enum List {
83 Allow,
84 Warn,
85 Deny,
86 }
87 let mut written: Vec<(usize, List, &str)> = Vec::new();
88 for (list, patterns) in [
89 (List::Allow, &lint.allow),
90 (List::Warn, &lint.warn),
91 (List::Deny, &lint.deny),
92 ] {
93 for pattern in patterns {
94 let rank = pattern.find('*').unwrap_or(usize::MAX);
95 written.push((rank, list, pattern));
96 }
97 }
98 written.sort_by_key(|(rank, list, _)| (*rank, *list));
99 let (wildcards, names): (Vec<_>, Vec<_>) = written
100 .into_iter()
101 .partition(|(rank, _, _)| *rank != usize::MAX);
102
103 let mut checks: Vec<String> = vec!["-*".to_owned()];
104 checks.extend(enabled.iter().map(|g| (*g).to_owned()));
105 let mut errors: Vec<String> = Vec::new();
106 let mut add = |checks: &mut Vec<String>, (_, list, pattern): (usize, List, &str)| {
107 match list {
108 List::Allow => checks.push(format!("-{pattern}")),
109 List::Warn | List::Deny => checks.push(pattern.to_owned()),
110 }
111 match list {
112 List::Allow | List::Warn => errors.push(format!("-{pattern}")),
113 List::Deny => errors.push(pattern.to_owned()),
114 }
115 };
116 for w in wildcards {
117 add(&mut checks, w);
118 }
119 checks.extend(excluded.iter().map(|g| (*g).to_owned()));
120 for n in names {
121 add(&mut checks, n);
122 }
123 TidyConfig {
124 checks,
125 warnings_as_errors: errors,
126 }
127}
128
129pub fn clang_tidy_file(lint: &Lint) -> String {
133 let config = clang_tidy_config(lint);
134 format!(
135 "{MARKER}\nChecks: '{}'\nWarningsAsErrors: '{}'\nHeaderFilterRegex: ''\nFormatStyle: file\n",
136 config.checks.join(","),
137 config.warnings_as_errors.join(","),
138 )
139}
140
141pub fn any_check(config: &TidyConfig) -> bool {
144 config.checks.iter().any(|glob| !glob.starts_with('-'))
145}
146
147pub fn unknown_names<'a>(lint: &'a Lint, known: &[String]) -> Vec<(&'static str, &'a str)> {
150 let mut unknown = Vec::new();
151 for (list, names) in [
152 ("lint.allow", &lint.allow),
153 ("lint.warn", &lint.warn),
154 ("lint.deny", &lint.deny),
155 ] {
156 for name in names {
157 if name.starts_with("clang-diagnostic-") {
160 continue;
161 }
162 let found = match name.find('*') {
163 Some(star) => {
164 let (before, after) = (&name[..star], &name[star + 1..]);
165 known.iter().any(|check| {
166 check.len() >= before.len() + after.len()
167 && check.starts_with(before)
168 && check.ends_with(after)
169 })
170 }
171 None => known.iter().any(|check| check == name),
172 };
173 if !found {
174 unknown.push((list, name.as_str()));
175 }
176 }
177 }
178 unknown
179}
180
181pub fn known_checks(
183 program: &Path,
184 env: &Env,
185 runner: &dyn Runner,
186) -> std::io::Result<Vec<String>> {
187 let args: [&OsStr; 2] = ["--list-checks".as_ref(), "--checks=*".as_ref()];
188 let output = runner.run(program, &args, env)?;
189 if !output.success {
190 return Err(std::io::Error::other("clang-tidy did not list its checks"));
191 }
192 Ok(String::from_utf8_lossy(&output.stdout)
193 .lines()
194 .map(str::trim)
195 .filter(|line| !line.is_empty() && !line.ends_with(':'))
196 .map(str::to_owned)
197 .collect())
198}
199
200pub struct ClangTidy<'a> {
202 pub program: &'a Path,
204 pub config: &'a Path,
206 pub root: &'a Path,
208 pub env: &'a Env,
210 pub jobs: usize,
212 pub fix: bool,
214 pub scratch: &'a Path,
216}
217
218#[derive(Debug, Default)]
220pub struct Linted {
221 pub shown: Vec<u8>,
224 pub warnings: usize,
226 pub errors: usize,
228 pub fixed: usize,
230 pub failed: Vec<(PathBuf, String)>,
232 pub not_fixed: Vec<(PathBuf, PathBuf, String)>,
236}
237
238pub fn lint(
242 sources: &[PathBuf],
243 tool: &ClangTidy<'_>,
244 ours: &(dyn Fn(&Path) -> bool + Sync),
245 runner: &(dyn Runner + Sync),
246) -> Linted {
247 let next = AtomicUsize::new(0);
248 let runs: Mutex<Vec<(usize, Run)>> = Mutex::new(Vec::new());
249 let jobs = if tool.fix { 1 } else { tool.jobs };
250 std::thread::scope(|scope| {
251 for _ in 0..jobs.clamp(1, sources.len().max(1)) {
252 scope.spawn(|| {
253 loop {
254 let i = next.fetch_add(1, Ordering::SeqCst);
255 let Some(source) = sources.get(i) else { break };
256 let run = if tool.fix {
257 fix_one(i, source, tool, ours, runner)
258 } else {
259 Run {
260 output: run_one(source, tool, Mode::Show, runner),
261 foreign: None,
262 }
263 };
264 runs.lock().unwrap().push((i, run));
265 }
266 });
267 }
268 });
269 let mut runs = runs.into_inner().unwrap();
270 runs.sort_by_key(|(i, _)| *i);
271 let mut linted = Linted::default();
272 let mut seen: HashSet<Vec<u8>> = HashSet::new();
273 for (i, run) in runs {
274 let source = &sources[i];
275 if let Some((foreign, why)) = run.foreign {
276 linted.not_fixed.push((source.clone(), foreign, why));
277 }
278 let output = match run.output {
279 Ok(output) => output,
280 Err(e) => {
281 linted.failed.push((source.clone(), e.to_string()));
282 continue;
283 }
284 };
285 let stderr = String::from_utf8_lossy(&output.stderr);
286 let unwritten = stderr
288 .lines()
289 .find(|line| line.contains("unable to overwrite file"));
290 if let Some(line) = unwritten {
291 linted.failed.push((source.clone(), line.trim().to_owned()));
292 }
293 let mut explained = false;
294 for finding in findings(&output.stdout) {
295 let path = tool.root.join(&finding.path);
296 let compile_error = finding.error && finding.check.contains("clang-diagnostic-");
300 if !compile_error && !ours(&path) {
301 explained |= finding.error;
302 continue;
303 }
304 explained |= finding.error;
305 if !seen.insert(finding.text.clone()) {
306 continue;
307 }
308 let fixed = unwritten.is_none()
309 && String::from_utf8_lossy(&finding.text).contains("FIX-IT applied");
310 if fixed {
311 linted.fixed += 1;
312 } else if finding.error {
313 linted.errors += 1;
314 } else {
315 linted.warnings += 1;
316 }
317 linted.shown.extend_from_slice(&finding.text);
318 }
319 if !output.success && !explained && unwritten.is_none() {
321 let said = stderr
322 .lines()
323 .find(|line| !line.trim().is_empty())
324 .unwrap_or("clang-tidy failed and said nothing");
325 linted.failed.push((source.clone(), said.trim().to_owned()));
326 }
327 }
328 linted
329}
330
331struct Run {
334 output: std::io::Result<cuno_toolchain::Output>,
335 foreign: Option<(PathBuf, String)>,
336}
337
338#[derive(Clone, Copy)]
340enum Mode<'a> {
341 Show,
343 Export(&'a Path),
345 Fix,
347}
348
349fn fix_one(
354 i: usize,
355 source: &Path,
356 tool: &ClangTidy<'_>,
357 ours: &(dyn Fn(&Path) -> bool + Sync),
358 runner: &dyn Runner,
359) -> Run {
360 let exported = tool.scratch.join(format!("fixes-{i}.yaml"));
361 let looked = run_one(source, tool, Mode::Export(&exported), runner);
362 let targets = std::fs::read_to_string(&exported)
363 .map(|text| fix_targets(&text))
364 .unwrap_or_default();
365 let _ = std::fs::remove_file(&exported);
366 let refused = targets.iter().find_map(|t| {
370 crate::write::code(&tool.root.join(t), ours)
371 .err()
372 .map(|why| (t.clone(), why.which()))
373 });
374 if let Some(foreign) = refused {
375 return Run {
376 output: looked,
377 foreign: Some(foreign),
378 };
379 }
380 if targets.is_empty() {
381 return Run {
382 output: looked,
383 foreign: None,
384 };
385 }
386 Run {
387 output: run_one(source, tool, Mode::Fix, runner),
388 foreign: None,
389 }
390}
391
392fn fix_targets(yaml: &str) -> Vec<PathBuf> {
395 yaml.lines()
396 .filter_map(|line| line.trim_start().strip_prefix("- FilePath:"))
397 .map(|value| PathBuf::from(unquote(value.trim())))
398 .collect()
399}
400
401fn unquote(value: &str) -> String {
404 if let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
405 inner.replace("''", "'")
406 } else if let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
407 let mut out = String::new();
408 let mut chars = inner.chars();
409 while let Some(c) = chars.next() {
410 if c == '\\' {
411 out.extend(chars.next());
412 } else {
413 out.push(c);
414 }
415 }
416 out
417 } else {
418 value.to_owned()
419 }
420}
421
422fn run_one(
423 source: &Path,
424 tool: &ClangTidy<'_>,
425 mode: Mode<'_>,
426 runner: &dyn Runner,
427) -> std::io::Result<cuno_toolchain::Output> {
428 let config = format!("--config-file={}", tool.config.display());
429 let database = format!("-p={}", tool.root.display());
430 let headers = match mode {
432 Mode::Show => "--header-filter=.*",
433 Mode::Export(_) | Mode::Fix => "--header-filter=^$",
434 };
435 let mut args: Vec<OsString> = vec![
436 config.into(),
437 database.into(),
438 headers.into(),
439 "--quiet".into(),
440 ];
441 match mode {
442 Mode::Show => {}
443 Mode::Export(file) => {
444 let mut arg = OsString::from("--export-fixes=");
445 arg.push(file);
446 args.push(arg);
447 }
448 Mode::Fix => args.push("--fix".into()),
449 }
450 args.push(source.into());
451 let args: Vec<&OsStr> = args.iter().map(OsString::as_os_str).collect();
452 runner.run_in(tool.program, &args, tool.env, tool.root)
453}
454
455struct Finding {
458 path: PathBuf,
459 error: bool,
460 check: String,
462 text: Vec<u8>,
463}
464
465fn findings(stdout: &[u8]) -> Vec<Finding> {
467 let mut found: Vec<Finding> = Vec::new();
468 for line in stdout.split_inclusive(|b| *b == b'\n') {
469 let text = String::from_utf8_lossy(line);
470 if let Some((path, error)) = finding_head(&text) {
471 let check = text
472 .trim_end()
473 .rsplit_once('[')
474 .map(|(_, rest)| rest.trim_end_matches(']').to_owned())
475 .unwrap_or_default();
476 found.push(Finding {
477 path,
478 error,
479 check,
480 text: line.to_vec(),
481 });
482 } else if summary(&text) {
483 continue;
484 } else if let Some(last) = found.last_mut() {
485 last.text.extend_from_slice(line);
486 }
487 }
488 found
489}
490
491fn finding_head(line: &str) -> Option<(PathBuf, bool)> {
495 if line.starts_with(char::is_whitespace) {
496 return None;
497 }
498 for (marker, error) in [(": warning: ", false), (": error: ", true)] {
499 let Some(at) = line.find(marker) else {
500 continue;
501 };
502 let mut parts = line[..at].rsplitn(3, ':');
503 let column = parts.next()?;
504 let row = parts.next()?;
505 let path = parts.next()?;
506 if column.parse::<u32>().is_ok() && row.parse::<u32>().is_ok() && !path.is_empty() {
507 return Some((PathBuf::from(path), error));
508 }
509 }
510 None
511}
512
513fn summary(line: &str) -> bool {
515 if line.starts_with(char::is_whitespace) {
518 return false;
519 }
520 let line = line.trim_end();
521 line.ends_with(" generated.")
522 || line.starts_with("Suppressed ")
523 || line.starts_with("Use -header-filter")
524 || line.starts_with("Found compiler error")
525 || line.starts_with("Error while processing")
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531
532 fn lint(extra: &str) -> Lint {
533 let toml = format!("[package]\nname = \"app\"\nversion = \"0.1.0\"\n{extra}");
534 let root = std::path::Path::new("/p");
535 cuno_manifest::parse_manifest(&toml, &root.join("Cuno.toml"), root)
536 .unwrap()
537 .value
538 .lint
539 }
540
541 struct Answers {
544 stdout: &'static str,
545 success: bool,
546 }
547
548 impl Runner for Answers {
549 fn run(
550 &self,
551 _program: &Path,
552 _args: &[&OsStr],
553 _env: &Env,
554 ) -> std::io::Result<cuno_toolchain::Output> {
555 Ok(cuno_toolchain::Output {
556 success: self.success,
557 stdout: self.stdout.as_bytes().to_vec(),
558 stderr: b"\nboom\n".to_vec(),
559 })
560 }
561 }
562
563 fn analyse(answers: &Answers, sources: &[&str]) -> Linted {
564 let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
565 let root = Path::new("/p");
566 let tool = ClangTidy {
567 program: Path::new("clang-tidy"),
568 config: Path::new("c"),
569 root,
570 env: &env,
571 jobs: 2,
572 fix: false,
573 scratch: Path::new("s"),
574 };
575 let sources: Vec<PathBuf> = sources.iter().map(|s| root.join(s)).collect();
576 let ours = |p: &Path| !p.to_string_lossy().contains("vendor");
577 super::lint(&sources, &tool, &ours, answers)
578 }
579
580 const OUTPUT: &str = "\
581/p/src/a.cpp:3:14: warning: use nullptr [modernize-use-nullptr]
582 3 | int* p = 0;
583 | ^
5841 warning generated.
585/p/src/a.h:1:1: error: bad [bugprone-x,-warnings-as-errors]
586/p/src/a.h:1:1: note: here
587/p/vendor/v.h:2:2: warning: theirs [bugprone-y]
5882 warnings generated.
589Suppressed 4 warnings (4 in non-user code).
590";
591
592 #[test]
599 fn findings_are_kept_once_and_only_the_package_s() {
600 let linted = analyse(
601 &Answers {
602 stdout: OUTPUT,
603 success: false,
604 },
605 &["src/a.cpp", "src/b.cpp"],
606 );
607 let shown = String::from_utf8(linted.shown).unwrap();
608 assert_eq!(
609 shown,
610 "/p/src/a.cpp:3:14: warning: use nullptr [modernize-use-nullptr]\n 3 | int* p = 0;\n | ^\n\
611 /p/src/a.h:1:1: error: bad [bugprone-x,-warnings-as-errors]\n/p/src/a.h:1:1: note: here\n",
612 );
613 assert_eq!((linted.warnings, linted.errors), (1, 1));
614 assert!(linted.failed.is_empty(), "{:?}", linted.failed);
615 }
616
617 #[test]
626 fn compile_errors_count_anywhere_and_excerpts_stay_whole() {
627 let linted = analyse(
628 &Answers {
629 stdout: "\
630/p/vendor/v.h:1:10: error: 'nope.h' file not found [clang-diagnostic-error]
631/p/src/a.cpp:2:5: warning: w [bugprone-x]
632 2 | puts(\"a.c:1:2: error: x\"); // all generated.
633 | ^
634",
635 success: false,
636 },
637 &["src/a.cpp"],
638 );
639 let shown = String::from_utf8(linted.shown).unwrap();
640 assert!(
641 shown.starts_with("/p/vendor/v.h:1:10: error: 'nope.h'"),
642 "{shown}"
643 );
644 assert!(
645 shown.contains("// all generated.\n | ^\n"),
646 "{shown}"
647 );
648 assert_eq!((linted.warnings, linted.errors), (1, 1));
649 assert!(linted.failed.is_empty(), "{:?}", linted.failed);
650
651 let linted = analyse(
652 &Answers {
653 stdout: "/p/vendor/v.h:1:1: error: theirs [bugprone-y,-warnings-as-errors]\n",
654 success: false,
655 },
656 &["src/a.cpp"],
657 );
658 assert!(linted.shown.is_empty());
659 assert_eq!(linted.errors, 0);
660 assert!(linted.failed.is_empty(), "{:?}", linted.failed);
661 }
662
663 #[test]
669 fn fix_targets_are_the_replacements_paths() {
670 let yaml = "\
671Diagnostics:
672 - DiagnosticName: x
673 DiagnosticMessage:
674 FilePath: 'C:\\p\\src\\a.cpp'
675 Replacements:
676 - FilePath: 'C:\\p\\src\\a.cpp'
677 Offset: 1
678 - FilePath: 'C:\\v\\it''s.h'
679 Offset: 2
680";
681 assert_eq!(
682 fix_targets(yaml),
683 [
684 PathBuf::from("C:\\p\\src\\a.cpp"),
685 PathBuf::from("C:\\v\\it's.h")
686 ]
687 );
688 }
689
690 #[test]
696 fn an_unexplained_failure_is_reported() {
697 let linted = analyse(
698 &Answers {
699 stdout: "",
700 success: false,
701 },
702 &["src/a.cpp"],
703 );
704 assert_eq!(linted.failed.len(), 1);
705 assert_eq!(linted.failed[0].1, "boom");
706 }
707
708 #[test]
714 fn unknown_names_are_found() {
715 let known: Vec<String> = ["bugprone-use-after-move", "modernize-use-nullptr"]
716 .map(str::to_owned)
717 .to_vec();
718 let l = lint(
719 "[lint]\nallow = [\"modernize-*\", \"clang-diagnostic-unused-variable\"]\nwarn = [\"bugprone-use\"]\ndeny = [\"nope-*\", \"modernize-use-nullptr\"]\n",
720 );
721 assert_eq!(
722 unknown_names(&l, &known),
723 [("lint.warn", "bugprone-use"), ("lint.deny", "nope-*")]
724 );
725 }
726
727 #[test]
731 fn none_with_nothing_written_enables_nothing() {
732 assert!(!any_check(&clang_tidy_config(&lint(
733 "[lint]\npreset = \"none\"\n"
734 ))));
735 assert!(any_check(&clang_tidy_config(&lint(
736 "[lint]\npreset = \"none\"\nwarn = [\"bugprone-*\"]\n"
737 ))));
738 assert!(any_check(&clang_tidy_config(&lint(""))));
739 }
740
741 fn last_match(globs: &[String], check: &str) -> bool {
743 let mut on = false;
744 for glob in globs {
745 let (negated, pattern) = match glob.strip_prefix('-') {
746 Some(rest) => (true, rest),
747 None => (false, glob.as_str()),
748 };
749 let matches = match pattern.strip_suffix('*') {
750 Some(prefix) => check.starts_with(prefix),
751 None => check == pattern,
752 };
753 if matches {
754 on = !negated;
755 }
756 }
757 on
758 }
759
760 fn judge(config: &TidyConfig, check: &str) -> (bool, bool) {
762 let on = last_match(&config.checks, check);
763 (on, on && last_match(&config.warnings_as_errors, check))
764 }
765
766 #[test]
771 fn presets_hold_what_the_spec_lists() {
772 let none = clang_tidy_config(&lint("[lint]\npreset = \"none\"\n"));
773 assert_eq!(none.checks, ["-*"]);
774 let rec = clang_tidy_config(&lint(""));
775 for (check, on) in [
776 ("bugprone-use-after-move", true),
777 ("bugprone-easily-swappable-parameters", false),
778 ("bugprone-throwing-static-initialization", false),
779 ("bugprone-exception-escape", false),
780 ("clang-analyzer-core.NullDereference", true),
781 ("performance-unnecessary-copy-initialization", true),
782 ("modernize-use-nullptr", true),
783 ("modernize-use-override", true),
784 ("modernize-make-unique", true),
785 ("modernize-use-emplace", true),
786 ("modernize-use-auto", false),
787 ("readability-isolate-declaration", true),
788 ("readability-braces-around-statements", false),
789 ] {
790 assert_eq!(judge(&rec, check), (on, false), "recommended {check}");
791 }
792 let strict = clang_tidy_config(&lint("[lint]\npreset = \"strict\"\n"));
793 for (check, on) in [
794 ("readability-braces-around-statements", true),
795 ("cppcoreguidelines-avoid-goto", true),
796 ("modernize-use-auto", true),
797 ("modernize-use-trailing-return-type", false),
798 ("readability-identifier-length", false),
799 ("bugprone-easily-swappable-parameters", false),
800 ] {
801 assert_eq!(judge(&strict, check), (on, false), "strict {check}");
802 }
803 }
804
805 #[test]
812 fn allow_warn_deny_follow_the_spec_s_precedence() {
813 let c = clang_tidy_config(&lint(
815 "[lint]\nwarn = [\"modernize-*\"]\nallow = [\"modernize-use-auto\"]\n",
816 ));
817 assert_eq!(judge(&c, "modernize-use-auto"), (false, false));
818 assert_eq!(judge(&c, "modernize-loop-convert"), (true, false));
819
820 let c = clang_tidy_config(&lint(
821 "[lint]\ndeny = [\"bugprone-*\", \"x-a\"]\nwarn = [\"bugprone-use-after-move\", \"x-a\", \"y-*\"]\n\
822 allow = [\"bugprone-*\", \"y-*\", \"x-a\"]\n",
823 ));
824 assert_eq!(judge(&c, "bugprone-use-after-move"), (true, false));
826 assert_eq!(judge(&c, "bugprone-macro-parentheses"), (true, true));
828 assert_eq!(judge(&c, "x-a"), (true, true));
830 assert_eq!(judge(&c, "y-b"), (true, false));
831
832 let c = clang_tidy_config(&lint(
834 "[lint]\ndeny = [\"performance-*\"]\nallow = [\"performance-noexcept-move-constructor\"]\n",
835 ));
836 assert_eq!(
837 judge(&c, "performance-noexcept-move-constructor"),
838 (false, false)
839 );
840 assert_eq!(judge(&c, "performance-for-range-copy"), (true, true));
841 }
842
843 #[test]
850 fn narrower_wildcards_win_and_exclusions_need_a_name() {
851 let c = clang_tidy_config(&lint(
852 "[lint]
853preset = \"none\"
854deny = [\"modernize-*\"]
855allow = [\"modernize-use-*\"]
856",
857 ));
858 assert_eq!(judge(&c, "modernize-use-nullptr"), (false, false));
859 assert_eq!(judge(&c, "modernize-loop-convert"), (true, true));
860 let c = clang_tidy_config(&lint(
861 "[lint]
862preset = \"none\"
863allow = [\"clang-analyzer-*\"]
864deny = [\"clang-analyzer-core.*\"]
865",
866 ));
867 assert_eq!(
868 judge(&c, "clang-analyzer-core.NullDereference"),
869 (true, true)
870 );
871 assert_eq!(
872 judge(&c, "clang-analyzer-cplusplus.NewDelete"),
873 (false, false)
874 );
875
876 let c = clang_tidy_config(&lint(
877 "[lint]
878deny = [\"bugprone-*\"]
879",
880 ));
881 assert_eq!(
882 judge(&c, "bugprone-easily-swappable-parameters"),
883 (false, false)
884 );
885 assert_eq!(judge(&c, "bugprone-use-after-move"), (true, true));
886 let c = clang_tidy_config(&lint(
887 "[lint]
888warn = [\"bugprone-easily-swappable-parameters\"]
889",
890 ));
891 assert_eq!(
892 judge(&c, "bugprone-easily-swappable-parameters"),
893 (true, false)
894 );
895 }
896
897 #[test]
901 fn the_file_holds_both_lists() {
902 let text = clang_tidy_file(&lint("[lint]\ndeny = [\"bugprone-*\"]\n"));
903 let lines: Vec<&str> = text.lines().collect();
904 assert_eq!(lines[0], MARKER);
905 assert!(lines[1].starts_with("Checks: '-*,bugprone-*,"), "{text}");
906 assert_eq!(lines[2], "WarningsAsErrors: 'bugprone-*'");
907 assert_eq!(lines[3], "HeaderFilterRegex: ''");
908 }
909
910 struct Exports {
913 file: String,
914 }
915
916 impl Runner for Exports {
917 fn run(
918 &self,
919 _program: &Path,
920 args: &[&OsStr],
921 _env: &Env,
922 ) -> std::io::Result<cuno_toolchain::Output> {
923 for arg in args {
924 if let Some(out) = arg.to_string_lossy().strip_prefix("--export-fixes=") {
925 std::fs::write(
926 out,
927 format!(
928 "Diagnostics:
929 - Replacements:
930 - FilePath: '{}'
931",
932 self.file
933 ),
934 )?;
935 }
936 }
937 Ok(cuno_toolchain::Output {
938 success: true,
939 stdout: Vec::new(),
940 stderr: Vec::new(),
941 })
942 }
943 }
944
945 #[cfg(windows)]
953 #[test]
954 fn a_fix_that_would_change_a_link_or_another_s_file_is_not_made() {
955 let root = tempfile::tempdir().unwrap();
956 let scratch = tempfile::tempdir().unwrap();
957 let real = root.path().join("real");
958 std::fs::create_dir(&real).unwrap();
959 let link = root.path().join("inc");
960 let made = std::process::Command::new("cmd")
961 .args(["/C", "mklink", "/J"])
962 .arg(&link)
963 .arg(&real)
964 .output()
965 .unwrap();
966 assert!(made.status.success(), "{made:?}");
967 let source = root.path().join("a.cpp");
968 std::fs::write(&source, "").unwrap();
969 let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
970 let tool = ClangTidy {
971 program: Path::new("clang-tidy"),
972 config: Path::new("c"),
973 root: root.path(),
974 env: &env,
975 jobs: 1,
976 fix: true,
977 scratch: scratch.path(),
978 };
979 let ours = |p: &Path| p.starts_with(root.path());
980 let fix = |file: &Path| {
981 super::lint(
982 std::slice::from_ref(&source),
983 &tool,
984 &ours,
985 &Exports {
986 file: file.display().to_string(),
987 },
988 )
989 .not_fixed
990 };
991 assert_eq!(
992 fix(&link),
993 [(
994 source.clone(),
995 link.clone(),
996 "which is a link cuno does not write through".to_owned()
997 )]
998 );
999 let outside = tempfile::tempdir().unwrap();
1000 let theirs = outside.path().join("v.h");
1001 std::fs::write(&theirs, "").unwrap();
1002 assert_eq!(
1003 fix(&theirs),
1004 [(
1005 source.clone(),
1006 theirs.clone(),
1007 "which is not the package's".to_owned()
1008 )]
1009 );
1010 std::fs::remove_dir(&link).unwrap();
1011 }
1012}