diff --git a/Cargo.toml b/Cargo.toml index 3c1e676..f2e503d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,11 +9,15 @@ anyhow = "1.0.92" clap = { version = "4.5.31", features = ["derive"] } console = "0.15.11" indicatif = "0.17.11" +logos = "0.15.0" regex = "1.11.1" serde = { version = "1.0.219", features = ["derive"] } -tokio = { version = "1.44.1", features = ["full"]} #["process", "rt", "io-util", "macros"] } +tokio = { version = "1.44.1", features = ["full", "process"] } #["process", "rt", "io-util", "macros"] } toml = "0.8.20" xshell = "0.2.6" [workspace.package] rust-version = "1.85" + +[dev-dependencies] +insta = "1.42.2" diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..c14b311 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,56 @@ +//! All CLI parsing and data + +use clap::Parser; + +#[derive(Parser, Debug)] +#[command(version, about, long_about = None)] +/// The struct representing all CLI arguments passed to the program, build with clap-derive +pub struct CLIArgs { + #[arg(short, long)] + /// Skip the cargo clean that tarpaulin would run, see tarpaulin --skip-clean documentation + pub skip_clean: bool, + + // #[arg(short, long)] + // /// Don't delete the old badges, they may be overwritten + // keep_badges: bool, + #[arg(short = 't', long)] + /// Dont generate the test:failing/passing badge + pub no_test: bool, + #[arg(short = 'c', long)] + /// Don't run the coverage and dont generate the coverage:(percent) badge + pub no_coverage: bool, + #[arg(short = 'v', long)] + /// Don't run the version tag check and dont generage the version:(number) badge + pub no_version: bool, + + #[arg(long, default_value_t = String::from("orange"))] + /// The color used to use on the version badge + pub version_color: String, + #[arg(long, default_value_t = String::from("red"))] + /// The color used to indicate failure on the test badges + pub failing_color: String, + #[arg(long, default_value_t = String::from("green"))] + /// The color used to indicate success on the badges + pub success_color: String, + + /// The color used on a high coverage + #[arg(long, default_value_t = String::from("green"))] + pub high_coverage_color: String, + /// The color used on a mid coverage + #[arg(long, default_value_t = String::from("orange"))] + pub mid_coverage_color: String, + /// The color used on a low coverage + #[arg(long, default_value_t = String::from("red"))] + pub low_coverage_color: String, + + /// The percent indicating a high coverage + #[arg(long, default_value_t = 1.)] + pub high_coverage_percent: f64, + /// The percent indicating a mid coverage + #[arg(long, default_value_t = 0.8)] + pub mid_coverage_percent: f64, + + #[arg(short, long, default_value_t = String::from("badges"))] + /// The output directory where all the badges will be saved + pub output: String, +} diff --git a/src/main.rs b/src/main.rs index c02ac3e..d909eb1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,243 +1,19 @@ //! Basic badge generation using badge-maker and cargo-tarpaulin #![warn(clippy::missing_docs_in_private_items)] + // TODO: Testing and helper structs/methods // TODO: Better error handling -use anyhow::Context; use clap::Parser; -use console::style; -use indicatif::{MultiProgress, ProgressBar, ProgressState, ProgressStyle}; -use regex::Regex; -use serde::{Deserialize, Serialize}; -use std::io::Read; -use std::time::{Duration, Instant}; -use std::{fs::File, io::Write}; -use tokio::io::AsyncBufReadExt; -use tokio::runtime; +use cli::CLIArgs; +use indicatif::ProgressBar; +use progressbar::CurrentRunStats; +use utils::{load_status, remove_badges, run_coverage, run_version}; -use std::str; use xshell::Shell; -#[derive(Serialize, Deserialize, Default)] -/// Informations on the last run -/// -/// The informations are "split" between non-skip and skip instead of a -/// hash/identifier list storing many different kind of profiles -/// -/// A more thorough information struct would likely be useful however -/// this should the trick for now -struct LastRuns { - /// Status of the last run with full clean - last_run_clean: Option, - /// Status of the last run without a full clean - last_run_incremental: Option, -} - -#[derive(Serialize, Deserialize)] -/// The stats of a run, useful to print more helpful progress info and debug infos -struct RunStats { - /// Duration of the last run without a full clean - run_duration: Duration, - /// Status of the last run - run_status: RunStatus, - /// Lines parsed by the rust_autobadge - lines_parsed: usize, -} -impl Default for RunStats { - fn default() -> Self { - Self { - run_duration: Duration::from_secs(10), - run_status: RunStatus::default(), - lines_parsed: 10, - } - } -} - -/// Current run info, including the last run to save -struct CurrentRunStats { - /// The last run information, to be updated and saved again - last_runs_save: LastRuns, - /// Current run type - run_type: RunType, - /// The informations on the current run - current_run: RunStats, -} - -#[derive(Serialize, Deserialize, Default)] -/// A (very) simple run status -enum RunStatus { - /// The last run was a succes - Success, - #[default] - /// The tests failed to run - Failure, -} - -#[derive(Clone, Copy)] -#[allow(clippy::missing_docs_in_private_items)] -/// The enum over every type of run possible -/// This differentiation is usefull for debugging/time evaluation -enum RunType { - /// Any kind of run without a cleanup and full rebuild - Incremental, - /// Any kind of run with a cleanup and rebuild - Clean, -} - -/// Enum guessing at which state the program is -enum RunState { - /// 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 run is finished - Finished, -} - -impl RunState { - /// Create a new state - fn new() -> Self { - RunState::Compiling(String::new()) - } - - /// Output a human readable status from the current state - 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 - fn update(&mut self, ingest: &str) -> anyhow::Result<()> { - match self { - RunState::Compiling(_) => { - if !ingest.starts_with("Compiling") { - *self = RunState::Testing(String::new()); - } - } - RunState::Testing(_) => { - if !ingest.starts_with("Testing") { - *self = RunState::Coverage; - } - } - RunState::Coverage => *self = RunState::Finished, - RunState::Finished => (), - } - Ok(()) - } -} - -impl CurrentRunStats { - /// Generate a new run with the current context - fn from_last_run_with_context(last_run: LastRuns, args: &CLIArgs) -> Self { - let run_type = match args.skip_clean { - true => RunType::Incremental, - false => RunType::Clean, - }; - Self { - last_runs_save: last_run, - run_type, - current_run: RunStats::default(), - } - } - - /// Update the last run to save it - fn into_save_runs(self) -> LastRuns { - let mut last_runs = self.last_runs_save; - match self.run_type { - RunType::Incremental => last_runs.last_run_incremental = Some(self.current_run), - RunType::Clean => last_runs.last_run_clean = Some(self.current_run), - } - last_runs - } - - /// Save the status on disk - /// - /// Note that once saved, the status is consummed - pub fn save_status(self) -> anyhow::Result<()> { - let mut f = File::create(".run_status.toml")?; - f.write_all( - toml::to_string_pretty(&self.into_save_runs()) - .context("Serializing Last Run info")? - .as_bytes(), - ) - .context("Writing config to disk") - } - - /// Get the last run of the same type of runner - fn get_last_run(&self) -> &Option { - match self.run_type { - RunType::Incremental => &self.last_runs_save.last_run_incremental, - RunType::Clean => &self.last_runs_save.last_run_clean, - } - } - /// Get the last timer of the same type of runner - fn get_last_timer(&self) -> Duration { - if let Some(d) = self.get_last_run() { - d.run_duration - } else { - Duration::default() - } - } -} - -#[derive(Parser, Debug)] -#[command(version, about, long_about = None)] -/// The struct representing all CLI arguments passed to the program, build with clap-derive -struct CLIArgs { - #[arg(short, long)] - /// Skip the cargo clean that tarpaulin would run, see tarpaulin --skip-clean documentation - skip_clean: bool, - - // #[arg(short, long)] - // /// Don't delete the old badges, they may be overwritten - // keep_badges: bool, - #[arg(short = 't', long)] - /// Dont generate the test:failing/passing badge - no_test: bool, - #[arg(short = 'c', long)] - /// Don't run the coverage and dont generate the coverage:(percent) badge - no_coverage: bool, - #[arg(short = 'v', long)] - /// Don't run the version tag check and dont generage the version:(number) badge - no_version: bool, - - #[arg(long, default_value_t = String::from("orange"))] - /// The color used to use on the version badge - version_color: String, - #[arg(long, default_value_t = String::from("red"))] - /// The color used to indicate failure on the test badges - failing_color: String, - #[arg(long, default_value_t = String::from("green"))] - /// The color used to indicate success on the badges - success_color: String, - - /// The color used on a high coverage - #[arg(long, default_value_t = String::from("green"))] - high_coverage_color: String, - /// The color used on a mid coverage - #[arg(long, default_value_t = String::from("orange"))] - mid_coverage_color: String, - /// The color used on a low coverage - #[arg(long, default_value_t = String::from("red"))] - low_coverage_color: String, - - /// The percent indicating a high coverage - #[arg(long, default_value_t = 1.)] - high_coverage_percent: f64, - /// The percent indicating a mid coverage - #[arg(long, default_value_t = 0.8)] - mid_coverage_percent: f64, - - #[arg(short, long, default_value_t = String::from("badges"))] - /// The output directory where all the badges will be saved - output: String, -} +mod cli; +mod progressbar; +mod utils; // TODO: No anyhow result, first print a conprehensive error, then return an error // : To avoid code reuse, a custom pb with a behaviour on error would be nice @@ -248,24 +24,17 @@ struct CLIArgs { // if no tarp & test => only run test & generate test only // if no tarp & no test => no generation // #[cfg(not(tarpaulin_include))] - fn main() -> anyhow::Result<()> { let args = CLIArgs::parse(); let run_status = load_status(&args); let mut run_status = CurrentRunStats::from_last_run_with_context(run_status, &args); - let new_progress_bar = || { - ProgressBar::new_spinner() - // .with_style( - // ProgressStyle::default_spinner() - // .tick_strings(&["⢎⡰", "⢎⡡", "⢎⡑", "⢎⠱", "⠎⡱", "⢊⡱", "⢌⡱", "⢆⡱", " "]), - // ) - }; + let new_progress_bar = || ProgressBar::new_spinner(); let sh = Shell::new()?; - // TODO: Cleanup badges beforehand + if !args.skip_clean { - // sh.delete_dir(args.output)?; + remove_badges(&args, &sh); } sh.create_dir(&args.output)?; @@ -276,10 +45,11 @@ fn main() -> anyhow::Result<()> { match (args.no_coverage, args.no_test) { (true, true) => (), (true, false) => { - unimplemented!("Please run with tarpaulin for now") // run_tests_only(&sh, pb_model.clone(), &args)?; + unimplemented!("Please run with tarpaulin for now") } - (false, true) => run_coverage(&sh, new_progress_bar(), &args, &mut run_status)?, // The coverage know wether to write the badge test with the cli args + // 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)?, } @@ -289,289 +59,6 @@ fn main() -> anyhow::Result<()> { Ok(()) } -/// Load the run status from disk -fn load_status(args: &CLIArgs) -> LastRuns { - let _ = args; // Always try to load from disk - if let Ok(mut f) = File::open(".run_status.toml") { - let mut content = String::new(); - if f.read_to_string(&mut content).is_ok() { - if let Ok(deserde) = toml::from_str(&content) { - return deserde; - } - } - } - LastRuns::default() -} - -/// Run the coverage functions -// #[coverage(off)] // No real coverage can be done as it would recurse indefinitely -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(); - 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); - - // 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 = 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::BufReader::new(stdout).split(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 - }); - - if !args.no_test { - // Only write the test badge if it was asked for - // TODO: isolate in it's own command or use the wrapper struct to avoid multiple write badge - match run_info.current_run.run_status { - RunStatus::Success => { - write_badge("test", "passing", &args.success_color, "test", args)? - } - RunStatus::Failure => { - write_badge("test", "failing", &args.failing_color, "test", args)? - } - }; - } - - // update_final_coverage(args, run_info, started, progress_spinner, progress_bar)?; - - run_info.current_run.run_duration = started.elapsed(); - Ok(()) -} - -/// Create a progress bar for the run -fn create_progress_bar(last_duration: f64, multiprogress: &MultiProgress) -> ProgressBar { - let progress_bar = multiprogress.add(ProgressBar::new(20)); - // TODO: Update over lines parsed - 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})", - ) - .unwrap() - .progress_chars("=> ") - .with_key( - "eta", - move |state: &ProgressState, w: &mut dyn std::fmt::Write| { - write!( - w, - "{:.1}s", - (last_duration - state.elapsed().as_secs_f64()).max(0.) - ) - .unwrap() - }, - ), - ); - progress_bar -} - -/// Create a spinner, with a model -fn create_progress_spinner(pb: ProgressBar, multiprogress: &MultiProgress) -> ProgressBar { - let progress_spinner = multiprogress.add(pb); - progress_spinner.enable_steady_tick(Duration::from_millis(100)); - - progress_spinner.with_message(formatted_width("[Coverage]", "Mesuring coverage...")) -} - -/// Output the standard width of the program -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 -async fn parse_all_lines_sync( - args: &CLIArgs, - run_info: &mut CurrentRunStats, - mut reader: tokio::io::Split>, - progress_spinner: ProgressBar, - progress_bar: ProgressBar, - state: &mut RunState, -) -> anyhow::Result<()> { - let _ = args; - let mut lines_parsed = 0; - - while let Ok(Some(line)) = reader.next_segment().await { - let line = String::from_utf8(line).unwrap_or_default(); - progress_bar.inc(1); - lines_parsed += 1; - state.update(&line)?; - progress_spinner.set_message(state.status()); - } - run_info.current_run.lines_parsed = lines_parsed; - Ok(()) -} - -/// 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, - 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); - if let Some(c) = coverage { - let coverage_value = c.get(1).unwrap().as_str(); - let coverage_value: f64 = coverage_value.parse()?; - let color = if coverage_value >= args.high_coverage_percent { - &args.high_coverage_color - } else if coverage_value > args.mid_coverage_percent { - &args.mid_coverage_color - } else { - &args.low_coverage_color - }; - write_badge( - "test-coverage", - &format!("{coverage_value:.0}%"), - color, - "coverage", - args, - )?; - - progress_spinner.finish_with_message(format!( - "{:>10} Found {coverage_value:.2}% - Badge done ({:.2}s)", - style("[Coverage]").bold().green(), - started.elapsed().as_secs_f32() - )); - run_info.current_run.run_status = RunStatus::Success; - } else { - write_badge("test-coverage", "N/A", "red", "coverage", args)?; - progress_spinner.finish_with_message(format!( - "{:<10} Couldn't find coverage - Badge failed ({:.2}s)", - style("[Coverage]").bold().red(), - started.elapsed().as_secs_f32() - )); - run_info.current_run.run_status = RunStatus::Failure; - } - progress_bar.finish_and_clear(); - Ok(()) -} - -/// Extract version and write it as a badge -fn run_version(sh: &Shell, pb: ProgressBar, args: &CLIArgs) -> Result<(), anyhow::Error> { - let started = Instant::now(); - let pb = pb.with_message(format!( - "{:>10} Finding vesion...", - style("[Version]").bold().green() - )); - // println!("Finding version..."); - let manifest = sh.read_file("Cargo.toml").context("Opening Cargo.toml")?; - let version = manifest - .split_once("version = \"") - .and_then(|it| it.1.split_once('\"')) - .map(|it| it.0) - .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).", - style("[Version]").bold().green(), - started.elapsed().as_millis() - )); - Ok(()) -} - -// fn run_test(sh: &Shell) -> Result<(), anyhow::Error> { -// print!("Running tests..."); -// let test_status = cmd!(sh, "cargo test --").ignore_stdout().quiet().run(); -// if let Err(e) = test_status { -// println!("failed!"); -// println!("{:?}", e); -// write_badge("test", "failing", "test")?; -// } else { -// println!("succes!"); -// write_badge("test", "passed", "test")?; -// }; -// println!("done!"); -// Ok(()) -// } - -/// Write the badge to a specific directory using badge-maker -fn write_badge( - name: &str, - value: &str, - color: &str, - test_name: &str, - args: &CLIArgs, -) -> Result<(), anyhow::Error> { - let output = std::process::Command::new("badge-maker") - .args(vec!["-s", "plastic", name, value, "-c", color]) - .output() - .context("Running badge-maker to export the badge")?; - let mut f = File::create(format!("{}/{}.svg", args.output, test_name)).unwrap(); - f.write_all(&output.stdout)?; - Ok(()) -} - #[cfg(test)] mod test { #[ignore] diff --git a/src/progressbar.rs b/src/progressbar.rs new file mode 100644 index 0000000..ae0be19 --- /dev/null +++ b/src/progressbar.rs @@ -0,0 +1,340 @@ +//! All progressbar logic + +use crate::CLIArgs; +use anyhow::Context; +use console::style; +use indicatif::{MultiProgress, ProgressBar, ProgressState, ProgressStyle}; +use logos::Logos; +use std::fs::File; +use std::io::Write; + +use serde::{Deserialize, Serialize}; +use std::time::Duration; + +#[derive(Serialize, Deserialize, Default)] +/// Informations on the last run +/// +/// The informations are "split" between non-skip and skip instead of a +/// hash/identifier list storing many different kind of profiles +/// +/// A more thorough information struct would likely be useful however +/// this should the trick for now +pub struct LastRuns { + /// Status of the last run with full clean + last_run_clean: Option, + /// Status of the last run without a full clean + last_run_incremental: Option, +} + +#[derive(Serialize, Deserialize)] +/// 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 + pub run_duration: Duration, + /// Status of the last run + pub run_status: RunStatus, + /// Lines parsed by the rust_autobadge + pub lines_parsed: usize, +} +impl Default for RunStats { + fn default() -> Self { + Self { + run_duration: Duration::from_secs(10), + run_status: RunStatus::default(), + lines_parsed: 10, + } + } +} + +/// Current run info, including the last run to save +pub struct CurrentRunStats { + /// The last run information, to be updated and saved again + last_runs_save: LastRuns, + /// Current run type + run_type: RunType, + /// The informations on the current run + pub current_run: RunStats, +} + +#[derive(Serialize, Deserialize, Default)] +/// A (very) simple run status +pub enum RunStatus { + /// The last run was a succes + Success, + #[default] + /// The tests failed to run + Failure, +} + +#[derive(Clone, Copy)] +#[allow(clippy::missing_docs_in_private_items)] +/// The enum over every type of run possible +/// This differentiation is usefull for debugging/time evaluation +enum RunType { + /// Any kind of run without a cleanup and full rebuild + Incremental, + /// Any kind of run with a cleanup and rebuild + Clean, +} + +/// Enum guessing at which state the program is +pub enum RunState { + /// 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 run is finished + Finished, +} + +impl RunState { + /// Create a new state + pub fn new() -> Self { + RunState::Compiling(String::new()) + } + + /// 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::Testing(_) => { + if !ingest.starts_with("Testing") { + *self = RunState::Coverage; + } + } + RunState::Coverage => *self = RunState::Finished, + RunState::Finished => (), + } + Ok(()) + } +} + +impl CurrentRunStats { + /// Generate a new run with the current context + pub fn from_last_run_with_context(last_run: LastRuns, args: &CLIArgs) -> Self { + let run_type = match args.skip_clean { + true => RunType::Incremental, + false => RunType::Clean, + }; + Self { + last_runs_save: last_run, + run_type, + current_run: RunStats::default(), + } + } + + /// Update the last run to save it + fn into_save_runs(self) -> LastRuns { + let mut last_runs = self.last_runs_save; + match self.run_type { + RunType::Incremental => last_runs.last_run_incremental = Some(self.current_run), + RunType::Clean => last_runs.last_run_clean = Some(self.current_run), + } + last_runs + } + + /// Save the status on disk + /// + /// Note that once saved, the status is consummed + pub fn save_status(self) -> anyhow::Result<()> { + let mut f = File::create(".run_status.toml")?; + f.write_all( + toml::to_string_pretty(&self.into_save_runs()) + .context("Serializing Last Run info")? + .as_bytes(), + ) + .context("Writing config to disk") + } + + /// Get the last run of the same type of runner + fn get_last_run(&self) -> &Option { + match self.run_type { + RunType::Incremental => &self.last_runs_save.last_run_incremental, + RunType::Clean => &self.last_runs_save.last_run_clean, + } + } + /// Get the last timer of the same type of runner + pub fn get_last_timer(&self) -> Duration { + if let Some(d) = self.get_last_run() { + d.run_duration + } else { + Duration::default() + } + } +} + +/// 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 + 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})", + ) + .unwrap() + .progress_chars("=> ") + .with_key( + "eta", + move |state: &ProgressState, w: &mut dyn std::fmt::Write| { + write!( + w, + "{:.1}s", + (last_duration - state.elapsed().as_secs_f64()).max(0.) + ) + .unwrap() + }, + ), + ); + progress_bar +} + +/// Create a spinner, with a model +pub fn create_progress_spinner(pb: ProgressBar, multiprogress: &MultiProgress) -> ProgressBar { + let progress_spinner = multiprogress.add(pb); + progress_spinner.enable_steady_tick(Duration::from_millis(100)); + + progress_spinner.with_message(formatted_width("[Coverage]", "Mesuring coverage...")) +} + +/// Output the standard width of the program +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( + args: &CLIArgs, + run_info: &mut CurrentRunStats, + mut reader: tokio::io::Split>, + progress_spinner: ProgressBar, + progress_bar: ProgressBar, + state: &mut RunState, +) -> anyhow::Result<()> { + let _ = args; + let mut lines_parsed = 0; + + while let Ok(Some(line)) = reader.next_segment().await { + let line = String::from_utf8(line).unwrap_or_default(); + progress_bar.inc(1); + lines_parsed += 1; + state.update(&line)?; + progress_spinner.set_message(state.status()); + } + run_info.current_run.lines_parsed = lines_parsed; + Ok(()) +} + +#[derive(Logos, Debug, PartialEq)] +#[logos(skip r"[ \t\n\f]+")] +#[allow(missing_docs, clippy::missing_docs_in_private_items)] +enum LineType { + #[token("Creating config")] + ConfigCreation, + + #[token("Running Tarpaulin")] + RunningTarpaulin, + + #[token("Building project")] + ProjectBuilding, + + #[token("Cleaning project")] + CleaningProject, + + #[token("Launching test")] + LaunchingTest, + + // #[token(r"running /\alpha+/", |lex| lex.remainder().to_string())] + // TestRunner(String), + + // // running 4 tests + #[regex(r"running \d+ tests", |lex| lex.slice()[8..lex.slice().len()-4].to_string().parse().ok())] + LaunchingNTests(String), + + // // test test::test_badge_writing ... ignored + // #[regex("test .* ... .*")] + // LaunchingOneTest(String), + + // // // 0.00% coverage, 0/163 lines covered, +0.00% change in coverage + // // #[regex(r"\d+.\d+% coverage,")] + // // Coverage(f64), + // + /// Default variant, meaning the line couldn't be parsed + Unparsed, +} + +impl LineType { + /// Find a valid token given an input line + pub fn find_token(line: &str) -> Self { + let lex = LineType::lexer(line); + if let Some(token) = lex.flatten().next() { + return token; + } + LineType::Unparsed + } +} +#[cfg(test)] +mod test { + use crate::progressbar::LineType; + + #[test] + fn test_line_parser() { + let inner_data = &[ + "[2m2025-03-19T13:50:48.031029Z  INFO cargo_tarpaulin::config: Creating config", + "[2m2025-03-19T13:50:48.086450Z  INFO cargo_tarpaulin: Running Tarpaulin", + "[2m2025-03-19T13:50:48.086466Z  INFO cargo_tarpaulin: Building project", + "[2m2025-03-19T13:50:48.086469Z  INFO cargo_tarpaulin::cargo: Cleaning project", + "[2m2025-03-19T13:51:01.196213Z  INFO cargo_tarpaulin::process_handling::linux: Launching test", + "[2m2025-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", + ]; + for line in inner_data { + println!("{:?},", LineType::find_token(line)); + } + let c: Vec<(String, LineType)> = inner_data + .iter() + .map(|v| (v.to_string(), LineType::find_token(v))) + .collect(); + insta::assert_debug_snapshot!(c); + todo!() + } +} diff --git a/src/snapshots/rust_autobadges__progressbar__test__line_parser.snap.new b/src/snapshots/rust_autobadges__progressbar__test__line_parser.snap.new new file mode 100644 index 0000000..07e9ed2 --- /dev/null +++ b/src/snapshots/rust_autobadges__progressbar__test__line_parser.snap.new @@ -0,0 +1,85 @@ +--- +source: src/progressbar.rs +assertion_line: 337 +expression: c +--- +[ + ( + "[2m2025-03-19T13:50:48.031029Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin::config\u{1b}[0m\u{1b}[2m:\u{1b}[0m Creating config", + ConfigCreation, + ), + ( + "[2m2025-03-19T13:50:48.086450Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin\u{1b}[0m\u{1b}[2m:\u{1b}[0m Running Tarpaulin", + RunningTarpaulin, + ), + ( + "[2m2025-03-19T13:50:48.086466Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin\u{1b}[0m\u{1b}[2m:\u{1b}[0m Building project", + ProjectBuilding, + ), + ( + "[2m2025-03-19T13:50:48.086469Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin::cargo\u{1b}[0m\u{1b}[2m:\u{1b}[0m Cleaning project", + CleaningProject, + ), + ( + "[2m2025-03-19T13:51:01.196213Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin::process_handling::linux\u{1b}[0m\u{1b}[2m:\u{1b}[0m Launching test", + LaunchingTest, + ), + ( + "[2m2025-03-19T13:51:01.196247Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin::process_handling\u{1b}[0m\u{1b}[2m:\u{1b}[0m running /home/beffroi/Documents/Git/rust_autobadges/target/debug/deps/rust_autobadges-88a057f7e5bc03ef", + Unparsed, + ), + ( + "running 4 tests", + LaunchingNTests( + "4 t", + ), + ), + ( + "test test::test_badge_writing ... ignored", + Unparsed, + ), + ( + "test test::test_coverage_parsing ... ignored", + Unparsed, + ), + ( + "test test::test_structs ... ignored", + Unparsed, + ), + ( + "test test::test_version_parsing ... ignored", + Unparsed, + ), + ( + "test result: ok. 0 passed; 0 failed; 4 ignored; 0 measured; 0 filtered out; finished in 0.00s", + Unparsed, + ), + ( + "\u{1b}[2m2025-03-19T13:51:07.936086Z\u{1b}[0m \u{1b}[32m INFO\u{1b}[0m \u{1b}[2mcargo_tarpaulin::report\u{1b}[0m\u{1b}[2m:\u{1b}[0m Coverage Results:", + Unparsed, + ), + ( + "|| Uncovered Lines:", + Unparsed, + ), + ( + "|| 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", + Unparsed, + ), + ( + "|| Tested/Total Lines:", + Unparsed, + ), + ( + "|| src/main.rs: 0/163 +0.00%", + Unparsed, + ), + ( + "|| ", + Unparsed, + ), + ( + "0.00% coverage, 0/163 lines covered, +0.00% change in coverage", + Unparsed, + ), +] diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..0068936 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,238 @@ +//! Run the actions selected by the CLI + +use std::{ + fs::File, + io::{Read, Write}, + time::Instant, +}; + +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, + }, +}; +/// Remove all the badges +pub fn remove_badges(args: &CLIArgs, sh: &Shell) { + let _ = sh.remove_path(args.output.clone() + "/coverage.svg"); + let _ = sh.remove_path(args.output.clone() + "/release.svg"); + let _ = sh.remove_path(args.output.clone() + "/test.svg"); + let _ = sh.remove_path(args.output.clone() + "/version.svg"); +} + +/// Load the run status from disk +pub fn load_status(args: &CLIArgs) -> LastRuns { + let _ = args; // Always try to load from disk + if let Ok(mut f) = File::open(".run_status.toml") { + let mut content = String::new(); + if f.read_to_string(&mut content).is_ok() { + if let Ok(deserde) = toml::from_str(&content) { + return deserde; + } + } + } + LastRuns::default() +} + +/// Run the coverage functions +// #[coverage(off)] // No real coverage can be done as it would recurse indefinitely +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(); + 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); + + // 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 + }); + + if !args.no_test { + // Only write the test badge if it was asked for + // TODO: isolate in it's own command or use the wrapper struct to avoid multiple write badge + match run_info.current_run.run_status { + RunStatus::Success => { + write_badge("test", "passing", &args.success_color, "test", args)? + } + RunStatus::Failure => { + write_badge("test", "failing", &args.failing_color, "test", args)? + } + }; + } + + // update_final_coverage(args, run_info, started, progress_spinner, progress_bar)?; + + run_info.current_run.run_duration = started.elapsed(); + Ok(()) +} + +/// Extract version and write it as a badge +pub fn run_version(sh: &Shell, pb: ProgressBar, args: &CLIArgs) -> Result<(), anyhow::Error> { + let started = Instant::now(); + let pb = pb.with_message(format!( + "{:>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 = \"") + .and_then(|it| it.1.split_once('\"')) + .map(|it| it.0) + .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(), + started.elapsed().as_millis() + )); + Ok(()) +} + +// pub fn run_test(sh: &Shell) -> Result<(), anyhow::Error> { +// print!("Running tests..."); +// let test_status = cmd!(sh, "cargo test --").ignore_stdout().quiet().run(); +// if let Err(e) = test_status { +// println!("failed!"); +// println!("{:?}", e); +// write_badge("test", "failing", "test")?; +// } else { +// println!("succes!"); +// write_badge("test", "passed", "test")?; +// }; +// println!("done!"); +// Ok(()) +// } + +/// Write the badge to a specific directory using badge-maker +pub fn write_badge( + name: &str, + value: &str, + color: &str, + test_name: &str, + args: &CLIArgs, +) -> Result<(), anyhow::Error> { + let output = std::process::Command::new("badge-maker") + .args(vec!["-s", "plastic", name, value, "-c", color]) + .output() + .context("Running badge-maker to export the badge")?; + let mut f = File::create(format!("{}/{}.svg", args.output, test_name)).unwrap(); + f.write_all(&output.stdout)?; + Ok(()) +} + +/// 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, + 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()?; + let color = if coverage_value >= args.high_coverage_percent { + &args.high_coverage_color + } else if coverage_value > args.mid_coverage_percent { + &args.mid_coverage_color + } else { + &args.low_coverage_color + }; + write_badge( + "test-coverage", + &format!("{coverage_value:.0}%"), + color, + "coverage", + args, + )?; + + progress_spinner.finish_with_message(format!( + "{:>10} Found {coverage_value:.2}% - Badge done ({:.2}s)", + console::style("[Coverage]").bold().green(), + started.elapsed().as_secs_f32() + )); + RunStatus::Success + } else { + write_badge("test-coverage", "N/A", "red", "coverage", args)?; + progress_spinner.finish_with_message(format!( + "{:<10} Couldn't find coverage - Badge failed ({:.2}s)", + console::style("[Coverage]").bold().red(), + started.elapsed().as_secs_f32() + )); + RunStatus::Failure + }; + progress_bar.finish_and_clear(); + Ok(()) +}