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
16 changed files with 36 additions and 1680 deletions

7
.gitignore vendored
View File

@ -4,6 +4,10 @@
debug/
target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
@ -16,6 +20,3 @@ target/
/target
*.html
/coverage/
/badges/
/.run_status.toml

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

1053
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -3,21 +3,21 @@ name = "rust_autobadges"
version = "0.1.0"
edition = "2024"
resolver = "2"
license = "0BSD"
rust-version = "1.85"
[dependencies]
anyhow = "1.0.92"
badge-maker-rs = "=0.1.0"
clap = { version = "4.5.31", features = ["derive"] }
console = "0.16.6"
indicatif = "0.18.6"
console = "0.15.11"
indicatif = "0.17.11"
logos = "0.15.0"
regex = "1.11.1"
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.151"
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"

245
Jenkinsfile vendored
View File

@ -1,245 +0,0 @@
// Add this webhook in Gitea
// https://192.168.1.37:8080/gitea-webhook/post
pipeline {
agent { label 'rust_nodocker' }
environment {
CARGO_TERM_COLOR = 'never'
RUST_BACKTRACE = '1'
CARGO_AUDIT_VERSION = '0.22.2'
CARGO_DENY_VERSION = '0.20.2'
CARGO_TARPAULIN_VERSION = '0.37.5'
BADGE_PUBLICATION_ROOT = '/mnt/assets/coverage'
BADGE_OWNER = 'Dandaedre'
BADGE_PROJECT = 'rust_autobadges'
DEFAULT_BRANCH = 'main'
}
stages {
stage('Checkout') {
steps {
checkout scm
sh '''
set -eu
git submodule sync --recursive
git submodule update --init --recursive
rm -rf coverage
mkdir -p coverage
rm -f target/release/rust_autobadges
'''
}
}
stage('Setup Rust') {
steps {
sh '''
set -eu
if ! command -v rustup >/dev/null 2>&1; then
echo "ERROR: rustup is not installed on this worker." >&2
exit 1
fi
rustup toolchain install stable \
--profile minimal \
--component rustfmt \
--component clippy
rustup default stable
rustc --version
cargo --version
'''
}
}
stage('Setup Supply-Chain Tools') {
steps {
sh '''
set -eu
audit_version="$(cargo audit --version 2>/dev/null | awk '{print $2}' || true)"
if [ "$audit_version" != "$CARGO_AUDIT_VERSION" ]; then
cargo install --locked --version "$CARGO_AUDIT_VERSION" cargo-audit
fi
deny_version="$(cargo deny --version 2>/dev/null | awk '{print $2}' || true)"
if [ "$deny_version" != "$CARGO_DENY_VERSION" ]; then
cargo install --locked --version "$CARGO_DENY_VERSION" cargo-deny
fi
cargo audit --version
cargo deny --version
tarpaulin_version="$(cargo tarpaulin --version 2>/dev/null | awk '{print $2}' || true)"
if [ "$tarpaulin_version" != "$CARGO_TARPAULIN_VERSION" ]; then
cargo install --locked --version "$CARGO_TARPAULIN_VERSION" cargo-tarpaulin
fi
cargo tarpaulin --version
'''
}
}
stage('Cargo Audit') {
steps {
sh '''
set -eu
cargo audit --deny warnings
'''
}
}
stage('Dependency Policy') {
steps {
sh '''
set -eu
cargo deny check
'''
}
}
stage('Format') {
steps {
sh '''
set -eu
cargo fmt --all -- --check
'''
}
}
stage('Tests') {
steps {
sh '''
set -eu
cargo test --locked --all-targets --all-features
: > "coverage/.tests-passed-$BUILD_NUMBER"
'''
}
}
stage('Clippy') {
steps {
sh '''
set -eu
cargo clippy --locked --all-targets --all-features
'''
}
}
stage('Build Release') {
steps {
sh '''
set -eu
cargo build --locked --release --all-features
'''
}
}
stage('Coverage') {
steps {
sh '''
set -eu
cargo tarpaulin
test -s coverage/tarpaulin-report.json
target/release/rust_autobadges badge coverage \
--summary coverage/tarpaulin-report.json
rm -f coverage/tarpaulin-report.json
: > "coverage/.coverage-ready-$BUILD_NUMBER"
'''
}
}
}
post {
success {
publishChecks(
conclusion: 'SUCCESS',
name: 'Rust CI',
summary: 'rust_autobadges passed CI.',
text: 'Security policy, formatting, tests, Clippy, coverage and badge generation completed successfully.',
title: 'Build Successful'
)
}
failure {
publishChecks(
conclusion: 'FAILURE',
name: 'Rust CI',
summary: 'rust_autobadges failed CI.',
text: 'A Rust check, test, coverage floor, or badge step failed. Cleanup publishes failing and neutral status badges.',
title: 'Build Failed'
)
}
unstable {
publishChecks(
conclusion: 'ACTION_REQUIRED',
name: 'Rust CI',
summary: 'rust_autobadges CI is unstable.',
text: 'The build is unstable; cleanup publishes badges that reflect this build.',
title: 'Build Unstable'
)
}
cleanup {
sh '''
set -eu
badge_bin=target/release/rust_autobadges
if [ ! -x "$badge_bin" ]; then
cargo build --locked --release --all-features
fi
if [ -f "coverage/.tests-passed-$BUILD_NUMBER" ]; then
"$badge_bin" badge test --value passing
else
"$badge_bin" badge test --value failing
fi
if [ ! -f "coverage/.coverage-ready-$BUILD_NUMBER" ]; then
"$badge_bin" badge coverage --value -
fi
"$badge_bin" badge version
rm -f coverage/tarpaulin-report.json \
"coverage/.tests-passed-$BUILD_NUMBER" \
"coverage/.coverage-ready-$BUILD_NUMBER"
for badge in version test coverage; do
file="coverage/$badge.svg"
test -f "$file"
test ! -L "$file"
test -s "$file"
done
count="$(find coverage -maxdepth 1 -type f -name '*.svg' | wc -l | tr -d ' ')"
test "$count" = 3
'''
archiveArtifacts(
allowEmptyArchive: false,
artifacts: 'coverage/version.svg,coverage/test.svg,coverage/coverage.svg',
fingerprint: true
)
script {
if (!env.BRANCH_NAME) {
error('BRANCH_NAME is required; badge publication expects a Jenkins multibranch job.')
}
if (env.BRANCH_NAME == env.DEFAULT_BRANCH) {
sh '''
scripts/publish-coverage-badges.sh \
"$BADGE_PUBLICATION_ROOT" \
"$BADGE_OWNER" \
"$BADGE_PROJECT" \
"$DEFAULT_BRANCH" \
version test coverage
'''
}
}
}
}
}

