rust_autobadges/src/main.rs

396 lines
13 KiB
Rust

//! Basic badge generation using badge-maker and cargo-tarpaulin
// TODO: Testing and helper structs/methods
// TODO: Better error handling
use console::style;
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use serde::{Deserialize, Serialize};
use std::io::Read;
use std::time::{Duration, Instant};
use std::{fs::File, io::Write, process::Command};
use anyhow::Context;
use clap::Parser;
use regex::Regex;
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<RunStats>,
/// Status of the last run without a full clean
last_run_incremental: Option<RunStats>,
}
#[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,
}
impl Default for RunStats{
fn default() -> Self {
Self{
run_duration: Duration::from_secs(10),
run_status: RunStatus::default(),
}
}
}
/// 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
Succes,
#[default]
/// The tests failed to run
Failure,
}
#[derive(Clone, Copy)]
enum RunType {
Incremental,
Clean,
}
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
}
/// Get the last run of the same type
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,
}
}
}
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
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,
}
// 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
// TODO: Better than manual alignment
// TODO: The cargo test usage is conditionnal of tarpaulin selection,
// if tarpaulin & test => only run tarp & generate both
// if tarpaulin & no test => only run tarp & generate tarp only
// 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 new_progress_bar = || {
ProgressBar::new_spinner()
// .with_style(
// ProgressStyle::default_spinner()
// .tick_strings(&["⢎⡰", "⢎⡡", "⢎⡑", "⢎⠱", "⠎⡱", "⢊⡱", "⢌⡱", "⢆⡱", " "]),
// )
};
let sh = Shell::new()?;
// TODO: Cleanup badges beforehand
if !args.skip_clean {
// sh.delete_dir(args.output)?;
}
sh.create_dir(&args.output)?;
if !args.no_version {
run_version(&sh, new_progress_bar(), &args)?;
}
// TODO: Modular testing
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)?;
}
(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)?,
}
// TODO: Maybe make save a method instead ?
if let Err(e) = save_status(&run_status.into_save_runs()) {
println!("Couldn't save the run configuration: {e}");
}
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()
}
/// 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> {
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})",
)
.unwrap().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()
}));
personnal_progress_bar.enable_steady_tick(Duration::from_millis(100));
// 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)?,
};
}
let test = String::from_utf8(output.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,
)?;
pb.finish_with_message(format!(
"{:>10} Found {coverage_value:.2}% - Badge done ({:.2}s)",
style("[Coverage]").bold().green(),
started.elapsed().as_secs_f32()
));
} else {
write_badge("test-coverage", "N/A", "red", "coverage", args)?;
pb.finish_with_message(format!(
"{:<10} Couldn't find coverage - Badge failed ({:.2}s)",
style("[Coverage]").bold().red(),
started.elapsed().as_secs_f32()
));
}
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 = 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]
#[test]
fn test_badge_writing() {}
#[ignore]
#[test]
fn test_structs() {}
#[ignore]
#[test]
fn test_version_parsing() {}
#[ignore]
#[test]
fn test_coverage_parsing() {}
}