Not working, in a good way ?

This commit is contained in:
Dandaedre 2025-03-19 08:17:08 -05:00
parent d911510a64
commit c79b101d52
3 changed files with 235 additions and 62 deletions

7
.run_status.toml Normal file
View File

@ -0,0 +1,7 @@
[last_run_incremental]
run_status = "Failure"
lines_parsed = 12
[last_run_incremental.run_duration]
secs = 13
nanos = 274357405

View File

@ -11,6 +11,7 @@ console = "0.15.11"
indicatif = "0.17.11"
regex = "1.11.1"
serde = { version = "1.0.219", features = ["derive"] }
tokio = { version = "1.44.1", features = ["full"]} #["process", "rt", "io-util", "macros"] }
toml = "0.8.20"
xshell = "0.2.6"

View File

@ -1,16 +1,20 @@
//! 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::{ProgressBar, ProgressState, ProgressStyle};
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, process::Command};
use std::{fs::File, io::Write};
use tokio::io::AsyncBufReadExt;
use tokio::runtime;
use anyhow::Context;
use clap::Parser;
use regex::Regex;
use std::str;
use xshell::Shell;
#[derive(Serialize, Deserialize, Default)]
@ -35,12 +39,15 @@ struct RunStats {
run_duration: Duration,
/// Status of the last run
run_status: RunStatus,
/// Lines parsed by the rust_autobadge
lines_parsed: usize,
}
impl Default for RunStats{
impl Default for RunStats {
fn default() -> Self {
Self{
Self {
run_duration: Duration::from_secs(10),
run_status: RunStatus::default(),
lines_parsed: 10,
}
}
}
@ -66,8 +73,13 @@ enum RunStatus {
}
#[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,
}
@ -95,18 +107,39 @@ impl CurrentRunStats {
last_runs
}
/// Get the last run of the same type
fn get_last_run(&self) -> &Option<RunStats>{
match self.run_type{
/// 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<RunStats> {
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
@ -166,11 +199,12 @@ 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 run_status = CurrentRunStats::from_last_run_with_context(run_status, &args);
let mut run_status = CurrentRunStats::from_last_run_with_context(run_status, &args);
let new_progress_bar = || {
ProgressBar::new_spinner()
@ -196,12 +230,11 @@ fn main() -> anyhow::Result<()> {
unimplemented!("Please run with tarpaulin for now")
// run_tests_only(&sh, pb_model.clone(), &args)?;
}
(false, true) => run_coverage(&sh, new_progress_bar(), &args, &run_status)?, // The coverage know wether to write the badge test with the cli args
(false, false) => run_coverage(&sh, new_progress_bar(), &args, &run_status)?,
(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
(false, false) => run_coverage(&sh, new_progress_bar(), &args, &mut run_status)?,
}
// TODO: Maybe make save a method instead ?
if let Err(e) = save_status(&run_status.into_save_runs()) {
if let Err(e) = run_status.save_status() {
println!("Couldn't save the run configuration: {e}");
}
Ok(())
@ -221,38 +254,122 @@ fn load_status(args: &CLIArgs) -> LastRuns {
LastRuns::default()
}
/// Save the status on disk
fn save_status(status: &LastRuns) -> anyhow::Result<()> {
let mut f = File::create(".run_status.toml")?;
f.write_all(
toml::to_string_pretty(status)
.context("Serializing Last Run info")?
.as_bytes(),
)
.context("Writing config to disk")
}
/// Run the coverage functions
// 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:
// #[coverage(off)] // No real coverage can be done as it would recurse indefinitely
fn run_coverage(_sh: &Shell, pb: ProgressBar, args: &CLIArgs, run_info: &CurrentRunStats) -> Result<(), anyhow::Error> {
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();
// FORMAT: 84.78% coverage, 78/92 lines covered, -15.22% change in coverage
let pb = pb.with_message(format!(
"{:>10} Mesuring coverage...",
style("[Coverage]").green().bold()
));
pb.enable_steady_tick(Duration::from_millis(100));
let last_duration = Duration::from_secs(2).as_secs_f64();
let personnal_progress_bar = ProgressBar::new(20); // Update over lines parsed
personnal_progress_bar
.set_style(ProgressStyle::with_template(
"{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] (lines: {pos}/{len}) (speed: {per_sec}) (eta: {eta})",
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 (<crates>), linking (<project>), running tests (<latest parsed test name>), etc..)
// cmd!(sh, "cargo tarpaulin").quiet().ignore_stdout().run()?;
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_time()
.enable_io()
.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());
// // FORMAT: 84.78% coverage, 78/92 lines covered, -15.22% change in coverage
// let mut child = cmd.spawn().expect("Failed to spawn command");
// let stdout = child
// .stdout
// .take()
// .expect("Child did not have a handle to stdout");
// let reader = tokio::io::BufReader::new(stdout).split(0xA);
// // Ensure the child process is spawned in the runtime so it can
// // make progress on its own while we await for any output.
// tokio::task::spawn(async move {
// let _status = child
// .wait()
// .await
// .expect("Child process encountered an error");
// // sleep(Duration::from_millis(100)).await;
// // println!("Child status was: {}", status);
// });
rt.block_on(async {
let mut child = cmd.spawn().expect("Failed to spawn command");
let stdout = child
.stdout
.take()
.expect("Child did not have a handle to stdout");
let mut reader = tokio::io::BufReader::new(stdout).split(0xA);
while let Ok(Some(line)) = reader.next_segment().await {
// progress_spinner.set_message(
// // String::from_utf8(line).unwrap_or_default(), // "No",
// "no",
// );
}
// parse_all_line_sync(args, run_info, reader, progress_spinner, progress_bar)
// .await
// .expect("Impossible to parse line");
});
// 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 &output.status.success() {
// true => write_badge("test", "passing", &args.success_color, "test", args)?,
// false => write_badge("test", "failing", &args.failing_color, "test", args)?,
// };
// }
// update_final_coverage(
// args,
// run_info,
// started,
// progress_spinner,
// progress_bar,
// output,
// )?;
run_info.current_run.run_duration = started.elapsed();
run_info.current_run.lines_parsed = 12; // TODO: Update lines
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().with_key("eta",
.unwrap()
.progress_chars("=> ")
.with_key(
"eta",
move |state: &ProgressState, w: &mut dyn std::fmt::Write| {
write!(
w,
@ -260,27 +377,72 @@ fn run_coverage(_sh: &Shell, pb: ProgressBar, args: &CLIArgs, run_info: &Current
(last_duration - state.elapsed().as_secs_f64()).max(0.)
)
.unwrap()
}));
personnal_progress_bar.enable_steady_tick(Duration::from_millis(100));
},
),
);
progress_bar
}
// TODO: Update the status with basic parsing from the output (compiling (<crates>), linking (<project>), running tests (<latest parsed test name>), etc..)
// cmd!(sh, "cargo tarpaulin").quiet().ignore_stdout().run()?;
let mut args_tarpaulin = vec!["tarpaulin", "-o", "html"];
if args.skip_clean {
args_tarpaulin.push("--skip-clean");
}
let output = Command::new("cargo").args(args_tarpaulin).output()?;
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 &output.status.success() {
true => write_badge("test", "passing", &args.success_color, "test", args)?,
false => write_badge("test", "failing", &args.failing_color, "test", args)?,
};
/// 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(format!(
"{:>10} Mesuring coverage...",
style("[Coverage]").green().bold()
))
}
/// Mod
async fn parse_all_line_sync(
args: &CLIArgs,
run_info: &mut CurrentRunStats,
mut reader: tokio::io::Split<tokio::io::BufReader<tokio::process::ChildStdout>>,
progress_spinner: ProgressBar,
progress_bar: ProgressBar,
) -> anyhow::Result<()> {
let mut lines_parsed = 0;
loop {
let res = reader.next_segment().await;
// // let new = min(built + 1, to_build);
// let new = if built < to_build {
// built + 1
// } else {
// to_build += 1;
// pb.set_length(to_build);
// built + 1
// };
// built = new;
// pb.set_position(new);
// current_run.lines_parsed += 1;
//
if let Err(e) = res {
return Err(anyhow::anyhow!("[CORE] Runtime error : {}", e));
} else if let Ok(Some(line)) = res {
progress_bar.inc(1);
lines_parsed += 1;
progress_spinner.set_message(
String::from_utf8(line).unwrap_or_default(), // "No",
);
} else {
break;
}
}
run_info.current_run.lines_parsed = lines_parsed;
Ok(())
}
/// Update the final coverage from the final output
fn update_final_coverage(
args: &CLIArgs,
run_info: &mut CurrentRunStats,
started: Instant,
progress_spinner: ProgressBar,
progress_bar: ProgressBar,
output: std::process::Output,
) -> Result<(), anyhow::Error> {
let test = String::from_utf8(output.stdout)?;
let re = Regex::new(r"(\d+.\d+)% coverage, ").unwrap();
let coverage = re.captures(&test);
@ -302,19 +464,22 @@ fn run_coverage(_sh: &Shell, pb: ProgressBar, args: &CLIArgs, run_info: &Current
args,
)?;
pb.finish_with_message(format!(
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::Succes;
} else {
write_badge("test-coverage", "N/A", "red", "coverage", args)?;
pb.finish_with_message(format!(
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(())
}
@ -366,7 +531,7 @@ fn write_badge(
test_name: &str,
args: &CLIArgs,
) -> Result<(), anyhow::Error> {
let output = Command::new("badge-maker")
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")?;