diff --git a/cpp-linter/src/clang_tools/clang_format.rs b/cpp-linter/src/clang_tools/clang_format.rs index b14d59fe..e271a844 100644 --- a/cpp-linter/src/clang_tools/clang_format.rs +++ b/cpp-linter/src/clang_tools/clang_format.rs @@ -52,6 +52,34 @@ pub fn summarize_style(style: &str) -> String { } } +/// Describe the given `--style` for a sentence such as "Line 4 does not match {description}." +/// +/// - `file` (or no value): the style in `.clang-format` +/// - `file:`: the style in that file +/// - a predefined style (eg. `llvm`): the LLVM style +/// - anything else (eg. `{BasedOnStyle: llvm}`): the configured style +pub fn describe_style(style: &str) -> String { + if style.is_empty() || style == "file" { + String::from("the style in .clang-format") + } else if let Some(path) = style.strip_prefix("file:") { + format!("the style in {path}") + } else if [ + "google", + "chromium", + "microsoft", + "mozilla", + "webkit", + "llvm", + "gnu", + ] + .contains(&style) + { + format!("the {} style", summarize_style(style)) + } else { + String::from("the configured style") + } +} + /// Get a total count of clang-format advice from the given list of [FileObj]s. pub fn tally_format_advice(files: &[Arc>]) -> Result { let mut total = 0; @@ -750,4 +778,21 @@ mod tests { println!("{style}{l}{style:#}"); } } + + #[test] + fn style_descriptions() { + use super::describe_style; + assert_eq!(describe_style("file"), "the style in .clang-format"); + assert_eq!(describe_style(""), "the style in .clang-format"); + assert_eq!( + describe_style("file:../.clang-format"), + "the style in ../.clang-format" + ); + assert_eq!(describe_style("llvm"), "the LLVM style"); + assert_eq!(describe_style("google"), "the Google style"); + assert_eq!( + describe_style("{BasedOnStyle: llvm}"), + "the configured style" + ); + } } diff --git a/cpp-linter/src/clang_tools/clang_tidy/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/mod.rs index b1337390..9f1ef7a9 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/mod.rs @@ -16,7 +16,12 @@ use regex::Regex; use serde::Deserialize; // project-specific modules/crates -use crate::{cli::ClangParams, common_fs::FileObj, error::ClangCaptureError}; +use crate::{ + cli::ClangParams, + common_fs::FileObj, + error::ClangCaptureError, + markdown::{self, Status}, +}; pub mod other_files; use other_files::{OtherFileFix, Replacement, TidyFixes}; @@ -146,7 +151,43 @@ impl TidyNotification { /// The heading of a review suggestion that no clang-tidy note fixes. /// /// Such a suggestion only has changes from clang-format. -pub(crate) const FORMAT_SUGGESTION_HEADING: &str = "### clang-format suggestion\n"; +pub(crate) const FORMAT_SUGGESTION_HEADING: &str = "**clang-format** suggests this formatting.\n"; + +impl TidyNotification { + /// Describe this notification in a PR review comment (in markdown). + /// + /// The comment is shown under the line it is about, + /// so the file name and line number are left out: + /// a line with the severity and the linked diagnostic name, then the rationale, + /// then the parts of the fix that were not applied (if any). + pub(crate) fn review_text(&self) -> String { + let (mark, severity) = match self.severity.as_str() { + "error" => (Status::Failed.small_mark(), String::from("Error")), + "warning" => (Status::Warned.small_mark(), String::from("Warning")), + other => { + let mut chars = other.chars(); + let word = chars + .next() + .map(|first| first.to_uppercase().collect::() + chars.as_str()) + .unwrap_or_default(); + (String::from("ℹ"), word) + } + }; + let mut text = format!( + "{mark} **{severity}**: {}\n\n{}\n", + self.diagnostic_link(), + markdown::escape(&self.rationale) + ); + for skipped in &self.skipped_fixes { + text.push_str(&format!( + "\n{} {}\n", + Status::Warned.small_mark(), + skipped.describe() + )); + } + text + } +} /// A struct to hold notification from clang-tidy about a single file #[derive(Debug, Clone)] @@ -160,26 +201,19 @@ impl TidyAdvice { let mut diagnostics = vec![]; for note in &self.notes { // A fix can change more than one line of the same hunk. - // List the note's rationale once, not once per fixed line. + // Describe the note once, not once per fixed line. if note .fixed_lines .iter() .any(|fixed_line| (start_line..=end_line).contains(fixed_line)) { - diagnostics.push(format!( - "- {} [{}]\n", - note.rationale, - note.diagnostic_link() - )); - for skipped in ¬e.skipped_fixes { - diagnostics.push(format!(" - :warning: {}\n", skipped.describe())); - } + diagnostics.push(note.review_text()); } } if diagnostics.is_empty() { return FORMAT_SUGGESTION_HEADING.to_string(); } - format!("### clang-tidy diagnostic(s)\n{}", diagnostics.join("")) + diagnostics.join("\n") } } 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 47ad8170..4e3f15ed 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 @@ -161,7 +161,10 @@ async fn fix_analyzed_header() { .as_ref() .unwrap() .get_suggestion_help(2, 2); - assert!(help.starts_with("### clang-tidy diagnostic(s)"), "{help}"); + assert!( + help.starts_with("\"⚠\"") **Warning**: "), + "{help}" + ); assert!(help.contains(¬e.rationale), "{help}"); assert_eq!(tally_tidy_advice(&files).unwrap(), 1); } diff --git a/cpp-linter/src/clang_tools/clang_tidy/test.rs b/cpp-linter/src/clang_tools/clang_tidy/test.rs index 2586c6ec..10098895 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/test.rs @@ -297,13 +297,25 @@ fn suggestion_help_with_and_without_fixes() { let advice = TidyAdvice { notes: vec![dummy_note("demo.cpp", vec![5])], }; - // A fixed line within the range yields a "diagnostic(s)" header plus the rationale. + // A fixed line within the range yields the severity, the diagnostic and the rationale. let help = advice.get_suggestion_help(1, 10); - assert!(help.contains("clang-tidy diagnostic(s)")); - assert!(help.contains("a dummy rationale")); + assert_eq!( + help, + "\"⚠\" **Warning**: [modernize-use-auto](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-auto.html)\n\na dummy rationale\n" + ); // No fixed line within the range: the suggestion only has clang-format changes. let help = advice.get_suggestion_help(20, 30); - assert_eq!(help, "### clang-format suggestion\n"); + assert_eq!(help, "**clang-format** suggests this formatting.\n"); +} + +#[test] +fn review_text_for_other_severities() { + let mut note = dummy_note("demo.cpp", vec![]); + note.severity = String::from("note"); + assert_eq!( + note.review_text(), + "ℹ **Note**: [modernize-use-auto](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-auto.html)\n\na dummy rationale\n" + ); } #[test] @@ -319,7 +331,7 @@ fn suggestion_help_lists_a_multi_line_fix_once() { let advice = TidyAdvice { notes: vec![note] }; let help = advice.get_suggestion_help(1, 10); assert_eq!(help.matches("a dummy rationale").count(), 1); - assert_eq!(help.matches(":warning:").count(), 1); + assert_eq!(help.matches("/m/w.png\"> Part of this fix").count(), 1); // The note is still listed when only one of its fixed lines is in the hunk. let help = advice.get_suggestion_help(6, 8); assert_eq!(help.matches("a dummy rationale").count(), 1); @@ -337,7 +349,7 @@ fn suggestion_help_with_skipped_fixes() { let advice = TidyAdvice { notes: vec![note] }; let help = advice.get_suggestion_help(5, 5); assert!(help.contains( - "\n - :warning: Part of this fix was not applied to `demo.h` \ + "/m/w.png\"> Part of this fix was not applied to `demo.h` \ because it is not one of the analyzed files.\n" )); } diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index 73b2e5db..131d8062 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -19,6 +19,7 @@ use crate::{ clang_tools::clang_tidy::CompilationUnit, cli::ClangParams, error::{ClangCaptureError, ClangTaskError}, + markdown::{Status, plural}, rest_client::{RestClient, USER_OUTREACH}, }; pub mod clang_format; @@ -310,6 +311,9 @@ pub struct ReviewComments { /// a file that clang-format failed to run on, or fixes for a file that is /// not UTF-8 encoded. pub not_posted: Vec, + /// Whether a finding in the diff is an error (from clang-tidy), + /// or clang-format failed to run on a file. + pub has_errors: bool, } /// The notice added to a review summary instead of a patch that does not fit. @@ -328,31 +332,50 @@ impl ReviewComments { total_review_comments: u32, summary_only: bool, ) -> String { - let mut body = String::from("## Cpp-linter Review\n"); + let total = comments.len() as u32; + // Only congratulate if there were no findings, no reused comments, + // no fix parts left for the user to apply, and no concerns that could not be posted. + let is_lgtm = self.tool_total == 0 + && !self.has_errors + && self.full_patch.is_empty() + && total_review_comments == 0 + && self.skipped_fixes.is_empty() + && self.not_posted.is_empty(); + let status = if is_lgtm { + Status::Passed + } else if self.has_errors { + Status::Failed + } else { + Status::Warned + }; + let mut body = format!("## {} cpp-linter review\n\n", status.mark()); + let headline = if summary_only && self.tool_total > 0 { + format!("**Found {}**", plural(self.tool_total.into(), "issue")) + } else if total > 0 { + format!("**{}**", plural(total.into(), "comment")) + } else if is_lgtm { + log::info!("No concerns to report: LGTM"); + String::from("No issues in this diff") + } else { + String::from("No new comments in this diff") + }; let versions = [ ( ClangTool::ClangFormat, clang_versions.format_version.as_ref(), ), (ClangTool::ClangTidy, clang_versions.tidy_version.as_ref()), - ]; - for (tool_name, tool_version) in versions { - if let Some(ver) = tool_version { - // If a tool was used, then we know it's version at this point. - body.push_str(format!("### Used {tool_name} v{ver}\n").as_str()); - } + ] + .into_iter() + // If a tool was used, then we know its version at this point. + .filter_map(|(tool_name, version)| version.map(|ver| format!("{tool_name} {ver}"))) + .collect::>(); + body.push_str(&headline); + if !versions.is_empty() { + body.push_str(&format!(" ({})", versions.join(", "))); } + body.push('\n'); - let total = comments.len() as u32; - if summary_only && self.tool_total > 0 { - body.push_str( - format!( - "\nFound {} areas of concern according to clang tools output.\n", - self.tool_total - ) - .as_str(), - ); - } if !summary_only && self.in_diff != self.tool_total { log::info!( "Only {} out of {} concerns fit within this pull request's diff.", @@ -361,7 +384,7 @@ impl ReviewComments { ); body.push_str( format!( - "\nOnly {} out of {} concerns fit within this pull request's diff.\n", + "\nOnly {} of {} findings are in this pull request's diff.\n", self.in_diff, self.tool_total, ) .as_str(), @@ -373,9 +396,14 @@ impl ReviewComments { log::info!( "Found and removed {dupes} concerns that were duplicates of previous reviews." ); - body.push_str( - format!("\n{dupes} suggestions were duplicates of previous reviews.\n").as_str(), - ); + body.push_str(&format!( + "\n{} already posted in a previous review.\n", + if dupes == 1 { + String::from("1 comment was") + } else { + format!("{dupes} comments were") + } + )); } self.summarize_skipped_fixes(&mut body); self.summarize_not_posted(&mut body); @@ -383,14 +411,14 @@ impl ReviewComments { // It can also contain suggestions that were duplicates of previous reviews. if !self.full_patch.is_empty() { let current_len = body.len() + USER_OUTREACH.len(); - let mut patch_prefix = "\n
Click here for ".to_string(); + let mut patch_prefix = "\n
".to_string(); if summary_only { - patch_prefix.push_str("the full patch of fixes"); + patch_prefix.push_str("The full patch of fixes"); } else { - patch_prefix.push_str("a patch of fixes outside the diff"); + patch_prefix.push_str("A patch of fixes outside the diff"); } - patch_prefix.push_str("

