From 41edba45f848d86a46f54ca0b662c8bd10a3b069 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:35:06 +0000 Subject: [PATCH 1/6] fix: count files that clang-tidy did not analyze as failed checks A compilation database made in another folder makes clang-tidy abort ("Cannot chdir into ..."), and an empty one makes it skip every file ("Compile command not found."). Both left no findings, so the check passed although nothing was checked. Such a file now counts as a failed check, like a clang-format failure: a WARN log with clang-tidy's error, a warning annotation, a line in the comment and step summary (with a hint about the database), the review, and an issue in the code quality report. Compiler errors and a .clang-tidy file that enables no checks are not counted. --- cpp-linter/src/clang_tools/clang_tidy/mod.rs | 77 ++++++++- .../clang_tools/clang_tidy/other_files/mod.rs | 4 +- .../clang_tidy/other_files/test.rs | 1 + cpp-linter/src/clang_tools/clang_tidy/test.rs | 152 +++++++++++++++++- cpp-linter/src/code_quality.rs | 18 ++- cpp-linter/src/common_fs.rs | 8 + cpp-linter/src/rest_client/annotations.rs | 14 ++ cpp-linter/src/rest_client/comment.rs | 72 ++++++++- cpp-linter/src/rest_client/test.rs | 54 ++++++- cpp-linter/src/sarif.rs | 2 + 10 files changed, 383 insertions(+), 19 deletions(-) diff --git a/cpp-linter/src/clang_tools/clang_tidy/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/mod.rs index cf989af4..421b214d 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/mod.rs @@ -191,10 +191,17 @@ impl TidyNotification { } /// A struct to hold notification from clang-tidy about a single file -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct TidyAdvice { /// A list of notifications parsed from clang-tidy stdout. pub notes: Vec, + + /// Is `true` if clang-tidy did not analyze the file (see [`tidy_failure()`]). + /// + /// Such a file has no [`TidyAdvice::notes`], but it still counts as a failed + /// clang-tidy check, so an out-of-date or empty compilation database does not + /// pass silently. + pub failed: bool, } impl TidyAdvice { @@ -328,6 +335,9 @@ pub fn tally_tidy_advice(files: &[Arc>]) -> Result { for file in files { let file = file.lock().map_err(|e| e.to_string())?; if let Some(advice) = &file.tidy_advice { + if advice.failed { + total += 1; + } for tidy_note in &advice.notes { let file_path = PathBuf::from(&tidy_note.filename); if file_path == file.name { @@ -703,6 +713,48 @@ fn read_exported_fixes(fixes_path: &Path) -> Result Option { + let skipped = stderr.contains("Compile command not found."); + let crashed = !success && notes.is_empty() && !stderr.contains("no checks enabled"); + if !skipped && !crashed { + return None; + } + // Leave out a crash's stack dump. + let reason = stderr + .lines() + .map(str::trim_end) + .filter(|line| !line.is_empty()) + .take_while(|line| { + !line.starts_with("PLEASE submit a bug report") && !line.starts_with("Stack dump:") + }) + .take(10) + .collect::>() + .join("\n"); + Some(if reason.is_empty() { + String::from("clang-tidy exited with an error and reported nothing") + } else { + reason + }) +} + /// Run clang-tidy, then parse and return it's output. /// /// clang-tidy is not allowed to modify any files. @@ -776,6 +828,24 @@ pub fn run_clang_tidy( &clang_params.database_json, &clang_params.repo_root, )?; + if let Some(reason) = tidy_failure( + output.status.success(), + &String::from_utf8_lossy(&output.stderr), + ¬es, + ) { + logs.push(( + log::Level::Warn, + format!( + "clang-tidy did not analyze {file_name}; counting it as a failed check:\n{reason}" + ), + )); + remove_file_if_exists(&fixes_path)?; + file.tidy_advice = Some(TidyAdvice { + failed: true, + ..Default::default() + }); + return Ok((logs, TidyFixes::default())); + } let fixes = read_exported_fixes(&fixes_path)?; let working_dir = std::path::absolute(&clang_params.repo_root) @@ -787,7 +857,10 @@ pub fn run_clang_tidy( if clang_params.gen_patch { file.patched_path = Some(write_cache(clang_params, &file.name, &patched)?); } - file.tidy_advice = Some(TidyAdvice { notes }); + file.tidy_advice = Some(TidyAdvice { + notes, + failed: false, + }); Ok((logs, tidy_fixes)) } diff --git a/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs index 6cfd920f..a784b07f 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs @@ -301,9 +301,7 @@ pub fn apply_other_file_fixes( file.patched_path = Some(write_cache(clang_params, &file.name, &patched)?); } let name = file.name.to_string_lossy().replace('\\', "/"); - let advice = file - .tidy_advice - .get_or_insert_with(|| TidyAdvice { notes: vec![] }); + let advice = file.tidy_advice.get_or_insert_with(TidyAdvice::default); for note in notes { merge_note(&mut advice.notes, note, &name); } diff --git a/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs b/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs index 4e3f15ed..889b020d 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs @@ -179,6 +179,7 @@ fn not_analyzed() { let mut source = FileObj::new(PathBuf::from("fix.cpp")); source.tidy_advice = Some(TidyAdvice { notes: vec![source_note()], + ..Default::default() }); let files = as_files(vec![source]); let mut without_note = header_fix(tmp.path()); diff --git a/cpp-linter/src/clang_tools/clang_tidy/test.rs b/cpp-linter/src/clang_tools/clang_tidy/test.rs index 63c85196..fbc2ccaa 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/test.rs @@ -18,7 +18,8 @@ use crate::{ use super::{ CLANG_DIAGNOSTICS_URL, ClangCaptureError, CompilationUnit, ExportedFixes, FixPaths, - NOTE_HEADER, OtherFileFix, Replacement, TidyNotification, apply_fixes, run_clang_tidy, + NOTE_HEADER, OtherFileFix, Replacement, TidyAdvice, TidyNotification, apply_fixes, + run_clang_tidy, tally_tidy_advice, tidy_failure, }; #[test] @@ -285,6 +286,7 @@ fn tally_counts_matching_notes() { // does not match the file name -> not counted dummy_note("other.cpp", vec![]), ], + ..Default::default() }); let files = vec![Arc::new(Mutex::new(file))]; assert_eq!(tally_tidy_advice(&files).unwrap(), 1); @@ -296,6 +298,7 @@ fn suggestion_help_with_and_without_fixes() { let advice = TidyAdvice { notes: vec![dummy_note("demo.cpp", vec![5])], + ..Default::default() }; // A fixed line within the range yields the severity, the diagnostic and the rationale. let help = advice.get_suggestion_help(1, 10); @@ -328,7 +331,10 @@ fn suggestion_help_lists_a_multi_line_fix_once() { file: "demo.h".to_string(), reason: "it is not one of the analyzed files".to_string(), }); - let advice = TidyAdvice { notes: vec![note] }; + let advice = TidyAdvice { + notes: vec![note], + ..Default::default() + }; let help = advice.get_suggestion_help(1, 10); assert_eq!(help.matches("a dummy rationale").count(), 1); assert_eq!(help.matches("/m/w.png\"> Part of this fix").count(), 1); @@ -346,7 +352,10 @@ fn suggestion_help_with_skipped_fixes() { file: "demo.h".to_string(), reason: "it is not one of the analyzed files".to_string(), }); - let advice = TidyAdvice { notes: vec![note] }; + let advice = TidyAdvice { + notes: vec![note], + ..Default::default() + }; let help = advice.get_suggestion_help(5, 5); assert!(help.contains( "/m/w.png\"> Part of this fix was not applied to `demo.h` \ @@ -861,3 +870,140 @@ Diagnostics: assert!(tidy_fixes.others.is_empty()); assert_eq!(notes[0].fixed_lines, vec![2]); } + +#[test] +fn tidy_failure_reasons() { + // a crash: the stack dump is left out + let crash = "LLVM ERROR: Cannot chdir into \"/gone/build\"!\n\ + PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/\n\ + Stack dump:\n0.\tProgram arguments: clang-tidy demo.cpp\n"; + assert_eq!( + tidy_failure(false, crash, &[]).unwrap(), + "LLVM ERROR: Cannot chdir into \"/gone/build\"!" + ); + // a file without an entry in the compilation database is skipped + let skipped = "Skipping /repo/demo.cpp. Compile command not found.\n"; + assert_eq!( + tidy_failure(true, skipped, &[]).unwrap(), + "Skipping /repo/demo.cpp. Compile command not found." + ); + // an error exit without any explanation + assert_eq!( + tidy_failure(false, "", &[]).unwrap(), + "clang-tidy exited with an error and reported nothing" + ); + // compiler errors make clang-tidy exit with an error, but they are findings + let compiler_errors = "1 error generated.\nError while processing demo.cpp.\n"; + assert!(tidy_failure(false, compiler_errors, &[dummy_note("demo.cpp", vec![])]).is_none()); + // a .clang-tidy file can turn off all checks for some folders + assert!(tidy_failure(false, "Error: no checks enabled.\n", &[]).is_none()); + // a normal run, with or without a summary + assert!(tidy_failure(true, "", &[]).is_none()); + assert!(tidy_failure(true, "2 warnings generated.\n", &[]).is_none()); +} + +#[test] +fn tally_counts_failed_files() { + let mut failed = FileObj::new(PathBuf::from("demo.cpp")); + failed.tidy_advice = Some(TidyAdvice { + failed: true, + ..Default::default() + }); + let mut found = FileObj::new(PathBuf::from("demo.cpp")); + found.tidy_advice = Some(TidyAdvice { + notes: vec![dummy_note("demo.cpp", vec![])], + ..Default::default() + }); + let files = [failed, found].map(|file| Arc::new(Mutex::new(file))); + assert_eq!(tally_tidy_advice(&files).unwrap(), 2); +} + +#[cfg(unix)] +#[test] +fn tidy_crash_counts_as_failed() { + let tmp_workspace = crate::test_common::setup_tmp_workspace(); + let tools_dir = tempfile::tempdir().unwrap(); + let fake_tidy = crate::test_common::make_fake_tool( + tools_dir.path(), + "clang-tidy", + r#"printf 'LLVM ERROR: Cannot chdir into "/gone/build"!\nStack dump:\n0. clang-tidy\n' >&2; exit 134"#, + ); + let mut clang_params = make_clang_params(tmp_workspace.path(), Some(fake_tidy)); + clang_params.gen_patch = true; + let file = Mutex::new(FileObj::new(PathBuf::from("demo/demo.cpp"))); + let mut file = file.lock().unwrap(); + let (logs, fixes) = run_clang_tidy(&mut file, &clang_params).unwrap(); + let advice = file.tidy_advice.as_ref().unwrap(); + assert!(advice.failed); + assert!(advice.notes.is_empty()); + assert!(fixes.own.is_empty() && fixes.others.is_empty()); + let (level, msg) = logs.last().unwrap(); + assert_eq!(*level, log::Level::Warn); + assert!(msg.starts_with("clang-tidy did not analyze demo/demo.cpp")); + assert!(msg.ends_with("LLVM ERROR: Cannot chdir into \"/gone/build\"!")); +} + +/// Make a workspace with `demo.cpp` and a compilation database (`build/compile_commands.json`). +fn workspace_with_database(database: &str) -> (tempfile::TempDir, ClangParams) { + let tmp_workspace = tempfile::TempDir::with_prefix("cpp-linter-unit-tests_").unwrap(); + fs::write( + tmp_workspace.path().join("demo.cpp"), + "int main() { return 0; }\n", + ) + .unwrap(); + let build = tmp_workspace.path().join("build"); + fs::create_dir(&build).unwrap(); + fs::write(build.join("compile_commands.json"), database).unwrap(); + let mut clang_params = make_clang_params(tmp_workspace.path(), Some(get_tidy_exe())); + clang_params.database = Some(build); + (tmp_workspace, clang_params) +} + +/// A compilation database that was made in another folder (eg. on another machine). +#[test] +fn tidy_with_database_from_another_folder() { + let missing = env::temp_dir().join("cpp-linter-unit-tests-missing-build-dir"); + assert!(!missing.exists()); + let database = serde_json::json!([{ + "directory": missing, + "command": "c++ -c demo.cpp", + "file": missing.join("demo.cpp"), + }]) + .to_string(); + let (_tmp_workspace, clang_params) = workspace_with_database(&database); + let file = Mutex::new(FileObj::new(PathBuf::from("demo.cpp"))); + let mut file = file.lock().unwrap(); + run_clang_tidy(&mut file, &clang_params).unwrap(); + assert!(file.tidy_advice.as_ref().unwrap().failed); +} + +/// A compilation database without any entries (eg. a header-only CMake project). +#[test] +fn tidy_with_empty_database() { + let (_tmp_workspace, clang_params) = workspace_with_database("[]"); + let file = Mutex::new(FileObj::new(PathBuf::from("demo.cpp"))); + let mut file = file.lock().unwrap(); + run_clang_tidy(&mut file, &clang_params).unwrap(); + assert!(file.tidy_advice.as_ref().unwrap().failed); +} + +/// A compilation database that matches the checkout is used as usual. +#[test] +fn tidy_with_matching_database() { + let (tmp_workspace, mut clang_params) = workspace_with_database("[]"); + let database = serde_json::json!([{ + "directory": tmp_workspace.path(), + "command": "c++ -c demo.cpp", + "file": tmp_workspace.path().join("demo.cpp"), + }]) + .to_string(); + let build = clang_params.database.clone().unwrap(); + fs::write(build.join("compile_commands.json"), database).unwrap(); + clang_params.tidy_checks = "-*,modernize-use-trailing-return-type".to_string(); + let file = Mutex::new(FileObj::new(PathBuf::from("demo.cpp"))); + let mut file = file.lock().unwrap(); + run_clang_tidy(&mut file, &clang_params).unwrap(); + let advice = file.tidy_advice.as_ref().unwrap(); + assert!(!advice.failed); + assert_eq!(advice.notes.len(), 1); +} diff --git a/cpp-linter/src/code_quality.rs b/cpp-linter/src/code_quality.rs index 19c744a9..0fb67498 100644 --- a/cpp-linter/src/code_quality.rs +++ b/cpp-linter/src/code_quality.rs @@ -225,7 +225,8 @@ impl CodeQualityReport { .flat_map(|advice| &advice.notes) .filter(|note| Path::new(¬e.filename) == file.name.as_path()) .collect::>(); - if format_advice.is_none() && tidy_notes.is_empty() { + let tidy_failed = file.tidy_advice.as_ref().is_some_and(|a| a.failed); + if format_advice.is_none() && tidy_notes.is_empty() && !tidy_failed { continue; } let path = relative_path(&file.name, repo_root, path_prefix); @@ -260,6 +261,17 @@ impl CodeQualityReport { } } + if tidy_failed { + builder.push( + CLANG_TIDY, + CLANG_TIDY, + "clang-tidy did not analyze this file, so it was not checked. See the job's log for details.".to_string(), + Severity::Major, + &path, + Lines { begin: 1, end: 1 }, + &SourceLines(vec![]), + ); + } for note in tidy_notes { // GitLab line numbers start at 1 let line = note.line.max(1); @@ -382,6 +394,7 @@ mod test { "clang-diagnostic-unused", ), ], + ..Default::default() }); let mut other = FileObj::new(PathBuf::from("./src/other.c")); other.format_advice = Some(FormatAdvice { @@ -392,11 +405,12 @@ mod test { let mut tidy_only = FileObj::new(PathBuf::from("src/other.c")); tidy_only.tidy_advice = Some(TidyAdvice { notes: vec![note("src/other.c", 4, "warning", "readability-y")], + ..Default::default() }); // a file without findings let mut clean = FileObj::new(PathBuf::from("src/clean.cpp")); clean.format_advice = Some(FormatAdvice::default()); - clean.tidy_advice = Some(TidyAdvice { notes: vec![] }); + clean.tidy_advice = Some(TidyAdvice::default()); // a file that the clang tools did not analyze let skipped = FileObj::new(PathBuf::from("src/skipped.cpp")); vec![ diff --git a/cpp-linter/src/common_fs.rs b/cpp-linter/src/common_fs.rs index 5ca194e7..66eb5943 100644 --- a/cpp-linter/src/common_fs.rs +++ b/cpp-linter/src/common_fs.rs @@ -249,6 +249,12 @@ impl FileObj { "- **{file_name}**: clang-format failed to run, so the formatting was not checked (see the logs)" )); } + if self.tidy_advice.as_ref().is_some_and(|a| a.failed) { + review_comments.has_errors = true; + review_comments.not_posted.push(format!( + "- **{file_name}**: clang-tidy did not analyze this file, so it was not checked (see the logs)" + )); + } // An error on a changed line fails the review, with or without a patched file. if let Some(advice) = &self.tidy_advice && advice.notes.iter().any(|note| { @@ -673,6 +679,7 @@ mod test { ..note(4, vec![]) }, ], + ..Default::default() }); let mut review_comments = ReviewComments::default(); @@ -726,6 +733,7 @@ mod test { severity: "error".to_string(), ..note(3, vec![]) }], + ..Default::default() }); errored .make_suggestions_from_patch( diff --git a/cpp-linter/src/rest_client/annotations.rs b/cpp-linter/src/rest_client/annotations.rs index e57fee59..a1eed86f 100644 --- a/cpp-linter/src/rest_client/annotations.rs +++ b/cpp-linter/src/rest_client/annotations.rs @@ -158,6 +158,20 @@ impl RestClient { // The tidy_advice vector is parallel to the files vector; meaning it serves as a file filterer. // lines are already filter as specified to clang-tidy CLI. if let Some(tidy_advice) = &file.tidy_advice { + if tidy_advice.failed { + annotations.push(FileAnnotation { + severity: AnnotationLevel::Warning, + path: name.clone(), + start_line: None, + end_line: None, + start_column: None, + end_column: None, + title: Some("clang-tidy".to_string()), + message: format!( + "clang-tidy did not analyze {name}, so it was not checked. See the logs for details." + ), + }); + } for note in &tidy_advice.notes { if note.filename == name { let annotation = FileAnnotation { diff --git a/cpp-linter/src/rest_client/comment.rs b/cpp-linter/src/rest_client/comment.rs index a3801377..bb9cf258 100644 --- a/cpp-linter/src/rest_client/comment.rs +++ b/cpp-linter/src/rest_client/comment.rs @@ -92,6 +92,8 @@ pub(super) struct FileFindings { pub(super) format_lines: Vec>, /// The clang-tidy notes about this file. pub(super) tidy_notes: Vec, + /// clang-tidy did not analyze this file. + pub(super) tidy_failed: bool, } impl FileFindings { @@ -129,7 +131,11 @@ impl Findings { .collect::>() }) .unwrap_or_default(); - if format_advice.is_none() && tidy_notes.is_empty() { + let tidy_failed = file + .tidy_advice + .as_ref() + .is_some_and(|advice| advice.failed); + if format_advice.is_none() && tidy_notes.is_empty() && !tidy_failed { continue; } findings.push(FileFindings { @@ -139,6 +145,7 @@ impl Findings { .map(|advice| advice.replacements.clone()) .unwrap_or_default(), tidy_notes, + tidy_failed, }); } Ok(Self(findings)) @@ -162,6 +169,11 @@ impl Findings { .count() as u64 } + /// Count the files that clang-tidy did not analyze. + fn tidy_failures(&self) -> u64 { + self.0.iter().filter(|file| file.tidy_failed).count() as u64 + } + /// Describe the clang-tidy notes in a few words: `1 error, 2 warnings, 1 fixable`. /// /// Also returns the status of the clang-tidy check. @@ -182,14 +194,23 @@ impl Findings { .filter(|(count, _)| *count > 0) .map(|(count, noun)| plural(count, noun)) .collect::>(); - if counts.is_empty() { - return (Status::Passed, String::from("no findings")); + let mut parts = vec![]; + if !counts.is_empty() { + let mut part = counts.join(", "); + if fixable > 0 { + part.push_str(&format!(", {fixable} fixable")); + } + parts.push(part); } - let mut result = counts.join(", "); - if fixable > 0 { - result.push_str(&format!(", {fixable} fixable")); + let failed = self.tidy_failures(); + if failed > 0 { + parts.push(format!("clang-tidy failed on {}", plural(failed, "file"))); + } + if parts.is_empty() { + return (Status::Passed, String::from("no findings")); } - let status = if errors > 0 { + let result = parts.join(", "); + let status = if errors > 0 || failed > 0 { Status::Failed } else { Status::Warned @@ -280,6 +301,29 @@ impl Findings { } } + let failed = self.tidy_failures(); + if failed > 0 { + let (these, were) = if failed == 1 { + ("this file", "it was") + } else { + ("these files", "they were") + }; + let failed = plural(failed, "file"); + comment.push_str(&if ctx.has_database { + format!( + "\nclang-tidy did not analyze {failed}, so {were} not checked. The \ + compilation database may be out of date (made in another folder) or have no \ + entry for {these}: check that it was generated for this checkout. \ + See the logs for clang-tidy's error.\n" + ) + } else { + format!( + "\nclang-tidy did not analyze {failed}, so {were} not checked. \ + See the logs for clang-tidy's error.\n" + ) + }); + } + let missing = self.missing_includes(); if missing > 0 { let missing = plural(missing, "included file"); @@ -330,7 +374,7 @@ impl Findings { /// Append the clang-tidy notes to the `comment`: a table of them per file. fn push_tidy_section(&self, comment: &mut String, summary: &str, fits: impl Fn(usize) -> bool) { - let count = self.tidy_notes().count(); + let count = self.tidy_notes().count() + self.tidy_failures() as usize; if count == 0 { return; } @@ -344,6 +388,18 @@ impl Findings { "\n**{}**\n\n| Line | Finding |\n|--:|:--|\n", file.display_name() ); + if file.tidy_failed { + let item = format!( + "\n**{}**: clang-tidy did not analyze this file; see the logs\n", + file.display_name() + ); + if omitted == 0 && fits(comment.len() + section.len() + item.len() + CLOSER.len()) { + section.push_str(&item); + } else { + omitted += 1; + } + continue; + } let mut rows = String::new(); for note in &file.tidy_notes { let severity = match note.severity.as_str() { diff --git a/cpp-linter/src/rest_client/test.rs b/cpp-linter/src/rest_client/test.rs index ce3a31d4..fbbe5e06 100644 --- a/cpp-linter/src/rest_client/test.rs +++ b/cpp-linter/src/rest_client/test.rs @@ -99,7 +99,10 @@ async fn create_comment(is_lgtm: bool) -> (String, String) { fixed_lines: vec![], skipped_fixes: vec![], }]; - file.tidy_advice = Some(TidyAdvice { notes }); + file.tidy_advice = Some(TidyAdvice { + notes, + ..Default::default() + }); file.format_advice = Some(FormatAdvice { #[allow(clippy::single_range_in_vec_init)] replacements: vec![1..=2], @@ -194,6 +197,7 @@ fn make_dummy_files(severity: &str) -> Vec>> { fixed_lines: vec![1], skipped_fixes: vec![], }], + ..Default::default() }); file.format_advice = Some(FormatAdvice { #[allow(clippy::single_range_in_vec_init)] @@ -614,6 +618,7 @@ fn findings_without_formatting() { format_failed: false, format_lines: vec![], tidy_notes: vec![], + tidy_failed: false, }]); // a backtick can't go in a code span, so the name is escaped instead assert_eq!(findings.0[0].display_name(), "odd\\`name.cpp"); @@ -1137,3 +1142,50 @@ async fn ignored_untracked_file_is_not_read() { let names: Vec = files.unwrap().into_iter().map(|f| f.name).collect(); assert_eq!(names, vec![PathBuf::from("src/ok.cpp")]); } + +#[test] +fn tidy_failure_feedback() { + let file = FileObj::new(PathBuf::from("tests/demo/demo.cpp")); + let file = Arc::new(Mutex::new(file)); + file.lock().unwrap().tidy_advice = Some(TidyAdvice { + failed: true, + ..Default::default() + }); + let files = vec![file]; + let annotations = RestClient::make_annotations(&files, "file".into()).unwrap(); + assert_eq!(annotations.len(), 1); + assert!(matches!(annotations[0].severity, AnnotationLevel::Warning)); + assert_eq!(annotations[0].title.as_deref(), Some("clang-tidy")); + for has_database in [false, true] { + let comment = RestClient::make_comment( + &files, + 0, + 1, + &dummy_versions(), + None, + false, + "file".into(), + has_database, + ) + .unwrap(); + assert!( + comment.contains("| clang-tidy failed on 1 file |"), + "{comment}" + ); + assert!(comment.contains("/m/hf.png"), "{comment}"); + assert!( + comment.contains("clang-tidy did not analyze 1 file, so it was not checked."), + "{comment}" + ); + assert_eq!( + comment.contains("The compilation database may be out of date"), + has_database, + "{comment}" + ); + assert!( + comment.contains("**`tests/demo/demo.cpp`**: clang-tidy did not analyze this file"), + "{comment}" + ); + assert!(!comment.contains("How to fix"), "{comment}"); + } +} diff --git a/cpp-linter/src/sarif.rs b/cpp-linter/src/sarif.rs index 3ac4efc5..2f96fe21 100644 --- a/cpp-linter/src/sarif.rs +++ b/cpp-linter/src/sarif.rs @@ -401,6 +401,7 @@ mod test { "modernize-use-trailing-return-type", ), ], + ..Default::default() }); let mut other = FileObj::new(PathBuf::from("src/other.c")); other.tidy_advice = Some(TidyAdvice { @@ -410,6 +411,7 @@ mod test { "remark", "clang-diagnostic-unused-variable", )], + ..Default::default() }); // a file that clang-tidy did not analyze let skipped = FileObj::new(PathBuf::from("src/skipped.cpp")); From 124babb18d0c2f0de297cf3c1541b69e214addae Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:36:46 +0000 Subject: [PATCH 2/6] chore: add chdir to the spelling words --- cspell.config.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/cspell.config.yml b/cspell.config.yml index bf62518c..d17df7ab 100644 --- a/cspell.config.yml +++ b/cspell.config.yml @@ -10,6 +10,7 @@ words: - Boolish - bugprone - cdylib + - chdir - choco - chrono - clippy From 3383c424fd272b7ff1bbff3d9094132926ab579a Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:43:12 +0000 Subject: [PATCH 3/6] fix: match the whole "no checks enabled" error line --- cpp-linter/src/clang_tools/clang_tidy/mod.rs | 6 +++++- cpp-linter/src/clang_tools/clang_tidy/test.rs | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/cpp-linter/src/clang_tools/clang_tidy/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/mod.rs index 421b214d..49dacf8d 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/mod.rs @@ -733,7 +733,11 @@ pub(crate) fn tidy_failure( notes: &[TidyNotification], ) -> Option { let skipped = stderr.contains("Compile command not found."); - let crashed = !success && notes.is_empty() && !stderr.contains("no checks enabled"); + let crashed = !success + && notes.is_empty() + && !stderr + .lines() + .any(|line| line.trim() == "Error: no checks enabled."); if !skipped && !crashed { return None; } diff --git a/cpp-linter/src/clang_tools/clang_tidy/test.rs b/cpp-linter/src/clang_tools/clang_tidy/test.rs index fbc2ccaa..fc9dc8cc 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/test.rs @@ -897,6 +897,9 @@ fn tidy_failure_reasons() { assert!(tidy_failure(false, compiler_errors, &[dummy_note("demo.cpp", vec![])]).is_none()); // a .clang-tidy file can turn off all checks for some folders assert!(tidy_failure(false, "Error: no checks enabled.\n", &[]).is_none()); + // but not a crash that only mentions those words + let crash = "LLVM ERROR: Cannot chdir into \"/gone/no checks enabled/build\"!\n"; + assert!(tidy_failure(false, crash, &[]).is_some()); // a normal run, with or without a summary assert!(tidy_failure(true, "", &[]).is_none()); assert!(tidy_failure(true, "2 warnings generated.\n", &[]).is_none()); From bc70c55ce1f9cbb3d29377e2960491cea7e7dc06 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:50:12 +0000 Subject: [PATCH 4/6] test: cover files that clang-tidy did not analyze in reports and reviews --- cpp-linter/src/code_quality.rs | 25 ++++++++++++++++++++++ cpp-linter/src/common_fs.rs | 28 ++++++++++++++++++++++++ cpp-linter/src/rest_client/test.rs | 34 ++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) diff --git a/cpp-linter/src/code_quality.rs b/cpp-linter/src/code_quality.rs index 0fb67498..3c84f792 100644 --- a/cpp-linter/src/code_quality.rs +++ b/cpp-linter/src/code_quality.rs @@ -547,6 +547,31 @@ mod test { assert_eq!(fingerprints.len(), issues.len()); } + #[test] + fn tidy_failure_in_report() { + let tmp_dir = tempfile::tempdir().unwrap(); + let mut failed = FileObj::new(PathBuf::from("src/failed.cpp")); + failed.tidy_advice = Some(TidyAdvice { + failed: true, + ..Default::default() + }); + let files = [Arc::new(Mutex::new(failed))]; + let report = CodeQualityReport::new(&files, "llvm", tmp_dir.path(), Path::new("")).unwrap(); + let json = to_json(&report); + let issues = json.as_array().unwrap(); + assert_eq!(issues.len(), 1); + assert_eq!(issues[0]["check_name"], "clang-tidy"); + assert_eq!(issues[0]["severity"], "major"); + assert_eq!(issues[0]["location"]["path"], "src/failed.cpp"); + assert_eq!(issues[0]["location"]["lines"]["begin"], 1); + assert!( + issues[0]["description"] + .as_str() + .unwrap() + .starts_with("clang-tidy did not analyze this file") + ); + } + #[test] fn fingerprint_ignores_line_numbers() { let tmp_dir = tempfile::tempdir().unwrap(); diff --git a/cpp-linter/src/common_fs.rs b/cpp-linter/src/common_fs.rs index 66eb5943..e1e18611 100644 --- a/cpp-linter/src/common_fs.rs +++ b/cpp-linter/src/common_fs.rs @@ -818,6 +818,34 @@ mod test { assert!(review_comments.not_posted[0].starts_with("- **failed.cpp**: clang-format failed")); } + /// A file that clang-tidy did not analyze has no findings, but a PR review must mention it + /// and must not pass. + #[test] + fn tidy_failure_is_not_posted_concern() { + let repo_root = TempDir::new().unwrap(); + let mut file_obj = FileObj::new(PathBuf::from("failed.cpp")); + file_obj.tidy_advice = Some(super::TidyAdvice { + failed: true, + ..Default::default() + }); + let mut review_comments = ReviewComments::default(); + file_obj + .make_suggestions_from_patch( + &mut review_comments, + false, + repo_root.path(), + &ClangParams::default_patch_path(repo_root.path()), + ) + .unwrap(); + assert!(review_comments.comments.is_empty()); + assert!(review_comments.has_errors); + assert_eq!(review_comments.not_posted.len(), 1); + assert!( + review_comments.not_posted[0] + .starts_with("- **failed.cpp**: clang-tidy did not analyze this file") + ); + } + /// Two separate fixes in a file that is not UTF-8 are counted in the summary. #[test] #[allow(clippy::single_range_in_vec_init)] diff --git a/cpp-linter/src/rest_client/test.rs b/cpp-linter/src/rest_client/test.rs index fbbe5e06..623b1622 100644 --- a/cpp-linter/src/rest_client/test.rs +++ b/cpp-linter/src/rest_client/test.rs @@ -1189,3 +1189,37 @@ fn tidy_failure_feedback() { assert!(!comment.contains("How to fix"), "{comment}"); } } + +#[test] +fn tidy_failure_on_two_files() { + let files = ["a.cpp", "b.cpp"] + .map(|name| { + let mut file = FileObj::new(PathBuf::from(name)); + file.tidy_advice = Some(TidyAdvice { + failed: true, + ..Default::default() + }); + Arc::new(Mutex::new(file)) + }) + .to_vec(); + let comment = RestClient::make_comment( + &files, + 0, + 2, + &dummy_versions(), + None, + false, + "file".into(), + true, + ) + .unwrap(); + assert!( + comment.contains("clang-tidy did not analyze 2 files, so they were not checked."), + "{comment}" + ); + assert!(comment.contains("no entry for these files"), "{comment}"); + assert!( + comment.contains("| clang-tidy failed on 2 files |"), + "{comment}" + ); +} From 11d8878cf70ac0d4634894ede32a74003b54f430 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:03:11 +0000 Subject: [PATCH 5/6] test: cover a comment without room for the files clang-tidy did not analyze --- cpp-linter/src/rest_client/test.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/cpp-linter/src/rest_client/test.rs b/cpp-linter/src/rest_client/test.rs index 623b1622..141ee8f1 100644 --- a/cpp-linter/src/rest_client/test.rs +++ b/cpp-linter/src/rest_client/test.rs @@ -1222,4 +1222,23 @@ fn tidy_failure_on_two_files() { comment.contains("| clang-tidy failed on 2 files |"), "{comment}" ); + + // without room for the list of files + let head = comment.find("\n Date: Sun, 29 Nov 2026 02:23:41 +0000 Subject: [PATCH 6/6] feat: stop when clang-tidy did not analyze any file --- cpp-linter/src/clang_tools/mod.rs | 59 +++++++++++++++++++++++++++++++ cpp-linter/src/error.rs | 9 +++++ 2 files changed, 68 insertions(+) diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index c46e8155..80bbb454 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -257,6 +257,7 @@ pub async fn capture_clang_tools_output( rest_api_client.end_log_group(&log_group_name); } check_format_failures(files)?; + check_tidy_failures(files)?; Ok(clang_versions) } @@ -284,6 +285,30 @@ fn check_format_failures(files: &[Arc>]) -> Result<(), ClangTaskE Ok(()) } +/// Fail if clang-tidy did not analyze any of the files it was run on. +/// +/// When clang-tidy does not analyze only some files, those files are counted as +/// failed checks (see [`TidyAdvice::failed`](clang_tidy::TidyAdvice::failed)). +/// But when it analyzes none of them, the cause is most likely the compilation +/// database (eg. made in another folder, or without any entries), so there are no +/// results worth reporting. +fn check_tidy_failures(files: &[Arc>]) -> Result<(), ClangTaskError> { + let (mut attempted, mut failed) = (0, 0); + for file in files { + let file = file.lock().map_err(|_| ClangCaptureError::MutexPoisoned)?; + if let Some(advice) = &file.tidy_advice { + attempted += 1; + if advice.failed { + failed += 1; + } + } + } + if attempted > 0 && failed == attempted { + return Err(ClangTaskError::TidyFailedOnAllFiles(failed)); + } + Ok(()) +} + /// A struct to describe a single suggestion in a pull_request review. pub struct Suggestion { /// The file's line number in the diff that begins the suggestion. @@ -887,6 +912,40 @@ mod tests { assert!(matches!(err, ClangTaskError::FormatFailedOnAllFiles(2))); } + fn files_with_tidy_results(results: &[Option]) -> Vec>> { + results + .iter() + .enumerate() + .map(|(i, failed)| { + let mut file = FileObj::new(PathBuf::from(format!("file{i}.cpp"))); + file.tidy_advice = failed.map(|failed| clang_tidy::TidyAdvice { + failed, + ..Default::default() + }); + Arc::new(Mutex::new(file)) + }) + .collect() + } + + #[test] + fn tidy_failed_on_all_files() { + // `None` = clang-tidy was not run on the file (eg. `--ignore-tidy`) + let files = files_with_tidy_results(&[Some(true), None, Some(true)]); + let err = check_tidy_failures(&files).unwrap_err(); + assert!(matches!(err, ClangTaskError::TidyFailedOnAllFiles(2))); + assert!(err.to_string().contains("compilation database")); + } + + #[test] + fn tidy_failed_on_some_files() { + let files = files_with_tidy_results(&[Some(true), Some(false)]); + check_tidy_failures(&files).unwrap(); + // clang-tidy was not run at all + let files = files_with_tidy_results(&[None, None]); + check_tidy_failures(&files).unwrap(); + check_tidy_failures(&[]).unwrap(); + } + #[test] fn format_failed_on_some_files() { let files = files_with_format_results(&[Some(true), Some(false)]); diff --git a/cpp-linter/src/error.rs b/cpp-linter/src/error.rs index 4e7ba0c7..4e6e6bee 100644 --- a/cpp-linter/src/error.rs +++ b/cpp-linter/src/error.rs @@ -242,4 +242,13 @@ pub enum ClangTaskError { "clang-format failed on all {0} file(s) it ran on; check the `--style` value and the `.clang-format` file" )] FormatFailedOnAllFiles(usize), + + /// Error when clang-tidy did not analyze any of the files it was run on. + /// + /// This usually means a compilation database that was made for another checkout + /// (or one without any entries). + #[error( + "clang-tidy did not analyze any of the {0} file(s) it ran on; check that the compilation database (`--database`) was generated for this checkout" + )] + TidyFailedOnAllFiles(usize), }