Skip to content

Commit

Permalink
🔊 - Move logging to env_logger
Browse files Browse the repository at this point in the history
This adds the ability to use log levels for CI. Running `RUST_LOG=warn
rewatch build` will only use `warn` and up.

See the [env_logger](https://docs.rs/env_logger/latest/env_logger/)
crate for more info.
  • Loading branch information
rolandpeelen committed Jun 26, 2024
1 parent f74c893 commit c49f942
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 54 deletions.
60 changes: 31 additions & 29 deletions src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use ahash::AHashSet;
use build_types::*;
use console::style;
use indicatif::{ProgressBar, ProgressStyle};
use log::{log_enabled, Level::Info};
use serde::Serialize;
use std::fmt;
use std::io::{stdout, Write};
Expand Down Expand Up @@ -148,13 +149,13 @@ pub fn initialize_build(
let root_config_name = packages::get_package_name(&project_root);
let rescript_version = helpers::get_rescript_version(&bsc_path);

print!("{}{}Building package tree...", style("[1/7]").bold().dim(), TREE);
log::info!("{}{}Building package tree...", style("[1/7]").bold().dim(), TREE);
let _ = stdout().flush();
let timing_package_tree = Instant::now();
let packages = packages::make(filter, &project_root, &workspace_root);
let timing_package_tree_elapsed = timing_package_tree.elapsed();

println!(
log::info!(
"{}{} {}Built package tree in {:.2}s",
LINE_CLEAR,
style("[1/7]").bold().dim(),
Expand All @@ -170,7 +171,7 @@ pub fn initialize_build(

let timing_source_files = Instant::now();

print!(
log::info!(
"{} {}Finding source files...",
style("[2/7]").bold().dim(),
LOOKING_GLASS
Expand All @@ -186,7 +187,7 @@ pub fn initialize_build(
);
packages::parse_packages(&mut build_state);
let timing_source_files_elapsed = timing_source_files.elapsed();
println!(
log::info!(
"{}{} {}Found source files in {:.2}s",
LINE_CLEAR,
style("[2/7]").bold().dim(),
Expand All @@ -196,7 +197,7 @@ pub fn initialize_build(
.as_secs_f64()
);

print!(
log::info!(
"{} {}Reading compile state...",
style("[3/7]").bold().dim(),
COMPILE_STATE
Expand All @@ -205,7 +206,7 @@ pub fn initialize_build(
let timing_compile_state = Instant::now();
let compile_assets_state = read_compile_state::read(&mut build_state);
let timing_compile_state_elapsed = timing_compile_state.elapsed();
println!(
log::info!(
"{}{} {}Read compile state {:.2}s",
LINE_CLEAR,
style("[3/7]").bold().dim(),
Expand All @@ -215,15 +216,15 @@ pub fn initialize_build(
.as_secs_f64()
);

print!(
log::info!(
"{} {}Cleaning up previous build...",
style("[4/7]").bold().dim(),
SWEEP
);
let timing_cleanup = Instant::now();
let (diff_cleanup, total_cleanup) = clean::cleanup_previous_build(&mut build_state, compile_assets_state);
let timing_cleanup_elapsed = timing_cleanup.elapsed();
println!(
log::info!(
"{}{} {}Cleaned {}/{} {:.2}s",
LINE_CLEAR,
style("[4/7]").bold().dim(),
Expand Down Expand Up @@ -263,7 +264,11 @@ pub fn incremental_build(
) -> Result<(), IncrementalBuildError> {
logs::initialize(&build_state.packages);
let num_dirty_modules = build_state.modules.values().filter(|m| is_dirty(m)).count() as u64;
let pb = ProgressBar::new(num_dirty_modules);
let pb = if log_enabled!(Info) {
ProgressBar::new(num_dirty_modules)
} else {
ProgressBar::hidden()
};
let mut current_step = if only_incremental { 1 } else { 5 };
let total_steps = if only_incremental { 3 } else { 7 };
pb.set_style(
Expand All @@ -281,26 +286,26 @@ pub fn incremental_build(

match result_asts {
Ok(err) => {
println!(
log::info!(
"{}{} {}Parsed {} source files in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
CODE,
num_dirty_modules,
default_timing.unwrap_or(timing_ast_elapsed).as_secs_f64()
);
print!("{}", &err);
log::warn!("{}", &err);
}
Err(err) => {
logs::finalize(&build_state.packages);
println!(
log::error!(
"{}{} {}Error parsing source files in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
CROSS,
default_timing.unwrap_or(timing_ast_elapsed).as_secs_f64()
);
print!("{}", &err);
log::error!("{}", &err);
return Err(IncrementalBuildError::SourceFileParseError);
}
}
Expand All @@ -309,7 +314,7 @@ pub fn incremental_build(
let timing_deps_elapsed = timing_deps.elapsed();
current_step += 1;

println!(
log::info!(
"{}{} {}Collected deps in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
Expand Down Expand Up @@ -339,15 +344,12 @@ pub fn incremental_build(
// }

let start_compiling = Instant::now();
let pb = ProgressBar::new(build_state.modules.len().try_into().unwrap());
pb.set_style(
ProgressStyle::with_template(&format!(
"{} {}Compiling... {{spinner}} {{pos}}/{{len}} {{msg}}",
format_step(current_step, total_steps),
SWORDS
))
.unwrap(),
);
let pb = if log_enabled!(Info) {
ProgressBar::new(build_state.modules.len().try_into().unwrap())
} else {
ProgressBar::hidden()
};

let (compile_errors, compile_warnings, num_compiled_modules) =
compile::compile(build_state, || pb.inc(1), |size| pb.set_length(size));
let compile_duration = start_compiling.elapsed();
Expand All @@ -359,17 +361,17 @@ pub fn incremental_build(
pb.finish();
if !compile_errors.is_empty() {
if helpers::contains_ascii_characters(&compile_warnings) {
println!("{}", &compile_warnings);
log::error!("{}", &compile_warnings);
}
println!(
log::info!(
"{}{} {}Compiled {} modules in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
CROSS,
num_compiled_modules,
default_timing.unwrap_or(compile_duration).as_secs_f64()
);
print!("{}", &compile_errors);
log::error!("{}", &compile_errors);
// mark the original files as dirty again, because we didn't complete a full build
for (module_name, module) in build_state.modules.iter_mut() {
if tracked_dirty_modules.contains(module_name) {
Expand All @@ -378,7 +380,7 @@ pub fn incremental_build(
}
Err(IncrementalBuildError::CompileError)
} else {
println!(
log::info!(
"{}{} {}Compiled {} modules in {:.2}s",
LINE_CLEAR,
format_step(current_step, total_steps),
Expand All @@ -387,7 +389,7 @@ pub fn incremental_build(
default_timing.unwrap_or(compile_duration).as_secs_f64()
);
if helpers::contains_ascii_characters(&compile_warnings) {
print!("{}", &compile_warnings);
log::warn!("{}", &compile_warnings);
}
Ok(())
}
Expand Down Expand Up @@ -433,7 +435,7 @@ pub fn build(
match incremental_build(&mut build_state, default_timing, true, false, create_sourcedirs) {
Ok(_) => {
let timing_total_elapsed = timing_total.elapsed();
println!(
log::info!(
"\n{}{}Finished Compilation in {:.2}s",
LINE_CLEAR,
SPARKLES,
Expand Down
10 changes: 5 additions & 5 deletions src/build/clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,14 +332,14 @@ pub fn clean(path: &str, bsc_path: Option<String>) {
let rescript_version = helpers::get_rescript_version(&bsc_path);

let timing_clean_compiler_assets = Instant::now();
print!(
log::info!(
"{} {} Cleaning compiler assets...",
style("[1/2]").bold().dim(),
SWEEP
);
std::io::stdout().flush().unwrap();
packages.iter().for_each(|(_, package)| {
print!(
log::info!(
"{}{} {} Cleaning {}...",
LINE_CLEAR,
style("[1/2]").bold().dim(),
Expand All @@ -358,7 +358,7 @@ pub fn clean(path: &str, bsc_path: Option<String>) {
});
let timing_clean_compiler_assets_elapsed = timing_clean_compiler_assets.elapsed();

println!(
log::info!(
"{}{} {}Cleaned compiler assets in {:.2}s",
LINE_CLEAR,
style("[1/2]").bold().dim(),
Expand All @@ -368,7 +368,7 @@ pub fn clean(path: &str, bsc_path: Option<String>) {
std::io::stdout().flush().unwrap();

let timing_clean_mjs = Instant::now();
print!("{} {} Cleaning mjs files...", style("[2/2]").bold().dim(), SWEEP);
log::info!("{} {} Cleaning mjs files...", style("[2/2]").bold().dim(), SWEEP);
std::io::stdout().flush().unwrap();
let mut build_state = BuildState::new(
project_root.to_owned(),
Expand All @@ -381,7 +381,7 @@ pub fn clean(path: &str, bsc_path: Option<String>) {
packages::parse_packages(&mut build_state);
clean_mjs_files(&build_state);
let timing_clean_mjs_elapsed = timing_clean_mjs.elapsed();
println!(
log::info!(
"{}{} {}Cleaned mjs files in {:.2}s",
LINE_CLEAR,
style("[2/2]").bold().dim(),
Expand Down
20 changes: 10 additions & 10 deletions src/build/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ pub fn read_folders(
if metadata.file_type().is_dir() && recurse {
match read_folders(filter, package_dir, &new_path, recurse) {
Ok(s) => map.extend(s),
Err(e) => println!("Error reading directory: {}", e),
Err(e) => log::error!("Error reading directory: {}", e),
}
}

Expand All @@ -167,8 +167,8 @@ pub fn read_folders(
);
}

Ok(_) => println!("Filtered: {:?}", name),
Err(ref e) => println!("Error reading directory: {}", e),
Ok(_) => log::info!("Filtered: {:?}", name),
Err(ref e) => log::error!("Error reading directory: {}", e),
},
_ => (),
}
Expand Down Expand Up @@ -309,7 +309,7 @@ fn read_dependencies(
let (bsconfig, canonical_path) =
match read_dependency(package_name, parent_path, project_root, &workspace_root) {
Err(error) => {
print!(
log::error!(
"{} {} Error building package tree. {}",
style("[1/2]").bold().dim(),
CROSS,
Expand Down Expand Up @@ -453,12 +453,12 @@ pub fn get_source_files(
match read_folders(filter, package_dir, path_dir, recurse) {
Ok(files) => map.extend(files),
Err(_e) if type_ == &Some("dev".to_string()) => {
println!(
log::warn!(
"Could not read folder: {}... Probably ok as type is dev",
path_dir.to_string_lossy()
)
}
Err(_e) => println!("Could not read folder: {}...", path_dir.to_string_lossy()),
Err(_e) => log::error!("Could not read folder: {}...", path_dir.to_string_lossy()),
}
}

Expand Down Expand Up @@ -666,7 +666,7 @@ pub fn parse_packages(build_state: &mut BuildState) {
implementation_filename.pop();
match source_files.get(&implementation_filename) {
None => {
println!(
log::warn!(
"{}Warning: No implementation file found for interface file (skipping): {}",
LINE_CLEAR, file
)
Expand Down Expand Up @@ -799,7 +799,7 @@ pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> b
});
}
for (package_name, unallowed_deps) in detected_unallowed_dependencies.iter() {
println!(
log::error!(
"\n{}: {} has the following unallowed dependencies:",
console::style("Error").red(),
console::style(package_name).bold()
Expand All @@ -813,7 +813,7 @@ pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> b
.iter()
.for_each(|(deps_type, map)| {
if !map.is_empty() {
println!(
log::info!(
"{} dependencies: {}",
console::style(deps_type).bold().dim(),
console::style(map.join(" \n -")).bold().dim()
Expand All @@ -824,7 +824,7 @@ pub fn validate_packages_dependencies(packages: &AHashMap<String, Package>) -> b
let has_any_unallowed_dependent = detected_unallowed_dependencies.len() > 0;

if has_any_unallowed_dependent {
println!(
log::error!(
"\nUpdate the {} value in the {} of the unallowed dependencies to solve the issue!",
console::style("unallowed_dependents").bold().dim(),
console::style("bsconfig.json").bold().dim()
Expand Down
3 changes: 2 additions & 1 deletion src/build/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,8 @@ fn generate_ast(
Ok((ast_path, None))
}
} else {
println!("Parsing file {}...", filename);
log::info!("Parsing file {}...", filename);

Err(format!(
"Could not find canonicalize_string_path for file {} in package {}",
filename, package.name
Expand Down
6 changes: 3 additions & 3 deletions src/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::time::Instant;
pub fn run(command_string: String) {
let start_subcommand = Instant::now();

print!(
log::info!(
"{} {}Running subcommand... \n{}\n",
style("[...]").bold().dim(),
COMMAND,
Expand Down Expand Up @@ -39,11 +39,11 @@ pub fn run(command_string: String) {
}

for line in std_err {
println!("{}", line.unwrap());
eprintln!("{}", line.unwrap());
}

let subcommand_duration = start_subcommand.elapsed();
println!(
log::info!(
"{}{} {}Ran subcommand in {:.2}s",
LINE_CLEAR,
style("[...]").bold().dim(),
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ fn main() {

match lock::get(&folder) {
lock::Lock::Error(ref e) => {
eprintln!("Error while trying to get lock: {e}");
log::error!("Error while trying to get lock: {e}");
std::process::exit(1)
}
lock::Lock::Aquired(_) => match command {
Expand All @@ -96,7 +96,7 @@ fn main() {
args.bsc_path,
) {
Err(e) => {
eprintln!("Error Building: {e}");
log::error!("Error Building: {e}");
std::process::exit(1)
}
Ok(_) => {
Expand Down
Loading

0 comments on commit c49f942

Please sign in to comment.