Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

cli.rs

Helper script for rust-cargo-workspace-designer · 229 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references6 scripts
scripts/cli.rs
//! Command line, file walking, edition detection and reporting shared by the workspace scripts.
//! Not an entry point; pulled in with `mod cli;`.
#![allow(dead_code)]

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::exit;

pub struct Rule {
    pub id: &'static str,
    pub name: &'static str,
    pub severity: &'static str,
    pub why: &'static str,
    pub fix: &'static str,
}

pub struct Finding {
    pub file: String,
    pub line: usize,
    pub id: &'static str,
    pub msg: String,
    pub fix: String,
}

pub struct Input {
    pub name: String,
    pub text: String,
    pub edition: u32,
}

pub struct Opts {
    pub paths: Vec<String>,
    pub json: bool,
    pub strict: bool,
    select: Vec<String>,
    ignore: Vec<String>,
    edition: Option<u32>,
    values: Vec<(String, String)>,
    switches: Vec<String>,
}

pub fn die(msg: &str) -> ! {
    eprintln!("error: {msg}");
    exit(2);
}

pub const COMMON_OPTIONS: &str = "options:
  --json               machine-readable findings
  --strict             exit 1 when there are findings (CI gate)
  --select IDS         only these rules (ids, id prefixes or names, comma separated)
  --ignore IDS         skip these rules
  --list-rules         print every rule with why and fix
  -h, --help
Input: a workspace directory, any Cargo.toml in it (the whole workspace is checked), or - for
one manifest on stdin (no file-system checks). Exit: 0 clean (or findings without --strict),
1 findings with --strict, 2 usage error or unreadable/invalid root manifest.";

/// Parse argv. `value_flags` take a value (e.g. "--max-lifetimes"); `switches` are booleans ("--lib").
pub fn parse(usage: &str, rules: &[Rule], value_flags: &[&str], switches: &[&str]) -> Opts {
    let mut o = Opts { paths: vec![], json: false, strict: false, select: vec![], ignore: vec![], edition: None, values: vec![], switches: vec![] };
    let mut args = std::env::args().skip(1);
    while let Some(a) = args.next() {
        let mut value = |name: &str| args.next().unwrap_or_else(|| die(&format!("{name} needs a value")));
        match a.as_str() {
            "-h" | "--help" => { println!("{usage}\n\n{COMMON_OPTIONS}"); exit(0) }
            "--list-rules" => {
                for r in rules {
                    println!("{} {} [{}]\n  why: {}\n  fix: {}", r.id, r.name, r.severity, r.why, r.fix);
                }
                exit(0)
            }
            "--json" => o.json = true,
            "--strict" => o.strict = true,
            "--select" => o.select = list(&value("--select")),
            "--ignore" => o.ignore = list(&value("--ignore")),
            "--edition" => {
                let v = value("--edition");
                o.edition = match v.as_str() {
                    "auto" => None,
                    "2015" | "2018" | "2021" | "2024" => v.parse().ok(),
                    _ => die(&format!("unknown edition {v}")),
                }
            }
            f if value_flags.contains(&f) => { let v = value(f); o.values.push((f.to_string(), v)) }
            f if switches.contains(&f) => o.switches.push(f.to_string()),
            f if f.starts_with("--") => die(&format!("unknown option {f}\n\n{usage}")),
            _ => o.paths.push(a),
        }
    }
    if o.paths.is_empty() {
        die(&format!("no input; pass files, directories or - for stdin\n\n{usage}"));
    }
    for key in o.select.iter().chain(&o.ignore) {
        if !rules.iter().any(|r| matches(r, key)) {
            die(&format!("unknown rule {key}; see --list-rules"));
        }
    }
    o
}

fn list(s: &str) -> Vec<String> {
    s.split(',').map(|x| x.trim().to_string()).filter(|x| !x.is_empty()).collect()
}

fn matches(r: &Rule, key: &str) -> bool {
    r.id.starts_with(&key.to_uppercase()) || r.name == key
}

impl Opts {
    pub fn enabled(&self, r: &Rule) -> bool {
        (self.select.is_empty() || self.select.iter().any(|k| matches(r, k))) && !self.ignore.iter().any(|k| matches(r, k))
    }