\n\n```diff\n"); - let patch_suffix = "```\n\n

\n"; + patch_prefix.push_str("
\n\n```diff\n"); + let patch_suffix = "```\n\n
\n"; if (current_len + patch_prefix.len() + self.full_patch.len() + patch_suffix.len()) > u16::MAX as usize @@ -404,14 +432,6 @@ impl ReviewComments { body.push_str(self.full_patch.as_str()); body.push_str(patch_suffix); } - } else if total_review_comments == 0 - && self.skipped_fixes.is_empty() - && self.not_posted.is_empty() - { - // Only congratulate if there was no reused comments, - // no fix parts left for the user to apply, and no concerns that could not be posted - log::info!("No concerns to report: LGTM"); - body.push_str("\nNo concerns to report. Great job! :tada:\n"); } body.push_str(USER_OUTREACH); body @@ -432,7 +452,7 @@ impl ReviewComments { /// /// The same length limit applies as in [`Self::summarize_skipped_fixes()`]. fn summarize_not_posted(&self, body: &mut String) { - const HEADING: &str = "\nSome concerns could not be posted as suggestions:\n\n"; + const HEADING: &str = "\nSome findings could not be posted as suggestions:\n\n"; Self::summarize_list( body, HEADING, @@ -630,7 +650,43 @@ mod tests { total_review_comments, summary_only, ); - assert!(review_summary.contains("suggestions were duplicates of previous reviews")); + assert!(review_summary.contains("1 comment was already posted in a previous review.")); + } + + /// A summary-only review of a finding with no fix shows no pass mark. + #[test] + fn summary_only_review_with_findings_is_not_passed() { + let clang_versions = ClangVersions { + format_version: None, + tidy_version: Some(PSEUDO_VERSION), + }; + let review = ReviewComments { + tool_total: 1, + in_diff: 1, + ..Default::default() + }; + let summary = review.summarize(&clang_versions, &[], 0, true); + assert!(summary.contains("/m/hw.png"), "{summary}"); + assert!(summary.contains("**Found 1 issue**"), "{summary}"); + let clean = ReviewComments::default().summarize(&clang_versions, &[], 0, true); + assert!(clean.contains("/m/hp.png"), "{clean}"); + } + + /// An error in the diff makes the review's mark red, like the thread comment's. + #[test] + fn review_with_errors_is_failed() { + let clang_versions = ClangVersions { + format_version: None, + tidy_version: Some(PSEUDO_VERSION), + }; + let review = ReviewComments { + tool_total: 1, + in_diff: 1, + has_errors: true, + ..Default::default() + }; + let summary = review.summarize(&clang_versions, &[], 0, true); + assert!(summary.contains("/m/hf.png"), "{summary}"); } #[test] @@ -648,8 +704,8 @@ mod tests { .summarize(&clang_versions, &[], 2, false) }; // concerns merged into fewer comments still fit within the diff - assert!(!summarize(6).contains("concerns fit within")); - assert!(summarize(2).contains("\nOnly 2 out of 6 concerns fit within")); + assert!(!summarize(6).contains("findings are in this")); + assert!(summarize(2).contains("\nOnly 2 of 6 findings are in this pull request's diff.")); } #[test] @@ -666,7 +722,7 @@ mod tests { assert!( review_summary.contains("Please apply these parts yourself:\n\n- first\n- second\n") ); - assert!(!review_summary.contains("No concerns to report")); + assert!(!review_summary.contains("No issues in this diff")); } #[test] @@ -681,9 +737,9 @@ mod tests { } .summarize(&clang_versions, &[], 0, false); assert!(review_summary.contains( - "Some concerns could not be posted as suggestions:\n\n- **demo.cpp**: clang-format failed\n" + "Some findings could not be posted as suggestions:\n\n- **demo.cpp**: clang-format failed\n" )); - assert!(!review_summary.contains("No concerns to report")); + assert!(!review_summary.contains("No issues in this diff")); } #[test] diff --git a/cpp-linter/src/cli/structs.rs b/cpp-linter/src/cli/structs.rs index 79360ed8..469dca95 100644 --- a/cpp-linter/src/cli/structs.rs +++ b/cpp-linter/src/cli/structs.rs @@ -11,6 +11,7 @@ use super::{Cli, convert_extra_arg_val, ignore_patterns}; use crate::clang_tools::clang_tidy::CompilationUnit; #[cfg(feature = "bin")] use crate::common_fs::is_stdout; +use crate::rest_client::FormatRun; use git_bot_feedback::FileFilter; @@ -353,6 +354,9 @@ pub struct FeedbackInput { /// The clang-format style to show in file annotations. pub style: String, + /// Whether clang-format only checked the changed lines (see `--lines-changed-only`). + pub format_lines_only: bool, + /// Whether to post a PR review. pub pr_review: bool, @@ -374,6 +378,15 @@ pub struct FeedbackInput { } impl FeedbackInput { + /// How clang-format ran, to tell the user how to run it the same way. + pub fn format_run(&self) -> FormatRun<'_> { + FormatRun { + style: &self.style, + lines_only: self.format_lines_only, + path_prefix: Path::new(""), + } + } + /// Is a report (`--sarif-file -` or `--code-quality-file -`) written to stdout? /// /// Then other output (the generated patch, and log messages in a local run) @@ -392,6 +405,7 @@ impl From<&Cli> for FeedbackInput { fn from(args: &Cli) -> Self { FeedbackInput { style: args.format_options.style.clone(), + format_lines_only: args.source_options.lines_changed_only != LinesChangedOnly::Off, no_lgtm: args.feedback_options.no_lgtm, step_summary: args.feedback_options.step_summary, thread_comments: args.feedback_options.thread_comments.clone(), @@ -433,6 +447,7 @@ impl Default for FeedbackInput { step_summary: false, file_annotations: true, style: "llvm".to_string(), + format_lines_only: false, pr_review: false, passive_reviews: false, repo_root: PathBuf::from("."), diff --git a/cpp-linter/src/code_quality.rs b/cpp-linter/src/code_quality.rs index 0423bc5e..19c744a9 100644 --- a/cpp-linter/src/code_quality.rs +++ b/cpp-linter/src/code_quality.rs @@ -19,7 +19,7 @@ use sha2::{Digest, Sha256}; // project-specific modules/crates use crate::{ - clang_tools::clang_format::summarize_style, + clang_tools::clang_format::describe_style, common_fs::{FileObj, is_stdout}, error::ClientError, }; @@ -212,7 +212,7 @@ impl CodeQualityReport { repo_root: &Path, path_prefix: &Path, ) -> Result { - let style_guide = summarize_style(style); + let style_description = describe_style(style); let mut builder = IssueBuilder::default(); for file in files { let file = file @@ -250,7 +250,7 @@ impl CodeQualityReport { CLANG_FORMAT, CLANG_FORMAT, format!( - "Code does not conform to {style_guide} style guidelines. Run clang-format to fix it." + "Code does not match {style_description}. Run clang-format to fix it." ), Severity::Minor, &path, @@ -492,7 +492,7 @@ mod test { assert_eq!(issues[0]["location"]["lines"]["end"], 3); assert_eq!( issues[0]["description"], - "Code does not conform to LLVM style guidelines. Run clang-format to fix it." + "Code does not match the LLVM style. Run clang-format to fix it." ); // line numbers start at 1 assert_eq!(issues[1]["location"]["lines"]["begin"], 1); @@ -567,7 +567,7 @@ mod test { } assert_eq!( after[0]["description"], - "Code does not conform to Custom style guidelines. Run clang-format to fix it." + "Code does not match the style in .clang-format. Run clang-format to fix it." ); } diff --git a/cpp-linter/src/common_fs.rs b/cpp-linter/src/common_fs.rs index f2b400c9..5ca194e7 100644 --- a/cpp-linter/src/common_fs.rs +++ b/cpp-linter/src/common_fs.rs @@ -244,10 +244,21 @@ impl FileObj { let file_name = self.name.to_string_lossy().replace("\\", "/"); if self.format_advice.as_ref().is_some_and(|a| a.failed) { // There is nothing to suggest, but the review must not approve this file. + review_comments.has_errors = true; review_comments.not_posted.push(format!( "- **{file_name}**: clang-format failed to run, so the formatting 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| { + note.filename == file_name + && note.severity == "error" + && self.is_line_in_diff(¬e.line) + }) + { + review_comments.has_errors = true; + } let Some(contents) = self.read_contents(repo_root)? else { return Ok(()); }; @@ -266,25 +277,24 @@ impl FileObj { "{file_name} is not UTF-8 encoded, so its fixes are only in the patch file, not in the PR review" ); review_comments.not_posted.push(format!( - "- **{file_name}**: {fixes} fix(es) are only in the patch file because the file is not UTF-8 encoded" + "- **{file_name}**: {} only in the patch file because the file is not UTF-8 encoded", + if fixes == 1 { + String::from("1 fix is") + } else { + format!("{fixes} fixes are") + } )); } } if let Some(advice) = &self.tidy_advice { // now check for clang-tidy warnings with no fixes applied - let file_ext = self - .name - .extension() - .unwrap_or_default() - .to_str() - .unwrap_or_default(); - // Count of clang-tidy diagnostics that had no fixes applied + // (a count of such clang-tidy diagnostics) let mut total = 0; for note in &advice.notes { if note.filename == file_name { for skipped in ¬e.skipped_fixes { review_comments.skipped_fixes.push(format!( - "- **{file_name}:{}** [{}]: {}", + "- **{file_name}:{}** {}: {}", note.line, note.diagnostic_link(), skipped.describe() @@ -303,29 +313,14 @@ impl FileObj { continue; } review_comments.in_diff += 1; - let mut suggestion = format!( - "### clang-tidy diagnostic\n**{file_name}:{}:{}** {}: [{}]\n\n> {}\n", - note.line, - note.cols, - note.severity, - note.diagnostic_link(), - note.rationale - ); - if !note.suggestion.is_empty() { - suggestion.push_str( - format!("\n```{file_ext}\n{}\n```\n", note.suggestion.join("\n")) - .as_str(), - ); - } - for skipped in ¬e.skipped_fixes { - suggestion.push_str(&format!("\n:warning: {}\n", skipped.describe())); - } + let suggestion = note.review_text(); let mut is_merged = false; for s in &mut review_comments.comments { if s.path == file_name && s.line_end >= note.line && s.line_start <= note.line { + s.suggestion.push('\n'); s.suggestion.push_str(suggestion.as_str()); is_merged = true; break; @@ -531,7 +526,7 @@ mod test { use super::{FileObj, FormatAdvice}; use crate::{ - clang_tools::ReviewComments, + clang_tools::{ClangVersions, ReviewComments}, cli::{ClangParams, LinesChangedOnly}, }; @@ -674,6 +669,7 @@ mod test { // a diagnostic about an included header is not about this file's line 4 TidyNotification { filename: "test_file.h".to_string(), + severity: "error".to_string(), ..note(4, vec![]) }, ], @@ -701,19 +697,61 @@ mod test { assert_eq!(new_suggestion.line_start, 3); assert_eq!(new_suggestion.line_end, 3); assert!(new_suggestion.suggestion.contains("rationale for line 3")); - assert!(new_suggestion.suggestion.contains("```cpp\nline3\n```")); + // The comment is shown under the line, so the code snippet is left out. + assert!(!new_suggestion.suggestion.contains("line3")); + assert!(!new_suggestion.suggestion.contains("test_file.cpp:3")); let skipped = "Part of this fix was not applied to `test_file.h` \ because it is not one of the analyzed files."; assert!( new_suggestion .suggestion - .contains(&format!("\n:warning: {skipped}\n")) + .contains(&format!("/m/w.png\"> {skipped}\n")) ); assert_eq!(review_comments.skipped_fixes.len(), 1); - assert!( - review_comments.skipped_fixes[0].starts_with("- **test_file.cpp:3** [[readability") - ); + assert!(review_comments.skipped_fixes[0].starts_with("- **test_file.cpp:3** [readability")); assert!(review_comments.skipped_fixes[0].ends_with(skipped)); + // the error is about another file, so the review is not marked as failed + assert!(!review_comments.has_errors); + + // an error on a changed line of this file marks the review as failed + let mut with_error = ReviewComments::default(); + let mut errored = FileObj::from( + PathBuf::from("test_file.cpp"), + vec![1, 3], + vec![1..=1, 3..=4], + ); + errored.patched_path = Some(patched_file.path().to_path_buf()); + errored.tidy_advice = Some(TidyAdvice { + notes: vec![TidyNotification { + severity: "error".to_string(), + ..note(3, vec![]) + }], + }); + errored + .make_suggestions_from_patch( + &mut with_error, + false, + repo_root.path(), + &ClangParams::default_patch_path(repo_root.path()), + ) + .unwrap(); + assert!(with_error.has_errors); + // also without a patched file (no fixes were made) + errored.patched_path = None; + let mut without_patch = ReviewComments::default(); + errored + .make_suggestions_from_patch( + &mut without_patch, + false, + repo_root.path(), + &ClangParams::default_patch_path(repo_root.path()), + ) + .unwrap(); + assert!(without_patch.has_errors); + // An error with nothing to post still keeps the review from passing. + assert_eq!(without_patch.tool_total, 0); + let summary = without_patch.summarize(&ClangVersions::default(), &[], 0, false); + assert!(summary.contains("/m/hf.png"), "{summary}"); // Processing the same file again merges duplicate suggestions file_obj @@ -772,6 +810,48 @@ mod test { assert!(review_comments.not_posted[0].starts_with("- **failed.cpp**: clang-format failed")); } + /// Two separate fixes in a file that is not UTF-8 are counted in the summary. + #[test] + #[allow(clippy::single_range_in_vec_init)] + fn non_utf8_file_with_two_fixes() { + let repo_root = TempDir::new().unwrap(); + let file_name = PathBuf::from("gbk2.cpp"); + let filler = "int x;\n".repeat(10); + let original = [ + &b"// \xd6\xd0\xce\xc4\nint a;\n"[..], + filler.as_bytes(), + b"int b;\n", + ] + .concat(); + let patched = [ + &b"// \xd6\xd0\xce\xc4\nint a;\n"[..], + filler.as_bytes(), + b"int b;\n", + ] + .concat(); + fs::write(repo_root.path().join(&file_name), &original).unwrap(); + let patched_file = NamedTempFile::new().unwrap(); + fs::write(patched_file.path(), &patched).unwrap(); + + let mut file_obj = FileObj::from(file_name, vec![2, 13], vec![1..=13]); + file_obj.patched_path = Some(patched_file.path().to_path_buf()); + let mut review_comments = ReviewComments::default(); + file_obj + .make_suggestions_from_patch( + &mut review_comments, + false, + repo_root.path(), + &repo_root.path().join("fixes.patch"), + ) + .unwrap(); + assert_eq!( + review_comments.not_posted, + vec![ + "- **gbk2.cpp**: 2 fixes are only in the patch file because the file is not UTF-8 encoded" + ] + ); + } + /// A source file that is not UTF-8 (here: GBK) must not abort the run. /// Its fixes go into the patch file byte for byte, but not into review suggestions. #[test] @@ -804,7 +884,7 @@ mod test { assert_eq!( review_comments.not_posted, vec![ - "- **gbk.cpp**: 1 fix(es) are only in the patch file because the file is not UTF-8 encoded" + "- **gbk.cpp**: 1 fix is only in the patch file because the file is not UTF-8 encoded" ] ); diff --git a/cpp-linter/src/lib.rs b/cpp-linter/src/lib.rs index a55b2622..87b17838 100644 --- a/cpp-linter/src/lib.rs +++ b/cpp-linter/src/lib.rs @@ -21,6 +21,7 @@ pub mod code_quality; pub mod common_fs; pub mod error; mod git; +pub(crate) mod markdown; pub mod rest_client; pub mod run; pub mod sarif; diff --git a/cpp-linter/src/markdown.rs b/cpp-linter/src/markdown.rs new file mode 100644 index 00000000..c5d97757 --- /dev/null +++ b/cpp-linter/src/markdown.rs @@ -0,0 +1,226 @@ +//! Small helpers that write the Markdown of thread comments, step summaries and +//! PR reviews. +//! +//! These keep the wording and the look of every report the same: +//! a status mark in front of a heading that states the result, +//! counted nouns that agree with their numbers, and user text that cannot +//! break out of a table cell or a code block. + +use std::ops::RangeInclusive; + +/// Where the status marks are hosted. +/// +/// The marks are drawn from the logo: its amber ring with a green check, an amber "!" or a +/// red cross (`branding/status/brush/` in the cpp-linter/.github repository builds them). +/// Heading marks keep the ring (`hp`, `hw`, `hf`); row marks are the glyph alone +/// (`p`, `w`, `f`). The org site serves them under a short path to keep comments small. +/// Posted comments keep pointing here, so these files must not move. +pub const STATUS_MARK_URL: &str = "https://cpp-linter.github.io/m"; + +/// The overall result of a report, shown as a mark in front of its heading. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + /// Nothing to report. + Passed, + /// Findings, but nothing that clang reported as an error. + Warned, + /// An error from clang-tidy, or a file that clang-format failed to run on. + Failed, +} + +impl Status { + /// The text glyph for this status: the `alt` text of its marks, and plain text where an image does not fit. + pub fn glyph(self) -> &'static str { + match self { + Status::Passed => "✔", + Status::Warned => "⚠", + Status::Failed => "✖", + } + } + + /// The `` of this status's mark, sized to sit in front of a level 2 heading. + /// + /// The `alt` text is the [`Self::glyph`], so the heading still reads + /// right where images are not shown. + pub fn mark(self) -> String { + self.mark_sized("h", 24, "top") + } + + /// The `` of this status's mark, sized for a line of text (eg. a table cell). + pub fn small_mark(self) -> String { + self.mark_sized("", 20, "absmiddle") + } + + fn mark_sized(self, prefix: &str, size: u8, align: &str) -> String { + let name = match self { + Status::Passed => "p", + Status::Warned => "w", + Status::Failed => "f", + }; + format!( + "\"{}\"", + self.glyph() + ) + } +} + +/// Count a noun: `1 file`, `2 files`. +/// +/// Only regular plurals are needed (an `s` is appended). +pub fn plural(count: u64, noun: &str) -> String { + format!("{count} {noun}{}", if count == 1 { "" } else { "s" }) +} + +/// Escape text from clang (or from a file name) for Markdown. +/// +/// The text keeps its meaning in a paragraph, a list item or a table cell: +/// `*`, `_` and the like are shown as they are instead of starting emphasis, +/// `<`, `>` and `&` are not taken as HTML, a `|` does not end a table cell, +/// and line breaks do not end the list item or table row. +pub fn escape(text: &str) -> String { + let mut escaped = String::with_capacity(text.len()); + for c in text.trim().chars() { + match c { + '&' => escaped.push_str("&"), + '<' => escaped.push_str("<"), + '>' => escaped.push_str(">"), + '\r' => {} + '\n' => escaped.push(' '), + '\\' | '`' | '*' | '_' | '[' | ']' | '|' | '#' | '~' => { + escaped.push('\\'); + escaped.push(c); + } + _ => escaped.push(c), + } + } + escaped +} + +/// Sort line ranges and join those that touch or overlap: `3..=5, 6..=11` is `(3, 11)`. +pub fn join_ranges(ranges: &[RangeInclusive]) -> Vec<(u32, u32)> { + let mut sorted = ranges + .iter() + .filter(|r| !r.is_empty()) + .map(|r| (*r.start(), *r.end())) + .collect::>(); + sorted.sort_unstable(); + let mut joined: Vec<(u32, u32)> = vec![]; + for (start, end) in sorted { + match joined.last_mut() { + Some(last) if start <= last.1.saturating_add(1) => last.1 = last.1.max(end), + _ => joined.push((start, end)), + } + } + joined +} + +/// Describe line ranges in words: `line 12`, `lines 3-11, 20`. +/// +/// Ranges that touch or overlap are joined. +pub fn describe_lines(ranges: &[RangeInclusive]) -> String { + let joined = join_ranges(ranges); + let single = joined.len() == 1 && joined[0].0 == joined[0].1; + let list = joined + .iter() + .map(|(start, end)| { + if start == end { + start.to_string() + } else { + format!("{start}-{end}") + } + }) + .collect::>() + .join(", "); + format!("{} {list}", if single { "line" } else { "lines" }) +} + +/// A fenced code block that its `body` cannot close. +/// +/// The fence is one backtick longer than the longest run of backticks in `body`. +pub fn fenced(language: &str, body: &str) -> String { + let mut longest = 0; + let mut run = 0; + for c in body.chars() { + if c == '`' { + run += 1; + longest = longest.max(run); + } else { + run = 0; + } + } + let fence = "`".repeat((longest + 1).max(3)); + let newline = if body.ends_with('\n') { "" } else { "\n" }; + format!("{fence}{language}\n{body}{newline}{fence}\n") +} + +/// Quote a word for a POSIX shell, if it needs quotes. +pub fn shell_quote(word: &str) -> String { + let is_plain = !word.is_empty() + && word + .chars() + .all(|c| c.is_ascii_alphanumeric() || "-_./=+:@,".contains(c)); + if is_plain { + word.to_string() + } else { + format!("'{}'", word.replace('\'', r"'\''")) + } +} + +#[cfg(test)] +mod test { + use super::{RangeInclusive, Status, describe_lines, escape, fenced, plural, shell_quote}; + + #[test] + fn plurals() { + assert_eq!(plural(0, "file"), "0 files"); + assert_eq!(plural(1, "file"), "1 file"); + assert_eq!(plural(2, "warning"), "2 warnings"); + } + + #[test] + fn escaped_text() { + assert_eq!( + escape("conversion 'int *' to 'char *' in a|b \n"), + r"conversion 'int \*' to 'char \*' in a\|b <T>" + ); + assert_eq!(escape("line one\r\nline two"), "line one line two"); + assert_eq!( + escape("a <T> && b"), + "a &lt;T&gt; && b" + ); + } + + #[test] + fn lines_in_words() { + assert_eq!(describe_lines(&[RangeInclusive::new(12, 12)]), "line 12"); + assert_eq!(describe_lines(&[3..=5, 6..=11, 20..=20]), "lines 3-11, 20"); + assert_eq!(describe_lines(&[20..=20, 4..=4]), "lines 4, 20"); + } + + #[test] + fn fences() { + assert_eq!(fenced("bash", "ls"), "```bash\nls\n```\n"); + assert_eq!(fenced("text", "a ```` b\n"), "`````text\na ```` b\n`````\n"); + } + + #[test] + fn quoted_words() { + assert_eq!(shell_quote("src/demo.cpp"), "src/demo.cpp"); + assert_eq!(shell_quote("my file.cpp"), "'my file.cpp'"); + assert_eq!(shell_quote("it's"), r"'it'\''s'"); + } + + #[test] + fn marks() { + assert!(Status::Passed.mark().contains("alt=\"✔\"")); + assert_eq!( + Status::Failed.mark(), + "\"✖\"" + ); + assert_eq!(Status::Warned.glyph(), "⚠"); + assert_eq!( + Status::Warned.small_mark(), + "\"⚠\"" + ); + } +} diff --git a/cpp-linter/src/rest_client.rs b/cpp-linter/src/rest_client.rs index afaaf0fb..ab78efa3 100644 --- a/cpp-linter/src/rest_client.rs +++ b/cpp-linter/src/rest_client.rs @@ -3,6 +3,7 @@ use std::{ env, io::{BufRead, Write, stderr, stdout}, + ops::RangeInclusive, path::{Path, PathBuf}, sync::{Arc, Mutex}, }; @@ -17,13 +18,14 @@ use git_bot_feedback::{ use crate::{ clang_tools::{ ClangVersions, ReviewComments, - clang_format::{summarize_style, tally_format_advice}, - clang_tidy::tally_tidy_advice, + clang_format::{describe_style, tally_format_advice}, + clang_tidy::{TidyNotification, tally_tidy_advice}, }, cli::{FeedbackInput, ThreadComments}, code_quality::CodeQualityReport, common_fs::{FileObj, is_stdout}, error::ClientError, + markdown::{self, Status, plural}, sarif::SarifLog, }; @@ -35,8 +37,8 @@ pub const USER_AGENT: &str = concat!("cpp-linter/", env!("CARGO_PKG_VERSION"),); /// The user outreach message displayed in bot comments. pub const USER_OUTREACH: &str = concat!( - "\n\n---\n:sparkles: Powered by [**cpp-linter**](https://cpp-linter.github.io)", - " • [:speech_balloon: Feedback]", + "\n\nPowered by [**cpp-linter**](https://cpp-linter.github.io)", + " | [Feedback]", "(https://github.com/cpp-linter/cpp-linter-action/issues)" ); @@ -95,7 +97,7 @@ fn annotation_cap_message( ) { (true, true) => "The step summary and the thread comment list every finding.", (true, false) => "The step summary lists every finding.", - (false, true) => "The thread comment lists every finding.", + (false, true) => "The thread comment lists them, and the workflow log lists every finding.", (false, false) => { "Use `--step-summary` or `--thread-comments` to get a list of every finding." } @@ -234,16 +236,16 @@ impl RestClient { clang_versions: ClangVersions, ) -> Result { let tidy_checks_failed = tally_tidy_advice(files).map_err(ClientError::MutexPoisoned)?; + let format_run = FormatRun { + path_prefix: &self.repo_root_prefix, + ..feedback_inputs.format_run() + }; let format_checks_failed = tally_format_advice(files).map_err(ClientError::MutexPoisoned)?; let mut comment = None; if feedback_inputs.file_annotations { - // Outside CI, an annotation is shown with its file and line, - // so a short title (the check's name) is enough. - let short_titles = self.client_kind() == "local"; - let mut annotations = - Self::build_annotations(files, &feedback_inputs.style, short_titles)?; + let mut annotations = Self::build_annotations(files, format_run)?; for annotation in &mut annotations { annotation.path = prefix_feedback_path(&annotation.path, &self.repo_root_prefix); } @@ -254,34 +256,6 @@ impl RestClient { log::warn!("{msg}"); } } - if feedback_inputs.step_summary || feedback_inputs.summary_output_file.is_some() { - let summary = Self::make_comment( - files, - format_checks_failed, - tidy_checks_failed, - &clang_versions, - None, - feedback_inputs.gen_patch || feedback_inputs.pr_review, - )?; - if feedback_inputs.step_summary { - self.client.append_step_summary(&summary)?; - } - if let Some(output_file) = &feedback_inputs.summary_output_file { - if let Some(parent) = output_file.parent() { - std::fs::create_dir_all(parent).map_err(|e| ClientError::MkDirFailed { - file_path: output_file.clone(), - source: e, - })?; - } - std::fs::write(output_file, &summary).map_err(|e| { - ClientError::SummaryOutputFileWriteFailed { - file_path: output_file.to_owned(), - source: e, - } - })?; - } - comment = Some(summary); - } if let Some(output_file) = &feedback_inputs.sarif_file { SarifLog::new( files, @@ -329,6 +303,8 @@ impl RestClient { ]; self.client.write_output_variables(&output_vars)?; + // Write the patch first, so the reports can point to it. + let mut review = None; if self.client.is_pr_event() && feedback_inputs.pr_review { let summary_only = ["true", "on", "1"].contains( &env::var("CPP_LINTER_PR_REVIEW_SUMMARY_ONLY") @@ -349,7 +325,52 @@ impl RestClient { )?; } self.show_patch(&feedback_inputs)?; + review = Some((review_comments, summary_only)); + } else if feedback_inputs.gen_patch { + for file in files { + let file = file + .lock() + .map_err(|e| ClientError::MutexPoisoned(e.to_string()))?; + file.maybe_append_patch(&feedback_inputs.repo_root, &feedback_inputs.patch_path)?; + } + self.show_patch(&feedback_inputs)?; + } + + // Only point to the patch once this run has written it (`fix-patch-path` names it). + let patch_exists = (feedback_inputs.gen_patch || feedback_inputs.pr_review) + && std::fs::metadata(&feedback_inputs.patch_path).is_ok_and(|meta| meta.len() > 0); + if feedback_inputs.step_summary || feedback_inputs.summary_output_file.is_some() { + let summary = Self::make_comment( + files, + format_checks_failed, + tidy_checks_failed, + &clang_versions, + None, + patch_exists, + format_run, + )?; + if feedback_inputs.step_summary { + self.client.append_step_summary(&summary)?; + } + if let Some(output_file) = &feedback_inputs.summary_output_file { + if let Some(parent) = output_file.parent() { + std::fs::create_dir_all(parent).map_err(|e| ClientError::MkDirFailed { + file_path: output_file.clone(), + source: e, + })?; + } + std::fs::write(output_file, &summary).map_err(|e| { + ClientError::SummaryOutputFileWriteFailed { + file_path: output_file.to_owned(), + source: e, + } + })?; + } + comment = Some(summary); + } + // Post the review after the summary, so a failed review does not lose the summary. + if let Some((review_comments, summary_only)) = review { if self.client.is_pr_same_remote() { let mut options = ReviewOptions { marker: COMMENT_MARKER.to_string(), @@ -369,6 +390,7 @@ impl RestClient { let total_review_comments = options.comments.len() as u32; self.client.cull_pr_reviews(&mut options).await?; let has_changes = review_comments.tool_total > 0 + || review_comments.has_errors || !review_comments.skipped_fixes.is_empty() || !review_comments.not_posted.is_empty(); let is_lgtm = options.comments.is_empty() && !has_changes; @@ -397,14 +419,6 @@ impl RestClient { } else { log::warn!("PR is from a different remote, skipping review."); } - } else if feedback_inputs.gen_patch { - for file in files { - let file = file - .lock() - .map_err(|e| ClientError::MutexPoisoned(e.to_string()))?; - file.maybe_append_patch(&feedback_inputs.repo_root, &feedback_inputs.patch_path)?; - } - self.show_patch(&feedback_inputs)?; } if feedback_inputs.thread_comments != ThreadComments::Off { @@ -421,7 +435,8 @@ impl RestClient { tidy_checks_failed, &clang_versions, Some(u16::MAX as u64), - feedback_inputs.gen_patch || feedback_inputs.pr_review, + patch_exists, + format_run, )?); } let options = ThreadCommentOptions { @@ -448,40 +463,29 @@ impl RestClient { /// Post file annotations. pub fn make_annotations( files: &[Arc>], - style: &str, + format_run: FormatRun<'_>, ) -> Result, ClientError> { - Self::build_annotations(files, style, false) + Self::build_annotations(files, format_run) } /// Make the file annotations for [`Self::make_annotations`]. /// - /// With `short_titles`, a title is only the name of the check - /// (`clang-format` or the clang-tidy diagnostic) instead of a sentence - /// that repeats the file name and line. + /// A title is only the name of the check (`clang-format` or the clang-tidy + /// diagnostic): GitHub (and a local run) already shows the file name and line + /// next to it. fn build_annotations( files: &[Arc>], - style: &str, - short_titles: bool, + format_run: FormatRun<'_>, ) -> Result, ClientError> { - let style_guide = summarize_style(style); + let style_description = describe_style(format_run.style); let mut annotations = vec![]; - // iterate over clang-format advice and post annotations for file in files { let file = file .lock() .map_err(|e| ClientError::MutexPoisoned(e.to_string()))?; + let name = file.name.to_string_lossy().replace('\\', "/"); if let Some(format_advice) = &file.format_advice { - // assemble a list of line numbers - let mut lines = Vec::new(); - for replacement in &format_advice.replacements { - for i in replacement.clone() { - if !lines.contains(&i) { - lines.push(i); - } - } - } - let name = file.name.to_string_lossy().replace('\\', "/"); if format_advice.failed { annotations.push(FileAnnotation { severity: AnnotationLevel::Warning, @@ -490,42 +494,59 @@ impl RestClient { end_line: None, start_column: None, end_column: None, - title: Some(if short_titles { - "clang-format".to_string() - } else { - format!("clang-format failed on {name}") - }), + title: Some("clang-format".to_string()), message: format!( "clang-format exited with an error for {name}, so its formatting was not checked. See the logs for details." ), }); } // post annotation if any applicable lines were formatted - if !lines.is_empty() { - let title = if short_titles { - "clang-format".to_string() - } else { - format!("Run clang-format on {name}") - }; - let message = format!( - "File {name} does not conform to {style_guide} style guidelines. (lines {line_set})", - line_set = lines - .iter() - .map(|val| val.to_string()) - .collect::>() - .join(","), - ); - let annotation = FileAnnotation { + // Anchor the annotation to the first added line that needs formatting + // (GitHub shows an annotation in the diff only on a line of the diff), + // or else to the first line that needs formatting. + let first_added_line = format_advice + .replacements + .iter() + .flat_map(|r| file.added_lines.iter().filter(|line| r.contains(line))) + .min() + .copied(); + if let Some(first_line) = first_added_line.or_else(|| { + format_advice + .replacements + .iter() + .filter(|r| !r.is_empty()) + .map(|r| *r.start()) + .min() + }) { + let lines = markdown::describe_lines(&format_advice.replacements); + let mut lines_chars = lines.chars(); + let lines = lines_chars + .next() + .map(|first| { + first.to_uppercase().collect::() + lines_chars.as_str() + }) + .unwrap_or_default(); + annotations.push(FileAnnotation { severity: AnnotationLevel::Notice, - path: name, - start_line: None, - end_line: None, + path: name.clone(), + start_line: Some(first_line as usize), + end_line: Some(first_line as usize), start_column: None, end_column: None, - title: Some(title), - message, - }; - annotations.push(annotation); + title: Some("clang-format".to_string()), + message: format!( + "{lines} {} not match {style_description}. Run: {}", + if lines.starts_with("Lines") { + "do" + } else { + "does" + }, + format_run.command([( + format_run.file_name(&name).as_str(), + format_advice.replacements.as_slice() + )]), + ), + }); } } // end format_advice iterations @@ -534,29 +555,20 @@ impl RestClient { // lines are already filter as specified to clang-tidy CLI. if let Some(tidy_advice) = &file.tidy_advice { for note in &tidy_advice.notes { - let path = file.name.to_string_lossy().replace('\\', "/"); - if note.filename == path { - let title = if short_titles { - note.diagnostic.clone() - } else { - format!( - "{}:{}:{} [{}]", - note.filename, note.line, note.cols, note.diagnostic - ) - }; + if note.filename == name { let annotation = FileAnnotation { severity: match note.severity.as_str() { "warning" => AnnotationLevel::Warning, "error" => AnnotationLevel::Error, _ => AnnotationLevel::Notice, // default to notice for all else }, - path, + path: name.clone(), // `line` is required to anchor the annotation to a line in the file start_line: Some(note.line as usize), end_line: Some(note.line as usize), start_column: Some(note.cols as usize), end_column: None, - title: Some(title), + title: Some(note.diagnostic.clone()), message: note.rationale.clone(), }; annotations.push(annotation); @@ -567,14 +579,18 @@ impl RestClient { Ok(annotations) } - /// Makes a comment in MarkDown syntax based on the concerns in `format_advice` and - /// `tidy_advice` about the given set of `files`. + /// Makes a comment in Markdown syntax about the concerns in `format_advice` and + /// `tidy_advice` of the given `files`. + /// + /// The same comment is used for the step summary and the thread comment: + /// a heading that states the result, a table with a row per clang tool, + /// the findings of each tool, and how to fix them. + /// With `max_len`, findings that do not fit are left out (and counted), + /// and so is the "How to fix" section. /// /// This method has a default definition and should not need to be redefined by /// implementors. - /// - /// Returns the markdown comment as a string as well as the total count of - /// `format_checks_failed` and `tidy_checks_failed` (in respective order). + #[allow(clippy::too_many_arguments)] fn make_comment( files: &[Arc>], format_checks_failed: u64, @@ -582,43 +598,19 @@ impl RestClient { clang_versions: &ClangVersions, max_len: Option, patch_exists: bool, + format_run: FormatRun<'_>, ) -> Result { - let mut comment = format!("{COMMENT_MARKER}# Cpp-Linter Report "); - let mut remaining_length = - max_len.unwrap_or(u64::MAX) - comment.len() as u64 - USER_OUTREACH.len() as u64; - - if format_checks_failed > 0 || tidy_checks_failed > 0 { - let prompt = ":warning:\nSome files did not pass the configured checks!\n"; - remaining_length -= prompt.len() as u64; - comment.push_str(prompt); - if format_checks_failed > 0 - && let Some(format_version) = &clang_versions.format_version - { - make_format_comment( - files, - &mut comment, - format_checks_failed, - &format_version.to_string(), - &mut remaining_length, - )?; - } - if tidy_checks_failed > 0 - && let Some(tidy_version) = &clang_versions.tidy_version - { - make_tidy_comment( - files, - &mut comment, - tidy_checks_failed, - &tidy_version.to_string(), - &mut remaining_length, - patch_exists, - )?; - } - } else { - comment.push_str(":heavy_check_mark:\nNo problems need attention."); - } - comment.push_str(USER_OUTREACH); - Ok(comment) + let findings = Findings::collect(files, format_run)?; + Ok(findings.to_markdown(&CommentContext { + total: format_checks_failed + tidy_checks_failed, + files_checked: files.len() as u64, + clang_versions, + max_len: max_len + .and_then(|len| usize::try_from(len).ok()) + .unwrap_or(usize::MAX), + patch_exists, + format_run, + })) } /// Show the generated patch content in the console output. @@ -678,131 +670,543 @@ impl RestClient { } /// A closing tag for details blocks in markdown comments. -const CLOSER: &str = "\n"; - -fn make_format_comment( - files: &[Arc>], - comment: &mut String, - format_checks_failed: u64, - version_used: &String, - remaining_length: &mut u64, -) -> Result<(), ClientError> { - let opener = format!( - "\n
clang-format (v{version_used}) reports: {format_checks_failed} file(s) not formatted\n\n", - ); - let mut format_comment = String::new(); - *remaining_length = remaining_length.saturating_sub(opener.len() as u64 + CLOSER.len() as u64); - for file in files { - let file = file - .lock() - .map_err(|e| ClientError::MutexPoisoned(e.to_string()))?; - if let Some(format_advice) = &file.format_advice - && format_advice.is_concern() - && *remaining_length > 0 - { - let name = file.name.to_string_lossy().replace('\\', "/"); - let note = if format_advice.failed { - format!("- {name} (clang-format failed to run; see the logs)\n") +const CLOSER: &str = "\n
\n"; + +/// Room kept at the end of a length-limited comment for what is added without +/// a size check: the wrappers of the clang-tidy and clang-format sections and +/// their notes about findings that were left out. +const OMITTED_RESERVE: usize = 600; + +/// The most files listed in one `clang-format -i` command of a comment. +const MAX_FILES_IN_COMMAND: usize = 50; + +/// The most clang-tidy findings listed in the prompt for an AI coding agent. +const MAX_NOTES_IN_PROMPT: usize = 50; + +/// How clang-format ran in this check, to tell the user how to run it the same way. +#[derive(Debug, Clone, Copy)] +pub struct FormatRun<'a> { + /// The `--style` given to clang-format. + pub style: &'a str, + /// Whether clang-format only checked some lines (see `--lines-changed-only`). + /// + /// Then a command to fix the formatting must not format the whole file; + /// it passes the lines that need formatting with `--lines`. + pub lines_only: bool, + /// Where `--repo-root` is in the git repository (empty when it is the repository root). + /// + /// File names in a report are relative to the repository root, so that the commands + /// in it can be run there. + pub path_prefix: &'a Path, +} + +impl<'a> From<&'a str> for FormatRun<'a> { + /// clang-format checked whole files with the given `--style`. + fn from(style: &'a str) -> Self { + Self { + style, + lines_only: false, + path_prefix: Path::new(""), + } + } +} + +impl FormatRun<'_> { + /// The name of a file as a report shows it: relative to the repository root. + fn file_name(&self, name: &str) -> String { + prefix_feedback_path(name, self.path_prefix) + } +} + +impl FormatRun<'_> { + /// The `clang-format` command(s) that fix the formatting of the given files in place: + /// one command for all files, or one command per file with its `--lines`. + fn command<'f>( + &self, + files: impl IntoIterator])>, + ) -> String { + let style = match self.style { + "" => String::from("file"), + // a relative path to a style file is relative to `--repo-root` + style => match style.strip_prefix("file:") { + Some(path) if Path::new(path).is_relative() => { + format!("file:{}", self.file_name(path)) + } + _ => style.to_string(), + }, + }; + let base = format!( + "clang-format -i {}", + markdown::shell_quote(&format!("--style={style}")) + ); + let mut whole_files = base.clone(); + let mut commands = vec![]; + for (file, lines) in files { + if self.lines_only { + let mut command = base.clone(); + for (start, end) in markdown::join_ranges(lines) { + command.push_str(&format!(" --lines={start}:{end}")); + } + command.push(' '); + command.push_str(&markdown::shell_quote(file)); + commands.push(command); } else { - let line_count = format_advice - .replacements - .iter() - .fold(0, |acc, r| acc + r.clone().count()); - format!( - "- {name} ({line_count} line{})\n", - if line_count > 1 { "s" } else { "" } - ) - }; - if (note.len() as u64) < *remaining_length { - format_comment.push_str(¬e.to_string()); - *remaining_length -= note.len() as u64; + whole_files.push(' '); + whole_files.push_str(&markdown::shell_quote(file)); } } + if self.lines_only { + commands.join("\n") + } else { + whole_files + } } - comment.push_str(&opener); - comment.push_str(&format_comment); - comment.push_str(CLOSER); - Ok(()) } -const TIDY_FIX_EXPLANATION: &str = "\n\n[^1]: Cpp-linter generates a patch with fixes from both clang-tidy and clang-format. In the CI workflow, the patch can be found using cpp-linter's output `fix-patch-path`."; - -fn make_tidy_comment( - files: &[Arc>], - comment: &mut String, - tidy_checks_failed: u64, - version_used: &String, - remaining_length: &mut u64, +/// What [`Findings::to_markdown`] needs to know besides the findings. +struct CommentContext<'a> { + /// The count of failed checks (files not formatted plus clang-tidy notes). + total: u64, + /// The count of files that were checked. + files_checked: u64, + clang_versions: &'a ClangVersions, + /// The longest comment allowed (in bytes). + max_len: usize, + /// Whether a patch file of fixes was written (see `fix-patch-path`). patch_exists: bool, -) -> Result<(), ClientError> { - let opener = format!( - "\n
clang-tidy (v{version_used}) reports: {tidy_checks_failed} concern(s)\n\n" - ); - let mut show_fix_explanation = false; - let mut tidy_comment = String::new(); - *remaining_length = remaining_length.saturating_sub(opener.len() as u64 + CLOSER.len() as u64); - for file in files { - let file = file - .lock() - .map_err(|e| ClientError::MutexPoisoned(e.to_string()))?; - if let Some(tidy_advice) = &file.tidy_advice { - for tidy_note in &tidy_advice.notes { - let file_path = PathBuf::from(&tidy_note.filename); - if file_path == file.name { - let uses_auto_fix = !tidy_note.fixed_lines.is_empty() && patch_exists; - let mut tmp_note = format!("- {}\n\n", tidy_note.filename); - tmp_note.push_str(&format!( - " {filename}:{line}:{cols}: {severity}: [{diagnostic}]{auto_fixable}{skipped_fixes}\n > {rationale}\n{concerned_code}", - filename = tidy_note.filename, - line = tidy_note.line, - cols = tidy_note.cols, - severity = tidy_note.severity, - diagnostic = tidy_note.diagnostic_link(), - auto_fixable = if uses_auto_fix { - "\n :zap: auto-fix included in generated patch[^1]" - } else { - "" - }, - skipped_fixes = tidy_note - .skipped_fixes - .iter() - .map(|skipped| format!("\n :warning: {}", skipped.describe())) - .collect::(), - rationale = tidy_note.rationale, - concerned_code = if tidy_note.suggestion.is_empty() {String::from("")} else { - format!("\n ```{ext}\n {suggestion}\n ```\n", - ext = file_path.extension().unwrap_or_default().to_string_lossy(), - suggestion = tidy_note.suggestion.join("\n "), - ).to_string() - }, - ).to_string()); - - let note_len = tmp_note.len() as u64 - + if uses_auto_fix && !show_fix_explanation { - TIDY_FIX_EXPLANATION.len() as u64 - } else { - 0 - }; + /// How clang-format ran. + format_run: FormatRun<'a>, +} - if note_len < *remaining_length { - tidy_comment.push_str(&tmp_note); - *remaining_length -= tmp_note.len() as u64; - if !show_fix_explanation && uses_auto_fix { - *remaining_length -= TIDY_FIX_EXPLANATION.len() as u64; - show_fix_explanation = true; - } - } +/// The findings about one file, for a thread comment or step summary. +struct FileFindings { + name: String, + /// clang-format failed to run on this file. + format_failed: bool, + /// The lines that clang-format would change. + format_lines: Vec>, + /// The clang-tidy notes about this file. + tidy_notes: Vec, +} + +impl FileFindings { + /// The file name for a list item or a table: in a code span, if it can be. + fn display_name(&self) -> String { + if self.name.contains('`') { + markdown::escape(&self.name) + } else { + format!("`{}`", self.name) + } + } +} + +/// The findings about all files that have some. +struct Findings(Vec); + +impl Findings { + fn collect(files: &[Arc>], format_run: FormatRun) -> Result { + let mut findings = vec![]; + for file in files { + let file = file + .lock() + .map_err(|e| ClientError::MutexPoisoned(e.to_string()))?; + let format_advice = file + .format_advice + .as_ref() + .filter(|advice| advice.is_concern()); + let tidy_notes = file + .tidy_advice + .as_ref() + .map(|advice| { + advice + .notes + .iter() + .filter(|note| Path::new(¬e.filename) == file.name.as_path()) + .cloned() + .collect::>() + }) + .unwrap_or_default(); + if format_advice.is_none() && tidy_notes.is_empty() { + continue; + } + findings.push(FileFindings { + name: format_run.file_name(&file.name.to_string_lossy()), + format_failed: format_advice.is_some_and(|advice| advice.failed), + format_lines: format_advice + .map(|advice| advice.replacements.clone()) + .unwrap_or_default(), + tidy_notes, + }); + } + Ok(Self(findings)) + } + + fn tidy_notes(&self) -> impl Iterator { + self.0 + .iter() + .flat_map(|file| file.tidy_notes.iter().map(move |note| (file, note))) + } + + /// Describe the clang-tidy notes in a few words: `1 error, 2 warnings, 1 fixable`. + /// + /// Also returns the status of the clang-tidy check. + fn tidy_result(&self) -> (Status, String) { + let (mut errors, mut warnings, mut others, mut fixable) = (0, 0, 0, 0); + for (_, note) in self.tidy_notes() { + match note.severity.as_str() { + "error" => errors += 1, + "warning" => warnings += 1, + _ => others += 1, + } + if !note.fixed_lines.is_empty() { + fixable += 1; + } + } + let counts = [(errors, "error"), (warnings, "warning"), (others, "note")] + .into_iter() + .filter(|(count, _)| *count > 0) + .map(|(count, noun)| plural(count, noun)) + .collect::>(); + if counts.is_empty() { + return (Status::Passed, String::from("no findings")); + } + let mut result = counts.join(", "); + if fixable > 0 { + result.push_str(&format!(", {fixable} fixable")); + } + let status = if errors > 0 { + Status::Failed + } else { + Status::Warned + }; + (status, result) + } + + /// Describe the clang-format findings in a few words: `1 file needs formatting`. + /// + /// Also returns the status of the clang-format check. + fn format_result(&self) -> (Status, String) { + let unformatted = self + .0 + .iter() + .filter(|file| !file.format_lines.is_empty()) + .count() as u64; + let failed = self.0.iter().filter(|file| file.format_failed).count() as u64; + let mut parts = vec![]; + if unformatted > 0 { + parts.push(format!( + "{} formatting", + if unformatted == 1 { + String::from("1 file needs") + } else { + format!("{unformatted} files need") + } + )); + } + if failed > 0 { + parts.push(format!("clang-format failed on {}", plural(failed, "file"))); + } + let status = if failed > 0 { + Status::Failed + } else if unformatted > 0 { + Status::Warned + } else { + return (Status::Passed, String::from("all files formatted")); + }; + (status, parts.join(", ")) + } + + fn to_markdown(&self, ctx: &CommentContext) -> String { + let fits = + |len: usize| len.saturating_add(USER_OUTREACH.len() + OMITTED_RESERVE) <= ctx.max_len; + let mut comment = String::from(COMMENT_MARKER); + let versions = [ + ("clang-format", ctx.clang_versions.format_version.as_ref()), + ("clang-tidy", ctx.clang_versions.tidy_version.as_ref()), + ]; + + if ctx.total == 0 { + comment.push_str(&format!( + "## {} cpp-linter passed\n\n", + Status::Passed.mark() + )); + let mut details = versions + .iter() + .filter_map(|(tool, version)| version.map(|ver| format!("{tool} {ver}"))) + .collect::>(); + details.push(format!("{} checked", plural(ctx.files_checked, "file"))); + comment.push_str(&details.join(", ")); + comment.push_str(USER_OUTREACH); + return comment; + } + + let (format_status, format_result) = self.format_result(); + let (tidy_status, tidy_result) = self.tidy_result(); + let status = if format_status == Status::Failed || tidy_status == Status::Failed { + Status::Failed + } else { + Status::Warned + }; + comment.push_str(&format!( + "## {} cpp-linter found {} in {}\n\n| Tool | Result |\n|:--|:--|\n", + status.mark(), + plural(ctx.total, "issue"), + plural(self.0.len() as u64, "file"), + )); + for ((tool, version), (row_status, result)) in versions.iter().zip([ + (format_status, format_result.as_str()), + (tidy_status, tidy_result.as_str()), + ]) { + if let Some(version) = version { + comment.push_str(&format!( + "| {} **{tool}** {version} | {result} |\n", + row_status.small_mark() + )); + } + } + + // "How to fix" matters most when there are many findings, so room for it is kept + // before the findings are listed (if it fits at all). + let how_to_fix = self.how_to_fix(ctx); + let how_to_fix = if fits(comment.len() + how_to_fix.len()) { + how_to_fix + } else { + String::new() + }; + let fits_findings = |len: usize| fits(len + how_to_fix.len()); + // The reserve covers each section's wrapper and its "not shown" note. Below that + // (a limit barely larger than the heading), a section is left out entirely. + let within = + |len: usize| len.saturating_add(how_to_fix.len() + USER_OUTREACH.len()) <= ctx.max_len; + let before = comment.len(); + self.push_tidy_section(&mut comment, &tidy_result, fits_findings); + if !within(comment.len()) { + comment.truncate(before); + } + let before = comment.len(); + self.push_format_section(&mut comment, fits_findings); + if !within(comment.len()) { + comment.truncate(before); + } + comment.push_str(&how_to_fix); + comment.push_str(USER_OUTREACH); + comment + } + + /// 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(); + if count == 0 { + return; + } + // A short list is open, so nobody has to click to see it. + let open = if count <= 10 { " open" } else { "" }; + let mut section = + format!("\nclang-tidy: {summary}\n"); + let mut omitted = 0; + for file in &self.0 { + let header = format!( + "\n**{}**\n\n| Line | Finding |\n|--:|:--|\n", + file.display_name() + ); + let mut rows = String::new(); + for note in &file.tidy_notes { + let severity = match note.severity.as_str() { + "warning" => String::new(), + other => format!("**{other}:** "), + }; + let fixable = if note.fixed_lines.is_empty() { + "" + } else { + " (fixable)" + }; + let skipped = note + .skipped_fixes + .iter() + .map(|skipped| { + format!( + "
{} {}", + Status::Warned.small_mark(), + // a `|` ends the table cell, even in a code span + skipped.describe().replace('|', "\\|") + ) + }) + .collect::(); + let row = format!( + "| {} | {severity}{}{fixable}
{}{skipped} |\n", + note.line, + markdown::escape(¬e.rationale), + note.diagnostic_link(), + ); + if omitted == 0 + && fits( + comment.len() + + section.len() + + header.len() + + rows.len() + + row.len() + + CLOSER.len(), + ) + { + rows.push_str(&row); + } else { + omitted += 1; } } + if !rows.is_empty() { + section.push_str(&header); + section.push_str(&rows); + } + } + if omitted > 0 { + section.push_str(&Self::omitted_note(omitted)); + } + section.push_str(CLOSER); + comment.push_str(§ion); + } + + /// Append the files that clang-format would change to the `comment`. + fn push_format_section(&self, comment: &mut String, fits: impl Fn(usize) -> bool) { + let files = self + .0 + .iter() + .filter(|file| file.format_failed || !file.format_lines.is_empty()) + .collect::>(); + if files.is_empty() { + return; + } + let mut section = format!( + "\n
clang-format: {}\n\n", + plural(files.len() as u64, "file") + ); + let mut omitted = 0; + for file in files { + let item = if file.format_lines.is_empty() { + format!( + "- {}: clang-format failed to run; see the logs\n", + file.display_name() + ) + } else { + format!( + "- {}, {}\n", + file.display_name(), + markdown::describe_lines(&file.format_lines) + ) + }; + if omitted == 0 && fits(comment.len() + section.len() + item.len() + CLOSER.len()) { + section.push_str(&item); + } else { + omitted += 1; + } } + if omitted > 0 { + section.push_str(&Self::omitted_note(omitted)); + } + section.push_str(CLOSER); + comment.push_str(§ion); + } + + /// The sentence about findings that a length-limited comment left out. + fn omitted_note(omitted: u64) -> String { + format!( + "\n{} not shown here because the comment would be too long. The workflow log lists every finding.\n", + if omitted == 1 { + String::from("1 more is") + } else { + format!("{omitted} more are") + } + ) } - comment.push_str(&opener); - comment.push_str(&tidy_comment); - comment.push_str(CLOSER); - if show_fix_explanation { - comment.push_str(TIDY_FIX_EXPLANATION); + + /// The "How to fix" section: a command for clang-format, the patch of all fixes, + /// and a prompt for an AI coding agent about the clang-tidy notes. + /// + /// Returns an empty string if there is nothing to say. + fn how_to_fix(&self, ctx: &CommentContext) -> String { + let mut parts = vec![]; + let unformatted = self + .0 + .iter() + .filter(|file| !file.format_lines.is_empty()) + .map(|file| (file.name.as_str(), file.format_lines.as_slice())) + .collect::>(); + if !unformatted.is_empty() { + let with_version = ctx + .clang_versions + .format_version + .as_ref() + .map(|version| format!(" with clang-format {}", version.major)) + .unwrap_or_default(); + let scope = if ctx.format_run.lines_only { + "the listed lines" + } else { + "these files" + }; + let mut part = format!( + "From the repository root, format {scope}{with_version}:\n\n{}", + markdown::fenced( + "bash", + &ctx.format_run + .command(unformatted.iter().take(MAX_FILES_IN_COMMAND).copied()) + ) + ); + if unformatted.len() > MAX_FILES_IN_COMMAND { + part.push_str(&format!( + "\nThis covers the first {MAX_FILES_IN_COMMAND} of {} files.\n", + unformatted.len() + )); + } + parts.push(part); + } + if ctx.patch_exists { + // The patch also has the formatting, so it is another way to do the step above. + let lead = if parts.is_empty() { + "Apply" + } else { + "Or apply" + }; + parts.push(format!( + "{lead} every fix at once: this step's `fix-patch-path` output is a patch for `git apply`.\n", + )); + } + let notes = self.tidy_notes().collect::>(); + if !notes.is_empty() { + let mut prompt = String::from("Fix these clang-tidy findings:\n"); + for (file, note) in notes.iter().take(MAX_NOTES_IN_PROMPT) { + prompt.push_str(&format!( + "- {}:{}:{}: {}: {} [{}]\n", + file.name, + note.line, + note.cols, + note.severity, + note.rationale.replace(['\r', '\n'], " "), + note.diagnostic + )); + } + let mut part = format!( + "For the clang-tidy findings, give this to your coding agent:\n\n{}", + markdown::fenced("text", &prompt) + ); + if notes.len() > MAX_NOTES_IN_PROMPT { + part.push_str(&format!( + "\nThis covers the first {MAX_NOTES_IN_PROMPT} of {} findings. \ + The workflow log lists every finding.\n", + notes.len() + )); + } + parts.push(part); + } + if parts.is_empty() { + return String::new(); + } + let mut section = String::from("\n
How to fix\n"); + for part in parts { + section.push('\n'); + section.push_str(&part); + } + section.push_str(CLOSER); + section } - Ok(()) } #[cfg(all(test, feature = "bin"))] @@ -813,7 +1217,8 @@ mod test { default::Default, env, io::Read, - path::PathBuf, + ops::RangeInclusive, + path::{Path, PathBuf}, sync::{Arc, Mutex}, }; @@ -824,8 +1229,8 @@ mod test { use git_bot_feedback::{AnnotationLevel, FileAnnotation, FileFilter}; use super::{ - RestClient, USER_OUTREACH, annotation_cap_message, normalize_changed_file_name, - prefix_feedback_path, repo_root_prefix, + FileFindings, Findings, FormatRun, RestClient, USER_OUTREACH, annotation_cap_message, + normalize_changed_file_name, prefix_feedback_path, repo_root_prefix, }; use crate::{ clang_tools::{ @@ -836,6 +1241,7 @@ mod test { cli::{FeedbackInput, ThreadComments}, common_fs::FileObj, error::ClientError, + markdown::Status, }; use clang_tools_manager::logger::try_init_logger; @@ -951,7 +1357,8 @@ mod test { #[tokio::test] async fn check_comment_concerns() { let (comment, gh_out) = create_comment(false).await; - assert!(&comment.contains(":warning:\nSome files did not pass the configured checks!\n")); + assert!(comment.contains(" cpp-linter found "), "{comment}"); + assert!(comment.contains("How to fix"), "{comment}"); let fmt_pattern = Regex::new(r"clang-format-checks-failed=(\d+)\n").unwrap(); let tidy_pattern = Regex::new(r"clang-tidy-checks-failed=(\d+)\n").unwrap(); for pattern in [fmt_pattern, tidy_pattern] { @@ -973,7 +1380,8 @@ mod test { env::set_var("ACTIONS_STEP_DEBUG", "true"); } let (comment, gh_out) = create_comment(true).await; - assert!(comment.contains(":heavy_check_mark:\nNo problems need attention.")); + assert!(comment.contains(" cpp-linter passed\n"), "{comment}"); + assert!(comment.contains(" files checked"), "{comment}"); assert_eq!( gh_out, "checks-failed=0\nclang-format-checks-failed=0\nclang-tidy-checks-failed=0\n" @@ -1006,6 +1414,85 @@ mod test { vec![Arc::new(Mutex::new(file))] } + /// With `--repo-root` in a subdirectory, file names and commands are relative + /// to the repository root, where the comment says to run them. + #[test] + fn comment_names_files_from_the_repository_root() { + let files = make_dummy_files("warning"); + let format_run = FormatRun { + style: "file", + lines_only: false, + path_prefix: Path::new("member"), + }; + let comment = + RestClient::make_comment(&files, 1, 1, &dummy_versions(), None, false, format_run) + .unwrap(); + assert!( + comment.contains("**`member/tests/demo/demo.cpp`**"), + "{comment}" + ); + assert!( + comment.contains("- `member/tests/demo/demo.cpp`, lines 1-2"), + "{comment}" + ); + assert!( + comment.contains("clang-format -i --style=file member/tests/demo/demo.cpp\n"), + "{comment}" + ); + assert!( + comment.contains("- member/tests/demo/demo.cpp:1:1: warning:"), + "{comment}" + ); + assert!(!comment.contains(" tests/demo/demo.cpp"), "{comment}"); + + // a style file given relative to `--repo-root` + let lines = [RangeInclusive::new(1, 2)]; + let style_file = FormatRun { + style: "file:config/.clang-format", + ..format_run + }; + assert_eq!( + style_file.command([("a.cpp", &lines[..])]), + "clang-format -i --style=file:member/config/.clang-format a.cpp" + ); + let absolute = FormatRun { + style: "file:/etc/.clang-format", + ..format_run + }; + assert_eq!( + absolute.command([("a.cpp", &lines[..])]), + "clang-format -i --style=file:/etc/.clang-format a.cpp" + ); + + let annotations = RestClient::build_annotations(&files, format_run).unwrap(); + let format_annotation = annotations + .iter() + .find(|a| a.title.as_deref() == Some("clang-format")) + .unwrap(); + assert!( + format_annotation + .message + .ends_with("Run: clang-format -i --style=file member/tests/demo/demo.cpp"), + "{}", + format_annotation.message + ); + } + + #[test] + fn skipped_fix_with_pipe_stays_in_its_cell() { + let files = make_dummy_files("warning"); + files[0].lock().unwrap().tidy_advice.as_mut().unwrap().notes[0] + .skipped_fixes + .push(SkippedFix { + file: "a|b.h".to_string(), + reason: "it is not one of the analyzed files".to_string(), + }); + let comment = + RestClient::make_comment(&files, 0, 1, &dummy_versions(), None, false, "file".into()) + .unwrap(); + assert!(comment.contains("`a\\|b.h`"), "{comment}"); + } + #[test] fn tidy_comment_with_skipped_fixes() { let files = make_dummy_files("warning"); @@ -1017,21 +1504,27 @@ mod test { reason: "it is not one of the analyzed files".to_string(), }); } - let mut comment = String::new(); - let mut remaining_length = u64::from(u16::MAX); - super::make_tidy_comment( - &files, - &mut comment, - 1, - &"1.2.3".to_string(), - &mut remaining_length, - true, - ) - .unwrap(); - assert!(comment.contains( - "auto-fix included in generated patch[^1]\n :warning: Part of this fix was not \ - applied to `tests/demo/demo.hpp` because it is not one of the analyzed files.\n > " - )); + let comment = + RestClient::make_comment(&files, 0, 1, &dummy_versions(), None, true, "file".into()) + .unwrap(); + assert!( + comment.contains( + " (fixable)
clang-diagnostic-error
\"⚠\" \ + Part of this fix was not \ + applied to `tests/demo/demo.hpp` because it is not one of the analyzed files. |\n" + ), + "{comment}" + ); + assert!( + comment.contains("Or apply every fix at once: this step's `fix-patch-path`"), + "{comment}" + ); + // The prompt is for the clang-tidy findings, not another way to do the formatting. + assert!( + comment.contains("\nFor the clang-tidy findings, give this to your coding agent:"), + "{comment}" + ); } fn dummy_versions() -> ClangVersions { @@ -1096,13 +1589,15 @@ mod test { #[test] fn annotation_severity() { - let annotations = RestClient::make_annotations(&make_dummy_files("error"), "llvm").unwrap(); + let annotations = + RestClient::make_annotations(&make_dummy_files("error"), "llvm".into()).unwrap(); assert!( annotations .iter() .any(|a| matches!(a.severity, AnnotationLevel::Error)) ); - let annotations = RestClient::make_annotations(&make_dummy_files("note"), "llvm").unwrap(); + let annotations = + RestClient::make_annotations(&make_dummy_files("note"), "llvm".into()).unwrap(); // both the clang-format and clang-tidy annotations are notices assert_eq!(annotations.len(), 2); assert!( @@ -1115,17 +1610,14 @@ mod test { #[test] fn tidy_annotation_points_to_line() { let annotations = - RestClient::make_annotations(&make_dummy_files("warning"), "llvm").unwrap(); + RestClient::make_annotations(&make_dummy_files("warning"), "llvm".into()).unwrap(); let tidy = annotations .iter() .find(|a| matches!(a.severity, AnnotationLevel::Warning)) .unwrap(); assert_eq!(tidy.start_line, Some(1)); assert_eq!(tidy.start_column, Some(1)); - assert_eq!( - tidy.title.as_deref(), - Some("tests/demo/demo.cpp:1:1 [clang-diagnostic-error]") - ); + assert_eq!(tidy.title.as_deref(), Some("clang-diagnostic-error")); assert!( tidy.fmt_github() .starts_with("::warning file=tests/demo/demo.cpp,line=1,col=1,") @@ -1135,7 +1627,7 @@ mod test { #[test] fn short_annotation_titles() { let files = make_dummy_files("warning"); - let annotations = RestClient::build_annotations(&files, "llvm", true).unwrap(); + let annotations = RestClient::build_annotations(&files, "llvm".into()).unwrap(); let titles = annotations .iter() .map(|a| a.title.as_deref().unwrap()) @@ -1148,10 +1640,109 @@ mod test { failed: true, ..Default::default() }); - let annotations = RestClient::build_annotations(&[file], "llvm", true).unwrap(); + let annotations = RestClient::build_annotations(&[file], "llvm".into()).unwrap(); assert_eq!(annotations[0].title.as_deref(), Some("clang-format")); } + #[test] + fn format_annotation_points_to_first_line() { + let file = FileObj::new(PathBuf::from("src/demo.cpp")); + let file = Arc::new(Mutex::new(file)); + file.lock().unwrap().format_advice = Some(FormatAdvice { + replacements: vec![20..=20, 3..=5, 6..=11], + ..Default::default() + }); + let annotations = + RestClient::build_annotations(std::slice::from_ref(&file), "file".into()).unwrap(); + assert_eq!(annotations[0].start_line, Some(3)); + assert_eq!( + annotations[0].message, + "Lines 3-11, 20 do not match the style in .clang-format. \ + Run: clang-format -i --style=file src/demo.cpp" + ); + file.lock().unwrap().format_advice = Some(FormatAdvice { + replacements: vec![RangeInclusive::new(4, 4)], + ..Default::default() + }); + let annotations = + RestClient::build_annotations(&[file], "{BasedOnStyle: llvm}".into()).unwrap(); + assert_eq!( + annotations[0].message, + "Line 4 does not match the configured style. \ + Run: clang-format -i '--style={BasedOnStyle: llvm}' src/demo.cpp" + ); + } + + /// When clang-format only checked the changed lines, the annotation sits on the + /// first added line that needs formatting, and its command formats only those lines. + #[test] + fn format_annotation_for_changed_lines() { + let mut file = FileObj::new(PathBuf::from("src/demo.cpp")); + file.added_lines = vec![12, 13]; + file.format_advice = Some(FormatAdvice { + replacements: vec![10..=12, 20..=21], + ..Default::default() + }); + let format_run = FormatRun { + style: "file", + lines_only: true, + path_prefix: Path::new(""), + }; + let annotations = + RestClient::build_annotations(&[Arc::new(Mutex::new(file))], format_run).unwrap(); + assert_eq!(annotations[0].start_line, Some(12)); + assert_eq!( + annotations[0].message, + "Lines 10-12, 20-21 do not match the style in .clang-format. \ + Run: clang-format -i --style=file --lines=10:12 --lines=20:21 src/demo.cpp" + ); + } + + #[test] + fn format_commands() { + let lines = [1..=2, 3..=3]; + let files = [("a.cpp", &lines[..]), ("b c.cpp", &lines[..1])]; + let whole = FormatRun::from("llvm"); + assert_eq!( + whole.command(files), + "clang-format -i --style=llvm a.cpp 'b c.cpp'" + ); + let scoped = FormatRun { + style: "llvm", + lines_only: true, + path_prefix: Path::new(""), + }; + assert_eq!( + scoped.command(files), + "clang-format -i --style=llvm --lines=1:3 a.cpp\n\ + clang-format -i --style=llvm --lines=1:2 'b c.cpp'" + ); + // no style given: clang-format looks for a .clang-format file + assert_eq!( + FormatRun::from("").command([("a.cpp", &lines[..])]), + "clang-format -i --style=file a.cpp" + ); + } + + #[test] + fn findings_without_formatting() { + let findings = Findings(vec![FileFindings { + name: String::from("odd`name.cpp"), + format_failed: false, + format_lines: vec![], + tidy_notes: vec![], + }]); + // 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"); + assert_eq!( + findings.format_result(), + (Status::Passed, String::from("all files formatted")) + ); + let mut comment = String::from("heading\n"); + findings.push_format_section(&mut comment, |_| true); + assert_eq!(comment, "heading\n"); + } + #[test] fn format_failure_feedback() { let file = FileObj::new(PathBuf::from("tests/demo/demo.cpp")); @@ -1161,27 +1752,56 @@ mod test { ..Default::default() }); let files = vec![file]; - let annotations = RestClient::make_annotations(&files, "llvm").unwrap(); + let annotations = RestClient::make_annotations(&files, "llvm".into()).unwrap(); assert_eq!(annotations.len(), 1); assert!(matches!(annotations[0].severity, AnnotationLevel::Warning)); - assert_eq!( - annotations[0].title.as_deref(), - Some("clang-format failed on tests/demo/demo.cpp") - ); + assert_eq!(annotations[0].title.as_deref(), Some("clang-format")); let comment = - RestClient::make_comment(&files, 1, 0, &dummy_versions(), None, false).unwrap(); + RestClient::make_comment(&files, 1, 0, &dummy_versions(), None, false, "llvm".into()) + .unwrap(); assert!( - comment.contains("- tests/demo/demo.cpp (clang-format failed to run; see the logs)") + comment.contains("- `tests/demo/demo.cpp`: clang-format failed to run; see the logs"), + "{comment}" ); + assert!(comment.contains("/m/hf.png"), "{comment}"); + assert!( + comment + .contains("/m/f.png\"> **clang-format** 1.2.3 | clang-format failed on 1 file |"), + "{comment}" + ); + // nothing to format, so no "How to fix" + assert!(!comment.contains("How to fix"), "{comment}"); } #[test] fn comment_without_tidy_concerns() { let files = make_dummy_files("warning"); + files[0].lock().unwrap().tidy_advice = None; let comment = - RestClient::make_comment(&files, 1, 0, &dummy_versions(), None, false).unwrap(); - assert!(comment.contains("clang-format (v1.2.3) reports")); - assert!(!comment.contains("clang-tidy (v1.2.3) reports")); + RestClient::make_comment(&files, 1, 0, &dummy_versions(), None, false, "llvm".into()) + .unwrap(); + assert!( + comment.contains(" cpp-linter found 1 issue in 1 file\n"), + "{comment}" + ); + assert!( + comment.contains("/m/w.png\"> **clang-format** 1.2.3 | 1 file needs formatting |"), + "{comment}" + ); + assert!( + comment.contains("/m/p.png\"> **clang-tidy** 1.2.3 | no findings |"), + "{comment}" + ); + assert!( + comment.contains("- `tests/demo/demo.cpp`, lines 1-2\n"), + "{comment}" + ); + assert!(!comment.contains("clang-tidy"), "{comment}"); + assert!( + comment.contains("```bash\nclang-format -i --style=llvm tests/demo/demo.cpp\n```"), + "{comment}" + ); + assert!(!comment.contains("AI coding agent"), "{comment}"); } #[tokio::test] @@ -1257,28 +1877,130 @@ mod test { let files = make_dummy_files("warning"); crate::test_common::poison_mutex(&files[0]); // poisoned while making the clang-format comment - assert!(RestClient::make_comment(&files, 1, 1, &dummy_versions(), None, false).is_err()); + assert!( + RestClient::make_comment(&files, 1, 1, &dummy_versions(), None, false, "llvm".into()) + .is_err() + ); // poisoned while making the clang-tidy comment - assert!(RestClient::make_comment(&files, 0, 1, &dummy_versions(), None, false).is_err()); + assert!( + RestClient::make_comment(&files, 0, 1, &dummy_versions(), None, false, "llvm".into()) + .is_err() + ); } #[test] fn comment_too_long_for_tidy_note() { + let files = make_dummy_files("error"); + let unlimited = + RestClient::make_comment(&files, 1, 1, &dummy_versions(), None, false, "llvm".into()) + .unwrap(); + assert!(unlimited.contains("| 1 | **error:** A test dummy rationale")); + assert!(unlimited.contains("/m/hf.png"), "{unlimited}"); + assert!(unlimited.contains("How to fix")); + // No room for the clang-tidy note and the clang-format list. + let head = unlimited.find("\nHow to fix").unwrap() + - USER_OUTREACH.len(); + let max_len = head + how_to_fix_len + USER_OUTREACH.len() + super::OMITTED_RESERVE + 500; + assert!(max_len < unlimited.len()); let limited = RestClient::make_comment( &files, - 0, 1, + 21, &dummy_versions(), - Some(unlimited.len() as u64 - 1), + Some(max_len as u64), false, + "llvm".into(), ) .unwrap(); - assert!(!limited.contains("A test dummy rationale")); + assert!(limited.len() <= max_len); + assert!(limited.contains("How to fix"), "{limited}"); + assert!(limited.contains("more are not shown here"), "{limited}"); + } + + /// The prompt for an AI coding agent lists at most 50 findings. + #[test] + fn ai_prompt_is_capped() { + let files = make_dummy_files("warning"); + { + let mut file = files[0].lock().unwrap(); + let notes = &mut file.tidy_advice.as_mut().unwrap().notes; + let note = notes[0].clone(); + notes.extend(std::iter::repeat_n(note, 59)); + } + let comment = + RestClient::make_comment(&files, 1, 60, &dummy_versions(), None, false, "llvm".into()) + .unwrap(); + let prompt = &comment[comment.find("Fix these clang-tidy findings").unwrap()..]; + assert_eq!(prompt.matches("A test dummy rationale").count(), 50); + assert!( + prompt.contains("This covers the first 50 of 60 findings."), + "{prompt}" + ); + } + + /// A length-limited comment never grows past its limit, even when both + /// sections have to leave out their findings. + #[test] + fn comment_stays_within_its_limit() { + let files = make_dummy_files("warning"); + { + let mut file = files[0].lock().unwrap(); + let notes = &mut file.tidy_advice.as_mut().unwrap().notes; + let note = notes[0].clone(); + notes.extend(std::iter::repeat_n(note, 50)); + } + let unlimited = + RestClient::make_comment(&files, 1, 51, &dummy_versions(), None, true, "llvm".into()) + .unwrap(); + let head = unlimited.find("\n {max_len}", limited.len()); + } } // ************************* tests for GitHub's annotation limits @@ -1334,7 +2056,9 @@ mod test { "{msg}" ); assert!( - msg.ends_with("The thread comment lists every finding."), + msg.ends_with( + "The thread comment lists them, and the workflow log lists every finding." + ), "{msg}" ); diff --git a/cpp-linter/tests/code_quality_stdout.rs b/cpp-linter/tests/code_quality_stdout.rs index ea8f5abc..6a0309dc 100644 --- a/cpp-linter/tests/code_quality_stdout.rs +++ b/cpp-linter/tests/code_quality_stdout.rs @@ -54,7 +54,7 @@ fn code_quality_to_stdout_is_valid_json() { // logs, download progress bars (if clang tools were installed), // file annotations and the patch go to stderr assert!(stderr.contains("Code Quality report on stdout"), "{stderr}"); - assert!(stderr.contains("does not conform to"), "{stderr}"); + assert!(stderr.contains("not match the LLVM style"), "{stderr}"); assert!(stderr.contains("Generated patch content:"), "{stderr}"); assert!(!tmp.path().join("-").exists()); } diff --git a/cpp-linter/tests/comments.rs b/cpp-linter/tests/comments.rs index 4efe079a..b9e356f6 100644 --- a/cpp-linter/tests/comments.rs +++ b/cpp-linter/tests/comments.rs @@ -219,14 +219,11 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) { ); } - let new_comment_match = Matcher::Regex(format!( - "# Cpp-Linter Report :{}:", - if test_params.force_lgtm { - "heavy_check_mark" - } else { - "warning" - } - )); + let new_comment_match = Matcher::Regex(String::from(if test_params.force_lgtm { + "## \\\\\"✔\\\\\"[^]+> cpp-linter passed" + } else { + "## \\\\\"[⚠✖]\\\\\"[^]+> cpp-linter found " + })); let lgtm_allowed = !test_params.force_lgtm || !test_params.no_lgtm; @@ -354,6 +351,9 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) { .trim() .to_string() }); + let patch_written = patch_path_from_output + .as_deref() + .is_some_and(|p| fs::metadata(p).is_ok_and(|meta| meta.len() > 0)); if test_params.gen_patch && let patch_path_from_output = patch_path_from_output.unwrap() { @@ -377,6 +377,12 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) { let summary_content = std::fs::read_to_string(&summary_out_file_path).unwrap(); assert!(summary_content.contains(COMMENT_MARKER)); assert!(summary_content.contains(USER_OUTREACH)); + // the report points to the patch exactly when this run wrote one + assert_eq!( + summary_content.contains("`fix-patch-path`"), + patch_written, + "{summary_content}" + ); // verify the SARIF log has 1 result per clang-tidy concern let tidy_checks_failed = output_vars diff --git a/cpp-linter/tests/reviews.rs b/cpp-linter/tests/reviews.rs index 60850c0e..9baf8092 100644 --- a/cpp-linter/tests/reviews.rs +++ b/cpp-linter/tests/reviews.rs @@ -226,15 +226,15 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) -> // results can be non-deterministic because different clang-versions output different diagnostic/changes ".*" // match anything } else if test_params.force_lgtm { - ".*No concerns to report. Great job! :tada:.*" + ".*No issues in this diff.*" } else if test_params.summary_only { - ".*Click here for the full patch of fixes.*" + ".*The full patch of fixes.*" } else { - ".*Click here for a patch of fixes outside the diff.*" + ".*A patch of fixes outside the diff.*" } }; let review_summary = format!( - "{}## Cpp-linter Review{tool_summary}{}", + "{}## ]+> cpp-linter review{tool_summary}{}", regex::escape(format!("{}", COMMENT_MARKER.escape_default()).as_str()), regex::escape(format!("{}", USER_OUTREACH.escape_default()).as_str()), ); @@ -277,6 +277,8 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) -> format_ignore.push_str("|**/*.cpp|**/*.h"); tidy_ignore.push_str("|**/*.hpp"); } + let summary_dir = TempDir::new().unwrap(); + let summary_file = summary_dir.path().join("summary.md"); let mut args = vec![ "cpp-linter".to_string(), "-v=debug".to_string(), @@ -291,6 +293,7 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) -> format!("-p={}", tmp_dir.path().join("build").to_str().unwrap()), "-i=build/**".to_string(), format!("--repo-root={}", tmp_dir.path().to_str().unwrap()), + format!("--summary-output-file={}", summary_file.to_str().unwrap()), ]; if test_params.force_lgtm { if test_params.pr_review { @@ -318,6 +321,11 @@ async fn setup(lib_root: &Path, tmp_dir: &TempDir, test_params: &TestParams) -> for mock in mocks { mock.assert(); } + if !test_params.bad_pr_info { + // the summary is written even when the review could not be posted + let summary = std::fs::read_to_string(&summary_file).unwrap(); + assert!(summary.contains("cpp-linter"), "{summary}"); + } posted_review.lock().unwrap().take() } diff --git a/cpp-linter/tests/sarif_stdout.rs b/cpp-linter/tests/sarif_stdout.rs index c467f326..f3386e8c 100644 --- a/cpp-linter/tests/sarif_stdout.rs +++ b/cpp-linter/tests/sarif_stdout.rs @@ -48,7 +48,7 @@ fn sarif_to_stdout_is_valid_json() { // logs, download progress bars (if clang tools were installed), // file annotations (incl. clang-format's) and the patch go to stderr assert!(stderr.contains("Wrote SARIF log to stdout"), "{stderr}"); - assert!(stderr.contains("does not conform to"), "{stderr}"); + assert!(stderr.contains("not match the LLVM style"), "{stderr}"); assert!(stderr.contains("Generated patch content:"), "{stderr}"); assert!(!tmp.path().join("-").exists()); } diff --git a/cspell.config.yml b/cspell.config.yml index 27c1cc69..bf62518c 100644 --- a/cspell.config.yml +++ b/cspell.config.yml @@ -1,6 +1,7 @@ version: "0.2" language: en words: + - absmiddle - armv - bindgen - binstall diff --git a/docs/docs/images/annotations-diff-dark.png b/docs/docs/images/annotations-diff-dark.png index a3c88cd8..0d9addf7 100644 Binary files a/docs/docs/images/annotations-diff-dark.png and b/docs/docs/images/annotations-diff-dark.png differ diff --git a/docs/docs/images/annotations-diff-light.png b/docs/docs/images/annotations-diff-light.png index bd74413f..3ac8dc3c 100644 Binary files a/docs/docs/images/annotations-diff-light.png and b/docs/docs/images/annotations-diff-light.png differ diff --git a/docs/docs/images/annotations-summary-dark.png b/docs/docs/images/annotations-summary-dark.png index e57f3bbf..dd00098b 100644 Binary files a/docs/docs/images/annotations-summary-dark.png and b/docs/docs/images/annotations-summary-dark.png differ diff --git a/docs/docs/images/annotations-summary-light.png b/docs/docs/images/annotations-summary-light.png index 0ff11639..80286ab5 100644 Binary files a/docs/docs/images/annotations-summary-light.png and b/docs/docs/images/annotations-summary-light.png differ diff --git a/docs/docs/images/pr-review-dark.png b/docs/docs/images/pr-review-dark.png index 674eae81..28dd3143 100644 Binary files a/docs/docs/images/pr-review-dark.png and b/docs/docs/images/pr-review-dark.png differ diff --git a/docs/docs/images/pr-review-light.png b/docs/docs/images/pr-review-light.png index e6e6068b..65ed0603 100644 Binary files a/docs/docs/images/pr-review-light.png and b/docs/docs/images/pr-review-light.png differ diff --git a/docs/docs/images/thread-comment-dark.png b/docs/docs/images/thread-comment-dark.png index 880136e3..d7ca378d 100644 Binary files a/docs/docs/images/thread-comment-dark.png and b/docs/docs/images/thread-comment-dark.png differ diff --git a/docs/docs/images/thread-comment-light.png b/docs/docs/images/thread-comment-light.png index 3ad2730d..1137f95f 100644 Binary files a/docs/docs/images/thread-comment-light.png and b/docs/docs/images/thread-comment-light.png differ