diff --git a/clang-tools-manager/src/lib.rs b/clang-tools-manager/src/lib.rs index 71623f75..cd2ffb6c 100644 --- a/clang-tools-manager/src/lib.rs +++ b/clang-tools-manager/src/lib.rs @@ -25,6 +25,12 @@ pub use version::{ClangVersion, GetToolError, RequestedVersion, RequestedVersion mod progress_bar; pub use progress_bar::ProgressBar; +/// Should log messages and progress bars be written to stderr instead of stdout? +/// +/// This is set with `logger::set_log_to_stderr()` (requires the `bin` feature). +pub(crate) static LOG_TO_STDERR: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + pub mod logger; #[cfg(all(test, unix))] diff --git a/clang-tools-manager/src/logger.rs b/clang-tools-manager/src/logger.rs index 1ffa2319..4882240c 100644 --- a/clang-tools-manager/src/logger.rs +++ b/clang-tools-manager/src/logger.rs @@ -3,7 +3,8 @@ use std::{ env, - io::{Write, stdout}, + io::{Write, stderr, stdout}, + sync::atomic::Ordering, }; use clap::builder::{ @@ -26,60 +27,83 @@ pub const CLI_HELP_STYLE: Styles = Styles::styled() .context_value(Style::new().fg_color(Some(Color::Ansi(AnsiColor::Cyan)))) .invalid(Style::new().fg_color(Some(Color::Ansi(AnsiColor::BrightRed)))); +use crate::LOG_TO_STDERR; + #[derive(Default)] struct SimpleLogger; -impl SimpleLogger { - fn level_color(level: &Level) -> String { - let name = format!("{:>5}", level.as_str().to_uppercase()); - match level { - Level::Error => name.red().bold().to_string(), - Level::Warn => name.yellow().bold().to_string(), - Level::Info => name.green().bold().to_string(), - Level::Debug => name.blue().bold().to_string(), - Level::Trace => name.magenta().bold().to_string(), - } - } +/// Write all log messages (including log grouping commands) and +/// progress bars (see [`ProgressBar`](crate::ProgressBar)) to stderr instead of stdout. +/// +/// This is meant for local (non-CI) use, when stdout is kept for output +/// that other programs read, such as a SARIF log. +/// In CI, logs stay on stdout so that log grouping commands and log messages +/// are shown in order. +pub fn set_log_to_stderr(enabled: bool) { + LOG_TO_STDERR.store(enabled, Ordering::Relaxed); } -#[allow(clippy::expect_used)] -impl Log for SimpleLogger { - fn enabled(&self, metadata: &Metadata) -> bool { - metadata.level() <= log::max_level() - } +/// Are log messages written to stderr instead of stdout? +/// +/// See [`set_log_to_stderr()`]. +pub fn is_log_to_stderr() -> bool { + LOG_TO_STDERR.load(Ordering::Relaxed) +} - fn log(&self, record: &Record) { - let mut stdout = stdout().lock(); +impl SimpleLogger { + #[allow(clippy::expect_used)] + fn write_record(&self, out: &mut impl Write, record: &Record) { if record.target() == "CI_LOG_GROUPING" { // this log is meant to manipulate a CI workflow's log grouping - writeln!(stdout, "{}", record.args()).expect("Failed to write log command to stdout"); - stdout - .flush() - .expect("Failed to flush log command in stdout"); + writeln!(out, "{}", record.args()).expect("Failed to write log command"); + out.flush().expect("Failed to flush log command"); } else if self.enabled(record.metadata()) { let module = record.module_path(); if module.is_none_or(|v| v.starts_with("cpp_linter") || v.starts_with("clang_tools")) { writeln!( - stdout, + out, "[{}]: {}", Self::level_color(&record.level()), record.args() ) - .expect("Failed to write log message to stdout"); + .expect("Failed to write log message"); } else if let Some(module) = module { writeln!( - stdout, + out, "[{}]{{{}:{}}}: {}", Self::level_color(&record.level()), module, record.line().unwrap_or_default(), record.args() ) - .expect("Failed to write detailed log message to stdout"); + .expect("Failed to write detailed log message"); } - stdout - .flush() - .expect("Failed to flush log message in stdout"); + out.flush().expect("Failed to flush log message"); + } + } + + fn level_color(level: &Level) -> String { + let name = format!("{:>5}", level.as_str().to_uppercase()); + match level { + Level::Error => name.red().bold().to_string(), + Level::Warn => name.yellow().bold().to_string(), + Level::Info => name.green().bold().to_string(), + Level::Debug => name.blue().bold().to_string(), + Level::Trace => name.magenta().bold().to_string(), + } + } +} + +impl Log for SimpleLogger { + fn enabled(&self, metadata: &Metadata) -> bool { + metadata.level() <= log::max_level() + } + + fn log(&self, record: &Record) { + if is_log_to_stderr() { + self.write_record(&mut stderr().lock(), record); + } else { + self.write_record(&mut stdout().lock(), record); } } @@ -164,4 +188,28 @@ mod test { ); logger.flush(); } + + #[test] + fn records_to_stderr() { + super::set_log_to_stderr(true); + let logger = SimpleLogger; + let info = Record::builder() + .args(format_args!("written to stderr")) + .level(Level::Info) + .module_path(Some("cpp_linter")) + .build(); + logger.log(&info); + let group = Record::builder() + .args(format_args!("start_log_group: dummy")) + .target("CI_LOG_GROUPING") + .level(Level::Info) + .build(); + logger.log(&group); + super::set_log_to_stderr(false); + + // the same format is used for either stream + let mut out = Vec::new(); + logger.write_record(&mut out, &group); + assert_eq!(String::from_utf8(out).unwrap(), "start_log_group: dummy\n"); + } } diff --git a/clang-tools-manager/src/progress_bar.rs b/clang-tools-manager/src/progress_bar.rs index 2d338ea3..e9e1791a 100644 --- a/clang-tools-manager/src/progress_bar.rs +++ b/clang-tools-manager/src/progress_bar.rs @@ -1,8 +1,11 @@ use std::{ - io::{IsTerminal, Result, Write, stdout}, + io::{IsTerminal, Result, Write, stderr, stdout}, num::NonZero, + sync::atomic::Ordering, }; +use crate::LOG_TO_STDERR; + /// A simple progress bar implementation that supports both interactive and non-interactive terminals. pub struct ProgressBar { /// The `total` size of the task being tracked, if known. @@ -14,11 +17,11 @@ pub struct ProgressBar { /// This is primarily used for tracking how many times the progress has changed. /// When `total` is unknown, this is the only way to track progress, and it will be incremented on every update.. steps: u32, - /// A mutex lock on the stdout. + /// A mutex lock on the stdout (or stderr if log messages are written to stderr). /// /// Using this instead of `print!()` allows for faster writes to stdout and /// prevents other threads from interrupting the output of the progress bar. - stdout_handle: std::io::StdoutLock<'static>, + stdout_handle: Box, /// Is the terminal session interactive? is_interactive: bool, /// The leading prompt to display before the progress bar (e.g. "Downloading") @@ -51,8 +54,18 @@ impl ProgressBar { /// // stdout lock is released when `progress_bar` goes out of scope /// ``` pub fn new(total: Option>, prompt: &str) -> Self { - let stdout_handle = stdout().lock(); - let is_interactive = stdout_handle.is_terminal(); + // Follow the log messages, so the progress bar is not mixed into + // output that other programs read from stdout (like a SARIF log). + let (stdout_handle, is_interactive): (Box, bool) = + if LOG_TO_STDERR.load(Ordering::Relaxed) { + let handle = stderr().lock(); + let is_interactive = handle.is_terminal(); + (Box::new(handle), is_interactive) + } else { + let handle = stdout().lock(); + let is_interactive = handle.is_terminal(); + (Box::new(handle), is_interactive) + }; Self { total, current: 0, @@ -184,6 +197,16 @@ mod tests { progress_bar.finish().unwrap(); } + #[test] + fn to_stderr() { + crate::LOG_TO_STDERR.store(true, std::sync::atomic::Ordering::Relaxed); + let mut progress_bar = ProgressBar::new(Some(NonZero::new(2).unwrap()), "Processing"); + progress_bar.render().unwrap(); + progress_bar.inc(2).unwrap(); + progress_bar.finish().unwrap(); + crate::LOG_TO_STDERR.store(false, std::sync::atomic::Ordering::Relaxed); + } + #[test] fn interactive_with_total() { let mut progress_bar = ProgressBar::new(Some(NonZero::new(100).unwrap()), "Processing"); diff --git a/cpp-linter/src/cli/mod.rs b/cpp-linter/src/cli/mod.rs index 07c5f2b8..a1c032d1 100644 --- a/cpp-linter/src/cli/mod.rs +++ b/cpp-linter/src/cli/mod.rs @@ -139,6 +139,39 @@ pub struct GeneralOptions { )] pub verbosity: Verbosity, + /// Exit with code 1 when any check fails. + /// + /// By default, cpp-linter exits with code 0 even when checks fail, + /// and a CI workflow reads the `checks-failed` output variable instead. + /// Use this option when only the exit code is read, as in a shell script, + /// a git hook or a coding agent. + /// + /// This can also be enabled with the `CPP_LINTER_STRICT_EXIT` environment variable + /// (`PRE_COMMIT=1` has the same effect). + /// + /// Exit codes: + /// + /// - `0`: no check failed, or checks failed without this option. + /// - `1`: checks failed (with this option), or the run stopped on an error. + /// The `cpp-linter` executable prints the error on a line starting with `Error:`. + /// The Python and Node.js bindings raise it as an exception instead. + /// - `2`: the command line arguments are invalid. + #[cfg_attr( + feature = "bin", + arg( + short = 'S', + long, + env = "CPP_LINTER_STRICT_EXIT", + default_value_t = false, + default_missing_value = "true", + num_args = 0..=1, + action = ArgAction::Set, + value_parser = FalseyValueParser::new(), + help_heading = "General options", + ) + )] + pub strict: bool, + /// Whether to use the system's available package managers. /// /// By default, this matches the value of a CI environment variable. @@ -543,6 +576,9 @@ pub struct FeedbackOptions { /// format. /// /// A relative path is relative to the current working directory. + /// Use `-` to write the SARIF log to stdout instead of a file. + /// Outside CI, log messages (including file annotations) and the generated patch + /// then go to stderr, so stdout holds only the SARIF log. /// /// The SARIF file only includes clang-tidy diagnostics that are also /// reported in other forms of feedback. So, source filters like diff --git a/cpp-linter/src/cli/structs.rs b/cpp-linter/src/cli/structs.rs index dc1f8c27..6bae8af1 100644 --- a/cpp-linter/src/cli/structs.rs +++ b/cpp-linter/src/cli/structs.rs @@ -8,7 +8,7 @@ use clap::{ValueEnum, builder::PossibleValue}; #[cfg(feature = "bin")] use super::{Cli, convert_extra_arg_val, ignore_patterns}; -use crate::clang_tools::clang_tidy::CompilationUnit; +use crate::{clang_tools::clang_tidy::CompilationUnit, sarif::SarifLog}; use git_bot_feedback::FileFilter; @@ -374,11 +374,14 @@ impl From<&Cli> for FeedbackInput { .summary_output_file .as_deref() .map(absolute_or_given), - sarif_file: args - .feedback_options - .sarif_file - .as_deref() - .map(absolute_or_given), + sarif_file: args.feedback_options.sarif_file.as_deref().map(|path| { + // `-` means stdout, so it is not a path to make absolute. + if SarifLog::is_stdout(path) { + path.to_path_buf() + } else { + absolute_or_given(path) + } + }), gen_patch: args.feedback_options.gen_patch || args.feedback_options.gen_patch_path.is_some(), patch_path: match &args.feedback_options.gen_patch_path { diff --git a/cpp-linter/src/rest_client.rs b/cpp-linter/src/rest_client.rs index d7966580..30f57a72 100644 --- a/cpp-linter/src/rest_client.rs +++ b/cpp-linter/src/rest_client.rs @@ -2,7 +2,7 @@ use std::{ env, - io::{BufRead, Write, stdout}, + io::{BufRead, Write, stderr, stdout}, path::{Path, PathBuf}, sync::{Arc, Mutex}, }; @@ -188,7 +188,11 @@ impl RestClient { let mut comment = None; if feedback_inputs.file_annotations { - let mut annotations = Self::make_annotations(files, &feedback_inputs.style)?; + // 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)?; for annotation in &mut annotations { annotation.path = prefix_feedback_path(&annotation.path, &self.repo_root_prefix); } @@ -229,7 +233,11 @@ impl RestClient { &feedback_inputs.repo_root, )? .write(output_file)?; - log::info!("Wrote SARIF log to {}", output_file.to_string_lossy()); + if SarifLog::is_stdout(output_file) { + log::info!("Wrote SARIF log to stdout"); + } else { + log::info!("Wrote SARIF log to {}", output_file.to_string_lossy()); + } } let output_vars = [ OutputVariable { @@ -367,6 +375,19 @@ impl RestClient { pub fn make_annotations( files: &[Arc>], style: &str, + ) -> Result, ClientError> { + Self::build_annotations(files, style, false) + } + + /// 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. + fn build_annotations( + files: &[Arc>], + style: &str, + short_titles: bool, ) -> Result, ClientError> { let style_guide = summarize_style(style); let mut annotations = vec![]; @@ -395,7 +416,11 @@ impl RestClient { end_line: None, start_column: None, end_column: None, - title: Some(format!("clang-format failed on {name}")), + title: Some(if short_titles { + "clang-format".to_string() + } else { + format!("clang-format failed on {name}") + }), message: format!( "clang-format exited with an error for {name}, so its formatting was not checked. See the logs for details." ), @@ -403,7 +428,11 @@ impl RestClient { } // post annotation if any applicable lines were formatted if !lines.is_empty() { - let title = format!("Run clang-format on {name}"); + 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 @@ -433,10 +462,14 @@ impl RestClient { for note in &tidy_advice.notes { let path = file.name.to_string_lossy().replace('\\', "/"); if note.filename == path { - let title = format!( - "{}:{}:{} [{}]", - note.filename, note.line, note.cols, note.diagnostic - ); + let title = if short_titles { + note.diagnostic.clone() + } else { + format!( + "{}:{}:{} [{}]", + note.filename, note.line, note.cols, note.diagnostic + ) + }; let annotation = FileAnnotation { severity: match note.severity.as_str() { "warning" => AnnotationLevel::Warning, @@ -526,10 +559,18 @@ impl RestClient { }])?; log::info!("Generated patch content:"); - let stdout_handle = stdout(); let mut reader = std::io::BufReader::new(patch_file); let mut raw_line = Vec::new(); - let mut stdout_lock = stdout_handle.lock(); + // `--sarif-file -` writes the SARIF log to stdout; keep stdout valid JSON. + let mut stdout_lock: Box = if feedback_inputs + .sarif_file + .as_deref() + .is_some_and(SarifLog::is_stdout) + { + Box::new(stderr().lock()) + } else { + Box::new(stdout().lock()) + }; while let bytes_read = reader .read_until(b'\n', &mut raw_line) .map_err(ClientError::PatchReadFailed)? @@ -992,6 +1033,26 @@ mod test { ); } + #[test] + fn short_annotation_titles() { + let files = make_dummy_files("warning"); + let annotations = RestClient::build_annotations(&files, "llvm", true).unwrap(); + let titles = annotations + .iter() + .map(|a| a.title.as_deref().unwrap()) + .collect::>(); + assert_eq!(titles, vec!["clang-format", "clang-diagnostic-error"]); + + let file = FileObj::new(PathBuf::from("tests/demo/demo.cpp")); + let file = Arc::new(Mutex::new(file)); + file.lock().unwrap().format_advice = Some(FormatAdvice { + failed: true, + ..Default::default() + }); + let annotations = RestClient::build_annotations(&[file], "llvm", true).unwrap(); + assert_eq!(annotations[0].title.as_deref(), Some("clang-format")); + } + #[test] fn format_failure_feedback() { let file = FileObj::new(PathBuf::from("tests/demo/demo.cpp")); diff --git a/cpp-linter/src/run.rs b/cpp-linter/src/run.rs index b285ddf1..83b51b99 100644 --- a/cpp-linter/src/run.rs +++ b/cpp-linter/src/run.rs @@ -12,7 +12,10 @@ use std::{ // non-std crates use anyhow::{Context, Result, anyhow}; -use clang_tools_manager::{RequestedVersion, logger::try_init_logger}; +use clang_tools_manager::{ + RequestedVersion, + logger::{set_log_to_stderr, try_init_logger}, +}; use clap::Parser; use log::{LevelFilter, set_max_level}; @@ -22,6 +25,7 @@ use crate::{ cli::{ClangParams, Cli, CliCommand, FeedbackInput, LinesChangedOnly, ignore_patterns}, common_fs::{FileObj, mk_path_abs}, rest_client::RestClient, + sarif::SarifLog, }; use git_bot_feedback::FileFilter; @@ -56,6 +60,14 @@ pub async fn run_main(args: Vec) -> Result<()> { return Ok(()); } + let sarif_to_stdout = cli + .feedback_options + .sarif_file + .as_deref() + .is_some_and(SarifLog::is_stdout); + // Until the client is known, keep log messages off stdout if it is meant for the SARIF log. + // This also resets the choice made by a previous call (from the Python or Node.js bindings). + set_log_to_stderr(sarif_to_stdout); try_init_logger(); let repo_root_abs = mk_path_abs(&cli.source_options.repo_root).with_context(|| { @@ -65,6 +77,9 @@ pub async fn run_main(args: Vec) -> Result<()> { ) })?; let mut rest_api_client = RestClient::new(&repo_root_abs)?; + // `--sarif-file -` writes the SARIF log to stdout, so in a local run everything else + // goes to stderr to keep stdout valid JSON. In CI, logs stay on stdout. + set_log_to_stderr(sarif_to_stdout && rest_api_client.client_kind() == "local"); set_max_level( if cli.general_options.verbosity.is_debug() || rest_api_client.is_debug_enabled() { LevelFilter::Debug @@ -201,7 +216,9 @@ pub async fn run_main(args: Vec) -> Result<()> { .post_feedback(&arc_files, user_inputs, clang_versions) .await?; rest_api_client.end_log_group("Posting feedback"); - if env::var("PRE_COMMIT").is_ok_and(|v| v == "1") && checks_failed > 0 { + if (cli.general_options.strict || env::var("PRE_COMMIT").is_ok_and(|v| v == "1")) + && checks_failed > 0 + { return Err(anyhow!("Some checks did not pass")); } Ok(()) @@ -213,6 +230,7 @@ pub(crate) mod test { use super::run_main; use crate::{cli::ClangParams, test_common::setup_tmp_workspace}; + use clang_tools_manager::logger::is_log_to_stderr; use std::env; /// helper to avoid writing to the same GITHUB_OUTPUT file in parallel-running tests. @@ -383,6 +401,91 @@ pub(crate) mod test { drop(tmp_gh_out); } + #[tokio::test] + async fn strict_exit() { + let tmp_gh_out = setup_tmp_gh_out_path(); + unsafe { + env::remove_var("PRE_COMMIT"); + env::remove_var("CPP_LINTER_STRICT_EXIT"); + } + let tmp_workspace = setup_tmp_workspace(); + let args = |strict: Option<&str>| { + let mut args = vec![ + "cpp-linter".to_string(), + "--lines-changed-only".to_string(), + "false".to_string(), + "--repo-root".to_string(), + tmp_workspace.path().to_str().unwrap().to_string(), + ]; + if let Some(value) = strict { + args.push(value.to_string()); + } + args + }; + // checks fail on the demo files, but the default exit code is still 0 + run_main(args(None)).await.unwrap(); + run_main(args(Some("--strict"))).await.unwrap_err(); + run_main(args(Some("--strict=false"))).await.unwrap(); + unsafe { + env::set_var("CPP_LINTER_STRICT_EXIT", "true"); + } + run_main(args(None)).await.unwrap_err(); + drop(tmp_gh_out); + } + + #[tokio::test] + async fn sarif_to_stdout() { + let tmp_gh_out = setup_tmp_gh_out_path(); + let tmp_workspace = setup_tmp_workspace(); + run_main(vec![ + "cpp-linter".to_string(), + "--lines-changed-only".to_string(), + "false".to_string(), + "--style".to_string(), + String::new(), + "--sarif-file".to_string(), + "-".to_string(), + "--repo-root".to_string(), + tmp_workspace.path().to_str().unwrap().to_string(), + ]) + .await + .unwrap(); + // no file named `-` is created + assert!(!std::path::Path::new("-").exists()); + assert!(!tmp_workspace.path().join("-").exists()); + drop(tmp_gh_out); + } + + #[tokio::test] + async fn sarif_to_stdout_then_not() { + unsafe { + // a local run + env::remove_var("GITHUB_ACTIONS"); + } + let tmp_workspace = setup_tmp_workspace(); + let args = |sarif_file: &str| { + vec![ + "cpp-linter".to_string(), + "-l=false".to_string(), + "-f=false".to_string(), + "--style=".to_string(), + "--tidy-checks=-*".to_string(), + format!("--sarif-file={sarif_file}"), + "--repo-root".to_string(), + tmp_workspace.path().to_str().unwrap().to_string(), + "demo/demo.cpp".to_string(), + ] + }; + run_main(args("-")).await.unwrap(); + assert!(is_log_to_stderr()); + // a later call (like from the Python or Node.js bindings) without `--sarif-file -` + // writes log messages to stdout again + let sarif_path = tmp_workspace.path().join("cpp-linter.sarif"); + run_main(args(sarif_path.to_str().unwrap())).await.unwrap(); + assert!(!is_log_to_stderr()); + assert!(sarif_path.exists()); + } + // Verifies that the system gracefully handles cases where all analysis is disabled. // This ensures no diagnostic comments are generated when analysis is explicitly skipped. #[tokio::test] diff --git a/cpp-linter/src/sarif.rs b/cpp-linter/src/sarif.rs index 05367d3d..b77d92b5 100644 --- a/cpp-linter/src/sarif.rs +++ b/cpp-linter/src/sarif.rs @@ -6,6 +6,7 @@ use std::{ collections::{BTreeMap, HashMap}, + io::Write, path::Path, sync::{Arc, Mutex}, }; @@ -222,6 +223,14 @@ fn make_rule(note: &TidyNotification) -> ReportingDescriptor { } impl SarifLog { + /// The `output_file` path that [`Self::write`] treats as stdout. + pub const STDOUT: &str = "-"; + + /// Is the given `output_file` [`Self::STDOUT`]? + pub fn is_stdout(output_file: &Path) -> bool { + output_file == Path::new(Self::STDOUT) + } + /// Create a SARIF log from the clang-tidy advice about the given `files`. /// /// Like other forms of feedback, only the diagnostics about the given `files` are @@ -313,15 +322,22 @@ impl SarifLog { /// Write the SARIF log (as JSON) to the given `output_file` path. /// /// Any missing parent directories are created. + /// If `output_file` is [`Self::STDOUT`] (`-`), the SARIF log is written to stdout. pub fn write(&self, output_file: &Path) -> Result<(), ClientError> { - if let Some(parent) = output_file.parent() { - std::fs::create_dir_all(parent).map_err(|e| ClientError::MkDirFailed { - file_path: output_file.to_path_buf(), - source: e, - })?; - } let json = serde_json::to_string_pretty(self).map_err(ClientError::SarifSerialize)?; - std::fs::write(output_file, json).map_err(|e| ClientError::SarifFileWriteFailed { + let written = if Self::is_stdout(output_file) { + let mut out = std::io::stdout().lock(); + writeln!(out, "{json}").and_then(|()| out.flush()) + } else { + if let Some(parent) = output_file.parent() { + std::fs::create_dir_all(parent).map_err(|e| ClientError::MkDirFailed { + file_path: output_file.to_path_buf(), + source: e, + })?; + } + std::fs::write(output_file, json) + }; + written.map_err(|e| ClientError::SarifFileWriteFailed { file_path: output_file.to_path_buf(), source: e, }) diff --git a/cpp-linter/tests/sarif_stdout.rs b/cpp-linter/tests/sarif_stdout.rs new file mode 100644 index 00000000..c467f326 --- /dev/null +++ b/cpp-linter/tests/sarif_stdout.rs @@ -0,0 +1,54 @@ +#![cfg(feature = "bin")] +//! `--sarif-file -` in a local run: stdout must hold only the SARIF log. + +use std::{env, fs, process::Command}; + +use tempfile::TempDir; + +#[test] +fn sarif_to_stdout_is_valid_json() { + let tmp = TempDir::with_prefix("cpp-linter-test").unwrap(); + for name in ["demo.cpp", "demo.hpp"] { + fs::copy(format!("tests/demo/{name}"), tmp.path().join(name)).unwrap(); + } + let output = Command::new(env!("CARGO_BIN_EXE_cpp-linter")) + .current_dir(tmp.path()) + // a local run, not a CI run + .env_remove("GITHUB_ACTIONS") + .env_remove("GITEA_ACTIONS") + .env_remove("FORGEJO_ACTIONS") + .env_remove("GITLAB_CI") + // checks fail in the demo, so don't exit with an error + .env_remove("CPP_LINTER_STRICT_EXIT") + .env_remove("PRE_COMMIT") + .args([ + format!("-V={}", env::var("CLANG_VERSION").unwrap_or_default()), + "--lines-changed-only=false".to_string(), + "--files-changed-only=false".to_string(), + "--repo-root=.".to_string(), + "--style=llvm".to_string(), + "--tidy-checks=-*,readability-braces-around-statements".to_string(), + "--sarif-file=-".to_string(), + // the generated patch must not be printed to stdout either + "--fix".to_string(), + "demo.cpp".to_string(), + ]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{stderr}"); + + let sarif: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| { + let stdout = String::from_utf8_lossy(&output.stdout); + panic!("stdout is not JSON ({e}):\n{stdout}\nstderr:\n{stderr}") + }); + assert_eq!(sarif["version"], "2.1.0"); + assert!(!sarif["runs"][0]["results"].as_array().unwrap().is_empty()); + + // 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("Generated patch content:"), "{stderr}"); + assert!(!tmp.path().join("-").exists()); +} diff --git a/docs/docs/git-servers.md b/docs/docs/git-servers.md index a553415d..350582e6 100644 --- a/docs/docs/git-servers.md +++ b/docs/docs/git-servers.md @@ -12,6 +12,7 @@ [passive-reviews]: cli.md#-r-passive-reviews [no-lgtm]: cli.md#-g-no-lgtm [file-annotations]: cli.md#-a-file-annotations +[strict]: cli.md#-s-strict [step-summary]: cli.md#-w-step-summary [lines-changed-only]: cli.md#-l-lines-changed-only [files-changed-only]: cli.md#-f-files-changed-only @@ -115,7 +116,7 @@ GitLab v17.9 or newer is needed. - GitLab has no step summary and no output variables. The values of the output variables are printed in the job's log, for example `checks-failed: 5`. - cpp-linter exits with code 0 when checks fail. Because there are no output variables, a job that - should fail on findings has to look for the `checks-failed` line in the log. + should fail on findings needs [`--strict`][strict], which makes cpp-linter exit with code 1. - Turn off [`--file-annotations`][file-annotations]. GitLab has no equivalent, and each annotation would be printed in the job's log instead.