    pub fn on(&self, switch: &str) -> bool {
        self.switches.iter().any(|s| s == switch)
    }

    pub fn value(&self, flag: &str) -> Option<&str> {
        self.values.iter().rev().find(|(f, _)| f == flag).map(|(_, v)| v.as_str())
    }

    /// Read every input: `-` (stdin), files, and `.rs` files under directories (skips target/, .git/).
    pub fn inputs(&self) -> Vec<Input> {
        let mut files = Vec::new();
        for p in &self.paths {
            if p == "-" {
                let mut text = String::new();
                std::io::stdin().read_to_string(&mut text).unwrap_or_else(|e| die(&format!("cannot read stdin: {e}")));
                files.push(Input { name: "<stdin>".into(), text, edition: self.edition.unwrap_or(2021) });
                continue;
            }
            let path = PathBuf::from(p);
            let mut found = Vec::new();
            if path.is_dir() {
                walk(&path, &mut found);
                found.sort();
            } else {
                found.push(path);
            }
            for f in found {
                let text = std::fs::read_to_string(&f).unwrap_or_else(|e| die(&format!("cannot read {}: {e}", f.display())));
                let edition = self.edition.unwrap_or_else(|| edition_for(&f));
                files.push(Input { name: f.display().to_string(), text, edition });
            }
        }
        files
    }
}

fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else { return };
    for e in entries.flatten() {
        let p = e.path();
        let name = e.file_name();
        if p.is_dir() {
            if name != "target" && name != ".git" {
                walk(&p, out);
            }
        } else if p.extension().is_some_and(|x| x == "rs") {
            out.push(p);
        }
    }
}

/// Edition from the nearest Cargo.toml that states one (follows `edition.workspace = true` upward).
pub fn edition_for(file: &Path) -> u32 {
    let mut dir = file.canonicalize().ok().and_then(|p| p.parent().map(Path::to_path_buf));
    while let Some(d) = dir {
        if let Ok(toml) = std::fs::read_to_string(d.join("Cargo.toml")) {
            for line in toml.lines() {
                let l = line.trim();
                if let Some(v) = l.strip_prefix("edition").map(str::trim).and_then(|r| r.strip_prefix('=')) {
                    if let Ok(year) = v.trim().trim_matches('"').parse() {
                        return year;
                    }
                }
            }
        }
        dir = d.parent().map(Path::to_path_buf);
    }
    2021
}

fn json_str(s: &str) -> String {
    let mut out = String::from("\"");
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Print findings and exit with the documented code.
pub fn finish(opts: &Opts, rules: &[Rule], mut findings: Vec<Finding>, nfiles: usize, topic: &str) -> ! {
    findings.sort_by(|a, b| (&a.file, a.line, a.id).cmp(&(&b.file, b.line, b.id)));
    let rule = |id: &str| rules.iter().find(|r| r.id == id).expect("rule id");
    if opts.json {
        let items: Vec<String> = findings
            .iter()
            .map(|f| {
                let r = rule(f.id);
                format!(
                    "{{\"file\":{},\"line\":{},\"rule\":{},\"name\":{},\"severity\":{},\"message\":{},\"fix\":{}}}",
                    json_str(&f.file), f.line, json_str(r.id), json_str(r.name), json_str(r.severity), json_str(&f.msg), json_str(&f.fix)
                )
            })
            .collect();
        println!("{{\"files\":{},\"findings\":[{}]}}", nfiles, items.join(","));
    } else if findings.is_empty() {
        println!("No {topic} issues found in {nfiles} file(s).");
    } else {
        for f in &findings {
            let r = rule(f.id);
            println!("{}:{}: {} [{}] {}: {}", f.file, f.line, r.id, r.severity, r.name, f.msg);
            if !f.fix.is_empty() {
                println!("    fix: {}", f.fix);
            }
        }
        println!("\n{} finding(s) in {} file(s).", findings.len(), nfiles);
    }
    exit(if opts.strict && !findings.is_empty() { 1 } else { 0 })
}
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-tokio-async-service-builder

Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.

rust-trait-design-reviewer

Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.

rust-unsafe-block-auditor

Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.