Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions clang-tools-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
Expand Down
108 changes: 78 additions & 30 deletions clang-tools-manager/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

use std::{
env,
io::{Write, stdout},
io::{Write, stderr, stdout},
sync::atomic::Ordering,
};

use clap::builder::{
Expand All @@ -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);
}
}

Expand Down Expand Up @@ -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");
}
}
33 changes: 28 additions & 5 deletions clang-tools-manager/src/progress_bar.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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<dyn Write>,
/// Is the terminal session interactive?
is_interactive: bool,
/// The leading prompt to display before the progress bar (e.g. "Downloading")
Expand Down Expand Up @@ -51,8 +54,18 @@ impl ProgressBar {
/// // stdout lock is released when `progress_bar` goes out of scope
/// ```
pub fn new(total: Option<NonZero<u64>>, 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<dyn Write>, 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,
Expand Down Expand Up @@ -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");
Expand Down
36 changes: 36 additions & 0 deletions cpp-linter/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
15 changes: 9 additions & 6 deletions cpp-linter/src/cli/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading