Compare commits

...

7 Commits

Author SHA1 Message Date
Dandaedre c7dc9867a4 Most progressbar work done 2025-03-20 12:31:51 -05:00
Dandaedre d795fb0d3a Adds snapshot 2025-03-20 07:37:01 -05:00
Dandaedre 51a6797a60 Split into modules, start parsing 2025-03-20 06:47:15 -05:00
Dandaedre 9da06075e1 Better run instance 2025-03-19 10:35:06 -05:00
Dandaedre c79b101d52 Not working, in a good way ? 2025-03-19 08:17:08 -05:00
Dandaedre d911510a64 Work on run info 2025-03-17 11:54:19 -05:00
Dandaedre fd6e49f6d2 Starts work on a progress bar 2025-03-14 11:46:49 -05:00
8 changed files with 788 additions and 196 deletions

8
.run_status.toml Normal file
View File

@ -0,0 +1,8 @@
[last_run_incremental]
run_status = "Success"
lines_parsed = 22
coverage = 3.37
[last_run_incremental.run_duration]
secs = 7
nanos = 826492210

View File

@ -9,8 +9,15 @@ anyhow = "1.0.92"
clap = { version = "4.5.31", features = ["derive"] } clap = { version = "4.5.31", features = ["derive"] }
console = "0.15.11" console = "0.15.11"
indicatif = "0.17.11" indicatif = "0.17.11"
logos = "0.15.0"
regex = "1.11.1" regex = "1.11.1"
serde = { version = "1.0.219", features = ["derive"] }
tokio = { version = "1.44.1", features = ["full", "process"] } #["process", "rt", "io-util", "macros"] }
toml = "0.8.20"
xshell = "0.2.6" xshell = "0.2.6"
[workspace.package] [workspace.package]
rust-version = "1.85" rust-version = "1.85"
[dev-dependencies]
insta = "1.42.2"

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="116" height="18" role="img" aria-label="test-coverage: 0%"><title>test-coverage: 0%</title><linearGradient id="bms-1031a6650666d425" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-1031a6650666d425"><rect width="116" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-1031a6650666d425)"><rect width="87" height="18" fill="#555"/><rect x="87" width="29" height="18" fill="#e05d44"/><rect width="116" height="18" fill="url(#bms-1031a6650666d425)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1005" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="190">0%</text><text x="1005" y="130" transform="scale(.1)" fill="#fff" textLength="190">0%</text></g></svg> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="116" height="18" role="img" aria-label="test-coverage: 3%"><title>test-coverage: 3%</title><linearGradient id="bms-aab211aa1257fcf9" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-aab211aa1257fcf9"><rect width="116" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-aab211aa1257fcf9)"><rect width="87" height="18" fill="#555"/><rect x="87" width="29" height="18" fill="#97ca00"/><rect width="116" height="18" fill="url(#bms-aab211aa1257fcf9)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1005" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="190">3%</text><text x="1005" y="130" transform="scale(.1)" fill="#fff" textLength="190">3%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

56
src/cli.rs Normal file
View File

@ -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,
}

View File

