Compare commits
8 Commits
progressba
...
main
| Author | SHA1 | Date |
|---|---|---|
|
|
5f62e6f470 | |
|
|
af5f84808e | |
|
|
46dd9ac3a0 | |
|
|
d515b51545 | |
|
|
a1cecfa301 | |
|
|
a4064df89d | |
|
|
729a064e7d | |
|
|
71cafd54ee |
|
|
@ -4,10 +4,6 @@
|
|||
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
|
||||
|
||||
|
|
@ -20,3 +16,6 @@ Cargo.lock
|
|||
|
||||
/target
|
||||
*.html
|
||||
/coverage/
|
||||
/badges/
|
||||
/.run_status.toml
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
17
Cargo.toml
17
Cargo.toml
|
|
@ -3,14 +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.15.11"
|
||||
indicatif = "0.17.11"
|
||||
regex = "1.11.1"
|
||||
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"
|
||||
|
||||
[workspace.package]
|
||||
rust-version = "1.85"
|
||||
[dev-dependencies]
|
||||
insta = "1.42.2"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,245 @@
|
|||
// 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
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
51
README.md
51
README.md
|
|
@ -1,11 +1,58 @@
|
|||
# rust_autobadges
|
||||
  
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
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]
|
||||
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: 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>
|
||||
|
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,32 @@
|
|||
[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 = []
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
//! All CLI parsing and data
|
||||
|
||||
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,
|
||||
|
||||
// #[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,
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
223
src/main.rs
223
src/main.rs
|
|
@ -1,67 +1,19 @@
|
|||
//! Basic badge generation using badge-maker and cargo-tarpaulin
|
||||
//! Basic badge generation using Shields-compatible SVGs and cargo-tarpaulin
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
|
||||
// TODO: Testing and helper structs/methods
|
||||
// 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 regex::Regex;
|
||||
use cli::{CLIArgs, Command};
|
||||
use indicatif::ProgressBar;
|
||||
use progressbar::CurrentRunStats;
|
||||
use utils::{load_status, remove_badges, render_ci_badge, run_coverage, run_version};
|
||||
|
||||
use xshell::Shell;
|
||||
|
||||
#[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,
|
||||
}
|
||||
mod cli;
|
||||
mod progressbar;
|
||||
mod utils;
|
||||
|
||||
// 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
|
||||
|
|
@ -75,17 +27,18 @@ struct CLIArgs {
|
|||
fn main() -> anyhow::Result<()> {
|
||||
let args = CLIArgs::parse();
|
||||
|
||||
let new_progress_bar = || {
|
||||
ProgressBar::new_spinner()
|
||||
// .with_style(
|
||||
// ProgressStyle::default_spinner()
|
||||
// .tick_strings(&["⢎⡰", "⢎⡡", "⢎⡑", "⢎⠱", "⠎⡱", "⢊⡱", "⢌⡱", "⢆⡱", " "]),
|
||||
// )
|
||||
};
|
||||
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);
|
||||
|
||||
let new_progress_bar = || ProgressBar::new_spinner();
|
||||
let sh = Shell::new()?;
|
||||
// TODO: Cleanup badges beforehand
|
||||
|
||||
if !args.skip_clean {
|
||||
// sh.delete_dir(args.output)?;
|
||||
remove_badges(&args, &sh);
|
||||
}
|
||||
sh.create_dir(&args.output)?;
|
||||
|
||||
|
|
@ -96,139 +49,17 @@ fn main() -> anyhow::Result<()> {
|
|||
match (args.no_coverage, args.no_test) {
|
||||
(true, true) => (),
|
||||
(true, false) => {
|
||||
unimplemented!("Please run with tarpaulin")
|
||||
// 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
|
||||
(false, false) => run_coverage(&sh, new_progress_bar(), &args)?,
|
||||
// The coverage know wether to write the badge test with the cli 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(())
|
||||
}
|
||||
|
||||
/// 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");
|
||||
if let Err(e) = run_status.save_status() {
|
||||
println!("Couldn't save the run configuration: {e}");
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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[0m [32m INFO[0m [2mcargo_tarpaulin::config[0m[2m:[0m Creating config",
|
||||
"[2m2025-03-19T13:50:48.086450Z[0m [32m INFO[0m [2mcargo_tarpaulin[0m[2m:[0m Running Tarpaulin",
|
||||
"[2m2025-03-19T13:50:48.086466Z[0m [32m INFO[0m [2mcargo_tarpaulin[0m[2m:[0m Building project",
|
||||
"[2m2025-03-19T13:50:48.086469Z[0m [32m INFO[0m [2mcargo_tarpaulin::cargo[0m[2m:[0m Cleaning project",
|
||||
"[2m2025-03-19T13:51:01.196213Z[0m [32m INFO[0m [2mcargo_tarpaulin::process_handling::linux[0m[2m:[0m Launching test",
|
||||
"[2m2025-03-19T13:51:01.196247Z[0m [32m INFO[0m [2mcargo_tarpaulin::process_handling[0m[2m:[0m 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",
|
||||
"[2m2025-03-19T13:51:07.936086Z[0m [32m INFO[0m [2mcargo_tarpaulin::report[0m[2m:[0m 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
),
|
||||
),
|
||||
]
|
||||
|
|
@ -0,0 +1,367 @@
|
|||
//! Run the actions selected by the CLI
|
||||
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
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},
|
||||
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");
|
||||
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
|
||||
pub fn write_badge(
|
||||
name: &str,
|
||||
value: &str,
|
||||
color: &str,
|
||||
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 mut f = File::create(format!("{}/{}.svg", args.output, test_name)).unwrap();
|
||||
write!(f, "{}", svg).context("Writing badge")?;
|
||||
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(())
|
||||
}
|
||||
|
|
@ -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