View File

@ -1,58 +1,11 @@
# rust_autobadges
![version](https://assets.dandaedre.com/coverage/Dandaedre/rust_autobadges/main/version.svg)
![tests](https://assets.dandaedre.com/coverage/Dandaedre/rust_autobadges/main/test.svg)
![coverage](https://assets.dandaedre.com/coverage/Dandaedre/rust_autobadges/main/coverage.svg)
![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg)
Runs cargo-tarpaulin to generate coverage and automatically create a badges/ folder with the generated coverage.svg, test.svg and version.svg
## Dependency security and policy
CI pins `cargo-audit` 0.22.2 and `cargo-deny` 0.20.2. Run the same supply-chain gates locally from the repository root:
```sh
cargo audit --deny warnings
cargo deny check
```
Both commands require network access so they can refresh RustSec advisory and crates.io registry data. A failed refresh is an error; CI does not silently accept stale data.
`cargo audit` checks the tracked `Cargo.lock` for RustSec vulnerabilities, unmaintained or unsound advisories, and yanked packages. It is limited to advisories present in RustSec and cannot detect undisclosed vulnerabilities or assess source-code behavior.
`cargo deny` enforces `deny.toml`: only the licenses used by the current dependency graph are allowed (with a confidence threshold of 0.8), wildcard requirements are denied, duplicate versions are reported as warnings, unknown registries and Git sources are denied, crates.io is the only allowed registry, and no Git sources are allowed. It builds the graph with all features enabled. Advisory ignores, crate bans, duplicate skips, license exceptions, and license clarifications start empty. The tool validates dependency metadata and known advisories; it is not a source-code or runtime scanner.
No other hardening tools are in scope for these CI gates.
## CI coverage badges
CI pins `cargo-tarpaulin` 0.37.5 and uses the tracked `tarpaulin.toml`. Run the exact coverage gate locally with:
```sh
cargo tarpaulin
```
The configuration uses locked dependencies, all features and targets, LLVM coverage, and an enforced 1.5% line-coverage floor. The measured JSON summary is temporary at `coverage/tarpaulin-report.json`; `rust_autobadges` reads its overall `coverage` value to generate the coverage badge, then CI removes it.
The release binary generates all three badges itself:
```sh
target/release/rust_autobadges badge version
target/release/rust_autobadges badge test --value passing
target/release/rust_autobadges badge coverage --summary coverage/tarpaulin-report.json
```
The version badge defaults to the authoritative package version compiled from `Cargo.toml`. Jenkins archives exactly `coverage/version.svg`, `coverage/test.svg`, and `coverage/coverage.svg`. On the `main` branch, cleanup publishes them under `/mnt/assets/coverage/Dandaedre/rust_autobadges/main/`; other branches only archive their generated badges. The Jenkins job must be multibranch so `BRANCH_NAME` can safely gate publication.
The public asset server should mount the publication directory read-only, disable directory listings, serve SVG with a restrictive content security policy, and revalidate these mutable URLs or give them a short cache lifetime.
# Usage
```
Usage: rust_autobadges [OPTIONS] [COMMAND]
Commands:
badge Render one CI badge without running tests or coverage
help Print this message or the help of the given subcommand(s)
Usage: rust_autobadges [OPTIONS]
Options:
-s, --skip-clean

1
badges/coverage.svg Normal file
View File

@ -0,0 +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: 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>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/release.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="94" height="18" role="img" aria-label="release: v0.1.0"><title>release: v0.1.0</title><linearGradient id="bms-162829b957040378" 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-162829b957040378"><rect width="94" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-162829b957040378)"><rect width="49" height="18" fill="#555"/><rect x="49" width="45" height="18" fill="#fe7d37"/><rect width="94" height="18" fill="url(#bms-162829b957040378)"/></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="255" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="390">release</text><text x="255" y="130" transform="scale(.1)" fill="#fff" textLength="390">release</text><text aria-hidden="true" x="705" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="350">v0.1.0</text><text x="705" y="130" transform="scale(.1)" fill="#fff" textLength="350">v0.1.0</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/test.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" 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-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></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="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/version.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.1.0"><title>version: 0.1.0</title><linearGradient id="bms-0431e50b7af7883f" 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-0431e50b7af7883f"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0431e50b7af7883f)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-0431e50b7af7883f)"/></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="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.1.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.1.0</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1,32 +0,0 @@
[graph]
all-features = true
[advisories]
ignore = []
[licenses]
allow = [
"0BSD",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"MIT",
"Unicode-3.0",
"Unlicense",
]
confidence-threshold = 0.8
exceptions = []
clarify = []
[bans]
multiple-versions = "warn"
wildcards = "deny"
allow = []
deny = []
skip = []
skip-tree = []
[sources]
unknown-registry = "deny"
unknown-git = "deny"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []

View File

@ -1,86 +0,0 @@
#!/bin/sh
set -eu
usage() {
echo "usage: $0 ABSOLUTE_ROOT OWNER PROJECT DEFAULT_BRANCH NAME..." >&2
exit 2
}
[ "$#" -ge 5 ] || usage
root=$1
owner=$2
project=$3
branch=$4
shift 4
case $root in /*) ;; *) echo "publication root must be absolute" >&2; exit 1 ;; esac
[ -d "$root" ] && [ ! -L "$root" ] && [ -w "$root" ] || {
echo "publication root must be an existing writable directory, not a symlink" >&2
exit 1
}
for component in "$owner" "$project" "$branch"; do
case $component in
''|*[!A-Za-z0-9._-]*) echo "invalid publication path component: $component" >&2; exit 1 ;;
esac
done
seen=' '
for name in "$@"; do
case $name in coverage|test|version) ;; *) echo "invalid badge name: $name" >&2; exit 1 ;; esac
case $seen in *" $name "*) echo "duplicate badge name: $name" >&2; exit 1 ;; esac
seen="$seen$name "
source_file="coverage/$name.svg"
[ -f "$source_file" ] && [ ! -L "$source_file" ] && [ -s "$source_file" ] || {
echo "invalid badge source: $source_file" >&2
exit 1
}
done
owner_dir=$root/$owner
project_dir=$owner_dir/$project
destination=$project_dir/$branch
for directory in "$owner_dir" "$project_dir"; do
[ ! -L "$directory" ] || { echo "refusing symlink directory: $directory" >&2; exit 1; }
[ ! -e "$directory" ] || [ -d "$directory" ] || {
echo "publication component is not a directory: $directory" >&2
exit 1
}
mkdir -p "$directory"
chmod 0755 "$directory"
done
if [ -L "$destination" ]; then
unlink "$destination"
fi
[ ! -e "$destination" ] || [ -d "$destination" ] || {
echo "publication destination is not a directory: $destination" >&2
exit 1
}
mkdir -p "$destination"
chmod 0755 "$destination"
temporary_files=
cleanup() {
for temporary in $temporary_files; do
[ ! -e "$temporary" ] || rm -f "$temporary"
done
}
trap cleanup 0
trap 'cleanup; exit 1' HUP INT TERM
for name in "$@"; do
temporary=$destination/.$name.svg.tmp-$$
temporary_files="$temporary_files $temporary"
(umask 077; set -C; : > "$temporary") || {
echo "cannot create publication temporary: $temporary" >&2
exit 1
}
cp "coverage/$name.svg" "$temporary"
chmod 0644 "$temporary"
mv -f "$temporary" "$destination/$name.svg"
done
temporary_files=
trap - 0 HUP INT TERM

View File

@ -1,17 +1,11 @@
//! All CLI parsing and data
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand, ValueEnum};
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 {
#[command(subcommand)]
/// Run a focused command instead of the legacy all-in-one workflow
pub command: Option<Command>,
#[arg(short, long)]
/// Skip the cargo clean that tarpaulin would run, see tarpaulin --skip-clean documentation
pub skip_clean: bool,
@ -60,45 +54,3 @@ pub struct CLIArgs {
/// The output directory where all the badges will be saved
pub output: String,
}
#[derive(Subcommand, Debug)]
/// Focused commands exposed by rust_autobadges
pub enum Command {
/// Render one CI badge without running tests or coverage
Badge(BadgeArgs),
}
#[derive(Args, Debug)]
/// Options for rendering one CI badge
pub struct BadgeArgs {
/// Badge kind to render
#[arg(value_enum)]
pub kind: BadgeKind,
/// Badge value; version defaults to the package version and coverage also accepts `-`
#[arg(long)]
pub value: Option<String>,
/// Read coverage from a cargo-tarpaulin JSON report
#[arg(long, value_name = "FILE")]
pub summary: Option<PathBuf>,
/// Override the automatically selected value color
#[arg(long)]
pub color: Option<String>,
/// Output path; defaults to `coverage/<kind>.svg`
#[arg(long, value_name = "FILE")]
pub output: Option<PathBuf>,
}
#[derive(Clone, Copy, Debug, ValueEnum)]
/// CI badge kinds supported by the direct renderer
pub enum BadgeKind {
/// Package version badge
Version,
/// Test result badge
Test,
/// Line coverage badge
Coverage,
}

View File

@ -1,13 +1,13 @@
//! Basic badge generation using Shields-compatible SVGs 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: Better error handling
use clap::Parser;
use cli::{CLIArgs, Command};
use cli::CLIArgs;
use indicatif::ProgressBar;
use progressbar::CurrentRunStats;
use utils::{load_status, remove_badges, render_ci_badge, run_coverage, run_version};
use utils::{load_status, remove_badges, run_coverage, run_version};
use xshell::Shell;
@ -27,10 +27,6 @@ mod utils;
fn main() -> anyhow::Result<()> {
let args = CLIArgs::parse();
if let Some(Command::Badge(badge)) = &args.command {
return render_ci_badge(badge);
}
let run_status = load_status(&args);
let mut run_status = CurrentRunStats::from_last_run_with_context(run_status, &args);

View File

@ -1,150 +1,22 @@
//! Run the actions selected by the CLI
use std::{
fs::{self, File, OpenOptions},
fs::File,
io::{Read, Write},
path::{Path, PathBuf},
process,
time::Instant,
};
use anyhow::Context;
use badge_maker_rs::{BadgeOptions, Color, Style, make_badge};
use indicatif::{MultiProgress, ProgressBar};
use xshell::Shell;
use crate::{
cli::{BadgeArgs, BadgeKind, CLIArgs},
cli::CLIArgs,
progressbar::{
CurrentRunStats, LastRuns, RunState, RunStatus, create_progress_bar,
create_progress_spinner, parse_all_lines,
},
};
/// Render one CI badge directly, without running tests or coverage.
pub fn render_ci_badge(args: &BadgeArgs) -> anyhow::Result<()> {
let (label, value, default_color, filename) = match args.kind {
BadgeKind::Version => {
anyhow::ensure!(
args.summary.is_none(),
"--summary is only valid for coverage"
);
let value = args
.value
.clone()
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_owned());
("version", value, "orange", "version.svg")
}
BadgeKind::Test => {
anyhow::ensure!(
args.summary.is_none(),
"--summary is only valid for coverage"
);
let value = args.value.clone().context("test badges require --value")?;
let color = match value.as_str() {
"passing" => "green",
"failing" => "red",
_ => anyhow::bail!("test badge value must be `passing` or `failing`"),
};
("test", value, color, "test.svg")
}
BadgeKind::Coverage => {
anyhow::ensure!(
args.value.is_none() || args.summary.is_none(),
"coverage accepts either --value or --summary, not both"
);
let raw = if let Some(summary) = &args.summary {
let report: serde_json::Value =
serde_json::from_reader(File::open(summary).with_context(|| {
format!("opening coverage summary {}", summary.display())
})?)
.context("parsing cargo-tarpaulin JSON summary")?;
report
.get("coverage")
.and_then(serde_json::Value::as_f64)
.context("coverage summary has no numeric `coverage` field")?
.to_string()
} else {
args.value
.clone()
.context("coverage badges require --value or --summary")?
};
if raw == "-" {
("coverage", "-%".to_owned(), "lightgrey", "coverage.svg")
} else {
let coverage: f64 = raw.parse().context("coverage must be `-` or a number")?;
anyhow::ensure!(coverage.is_finite(), "coverage must be finite");
anyhow::ensure!(
(0.0..=100.0).contains(&coverage),
"coverage must be from 0 through 100"
);
let color = if coverage < 50.0 {
"red"
} else if coverage < 80.0 {
"yellow"
} else {
"green"
};
("coverage", format!("{coverage:.0}%"), color, "coverage.svg")
}
}
};
anyhow::ensure!(
!value.is_empty() && value.chars().all(|character| !character.is_control()),
"badge values must be nonempty printable text"
);
let output = args
.output
.clone()
.unwrap_or_else(|| PathBuf::from("coverage").join(filename));
write_badge_atomic(
label,
&value,
args.color.as_deref().unwrap_or(default_color),
&output,
)
}
/// Render a badge and atomically replace its destination.
fn write_badge_atomic(label: &str, value: &str, color: &str, output: &Path) -> anyhow::Result<()> {
let svg = make_badge(
&BadgeOptions::new(value)
.label(label)
.color(color.parse::<Color>().context("Parsing badge color")?)
.style(Style::Plastic)
.build(),
)
.context("Rendering badge SVG")?;
let parent = output
.parent()
.filter(|path| !path.as_os_str().is_empty())
.unwrap_or(Path::new("."));
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
let filename = output
.file_name()
.context("badge output must name a file")?
.to_string_lossy();
let temporary = parent.join(format!(".{filename}.tmp-{}", process::id()));
let result = (|| -> anyhow::Result<()> {
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&temporary)
.with_context(|| format!("creating {}", temporary.display()))?;
file.write_all(svg.as_bytes()).context("writing badge")?;
file.sync_all().context("syncing badge")?;
fs::rename(&temporary, output)
.with_context(|| format!("replacing {}", output.display()))?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
result
}
/// Remove all the badges
pub fn remove_badges(args: &CLIArgs, sh: &Shell) {
let _ = sh.remove_path(args.output.clone() + "/coverage.svg");
@ -301,7 +173,7 @@ pub fn run_version(sh: &Shell, pb: ProgressBar, args: &CLIArgs) -> Result<(), an
// Ok(())
// }
/// Write the badge to a specific directory
/// Write the badge to a specific directory using badge-maker
pub fn write_badge(
name: &str,
value: &str,
@ -309,17 +181,12 @@ pub fn write_badge(
test_name: &str,
args: &CLIArgs,
) -> Result<(), anyhow::Error> {
let svg = make_badge(
&BadgeOptions::new(value)
.label(name)
.color(color.parse::<Color>().context("Parsing badge color")?)
.style(Style::Plastic)
.build(),
)
.context("Rendering badge SVG")?;
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();
write!(f, "{}", svg).context("Writing badge")?;
f.write_all(&output.stdout)?;
Ok(())
}

View File

@ -1,9 +0,0 @@
[ci]
engine = "Llvm"
all-features = true
run-types = ["AllTargets"]
skip-clean = true
locked = true
output-dir = "coverage"
out = ["Json"]
fail-under = 1.5