Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Send all output to stderr; make -q less verbose #28

Merged
merged 1 commit into from
Jul 12, 2024
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
102 changes: 99 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ serde_json = "1.0"
serde_with = { version = "3.2", features = ["json"] }
tokio = { version = "1.29", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
url = { version = "2.4", features = ["serde"] }
nix_rs = "0.5.0"
direnv = "0.1.1"
Expand Down
37 changes: 24 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Health checks for the user's Nix install

pub mod check;
pub mod logging;
pub mod report;
pub mod traits;

Expand Down Expand Up @@ -81,26 +82,36 @@ impl NixHealth {
.collect()
}

pub fn print_report_returning_exit_code(checks: &[traits::Check], quiet: bool) -> i32 {
pub fn print_report_returning_exit_code(checks: &[traits::Check]) -> i32 {
let mut res = AllChecksResult::new();
for check in checks {
match &check.result {
traits::CheckResult::Green => {
if !quiet {
println!("{}", format!("✅ {}", check.title).green().bold());
println!(" {}", check.info.blue());
}
tracing::info!(
"✅ {}\n {}",
check.title.green().bold(),
check.info.blue()
);
}
traits::CheckResult::Red { msg, suggestion } => {
res.register_failure(check.required);
if check.required {
println!("{}", format!("❌ {}", check.title).red().bold());
tracing::error!(
"❌ {}\n {}\n {}\n {}",
check.title.red().bold(),
check.info.blue(),
msg.yellow(),
suggestion
);
} else {
println!("{}", format!("🟧 {}", check.title).yellow().bold());
tracing::warn!(
"🟧 {}\n {}\n {}\n {}",
check.title.yellow().bold(),
check.info.blue(),
msg.yellow(),
suggestion
);
}
println!(" {}", check.info.blue());
println!(" {}", msg.yellow());
println!(" {}", suggestion);
}
}
}
Expand Down Expand Up @@ -136,19 +147,19 @@ impl AllChecksResult {
fn report(self) -> i32 {
match self {
AllChecksResult::Pass => {
println!("{}", "✅ All checks passed".green().bold());
tracing::info!("{}", "✅ All checks passed".green().bold());
0
}
AllChecksResult::PassSomeFail => {
println!(
tracing::warn!(
"{}, {}",
"✅ Required checks passed".green().bold(),
"but some non-required checks failed".yellow().bold()
);
0
}
AllChecksResult::Fail => {
println!("{}", "❌ Some required checks failed".red().bold());
tracing::error!("{}", "❌ Some required checks failed".red().bold());
1
}
}
Expand Down
43 changes: 43 additions & 0 deletions src/logging.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::fmt;
use std::io;

use tracing::{Event, Level, Subscriber};
use tracing_subscriber::fmt::format;
use tracing_subscriber::{
fmt::{FmtContext, FormatEvent, FormatFields},
registry::LookupSpan,
};

/// A [tracing_subscriber] event formatter that suppresses everything but the
/// log message.
struct BareFormatter;

impl<S, N> FormatEvent<S, N> for BareFormatter
where
S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static,
{
fn format_event(
&self,
ctx: &FmtContext<'_, S, N>,
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
ctx.field_format().format_fields(writer.by_ref(), event)?;
writeln!(writer)
}
}

pub fn setup_logging(quiet: bool) {
let env_filter = if quiet {
"nix_health=warn,nix_rs=error"
} else {
"nix_health=info,nix_rs=error"
};
let builder = tracing_subscriber::fmt()
.with_writer(io::stderr)
.with_max_level(Level::INFO)
.with_env_filter(env_filter);

builder.event_format(BareFormatter).init();
}
11 changes: 7 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,17 @@ pub struct Args {
async fn main() -> anyhow::Result<()> {
human_panic::setup_panic!();
let args = Args::parse();

nix_health::logging::setup_logging(args.quiet);

if args.dump_schema {
println!("{}", NixHealth::schema()?);
tracing::info!("{}", NixHealth::schema()?);
return Ok(());
}

let checks = run_checks(args.flake_url).await?;

let exit_code = NixHealth::print_report_returning_exit_code(&checks, args.quiet);
let exit_code = NixHealth::print_report_returning_exit_code(&checks);

std::process::exit(exit_code)
}
Expand All @@ -50,11 +53,11 @@ async fn run_checks(flake_url: Option<FlakeUrl>) -> anyhow::Result<Vec<Check>> {
);
let health: NixHealth = match flake_url.as_ref() {
Some(flake_url) => {
println!("{}, using config from flake '{}':", action_msg, flake_url);
tracing::info!("{}, using config from flake '{}':", action_msg, flake_url);
NixHealth::from_flake(flake_url).await
}
None => {
println!("{}:", action_msg);
tracing::info!("{}:", action_msg);
Ok(NixHealth::default())
}
}?;
Expand Down