Skip to content

Commit

Permalink
[WIP] expose cli option for log levels
Browse files Browse the repository at this point in the history
  • Loading branch information
JamieMason committed Oct 25, 2024
1 parent 26af7c4 commit b62d500
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 34 deletions.
49 changes: 39 additions & 10 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use clap::{builder::ValueParser, crate_description, crate_name, crate_version, Arg, ArgMatches, Command};
use log::LevelFilter;
use regex::Regex;

#[derive(Debug)]
Expand Down Expand Up @@ -66,6 +67,14 @@ fn create() -> Command {
.action(clap::ArgAction::Set)
.value_parser(ValueParser::new(validate_filter))
.help("only include dependencies whose name matches this regex"),
)
.arg(
Arg::new("logLevels")
.long("logLevels")
.value_delimiter(',')
.value_parser(["off", "error", "warn", "info", "debug"])
.default_values(["error", "warn", "info"])
.help("control how detailed log output should be"),
),
)
.subcommand(
Expand Down Expand Up @@ -99,6 +108,14 @@ fn create() -> Command {
.action(clap::ArgAction::Set)
.value_parser(ValueParser::new(validate_filter))
.help("only include dependencies whose name matches this regex"),
)
.arg(
Arg::new("logLevels")
.long("logLevels")
.value_delimiter(',')
.value_parser(["off", "error", "warn", "info", "debug"])
.default_values(["error", "warn", "info"])
.help("control how detailed log output should be"),
),
)
}
Expand All @@ -122,11 +139,13 @@ pub struct CliOptions {
/// `true` when `--format` is passed or if none of `--format`, `--ranges`
/// or `--versions` are passed
pub format: bool,
/// How detailed the terminal output should be
pub log_levels: Vec<LevelFilter>,
/// Optional glob patterns to package.json files
pub source: Vec<String>,
/// `true` when `--versions` is passed or if none of `--format`, `--ranges`
/// or `--versions` are passed
pub versions: bool,
/// Optional glob patterns to package.json files
pub source: Vec<String>,
}

impl CliOptions {
Expand All @@ -137,18 +156,28 @@ impl CliOptions {
let use_format = matches.get_flag("format");
let use_versions = matches.get_flag("versions");
let use_all = !use_format && !use_versions;
let source = matches
.get_many::<String>("source")
.unwrap_or_default()
.map(|source| source.to_owned())
.collect::<Vec<_>>();
let filter = matches.get_one::<Regex>("filter").map(|filter| filter.to_owned());

CliOptions {
filter,
filter: matches.get_one::<String>("filter").map(|filter| Regex::new(filter).unwrap()),
format: use_all || use_format,
log_levels: matches
.get_many::<String>("logLevels")
.unwrap()
.map(|level| match level.as_str() {
"off" => LevelFilter::Off,
"error" => LevelFilter::Error,
"warn" => LevelFilter::Warn,
"info" => LevelFilter::Info,
"debug" => LevelFilter::Debug,
_ => unreachable!(),
})
.collect(),
source: matches
.get_many::<String>("source")
.unwrap_or_default()
.map(|source| source.to_owned())
.collect::<Vec<_>>(),
versions: use_all || use_versions,
source,
}
}
}
43 changes: 23 additions & 20 deletions src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,32 @@ use env_logger::Builder;
use log::{Level, LevelFilter};
use std::io::Write;

pub fn init() {
Builder::new()
// @TODO expose cli and rcfile options for log level
.filter_level(LevelFilter::Debug)
.format(|buf, record| {
match record.level() {
// Normal output shown to users
Level::Info => {
writeln!(buf, "{}", record.args())
}
Level::Error => {
/// Initialize the logger with the given log level
pub fn init(log_levels: &[LevelFilter]) {
if !log_levels.contains(&LevelFilter::Off) {
let error_enabled = log_levels.contains(&LevelFilter::Error);
let warn_enabled = log_levels.contains(&LevelFilter::Warn);
let info_enabled = log_levels.contains(&LevelFilter::Info);
let debug_enabled = log_levels.contains(&LevelFilter::Debug);
let trace_enabled = log_levels.contains(&LevelFilter::Trace);
Builder::new()
.filter_level(LevelFilter::Debug)
.format(move |buf, record| {
let level = record.level();
if level == Level::Error && error_enabled {
writeln!(buf, "{}", format!("✗ {}", record.args()).red())
}
Level::Warn => {
} else if level == Level::Warn && warn_enabled {
writeln!(buf, "{}", format!("! {}", record.args()).yellow())
}
Level::Debug => {
} else if level == Level::Info && info_enabled {
writeln!(buf, "{}", record.args())
} else if level == Level::Debug && debug_enabled {
writeln!(buf, "{}", format!("? {}", record.args()).cyan())
}
Level::Trace => {
} else if level == Level::Trace && trace_enabled {
writeln!(buf, "{}", record.args())
} else {
write!(buf, "")
}
}
})
.init();
})
.init();
}
}
5 changes: 3 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ mod version_group;
mod visit_packages;

fn main() {
logger::init();
let cli = Cli::parse();

logger::init(&cli.options.log_levels);

let cwd = current_dir().unwrap();
let cli = Cli::parse();
let config = Config::from_cli(cwd, cli);
let packages = Packages::from_config(&config);

Expand Down
3 changes: 2 additions & 1 deletion src/test/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ pub fn cli() -> Cli {
options: CliOptions {
filter: None,
format: false,
versions: true,
log_levels: vec![],
source: vec![],
versions: true,
},
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/visit_packages_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use super::*;
#[ctor::ctor]
fn init() {
use crate::logger;
logger::init();
logger::init(&[]);
}

// = Standard Version Group: Local =============================================
Expand Down

0 comments on commit b62d500

Please sign in to comment.