cargo-modernize
Health Gecti
- License — License: Apache-2.0
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Community trust — 14 GitHub stars
Code Gecti
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Gecti
- Permissions — No dangerous permissions requested
Bu listing icin henuz AI raporu yok.
Version-accurate Rust modernization knowledge catalog, AI agent skill, and fast read-only workspace scanner (Rust 1.64-1.100)
cargo-modernize
Modernize Rust workspaces with version-accurate idioms across Rust 1.64–1.100 and Edition 2021 / 2024.
Quick Start · What It Changes · Benchmark · Install · Catalog · Usage · CI
cargo-modernize combines three tools in one fast, read-only Cargo subcommand:
- An embedded Open Knowledge Catalog (
141curated entries derived from primary upstreamrust-lang/rustrelease inventories1.56–1.100,1,837triage records,RELEASES.md, Rust Edition Guides, andlibrary/dogfooding diffs — with compilable positive and negative fixtures for every executable rule). - A progressive-disclosure AI coding-agent skill & plugin (
guidelines list→explain→--diff) for Claude Code, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, and Antigravity — so agents write modern Rust without bloating context windows. - A sub-second, read-only-by-default workspace scanner (47 ms on this workspace; 143 ms on a 477k-LOC workspace, no compilation) that detects outdated Rust syntax, stdlib patterns,
Cargo.tomlsettings, and CI flags while respecting each crate's MSRV, edition,#![no_std]tier,constcontext, and SemVer boundaries — with optional transactional--fix --verifyautofix when you are ready to apply changes.
Quick Start
Install the prebuilt CLI binary (works on any local Rust toolchain):
cargo binstall cargo-modernize
Scan your workspace (strictly read-only — never edits files or .git/index):
# Scan the current Rust workspace
cargo modernize
# Scan only lines changed since origin/main
cargo modernize --diff origin/main --format compact
# Load version-accurate modernization guidelines for your workspace MSRV & edition
cargo modernize guidelines list
What It Changes
When you bump a workspace's rust-version (MSRV) or migrate to Rust Edition 2024, dozens of cleaner, safer, zero-dependency standard-library idioms become available — yet both humans and AI coding agents keep writing 2022-era Rust from muscle memory or training-cutoff defaults.
On a crate targeting Rust 1.98 / Edition 2024, cargo modernize catches all seven legacy idioms below in milliseconds without running rustc:
// Before (legacy patterns written from muscle memory or LLM defaults)
use std::collections::HashSet;
use std::time::Duration;
use once_cell::sync::Lazy;
pub const CACHE_TTL: Duration = Duration::from_secs(300);
static RESERVED_HOSTS: Lazy<HashSet<&'static str>> =
Lazy::new(|| HashSet::from(["localhost", "metadata.internal"]));
pub fn parse_bracketed_host(raw: &str) -> Option<&str> {
if let Some(host) = raw.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
if !RESERVED_HOSTS.contains(host) {
return Some(host);
}
}
None
}
pub fn is_monotonic(samples: &[u64]) -> bool {
samples.windows(2).all(|w| w[0] <= w[1])
}
pub fn truncate_utf8(s: &str, max_bytes: usize) -> &str {
let mut end = max_bytes.min(s.len());
while !s.is_char_boundary(end) {
end -= 1;
}
&s[..end]
}
pub fn normalized_label(raw: Option<&str>) -> &str {
raw.map(str::trim).unwrap_or_default()
}
// After (modernized for Rust 1.98 / Edition 2024 — drops `once_cell` and manual loops)
use std::collections::HashSet;
use std::sync::LazyLock;
use std::time::Duration;
pub const CACHE_TTL: Duration = Duration::from_mins(5); // 1.91
static RESERVED_HOSTS: LazyLock<HashSet<&'static str>> = // 1.80
LazyLock::new(|| HashSet::from(["localhost", "metadata.internal"]));
pub fn parse_bracketed_host(raw: &str) -> Option<&str> {
if let Some(host) = raw.strip_circumfix('[', ']') // 1.98
&& !RESERVED_HOSTS.contains(host) // 1.88 (Ed 2024)
{
return Some(host);
}
None
}
pub fn is_monotonic(samples: &[u64]) -> bool {
samples.array_windows().all(|[a, b]| a <= b) // 1.94
}
pub fn truncate_utf8(s: &str, max_bytes: usize) -> &str {
&s[..s.floor_char_boundary(max_bytes)] // 1.91
}
pub fn normalized_label(raw: Option<&str>) -> &str {
raw.map_or_default(str::trim) // 1.98
}
More examples across Rust 1.64–1.100:
| Legacy pattern | Modern Rust idiom | Stabilized |
|---|---|---|
once_cell::sync::Lazy / lazy_static! |
std::sync::LazyLock / OnceLock |
Rust 1.80 / 1.70 |
Nested if let Some(a) = x { if cond { ... } } |
if let Some(a) = x && cond { ... } (let chains) |
Rust 1.88 (Ed 2024) |
let x = match opt { Some(v) => v, None => return }; |
let Some(x) = opt else { return }; |
Rust 1.65 |
futures::task::noop_waker_ref() |
core::task::Waker::noop() |
Rust 1.85 |
CStr::from_bytes_with_nul(b"hi\0").unwrap() |
c"hi" (C-string literals) |
Rust 1.77 |
let mut h = bh.build_hasher(); k.hash(&mut h); h.finish() |
bh.hash_one(&k) |
Rust 1.71 |
&x as *const _ / &mut x as *mut _ |
core::ptr::from_ref(&x) / from_mut(&mut x) |
Rust 1.76 |
Arc::try_unwrap(a).ok() |
Arc::into_inner(a) |
Rust 1.70 |
Duration::from_secs(300) |
Duration::from_mins(5) |
Rust 1.91 |
RUSTFLAGS="-D warnings" in CI |
CARGO_BUILD_WARNINGS=deny / [build] warnings = "deny" |
Rust 1.97 |
Beyond syntax-detectable rules, cargo-modernize also ships 60 C4 type-wall guidelines for high-leverage features that require type information (! never-type, core::alloc::Allocator, core::range, #[expect], trait upcasting, extract_if, as_chunks, div_ceil, midpoint, strict provenance, async fn in traits, core::error::Error, RwLockWriteGuard::downgrade, Box::new_uninit / Box::write, and more).
Benchmark
In our November 2026 v0.2.1 single-pass evaluation (54 runs, 3 models × 3 conditions × 6 realistic Rust tasks, 80% deterministic assertions + 20% cold blind qualitative review, 0 retries), simply prompting agents to "write modern Rust" (prompt-only) added only +1.1 pp pooled (87.4% → 88.5%), whereas cargo-modernize v0.2.1 lifted combined pass rates to 95.9% (+8.5 pp vs baseline / +7.4 pp vs prompt-only) — bringing Claude Opus 5.5 to 100%, GPT-6.2-Astra to 98.9% (both with 0 residual findings across 12/12 runs), and lifting daily-driver Claude Sonnet 5.5 by +10.0 pp:
| Model | baseline |
prompt-only |
cargo-modernize v0.2.1 |
Lift vs Base / Prompt | Residual Findings (base / prompt / cm) |
Median Duration (base / prompt / cm) |
|---|---|---|---|---|---|---|
| Claude Opus 5.5 | 82/90 (91.1%) |
80/90 (88.9%) |
90/90 (100.0%) |
+8.9 / +11.1 pp |
10 / 9 / 0 | 53.3 s / 44.4 s / 43.6 s |
| Claude Sonnet 5.5 (mid-tier) | 71/90 (78.9%) |
73/90 (81.1%) |
80/90 (88.9%) |
+10.0 / +7.8 pp |
16 / 14 / 6 | 18.1 s / 22.4 s / 34.3 s |
| GPT-6.2-Astra (Codex) | 83/90 (92.2%) |
86/90 (95.6%) |
89/90 (98.9%) |
+6.7 / +3.3 pp |
3 / 0 / 0 | 64.0 s / 75.9 s / 69.1 s |
Pooled (270 / cond) |
236/270 (87.4%) |
239/270 (88.5%) |
259/270 (95.9%) |
+8.5 / +7.4 pp |
29 / 23 / 6 | 53.3 s / 44.4 s / 46.7 s |
- Context & scanner speed (zero-LLM,
v0.2.1,141entries):guidelines list --msrv 1.98 --edition 2024 --format compactshrinks the catalog by 94.0% (73.4k → 4.4kest. tokens;--impact high --format compact+ 5 batchedexplainIDs saves 93.7%). The release binary scans this workspace in 46.6 ms median (vs 95.5 ms warm no-opcargo clippy— 2.05× faster) and a 477k-LOC external Rust workspace in 143.1 ms median (3,200.rsfiles/s, 0 panics). - Transactional
--fix --verifyrollback: AppliedMachineApplicablefixes cleanly in 65–83 ms (post-fixcargo testgreen) and restored all files 100% byte-for-byte (exit=2) when a compile error was injected. - Honest caveats: All 3 models already hit
100%on1.81–1.96C4idioms (Task 03 ceiling), Sonnet paid higher latency/cache overhead (34.3 svs18.1 s) and missed medium-impactC4rules when filtered by--impact high, Task 05 saw a 1-point pooled regression onint-div-ceiloverflow semantics, and agents edited files directly (0/18autonomous--fixinvocations). See the fullv0.2.1report &v0.1.0 → v0.2.1deltas (and the earlierv0.1.0baseline).
Install
1. CLI Binary
Prebuilt binary via cargo-binstall (recommended)
Works on any project regardless of your locally installed Rust toolchain:
cargo binstall cargo-modernize
Prebuilt binary via shell installer (macOS / Linux)
Downloads the latest GitHub Release archive, verifies its SHA-256 checksum, and installs cargo-modernize into ${CARGO_HOME:-$HOME/.cargo}/bin (override with INSTALL_DIR or VERSION=v0.2.2):
curl -fsSL https://raw.githubusercontent.com/Dankosik/cargo-modernize/main/install.sh | sh
GitHub Releases
Download a prebuilt archive + .sha256 checksum for Linux (x86_64, aarch64), macOS (aarch64, x86_64), or Windows (x86_64) from GitHub Releases.
From source via cargo install
Building cargo-modernize from source requires Rust 1.98+ (edition = "2024"). Once built, the binary analyzes workspaces targeting any Rust version (1.56+) and any edition (2015–2024):
cargo install cargo-modernize --locked
2. AI Coding-Agent Skill & Plugin
The user-facing rust-modern-guidelines skill follows the open Agent Skills format and teaches coding agents a lean three-step loop:
cargo modernize guidelines list— load the compact index for the repo's exact MSRV & edition.cargo modernize explain <id>...— pull full before/after examples and edge cases only for relevant idioms (C1,C3, andC4).cargo modernize --diff --format compact— verify changed lines after editing.
Any agent, one command (skills)
npx skills add Dankosik/cargo-modernize --skill rust-modern-guidelines
Add -g to install for your user instead of the current project, or -a <agent> to target a specific tool (e.g., -a claude-code, -a codex, -a cursor).
Claude Code
Install as a plugin from the built-in marketplace:
claude plugin install cargo-modernize --marketplace Dankosik/cargo-modernize
Or inside an active Claude Code session (Claude Code 2.1.275+):
/plugin install cargo-modernize --marketplace Dankosik/cargo-modernize
(On earlier Claude Code versions: /plugin marketplace add Dankosik/cargo-modernize followed by /plugin install cargo-modernize@cargo-modernize.)
OpenAI Codex
Install as a plugin from the built-in marketplace:
codex plugin marketplace add Dankosik/cargo-modernize
codex plugin add cargo-modernize@cargo-modernize
GitHub Copilot
With GitHub CLI 2.90+:
gh skill install Dankosik/cargo-modernize rust-modern-guidelines
Gemini CLI
gemini skills install https://github.com/Dankosik/cargo-modernize --path skills/rust-modern-guidelines
Cursor, Antigravity, or manual copy
Copy skills/rust-modern-guidelines/ into your agent's skills directory:
| Agent | User directory | Project directory |
|---|---|---|
| Claude Code | ~/.claude/skills/ |
.claude/skills/ |
| OpenAI Codex | ~/.agents/skills/ |
.agents/skills/ |
| GitHub Copilot | ~/.copilot/skills/ or ~/.agents/skills/ |
.github/skills/ or .agents/skills/ |
| Cursor | ~/.cursor/skills/ or ~/.agents/skills/ |
.cursor/skills/ or .agents/skills/ |
| Gemini CLI | ~/.gemini/skills/ or ~/.agents/skills/ |
.gemini/skills/ or .agents/skills/ |
| Antigravity | ~/.gemini/antigravity/skills/ |
.agents/skills/ |
How It Compares to Clippy & Rust Style Guides
cargo-modernize is built to complement both cargo clippy and architectural style guides/skills (such as the Rust API Guidelines, Google Rust Style Guide, or BeautifulRust), not replace them:
- Style guides & style skills cover timeless Rust architecture (API design, encapsulation, error types, testing).
cargo clippyruns compiler-backed, type-checked lints during builds.cargo-modernizefocuses specifically on version-accurate Rust1.64–1.100& Edition2024modernization — keeping both humans and agents current across every Rust release without breaking MSRV,#![no_std],const, or SemVer.
| Capability | cargo clippy |
cargo-modernize |
|---|---|---|
Requires compiling the workspace (rustc / TyCtxt) |
Yes | No (pure lossless CST scan: ~47 ms on this repo, ~143 ms on 477k LOC) |
MSRV-aware (rust-version, clippy.toml, rust-toolchain.toml, #[rustversion::since]) |
Partial (opt-in msrv) |
Always on, per package & per #[rustversion] item |
#![no_std] (core / alloc / std) & const context gating |
Type-checked | Built-in crate-tier & const_since gating |
Type-dependent modernization handbook for AI agents (C4 guidelines) |
No | Yes (60 curated C4 entries via guidelines list + explain) |
Cargo.toml & CI/text modernization rules (--no-capture, build.warnings, resolver) |
No | Yes (6 manifest + 2 text rules) |
| Works alongside Clippy without duplicate warnings | — | Yes (--clippy-messages - deduplication + respects #[allow]/#[expect]) |
What's Inside the Catalog
- Open Knowledge Catalog (
cargo-modernize-catalog) — Zero-runtime-dependency#![no_std]data crate (MSRV 1.85) packaging build-time pre-digested upstream Rust release inventories (1.56–1.100), 100% triage coverage (1.64–1.100,1,837records), and141modernization entries:C1/C3executable rules (81total):73Rust CST rules (36C1+37C3across1.64–1.100),6structuralCargo.tomlmanifest rules (complementary to Cargo 1.100's native[lints.cargo]), and2non-Rust text rules (libtest-no-capture,cargo-build-warnings).C4type-wall guidelines (60total): rich before/after examples, behavioral edge cases,const/edition/#![no_std]metadata, upstream rustdoc links, andrust-clippycandidate notes (cargo xtask export-clippy-candidates).
- Progressive-Disclosure AI Agent Workflow — Compact index (
guidelines list) + on-demand multi-ID deep dive (explain) + diff verification (--diff), keeping context lean while covering 100% ofC1 + C3 + C4idioms. - Fast Read-Only-by-Default Workspace Scanner & Transactional
--fix— Respects per-packagerust-version,clippy.tomlmsrv,rust-toolchain.toml,#,constcontexts,#[rustversion::since],#[allow]/#[expect]/[lints.clippy], and public SemVer boundaries.- Zero working-tree or
.git/indexmutation by default (--write-keepand--fixare strictly opt-in). - Opt-in
--fixapplies non-overlappingMachineApplicablereplacements in place (with--dry-run,--allow-maybe-incorrect,--allow-dirty, Git clean-tree guard, canonical workspace-root containment, and transactional--verifyrollback oncargo checkfailure). - Diff-scoped scanning (
--diff [rev]for Gitmerge-base, Jujutsufork_point, or unified patch via--diff -),--since <1.NN>,--clippy-messages <path|->, and--checkCI exit codes (0clean,1findings,2error). - Reports in
text,compact,github(GitHub Actions annotations), andjson(cargo_metadata::Message/rustfix-compatible JSONL).
- Zero working-tree or
Usage
# Browse guidelines for the current workspace's MSRV & edition
cargo modernize guidelines list
# Focus on recent releases (e.g. Rust 1.88–1.100) or high-impact C4 idioms
cargo modernize guidelines list --since 1.88
cargo modernize guidelines list --class c4 --impact high
# Inspect detailed docs, before/after examples, behavior notes, and rustdoc links
cargo modernize explain duration-units strip-circumfix drop-guard
# Scan the whole workspace (read-only, exits 0)
cargo modernize
# Scan only changed lines in compact format
cargo modernize --diff --format compact
# Explain why a rule did or did not match a specific line
cargo modernize why duration-units src/lib.rs:42
# Preview MachineApplicable fixes without modifying files
cargo modernize --fix --dry-run
# Apply MachineApplicable fixes and transactionally verify with `cargo check`
cargo modernize --fix --verify
# Also apply MaybeIncorrect fixes (e.g. opt-in rules like pin-macro) with verification
cargo modernize --fix --allow-maybe-incorrect --enable pin-macro,size-of-prelude --verify
# Baseline existing findings into `.cargo-modernize.toml`
cargo modernize --write-keep --reason "Initial adoption baseline"
Inline suppressions require a reason so future readers know why the older form was kept:
// cargo-modernize: keep duration-units — protocol retry ladder stays in seconds
CI Integration (GitHub Actions)
Gate pull requests on changed lines with native GitHub Actions annotations (0 clean, 1 unsuppressed findings, 2 configuration/VCS/runtime error):
- name: Check Rust modernization idioms on PR diff
run: |
curl -fsSL https://raw.githubusercontent.com/Dankosik/cargo-modernize/main/install.sh | sh
cargo modernize --diff origin/main --format github --check
Deduplicate findings against Clippy in the same pipeline:
cargo clippy --workspace --all-targets --message-format=json \
| cargo modernize --diff origin/main --clippy-messages - --format github --check
Workspace Crates
| Crate | Purpose | MSRV |
|---|---|---|
cargo-modernize |
Standalone cargo modernize CLI subcommand (guidelines, explain, why, scanner, reporters) |
1.98 (analyzes 1.56+) |
cargo-modernize-core |
Lossless CST rules, scope resolver, suggestion validator, and parallel workspace engine | 1.98 |
cargo-modernize-catalog |
Zero-runtime-dependency #![no_std] catalog of Rust 1.56–1.100 inventories, triage, and 141 passports |
1.85 |
Development
Building from source requires Rust 1.98+ (edition = "2024"). cargo-modernize-catalog independently maintains #![no_std] and rust-version = "1.85".
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
cargo xtask check-catalog
cargo xtask export-clippy-candidates
Regenerate release inventories from upstream rust-lang/rust:
cargo xtask inventory 1.56..=1.100 --editions
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi