Skip to content

Commit

Permalink
add option for verbose logging
Browse files Browse the repository at this point in the history
  • Loading branch information
todor-a committed Aug 31, 2024
1 parent 0f3ab73 commit 32ee718
Showing 1 changed file with 35 additions and 9 deletions.
44 changes: 35 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clap::{CommandFactory, Parser, ValueEnum};
use colored::*;
use glob::GlobError;
use log::{debug, error, info};
use log::{debug, error, info, LevelFilter};
use rayon::prelude::*;
use serde::Serialize;
use serde_json::Value;
Expand Down Expand Up @@ -43,6 +43,26 @@ pub enum IndentStyle {
Spaces,
}

#[derive(Debug, Clone, ValueEnum)]
pub enum LogLevel {
#[clap()]
Quiet,
#[clap()]
Default,
#[clap()]
Verbose,
}

impl LogLevel {
pub fn to_level_filter(&self) -> LevelFilter {
match self {
LogLevel::Quiet => LevelFilter::Off,
LogLevel::Default => LevelFilter::Error,
LogLevel::Verbose => LevelFilter::Debug,
}
}
}

type Result<T> = std::result::Result<T, CustomError>;

#[derive(Parser, Debug)]
Expand Down Expand Up @@ -79,6 +99,10 @@ struct Args {
/// Specify the desired indent style
#[arg(long)]
indent_style: Option<IndentStyle>,

/// Specify the log level
#[arg(value_enum, long, default_value_t=LogLevel::Default)]
log_level: LogLevel,
}

#[derive(Debug)]
Expand Down Expand Up @@ -114,16 +138,18 @@ fn print_error(err: &CustomError) {
}

fn main() -> Result<()> {
env_logger::init();
if let Err(e) = run() {
let args = Args::parse();
env_logger::builder()
.filter_level(args.log_level.to_level_filter())
.init();
if let Err(e) = run(args) {
print_error(&e);
std::process::exit(1);
} else {
Ok(())
}
}
fn run() -> Result<()> {
let args = Args::parse();
fn run(args: Args) -> Result<()> {
let start_time = Instant::now();

if args.include.is_empty() {
Expand Down Expand Up @@ -165,12 +191,12 @@ fn run() -> Result<()> {

for (path, result, duration) in results {
match result {
Ok(_) => println!(
Ok(_) => info!(
"{}: Processed in {:.2?}",
path.display().to_string().green(),
duration
),
Err(e) => eprintln!(
Err(e) => error!(
"{}: {} (in {:.2?})",
path.display().to_string().red(),
e,
Expand All @@ -181,7 +207,7 @@ fn run() -> Result<()> {

let total_duration = start_time.elapsed();

println!(
info!(
"{}",
format!(
"Processed {} file(s) in {:.2?}",
Expand Down Expand Up @@ -213,7 +239,7 @@ fn process_file(path: &PathBuf, cfg: &Configuration) -> Result<()> {
info!("Sorted JSON written back to {:?}", path);
} else {
serde_json::to_string_pretty(&sorted_json)?;
info!("Sorted {:?}.\n", path);
info!("Sorted {:?}.", path);
}

Ok(())
Expand Down

0 comments on commit 32ee718

Please sign in to comment.