diff --git a/.run_status.toml b/.run_status.toml index 87a12b2..b819668 100644 --- a/.run_status.toml +++ b/.run_status.toml @@ -1,15 +1,8 @@ -[last_run_clean] -run_status = "Failure" -lines_parsed = 20 - -[last_run_clean.run_duration] -secs = 20 -nanos = 321146474 - [last_run_incremental] run_status = "Success" -lines_parsed = 19 +lines_parsed = 22 +coverage = 3.37 [last_run_incremental.run_duration] -secs = 9 -nanos = 407112483 +secs = 7 +nanos = 826492210 diff --git a/badges/coverage.svg b/badges/coverage.svg index e6a15fe..06d4451 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 0%test-coverage0% +test-coverage: 3%test-coverage3% diff --git a/run b/run deleted file mode 100644 index 92ac197..0000000 --- a/run +++ /dev/null @@ -1,22 +0,0 @@ -2025-03-19T13:50:48.031029Z  INFO cargo_tarpaulin::config: Creating config -2025-03-19T13:50:48.086450Z  INFO cargo_tarpaulin: Running Tarpaulin -2025-03-19T13:50:48.086466Z  INFO cargo_tarpaulin: Building project -2025-03-19T13:50:48.086469Z  INFO cargo_tarpaulin::cargo: Cleaning project -2025-03-19T13:51:01.196213Z  INFO cargo_tarpaulin::process_handling::linux: Launching test -2025-03-19T13:51:01.196247Z  INFO cargo_tarpaulin::process_handling: running /home/beffroi/Documents/Git/rust_autobadges/target/debug/deps/rust_autobadges-88a057f7e5bc03ef - -running 4 tests -test test::test_badge_writing ... ignored -test test::test_coverage_parsing ... ignored -test test::test_structs ... ignored -test test::test_version_parsing ... ignored - -test result: ok. 0 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out; finished in 0.00s - -2025-03-19T13:51:07.936086Z  INFO cargo_tarpaulin::report: Coverage Results: -|| Uncovered Lines: -|| src/main.rs: 46, 48-49, 100-101, 105-110, 116-117, 119-120, 124, 127, 133-136, 141, 146-150, 152, 158-162, 169-172, 176-178, 180, 248-249, 251-252, 254-255, 261, 266, 268-269, 272, 278-279, 282-283, 285, 289, 291-295, 299, 304, 310-312, 314-315, 319-321, 324, 329-331, 334-335, 337-339, 341, 344-345, 349-352, 354-356, 358, 380-381, 385-386, 388-390, 398-399, 402, 408, 412-414, 416, 418, 427, 435, 437-441, 444-445, 450, 458-467, 469, 473-474, 479, 481-482, 484, 486-487, 489-490, 492, 494-495, 499-501, 503, 506-507, 509-512, 515, 517-518, 520, 539, 546-547, 550-552 -|| Tested/Total Lines: -|| src/main.rs: 0/163 +0.00% -|| -0.00% coverage, 0/163 lines covered, +0.00% change in coverage diff --git a/run_err b/run_err deleted file mode 100644 index 015e224..0000000 --- a/run_err +++ /dev/null @@ -1,58 +0,0 @@ - Compiling proc-macro2 v1.0.94 - Compiling unicode-ident v1.0.18 - Compiling libc v0.2.170 - Compiling serde v1.0.219 - Compiling autocfg v1.4.0 - Compiling utf8parse v0.2.2 - Compiling parking_lot_core v0.9.10 - Compiling anstyle-parse v0.2.6 - Compiling anstyle-query v1.1.2 - Compiling equivalent v1.0.2 - Compiling hashbrown v0.15.2 - Compiling cfg-if v1.0.0 - Compiling colorchoice v1.0.3 - Compiling is_terminal_polyfill v1.70.1 - Compiling memchr v2.7.4 - Compiling scopeguard v1.2.0 - Compiling anstyle v1.0.10 - Compiling lock_api v0.4.12 - Compiling portable-atomic v1.11.0 - Compiling quote v1.0.39 - Compiling syn v2.0.100 - Compiling smallvec v1.14.0 - Compiling aho-corasick v1.1.3 - Compiling indexmap v2.8.0 - Compiling anstream v0.6.18 - Compiling regex-syntax v0.8.5 - Compiling anyhow v1.0.94 - Compiling once_cell v1.20.3 - Compiling unicode-width v0.2.0 - Compiling winnow v0.7.4 - Compiling strsim v0.11.1 - Compiling clap_lex v0.7.4 - Compiling heck v0.5.0 - Compiling clap_builder v4.5.31 - Compiling console v0.15.11 - Compiling regex-automata v0.4.9 - Compiling parking_lot v0.12.3 - Compiling signal-hook-registry v1.4.2 - Compiling socket2 v0.5.8 - Compiling mio v1.0.3 - Compiling bytes v1.10.1 - Compiling pin-project-lite v0.2.16 - Compiling number_prefix v0.4.0 - Compiling xshell-macros v0.2.7 - Compiling regex v1.11.1 - Compiling xshell v0.2.7 - Compiling serde_derive v1.0.219 - Compiling clap_derive v4.5.28 - Compiling tokio-macros v2.5.0 - Compiling indicatif v0.17.11 - Compiling tokio v1.44.1 - Compiling clap v4.5.31 - Compiling toml_datetime v0.6.8 - Compiling serde_spanned v0.6.8 - Compiling toml_edit v0.22.24 - Compiling toml v0.8.20 - Compiling rust_autobadges v0.1.0 (/home/beffroi/Documents/Git/rust_autobadges) - Finished `test` profile [unoptimized + debuginfo] target(s) in 12.96s diff --git a/src/main.rs b/src/main.rs index d909eb1..b1aa0e1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -49,8 +49,8 @@ fn main() -> anyhow::Result<()> { unimplemented!("Please run with tarpaulin for now") } // The coverage know wether to write the badge test with the cli args - (false, true) => run_coverage(&sh, new_progress_bar(), &args, &mut run_status)?, - (false, false) => run_coverage(&sh, new_progress_bar(), &args, &mut run_status)?, + (false, true) => run_status = run_coverage(&sh, new_progress_bar(), &args, run_status)?, + (false, false) => run_status = run_coverage(&sh, new_progress_bar(), &args, run_status)?, } if let Err(e) = run_status.save_status() { diff --git a/src/progressbar.rs b/src/progressbar.rs index 5744b6e..493b76c 100644 --- a/src/progressbar.rs +++ b/src/progressbar.rs @@ -26,7 +26,7 @@ pub struct LastRuns { last_run_incremental: Option, } -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, Debug)] /// The stats of a run, useful to print more helpful progress info and debug infos pub struct RunStats { /// Duration of the last run without a full clean @@ -34,7 +34,9 @@ pub struct RunStats { /// Status of the last run pub run_status: RunStatus, /// Lines parsed by the rust_autobadge - pub lines_parsed: usize, + pub lines_parsed: u64, + /// The code coverage found + coverage: Option, } impl Default for RunStats { fn default() -> Self { @@ -42,6 +44,7 @@ impl Default for RunStats { run_duration: Duration::from_secs(10), run_status: RunStatus::default(), lines_parsed: 10, + coverage: None, } } } @@ -56,7 +59,7 @@ pub struct CurrentRunStats { pub current_run: RunStats, } -#[derive(Serialize, Deserialize, Default)] +#[derive(Serialize, Deserialize, Default, Debug)] /// A (very) simple run status pub enum RunStatus { /// The last run was a succes @@ -79,12 +82,14 @@ enum RunType { /// Enum guessing at which state the program is pub enum RunState { + /// Tarpaulin is preparing the tests & test runners + Preparing(String), /// The program is compiling and the inner field is our guess as to what Compiling(String), /// The program is running the tests Testing(String), - /// The program is doing code coverage - Coverage, + // /// The program is doing code coverage + // Coverage, /// The run is finished Finished, } @@ -98,31 +103,24 @@ impl RunState { /// Output a human readable status from the current state pub fn status(&self) -> String { match self { - RunState::Compiling(guess) => format!("Compiling {}", guess), - RunState::Testing(test) => format!("Testing: {}", test), - RunState::Coverage => "Coverage".to_string(), - RunState::Finished => "Finished".to_string(), - } - } - - /// Update the status with the new info - // TODO: The coverage and some run info being dependent on this update, the method should be moved - pub fn update(&mut self, ingest: &str) -> anyhow::Result<()> { - match self { - RunState::Compiling(_) => { - if !ingest.starts_with("Compiling") { - *self = RunState::Testing(String::new()); - } + RunState::Compiling(guess) => { + format!( + "{:>10} Compiling ({guess})", + style("[Coverage]").green().bold(), + ) } - RunState::Testing(_) => { - if !ingest.starts_with("Testing") { - *self = RunState::Coverage; - } + RunState::Testing(test) => { + format!("{:>10} Testing {test}", style("[Coverage]").green().bold(),) + } + // RunState::Coverage => "Coverage".to_string(), + RunState::Finished => format!("{:>10} Finished", style("[Coverage]").green().bold(),), + RunState::Preparing(prep) => { + format!( + "{:>10} Preparing ({prep})", + style("[Coverage]").green().bold(), + ) } - RunState::Coverage => *self = RunState::Finished, - RunState::Finished => (), } - Ok(()) } } @@ -178,17 +176,56 @@ impl CurrentRunStats { Duration::default() } } + + /// Update the run info with a parsed line + fn update(&mut self, line: &str, state: &mut RunState) -> anyhow::Result<()> { + let stat = LineType::find_token(line); + match stat { + LineType::ConfigCreation => *state = RunState::Preparing("Config Creation".into()), + LineType::RunningTarpaulin => *state = RunState::Preparing("Running Tarpaullin".into()), + LineType::ProjectBuilding => *state = RunState::Preparing("Project Building".into()), + LineType::CleaningProject => *state = RunState::Preparing("Cleaning Project".into()), + LineType::LaunchingTest => *state = RunState::Preparing("Launching Tests".into()), + LineType::TestRunner(test) => *state = RunState::Testing(format!("Running [{test}]")), + LineType::LaunchingNTests(n) => { + *state = RunState::Testing(format!("Running {n} tests")) + } + LineType::Coverage(cov) => { + self.current_run.coverage = Some(cov); + *state = RunState::Finished; + } + LineType::Unparsed => (), + } + Ok(()) + } + + /// Get the coverage for the current run + pub(crate) fn get_coverage(&self) -> Option { + self.current_run.coverage + } + + /// Get the last line count or give a default value + pub(crate) fn get_last_linecount(&self) -> u64 { + match self.get_last_run() { + Some(nb) => nb.lines_parsed, + None => 6, // As good as any number + } + } } /// Create a progress bar for the run -pub fn create_progress_bar(last_duration: f64, multiprogress: &MultiProgress) -> ProgressBar { - let progress_bar = multiprogress.add(ProgressBar::new(20)); - // TODO: Update over lines parsed +pub fn create_progress_bar( + last_duration: f64, + last_lines: u64, + multiprogress: &MultiProgress, +) -> ProgressBar { + let progress_bar = multiprogress.add(ProgressBar::new(last_lines)); + progress_bar.enable_steady_tick(Duration::from_millis(100)); progress_bar.set_style( ProgressStyle::with_template( - "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}]\ - (lines: {pos}/{len}) (speed: {per_sec}) (eta: {eta})", + "{spinner:.green} [{elapsed_precise:.green}] [{wide_bar:.cyan/blue}]\ + (eta: {eta})", ) .unwrap() .progress_chars("=> ") @@ -212,30 +249,27 @@ pub fn create_progress_spinner(pb: ProgressBar, multiprogress: &MultiProgress) - let progress_spinner = multiprogress.add(pb); progress_spinner.enable_steady_tick(Duration::from_millis(100)); - progress_spinner.with_message(formatted_width("[Coverage]", "Mesuring coverage...")) + progress_spinner.with_message({ + format!( + "{:>10} Mesuring coverage...", + style("[Coverage]").green().bold(), + ) + }) } -/// Output the standard width of the program -pub fn formatted_width(cmd: &str, text: &str) -> String { - format!("{:>10} {}", style(cmd).green().bold(), text,) -} +// /// Output the standard width of the program +// #[inline] +// pub fn formatted_width(cmd: &str, text: &str) -> String { +// format!("{:>10} {}", style(cmd).green().bold(), text,) +// } /// Parse evert tarpaulin to try and guess what is happening -// FORMAT: Compiling strsim v0.11.1 -// FORMAT: Finished `test` profile [unoptimized + debuginfo] target(s) in 6.87s -// FORMAT: 2025-03-10T20:00:03.543721Z INFO cargo_tarpaulin::process_handling::linux: Launching test -// FORMAT: 2025-03-10T20:00:08.030646Z INFO cargo_tarpaulin::report: Coverage Results: -// 2025-03-19T13:50:48.031029Z  INFO cargo_tarpaulin::config: Creating config -// 2025-03-19T13:50:48.086450Z  INFO cargo_tarpaulin: Running Tarpaulin -// 2025-03-19T13:50:48.086466Z  INFO cargo_tarpaulin: Building project -// 2025-03-19T13:50:48.086469Z  INFO cargo_tarpaulin::cargo: Cleaning project -// 2025-03-19T13:51:01.196213Z  INFO cargo_tarpaulin::process_handling::linux: Launching test -pub async fn parse_all_lines_sync( +pub async fn parse_all_lines( args: &CLIArgs, run_info: &mut CurrentRunStats, mut reader: tokio::io::Split>, - progress_spinner: ProgressBar, - progress_bar: ProgressBar, + progress_spinner: &ProgressBar, + progress_bar: &ProgressBar, state: &mut RunState, ) -> anyhow::Result<()> { let _ = args; @@ -245,7 +279,7 @@ pub async fn parse_all_lines_sync( let line = String::from_utf8(line).unwrap_or_default(); progress_bar.inc(1); lines_parsed += 1; - state.update(&line)?; + run_info.update(&line, state)?; progress_spinner.set_message(state.status()); } run_info.current_run.lines_parsed = lines_parsed; @@ -300,6 +334,7 @@ impl LineType { LineType::Unparsed } } + #[cfg(test)] mod test { use crate::progressbar::LineType; diff --git a/src/utils.rs b/src/utils.rs index 0068936..c7ad52b 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -8,14 +8,13 @@ use std::{ use anyhow::Context; use indicatif::{MultiProgress, ProgressBar}; -use regex::Regex; use xshell::Shell; use crate::{ cli::CLIArgs, progressbar::{ CurrentRunStats, LastRuns, RunState, RunStatus, create_progress_bar, - create_progress_spinner, parse_all_lines_sync, + create_progress_spinner, parse_all_lines, }, }; /// Remove all the badges @@ -46,69 +45,19 @@ pub fn run_coverage( _sh: &Shell, pb: ProgressBar, args: &CLIArgs, - run_info: &mut CurrentRunStats, -) -> Result<(), anyhow::Error> { - let last_duration = run_info.get_last_timer().as_secs_f64(); + run_info: CurrentRunStats, +) -> Result { let started = Instant::now(); let multiprogress = MultiProgress::new(); let progress_spinner = create_progress_spinner(pb, &multiprogress); - let progress_bar = create_progress_bar(last_duration, &multiprogress); + let progress_bar = create_progress_bar( + run_info.get_last_timer().as_secs_f64(), + run_info.get_last_linecount(), + &multiprogress, + ); - // TODO: Update the status with basic parsing from the output - // (compiling (), linking (), running tests (), etc..) - let mut args_tarpaulin = vec!["tarpaulin", "-o", "html"]; - if args.skip_clean { - args_tarpaulin.push("--skip-clean"); - } - - let rt = tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .expect("[tokio] Failed to create runtime"); - - let mut cmd = tokio::process::Command::new("cargo"); - cmd.args(args_tarpaulin); - cmd.env("max_print_line", "3000"); - - // Specify that we want the command's standard output piped back to us. - cmd.stdout(std::process::Stdio::piped()); - cmd.stderr(std::process::Stdio::piped()); - - let run_info = rt.block_on(async { - let mut child = cmd.spawn().expect("Failed to spawn command"); - let mut state = RunState::new(); - - let stdout = child - .stdout - .take() - .expect("Child did not have a handle to stdout"); - // let stderr = child - // .stderr - // .take() - // .expect("Child did not have a handle to stderr"); - let reader = tokio::io::AsyncBufReadExt::split(tokio::io::BufReader::new(stdout), 0xA); - parse_all_lines_sync( - args, - run_info, - reader, - progress_spinner, - progress_bar, - &mut state, - ) - .await - .expect("Impossible to parse line"); - run_info.current_run.run_status = if let Ok(output) = child.wait_with_output().await { - if output.status.success() { - RunStatus::Success - } else { - RunStatus::Failure - } - } else { - RunStatus::Success - }; - run_info - }); + let mut run_info = run_tarpaulin(args, run_info, &progress_spinner, &progress_bar); if !args.no_test { // Only write the test badge if it was asked for @@ -123,10 +72,65 @@ pub fn run_coverage( }; } - // update_final_coverage(args, run_info, started, progress_spinner, progress_bar)?; - run_info.current_run.run_duration = started.elapsed(); - Ok(()) + + update_final_coverage(args, &run_info, started, progress_spinner, progress_bar)?; + Ok(run_info) +} + +/// Run tarpaulin in an async runner and iterate over the returned data +fn run_tarpaulin( + args: &CLIArgs, + mut run_info: CurrentRunStats, + progress_spinner: &ProgressBar, + progress_bar: &ProgressBar, +) -> CurrentRunStats { + let mut args_tarpaulin = vec!["tarpaulin", "-o", "html"]; + if args.skip_clean { + args_tarpaulin.push("--skip-clean"); + } + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("[tokio] Failed to create runtime"); + + let mut cmd = tokio::process::Command::new("cargo"); + cmd.args(args_tarpaulin); + cmd.env("max_print_line", "3000"); + + // Specify that we want the command's standard output piped back to us. + cmd.stdout(std::process::Stdio::piped()); + cmd.stderr(std::process::Stdio::piped()); + + rt.block_on(async { + let mut child = cmd.spawn().expect("Failed to spawn command"); + let mut state = RunState::new(); + + let stdout = child + .stdout + .take() + .expect("Child did not have a handle to stdout"); + let reader = tokio::io::AsyncBufReadExt::split(tokio::io::BufReader::new(stdout), 0xA); + parse_all_lines( + args, + &mut run_info, + reader, + progress_spinner, + progress_bar, + &mut state, + ) + .await + .expect("Impossible to parse line"); + run_info.current_run.run_status = if let Ok(output) = child.wait_with_output().await { + match output.status.success() { + true => RunStatus::Success, + false => RunStatus::Failure, + } + } else { + RunStatus::Success + }; + run_info + }) } /// Extract version and write it as a badge @@ -136,7 +140,7 @@ pub fn run_version(sh: &Shell, pb: ProgressBar, args: &CLIArgs) -> Result<(), an "{:>10} Finding vesion...", console::style("[Version]").bold().green() )); - // println!("Finding version..."); + let manifest = sh.read_file("Cargo.toml").context("Opening Cargo.toml")?; let version = manifest .split_once("version = \"") @@ -145,7 +149,7 @@ pub fn run_version(sh: &Shell, pb: ProgressBar, args: &CLIArgs) -> Result<(), an .ok_or_else(|| anyhow::format_err!("can't find version field in the manifest"))?; write_badge("version", version, &args.version_color, "version", args) .context("Writing version badge")?; - // println!(" Done!"); + pb.finish_with_message(format!( "{:>10} Found {version} - Badge done ({}ms).", console::style("[Version]").bold().green(), @@ -187,22 +191,14 @@ pub fn write_badge( } /// Update the final coverage from the final output -// FORMAT: 84.78% coverage, 78/92 lines covered, -15.22% change in coverage -// TODO: Add this into the line parser fn update_final_coverage( args: &CLIArgs, - run_info: &mut CurrentRunStats, + run_info: &CurrentRunStats, started: Instant, progress_spinner: ProgressBar, progress_bar: ProgressBar, - run: std::process::Output, ) -> Result<(), anyhow::Error> { - let test = String::from_utf8(run.stdout)?; - let re = Regex::new(r"(\d+.\d+)% coverage, ").unwrap(); - let coverage = re.captures(&test); - run_info.current_run.run_status = if let Some(c) = coverage { - let coverage_value = c.get(1).unwrap().as_str(); - let coverage_value: f64 = coverage_value.parse()?; + if let Some(coverage_value) = run_info.get_coverage() { let color = if coverage_value >= args.high_coverage_percent { &args.high_coverage_color } else if coverage_value > args.mid_coverage_percent {