@ -1,67 +1,19 @@
//! Basic badge generation using badge-maker and cargo-tarpaulin //! Basic badge generation using badge-maker and cargo-tarpaulin
#![warn(clippy::missing_docs_in_private_items)]
// TODO: Testing and helper structs/methods // TODO: Testing and helper structs/methods
// TODO: Better error handling // TODO: Better error handling
use console::style;
use indicatif::ProgressBar;
use std::time::{Duration, Instant};
use std::{fs::File, io::Write, process::Command};
use anyhow::Context;
use clap::Parser; use clap::Parser;
use regex::Regex; use cli::CLIArgs;
use indicatif::ProgressBar;
use progressbar::CurrentRunStats;
use utils::{load_status, remove_badges, run_coverage, run_version};
use xshell::Shell; use xshell::Shell;
#[derive(Parser, Debug)] mod cli;
#[command(version, about, long_about = None)] mod progressbar;
struct CLIArgs { mod utils;
#[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 // 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 // : To avoid code reuse, a custom pb with a behaviour on error would be nice
@ -75,17 +27,14 @@ struct CLIArgs {
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
let args = CLIArgs::parse(); let args = CLIArgs::parse();
let new_progress_bar = || { let run_status = load_status(&args);
ProgressBar::new_spinner() let mut run_status = CurrentRunStats::from_last_run_with_context(run_status, &args);
// .with_style(
// ProgressStyle::default_spinner() let new_progress_bar = || ProgressBar::new_spinner();
// .tick_strings(&["⢎⡰", "⢎⡡", "⢎⡑", "⢎⠱", "⠎⡱", "⢊⡱", "⢌⡱", "⢆⡱", " "]),
// )
};
let sh = Shell::new()?; let sh = Shell::new()?;
// TODO: Cleanup badges beforehand
if !args.skip_clean { if !args.skip_clean {
// sh.delete_dir(args.output)?; remove_badges(&args, &sh);
} }
sh.create_dir(&args.output)?; sh.create_dir(&args.output)?;
@ -96,139 +45,17 @@ fn main() -> anyhow::Result<()> {
match (args.no_coverage, args.no_test) { match (args.no_coverage, args.no_test) {
(true, true) => (), (true, true) => (),
(true, false) => { (true, false) => {
unimplemented!("Please run with tarpaulin")
// run_tests_only(&sh, pb_model.clone(), &args)?; // run_tests_only(&sh, pb_model.clone(), &args)?;
unimplemented!("Please run with tarpaulin for now")
} }
(false, true) => run_coverage(&sh, new_progress_bar(), &args)?, // 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, false) => run_coverage(&sh, new_progress_bar(), &args)?, (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)?,
} }
Ok(()) if let Err(e) = run_status.save_status() {
} println!("Couldn't save the run configuration: {e}");
/// 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) -> 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));
// 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(()) Ok(())
} }

374
src/progressbar.rs Normal file
View File

@ -0,0 +1,374 @@
//! 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<RunStats>,
/// Status of the last run without a full clean
last_run_incremental: Option<RunStats>,
}
#[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
pub run_duration: Duration,
/// Status of the last run
pub run_status: RunStatus,
/// Lines parsed by the rust_autobadge
pub lines_parsed: u64,
/// The code coverage found
coverage: Option<f64>,
}
impl Default for RunStats {
fn default() -> Self {
Self {
run_duration: Duration::from_secs(10),
run_status: RunStatus::default(),
lines_parsed: 10,
coverage: None,
}
}
}
/// 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, Debug)]
/// 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 {
/// 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 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!(
"{:>10} Compiling ({guess})",
style("[Coverage]").green().bold(),
)
}
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(),
)
}
}
}
}
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<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
pub fn get_last_timer(&self) -> Duration {
if let Some(d) = self.get_last_run() {
d.run_duration
} else {
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<f64> {
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,
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:.green}] [{wide_bar:.cyan/blue}]\
(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({
format!(
"{:>10} Mesuring coverage...",
style("[Coverage]").green().bold(),
)
})
}
// /// 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
pub async fn parse_all_lines(
args: &CLIArgs,
run_info: &mut CurrentRunStats,
mut reader: tokio::io::Split<tokio::io::BufReader<tokio::process::ChildStdout>>,
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;
run_info.update(&line, state)?;
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()-6].to_string().parse().ok())]
LaunchingNTests(usize),
// // 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,", |lex| lex.slice()[0..lex.slice().len()-11].parse().ok())]
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);
}
}

View File

@ -0,0 +1,86 @@
---
source: src/progressbar.rs
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,
),
),
(
"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",
Coverage(
0.0,
),
),
]

234
src/utils.rs Normal file
View File

@ -0,0 +1,234 @@
//! Run the actions selected by the CLI
use std::{
fs::File,
io::{Read, Write},
time::Instant,
};
use anyhow::Context;
use indicatif::{MultiProgress, ProgressBar};
use xshell::Shell;
use crate::{
cli::CLIArgs,
progressbar::{
CurrentRunStats, LastRuns, RunState, RunStatus, create_progress_bar,
create_progress_spinner, parse_all_lines,
},
};
/// 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: CurrentRunStats,
) -> Result<CurrentRunStats, anyhow::Error> {
let started = Instant::now();
let multiprogress = MultiProgress::new();
let progress_spinner = create_progress_spinner(pb, &multiprogress);
let progress_bar = create_progress_bar(
run_info.get_last_timer().as_secs_f64(),
run_info.get_last_linecount(),
&multiprogress,
);
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
// 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)?
}
};
}
run_info.current_run.run_duration = started.elapsed();
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
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()
));
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")?;
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
fn update_final_coverage(
args: &CLIArgs,
run_info: &CurrentRunStats,
started: Instant,
progress_spinner: ProgressBar,
progress_bar: ProgressBar,
) -> Result<(), anyhow::Error> {
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 {
&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(())
}