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

scaffold_errors.rs

Helper script for rust-error-handling-thiserror-anyhow-designer · 137 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references9 scripts
scripts/scaffold_errors.rs
//! Generate an `error.rs` module from a small JSON spec or a built-in preset: a thiserror 2
//! enum (non_exhaustive for libraries), code(), is_retryable(), http_status(), a Result alias,
//! an axum IntoResponse impl for HTTP apps, and tests.
//!
//! Build: rustc -O --edition 2021 scripts/scaffold_errors.rs -o /tmp/scaffold_errors
//! Usage: scaffold_errors --spec errors.json|- [-o src/error.rs] [--json]
//!        scaffold_errors --preset storage-lib|web-app [--print-spec]

mod errgen;
mod json;

use std::io::Read;
use std::process::exit;

const USAGE: &str = r#"usage: scaffold_errors (--spec FILE|- | --preset NAME) [-o FILE] [--json] [--print-spec]

Generate a Rust error module from a JSON spec:
  {"crate_kind": "lib"|"app", "name": "StoreError", "http": true, "variants": [
     {"name": "NotFound", "fields": {"id": "u64"}, "message": "item {id} not found"},
     {"name": "Io", "from": "std::io::Error", "message": "storage i/o failed"},
     {"name": "Decode", "fields": {"offset": "u64"}, "source": "serde_json::Error",
      "message": "cannot decode record at byte {offset}", "http": 500},
     {"name": "Internal", "transparent": "anyhow::Error"}]}
Variant keys: name, fields, message, from, source, transparent, retryable, http, code, doc.

options:
  --spec FILE|-      read the spec (- for stdin)
  --preset NAME      storage-lib (library: non_exhaustive, io kinds) or web-app (axum IntoResponse)
  --print-spec       print the preset's spec (start your own from it)
  -o FILE            write the module to FILE instead of stdout
  --json             print {"name", "variants", "rust"} instead of plain Rust
Exit: 0 generated, 2 invalid spec (the message names the problem) or usage error."#;

const STORAGE_LIB: &str = r#"{
  "crate_kind": "lib",
  "name": "StoreError",
  "http": false,
  "variants": [
    {"name": "NotFound", "fields": {"key": "String"}, "message": "key {key:?} not found", "doc": "The key does not exist."},
    {"name": "EmptyKey", "message": "key must not be empty"},
    {"name": "Busy", "message": "storage engine is busy", "retryable": true},
    {"name": "Open", "fields": {"path": "std::path::PathBuf"}, "source": "std::io::Error", "message": "failed to open {path:?}"},
    {"name": "Io", "from": "std::io::Error", "message": "i/o error on the store log"},
    {"name": "Corrupt", "fields": {"line": "usize"}, "message": "corrupt record at line {line}"}
  ]
}"#;

const WEB_APP: &str = r#"{
  "crate_kind": "app",
  "name": "ApiError",
  "http": true,
  "variants": [
    {"name": "NotFound", "fields": {"resource": "&'static str", "id": "String"}, "message": "{resource} {id} not found"},
    {"name": "Validation", "fields": {"field": "&'static str", "reason": "String"}, "message": "invalid {field}: {reason}", "http": 422},
    {"name": "Unauthorized", "message": "authentication required"},
    {"name": "Conflict", "fields": {"id": "String"}, "message": "{id} was modified concurrently"},
    {"name": "RateLimited", "fields": {"retry_after_secs": "u64"}, "message": "rate limited, retry in {retry_after_secs}s", "retryable": true},
    {"name": "Upstream", "fields": {"service": "&'static str"}, "source": "std::io::Error", "message": "upstream {service} failed", "http": 502},
    {"name": "Internal", "transparent": "anyhow::Error"}
  ]
}"#;

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

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 => out.push(c),
        }
    }
    out + "\""
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.is_empty() || args.iter().any(|a| a == "-h" || a == "--help") {
        println!("{USAGE}");
        exit(if args.is_empty() { 2 } else { 0 });
    }
    let (mut spec_path, mut preset, mut out_path) = (None, None, None);
    let (mut as_json, mut print_spec) = (false, false);
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let mut val = || it.next().cloned().unwrap_or_else(|| die(&format!("{a} needs a value")));
        match a.as_str() {
            "--spec" => spec_path = Some(val()),
            "--preset" => preset = Some(val()),
            "-o" | "--out" => out_path = Some(val()),
            "--json" => as_json = true,
            "--print-spec" => print_spec = true,
            other => die(&format!("unknown argument {other}")),
        }
    }
    let text = match (&spec_path, &preset) {
        (Some(_), Some(_)) => die("use either --spec or --preset"),
        (None, Some(p)) => match p.as_str() {
            "storage-lib" => STORAGE_LIB.to_string(),
            "web-app" => WEB_APP.to_string(),
            other => die(&format!("unknown preset '{other}' (storage-lib, web-app)")),
        },
        (Some(p), None) if p == "-" => {
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap_or_else(|e| die(&format!("cannot read stdin: {e}")));
            s
        }
        (Some(p), None) => std::fs::read_to_string(p).unwrap_or_else(|e| die(&format!("cannot read {p}: {e}"))),
        (None, None) => die("pass --spec FILE or --preset NAME"),
    };
    if print_spec {
        println!("{}", text.trim());
        return;
    }
    let doc = json::parse(&text).unwrap_or_else(|e| die(&format!("cannot parse spec JSON: {e}")));
    let spec = errgen::from_json(&doc).unwrap_or_else(|e| die(&format!("invalid spec: {e}")));
    let rust = errgen::render(&spec);
    let variants: Vec<String> = spec.variants.iter().map(|v| json_str(&v.name)).collect();
    let output = if as_json {
        format!("{{\"name\":{},\"variants\":[{}],\"rust\":{}}}\n", json_str(&spec.name), variants.join(","), json_str(&rust))
    } else {
        rust
    };
    match out_path {
        Some(p) => {
            std::fs::write(&p, &output).unwrap_or_else(|e| die(&format!("cannot write {p}: {e}")));
            eprintln!("wrote {p} ({} with {} variants)", spec.name, spec.variants.len());
        }
        None => print!("{output}"),
    }
}
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-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

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.