ci: publish coverage badges with rust_autobadges
Rust CI rust_autobadges passed CI.
Dandaedre/rust_autobadges/pipeline/head This commit looks good
Details
Rust CI rust_autobadges passed CI.
Dandaedre/rust_autobadges/pipeline/head This commit looks good
Details
This commit is contained in:
parent
af5f84808e
commit
5f62e6f470
|
|
@ -16,3 +16,6 @@ target/
|
|||
|
||||
/target
|
||||
*.html
|
||||
/coverage/
|
||||
/badges/
|
||||
/.run_status.toml
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
[last_run_incremental]
|
||||
run_status = "Success"
|
||||
lines_parsed = 22
|
||||
coverage = 3.37
|
||||
|
||||
[last_run_incremental.run_duration]
|
||||
secs = 7
|
||||
nanos = 826492210
|
||||
|
|
@ -635,6 +635,7 @@ dependencies = [
|
|||
"insta",
|
||||
"logos",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"toml",
|
||||
"xshell",
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ console = "0.16.6"
|
|||
indicatif = "0.18.6"
|
||||
logos = "0.15.0"
|
||||
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"
|
||||
|
|
|
|||
|
|
@ -9,6 +9,11 @@ pipeline {
|
|||
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 {
|
||||
|
|
@ -21,6 +26,10 @@ pipeline {
|
|||
|
||||
git submodule sync --recursive
|
||||
git submodule update --init --recursive
|
||||
|
||||
rm -rf coverage
|
||||
mkdir -p coverage
|
||||
rm -f target/release/rust_autobadges
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
|
@ -65,6 +74,12 @@ pipeline {
|
|||
|
||||
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
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
|
@ -101,6 +116,7 @@ pipeline {
|
|||
sh '''
|
||||
set -eu
|
||||
cargo test --locked --all-targets --all-features
|
||||
: > "coverage/.tests-passed-$BUILD_NUMBER"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
|
@ -122,6 +138,20 @@ pipeline {
|
|||
'''
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
|
|
@ -130,7 +160,7 @@ pipeline {
|
|||
conclusion: 'SUCCESS',
|
||||
name: 'Rust CI',
|
||||
summary: 'rust_autobadges passed CI.',
|
||||
text: 'Cargo audit, dependency policy, formatting, tests, Clippy and release build completed successfully.',
|
||||
text: 'Security policy, formatting, tests, Clippy, coverage and badge generation completed successfully.',
|
||||
title: 'Build Successful'
|
||||
)
|
||||
}
|
||||
|
|
@ -140,7 +170,7 @@ pipeline {
|
|||
conclusion: 'FAILURE',
|
||||
name: 'Rust CI',
|
||||
summary: 'rust_autobadges failed CI.',
|
||||
text: 'Cargo audit, dependency policy, or another Rust check failed. See the Jenkins log.',
|
||||
text: 'A Rust check, test, coverage floor, or badge step failed. Cleanup publishes failing and neutral status badges.',
|
||||
title: 'Build Failed'
|
||||
)
|
||||
}
|
||||
|
|
@ -150,9 +180,66 @@ pipeline {
|
|||
conclusion: 'ACTION_REQUIRED',
|
||||
name: 'Rust CI',
|
||||
summary: 'rust_autobadges CI is unstable.',
|
||||
text: 'Cargo audit, dependency policy, or another Rust check completed with an unstable status.',
|
||||
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
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
33
README.md
33
README.md
|
|
@ -1,5 +1,8 @@
|
|||
# rust_autobadges
|
||||
  
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
Runs cargo-tarpaulin to generate coverage and automatically create a badges/ folder with the generated coverage.svg, test.svg and version.svg
|
||||
|
||||
|
|
@ -20,10 +23,36 @@ Both commands require network access so they can refresh RustSec advisory and cr
|
|||
|
||||
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]
|
||||
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)
|
||||
|
||||
Options:
|
||||
-s, --skip-clean
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
<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 |
|
|
@ -1 +0,0 @@
|
|||
<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>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
|
|
@ -1 +0,0 @@
|
|||
<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>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
|
|
@ -1 +0,0 @@
|
|||
<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>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
|
|
@ -0,0 +1,86 @@
|
|||
#!/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
|
||||
50
src/cli.rs
50
src/cli.rs
|
|
@ -1,11 +1,17 @@
|
|||
//! All CLI parsing and data
|
||||
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Args, Parser, Subcommand, ValueEnum};
|
||||
|
||||
#[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,
|
||||
|
|
@ -54,3 +60,45 @@ 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,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,10 +4,10 @@
|
|||
// TODO: Testing and helper structs/methods
|
||||
// TODO: Better error handling
|
||||
use clap::Parser;
|
||||
use cli::CLIArgs;
|
||||
use cli::{CLIArgs, Command};
|
||||
use indicatif::ProgressBar;
|
||||
use progressbar::CurrentRunStats;
|
||||
use utils::{load_status, remove_badges, run_coverage, run_version};
|
||||
use utils::{load_status, remove_badges, render_ci_badge, run_coverage, run_version};
|
||||
|
||||
use xshell::Shell;
|
||||
|
||||
|
|
@ -27,6 +27,10 @@ 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);
|
||||
|
||||
|
|
|
|||
131
src/utils.rs
131
src/utils.rs
|
|
@ -1,8 +1,10 @@
|
|||
//! Run the actions selected by the CLI
|
||||
|
||||
use std::{
|
||||
fs::File,
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
process,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
|
|
@ -12,12 +14,137 @@ use indicatif::{MultiProgress, ProgressBar};
|
|||
use xshell::Shell;
|
||||
|
||||
use crate::{
|
||||
cli::CLIArgs,
|
||||
cli::{BadgeArgs, BadgeKind, 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");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
[ci]
|
||||
engine = "Llvm"
|
||||
all-features = true
|
||||
run-types = ["AllTargets"]
|
||||
skip-clean = true
|
||||
locked = true
|
||||
output-dir = "coverage"
|
||||
out = ["Json"]
|
||||
fail-under = 1.5
|
||||
Loading…
Reference in New Issue