### Install Rustqual from Source Source: https://github.com/saschaontour/rustqual/blob/main/book/getting-started.md Clone the repository and install rustqual from source. ```bash git clone https://github.com/SaschaOnTour/rustqual cd rustqual cargo install --path . ``` -------------------------------- ### Install Rustqual Source: https://github.com/saschaontour/rustqual/blob/main/book/getting-started.md Install the rustqual binary using cargo. ```bash cargo install rustqual ``` -------------------------------- ### JSON Query Examples Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-output-formats.md Examples demonstrating how to use `jq` to query the JSON output for specific information, such as quality scores or high-severity architecture findings. ```bash rustqual --format json | jq '.summary.quality_score' ``` ```bash rustqual --format json | jq '.architecture_findings[] | select(.severity == "high")' ``` -------------------------------- ### Install and Run rustqual Source: https://github.com/saschaontour/rustqual/blob/main/README.md Install rustqual using cargo and then run it on the current directory. The output shows a summary of code quality findings. ```bash $ cargo install rustqual $ rustqual . ── src/order.rs ✓ INTEGRATION process_order (line 12) ✓ OPERATION calculate_discount (line 28) ✗ VIOLATION process_payment (line 48) [MEDIUM] ═══ Summary ═══ Functions: 24 Quality Score: 82.3% IOSP: 85.7% Complexity: 90.0% DRY: 95.0% SRP: 100.0% Test Quality: 100.0% Coupling: 100.0% Architecture: 100.0% 4 quality findings. Run with --verbose for details. ``` -------------------------------- ### Configuration File Example Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Illustrates the structure of the rustqual.toml configuration file for setting dimension weights. ```toml [quality] weights = { iosp = 1.0, complexity = 0.5, dry = 0.5, srp = 1.0, coupling = 0.2, } ``` -------------------------------- ### Install and Run Rustqual Source: https://github.com/saschaontour/rustqual/blob/main/book/adapter-parity.md Install Rustqual using Cargo and run it on the current directory, failing on warnings. ```sh cargo install rustqual rustqual . --fail-on-warnings ``` -------------------------------- ### Install and Run RustQual Source: https://github.com/saschaontour/rustqual/blob/main/README.md Basic commands to install RustQual using cargo and run it on a Rust project. ```bash cargo install rustqual cd your-rust-project rustqual ``` -------------------------------- ### Top-level Configuration Example Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-configuration.md Example of top-level configuration settings in rustqual.toml, including file exclusions and maximum suppression ratio. ```toml exclude_files = ["examples/**", "vendor/**"] max_suppression_ratio = 0.05 ``` -------------------------------- ### Derive Default Example Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Illustrates the addition of `#[derive(Default)]` to `ProjectScope` for easier test setup. ```rust #[derive(Default)] struct ProjectScope { name: String, } ``` -------------------------------- ### GitLab CI Snippet Source: https://github.com/saschaontour/rustqual/blob/main/book/ci-integration.md Example GitLab CI script to install rustqual and generate a JSON quality report as an artifact. ```yaml quality: image: rust:latest script: - cargo install rustqual - rustqual --format json > quality.json artifacts: paths: - quality.json ``` -------------------------------- ### Minimal GitHub Actions CI Step Source: https://github.com/saschaontour/rustqual/blob/main/README.md Install rustqual and run a basic quality check with a minimum score of 90. ```yaml - run: cargo install rustqual - run: rustqual --format github --min-quality-score 90 ``` -------------------------------- ### Rustqual Self-Analysis Example Source: https://github.com/saschaontour/rustqual/blob/main/README.md Demonstrates running rustqual on its own source code to achieve 100% quality score, including coverage analysis. ```bash $ cargo run -- . --fail-on-warnings --coverage coverage.lcov ═══ Summary ═══ Quality Score: 100.0% IOSP: 100.0% Complexity: 100.0% DRY: 100.0% SRP: 100.0% Coupling: 100.0% Test Quality:100.0% Architecture:100.0% All quality checks passed! ✓ ``` -------------------------------- ### Expected Findings Output Source: https://github.com/saschaontour/rustqual/blob/main/examples/architecture/call_parity/README.md Running the example with `--findings` produces specific call parity issues related to delegation and reachability. ```text Running `cargo run -- examples/architecture/call_parity --findings` produces exactly two findings: 1. `architecture/call_parity/no_delegation` on `post_list` in `src/rest/handlers.rs` — it returns a hard-coded Vec instead of calling `application::list::list_items`. 2. `architecture/call_parity/missing_adapter` on `crate::application::list::list_items` — CLI + MCP both delegate into it, but REST doesn't, so the coverage set `{cli, mcp}` is missing `rest`. `cmd_debug` carries `// qual:allow(architecture, call_parity) reason: "…"` so the pipeline silences its would-be `no_delegation` finding. This is the explicit escape for intentionally asymmetric features (a bare `allow(architecture)` is rejected — the marker must name the rule family). ``` -------------------------------- ### Default Box Example Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Shows the simplification from `Box::new(T::default())` to `Box::default()`. ```rust Box::default() ``` -------------------------------- ### Rustqual Configuration Example Source: https://github.com/saschaontour/rustqual/blob/main/book/architecture-rules.md Basic TOML configuration to enable the architecture dimension in rustqual. Add specific rules like layers, forbidden edges, patterns, and trait contracts after enabling. ```toml [architecture] enabled = true # Then add layers, forbidden edges, patterns, trait_contract sections ``` -------------------------------- ### rustqual Configuration Example Source: https://github.com/saschaontour/rustqual/blob/main/book/module-quality.md This TOML snippet shows how to configure rustqual's SRP-related thresholds. Defaults are commented out, allowing customization of parameters like max_fields, max_methods, and file_length. ```toml [srp] enabled = true # max_fields = 12 # max_methods = 20 # max_fan_out = 10 # max_parameters = 5 # lcom4_threshold = 2 # file_length = 300 # max_independent_clusters = 2 # min_cluster_statements = 5 # smell_threshold = 0.6 # composite score for SRP-001 ``` -------------------------------- ### Rustqual Analysis Output Source: https://github.com/saschaontour/rustqual/blob/main/book/getting-started.md Example of rustqual's output, showing file analysis, function classifications, and a summary of quality metrics. ```text ── src/order.rs ✓ INTEGRATION process_order (line 12) ✓ OPERATION calculate_discount (line 28) ✗ VIOLATION process_payment (line 48) [MEDIUM] ═══ Summary ═══ Functions: 24 Quality Score: 82.3% IOSP: 85.7% Complexity: 90.0% DRY: 95.0% SRP: 100.0% Test Quality: 100.0% Coupling: 100.0% Architecture: 100.0% 4 quality findings. Run with --verbose for details. ``` -------------------------------- ### Struct Literal Syntax Example Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Demonstrates the replacement of `#[allow(clippy::field_reassign_with_default)]` with struct literal syntax. ```rust ProjectScope { name: "test_project".to_string(), ..Default::default() } ``` -------------------------------- ### Trait Dispatch Example Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Demonstrates how dynamic trait objects are dispatched to workspace implementations. This is useful for understanding call-parity in Ports & Adapters architectures. ```rust fn dispatch(h: &dyn Handler) { h.handle() } ``` -------------------------------- ### CLI Handler Example with Method Chain Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Illustrates a common CLI handler pattern where opening a session involves a method chain with error mapping. This was a source of false positives in previous versions. ```rust pub fn cmd_diff(path: &str) -> Result<(), Error> { let session = RlmSession::open_cwd().map_err(map_err)?; session.diff(path).map_err(map_err)?; Ok(()) } ``` -------------------------------- ### Test Quality Configuration Example Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-configuration.md Configures the test quality dimension, specifying custom assertion macros to be recognized. ```toml [test_quality] extra_assertion_macros = ["verify", "check_invariant", "expect_that"] ``` -------------------------------- ### Rustqual Configuration for Transparent Wrappers and Macros Source: https://github.com/saschaontour/rustqual/blob/main/book/adapter-parity.md Configuration example for rustqual to define adapter modules, the target module, and lists of transparent wrappers and macros. This allows the analyzer to correctly resolve calls through framework extractors and macros. ```toml [architecture.call_parity] adapters = ["cli", "mcp"] target = "application" transparent_wrappers = ["State", "Extension", "Json", "Data"] transparent_macros = ["tracing::instrument", "async_trait::async_trait"] ``` -------------------------------- ### Rust Method Call Example Source: https://github.com/saschaontour/rustqual/blob/main/book/adapter-parity.md Illustrates a typical Rust method call chain involving session operations. This is used to demonstrate the need for a sophisticated call graph analyzer. ```rust let session = Session::open_cwd().map_err(map_err)?; session.diff(path).map_err(map_err?); ``` -------------------------------- ### LLM Prompt with AI-JSON Format Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-output-formats.md Use the 'ai-json' format for compact JSON output suitable for LLM consumption. This example pipes the output to an LLM for analysis. ```json { "version": "1.2.2", "findings": 2, "findings_by_file": { "src/order.rs": [ { "category": "violation", "line": 48, "fn": "order::process_payment", "detail": "logic + calls (logic lines 50, call lines 53)" } ], "": [ { "category": "cycle", "line": 0, "fn": "", "detail": "a -> b -> a" } ] } } ``` ```bash rustqual --format ai | claude code "Fix these findings" ``` -------------------------------- ### Example rustqual Findings Output Source: https://github.com/saschaontour/rustqual/blob/main/book/function-quality.md Illustrates the typical output format for rustqual findings, showing violation codes, function names, line numbers, and severity. ```text ✗ VIOLATION process_order (line 48) [MEDIUM] IOSP — function mixes orchestration with logic CX-001 cognitive=18 > 15 CX-004 length=72 > 60 ⚠ SLM dispatch (line 124) — takes &self but never uses it ``` -------------------------------- ### Example Findings Output Source: https://github.com/saschaontour/rustqual/blob/main/book/architecture-rules.md Illustrates the one-line output format for architecture rule violations. These findings help identify specific rule breaches in the codebase. ```text src/domain/order.rs:5 ARCHITECTURE layer rank 0 ↛ rank 2 via crate::adapters::source::io: layer rule src/adapters/analyzers/iosp/visitor.rs:3 ARCHITECTURE forbidden import crate::adapters::analyzers::dry::mod: forbidden edge src/auth/session.rs:88 ARCHITECTURE shared method call unwrap: Production propagates errors typed instead of panicking src/ports/storage.rs:42 ARCHITECTURE trait Storage [forbidden_return_type_contains]: anyhow::: trait contract ``` -------------------------------- ### Rust Example with Transparent Wrapper Source: https://github.com/saschaontour/rustqual/blob/main/book/adapter-parity.md Demonstrates how a function using a transparent wrapper like `State` can have its calls resolved correctly by rustqual, allowing the underlying method calls (e.g., `db.query()`) to be tracked. ```rust fn h(State(db): State) { db.query() } ``` -------------------------------- ### Refactor Bloated Module Example Source: https://github.com/saschaontour/rustqual/blob/main/book/module-quality.md Illustrates refactoring a large, multi-responsibility module into smaller, single-responsibility modules. The 'order' module is split into validation, pricing, persistence, and notification. ```text # Before src/order/mod.rs # 850 lines: validation + pricing + persistence + email # After src/order/mod.rs # re-exports src/order/validation.rs # 180 lines src/order/pricing.rs # 220 lines src/order/persistence.rs # 190 lines src/order/notification.rs # 140 lines ``` -------------------------------- ### Initial Rustqual Configuration with Enabled Dimensions Source: https://github.com/saschaontour/rustqual/blob/main/book/legacy-adoption.md Configure rustqual.toml to enable specific dimensions like complexity and duplicates, while keeping others like SRP and coupling disabled initially. This allows for a phased rollout, starting with high-signal, low-controversy findings. ```toml # rustqual.toml — minimal initial config [complexity] enabled = true max_function_lines = 80 # initial floor; tighten over time [duplicates] enabled = true [test_quality] enabled = true [srp] enabled = false # enable later [coupling] enabled = false # enable later [architecture] enabled = false # enable when you've decided on layering ``` -------------------------------- ### First Run on Project Source: https://github.com/saschaontour/rustqual/blob/main/book/getting-started.md Navigate to your Rust project directory and run rustqual to analyze it. ```bash cd your-rust-project rustqual ``` -------------------------------- ### Inline Suppression Examples Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Examples of how to suppress specific quality analysis findings directly in the code. ```rust // qual:allow ``` ```rust // qual:allow(dim) ``` ```rust // iosp:allow ``` -------------------------------- ### Deprecated Handler Exclusion Example Source: https://github.com/saschaontour/rustqual/blob/main/book/adapter-parity.md This example shows a deprecated adapter public function that is excluded from parity checks. The `#[deprecated]` attribute, in any form, signals this exclusion. ```rust #[deprecated = "use cmd_search"] pub fn cmd_grep(args: ClapArgs) { /* … */ } // skipped from parity ``` -------------------------------- ### Rustqual Coupling Violation Examples Source: https://github.com/saschaontour/rustqual/blob/main/book/coupling-quality.md Examples of output from rustqual indicating various coupling violations. These include circular dependencies, Stable Dependencies Principle violations, orphaned impl blocks, single-impl traits, downcast escape hatches, and inconsistent error types. ```text ```text ✗ CP-001 src/auth/session.rs ↔ src/auth/token.rs (cycle of length 2) ✗ CP-002 src/domain/user.rs depends on src/api/handlers.rs (I=0.91) ⚠ OI impl Order in src/orders/persistence.rs (struct in src/orders/types.rs) ⚠ SIT trait OrderValidator (1 impl: BasicOrderValidator) ⚠ DEH downcast in src/registry/lookup.rs (line 88) ⚠ IET src/payment/mod.rs uses MyError (4×) and anyhow::Error (3×) ``` ``` -------------------------------- ### CI Configuration for Clippy Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md Shows how Clippy is configured to run with warnings enabled in the CI pipeline. ```bash RUSTFLAGS="-Dwarnings" cargo clippy ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-cli.md The fundamental structure for running the rustqual CLI. PATH defaults to the current directory. ```bash rustqual [OPTIONS] [PATH] ``` -------------------------------- ### Rustqual Suppression Annotations Source: https://github.com/saschaontour/rustqual/blob/main/README.md Examples of using rustqual suppression annotations to exempt specific code sections from quality checks, with explanations for each type. ```rust // qual:allow(iosp) — match dispatcher; arms intentionally inlined fn dispatch(cmd: Command) -> Result<()> { /* … */ } // qual:api — public re-export, callers live outside this crate pub fn parse(input: &str) -> Result { /* … */ } // qual:test_helper — used only from integration tests pub fn build_test_session() -> Session { /* … */ } ``` -------------------------------- ### Generate Configuration File Source: https://github.com/saschaontour/rustqual/blob/main/book/getting-started.md Generate a default rustqual.toml configuration file tailored to your project's metrics. ```bash rustqual --init ``` -------------------------------- ### Basic Rustqual Configuration for Call Parity Source: https://github.com/saschaontour/rustqual/blob/main/book/adapter-parity.md Enable Rustqual and define layer order in `rustqual.toml` to set up architecture rules, including call parity. ```toml # rustqual.toml [architecture] enabled = true [architecture.layers] order = ["domain", "application", "cli", "mcp"] # ... layer paths ... [architecture.call_parity] adapters = ["cli", "mcp"] target = "application" ``` -------------------------------- ### Refactor God-Struct with Disjoint Clusters Example Source: https://github.com/saschaontour/rustqual/blob/main/book/module-quality.md Demonstrates splitting a 'god-struct' with disjoint clusters into smaller, focused structs. 'UserSession' is divided into 'AuthSession' and 'UserPresentation'. ```rust // Before: SRP-001 with 2 clusters struct UserSession { token: Token, expires_at: DateTime, avatar_url: String, theme: Theme, } // After struct AuthSession { token: Token, expires_at: DateTime } struct UserPresentation { avatar_url: String, theme: Theme } ``` -------------------------------- ### Build and Test Commands Source: https://github.com/saschaontour/rustqual/blob/main/README.md Common commands for building, testing, and analyzing the Rust project, including running the full test suite, self-analysis with coverage, and Clippy lints. ```bash cargo nextest run # full test suite cargo run -- . --fail-on-warnings --coverage coverage.lcov # self-analysis RUSTFLAGS="-Dwarnings" cargo clippy --all-targets # lints (0 warnings) ``` -------------------------------- ### Allowing Architecture Rule Suppression Source: https://github.com/saschaontour/rustqual/blob/main/book/architecture-rules.md Example of suppressing an architecture rule using a `// qual:allow` annotation. A reason is mandatory, and suppressions count against `max_suppression_ratio`. ```rust // qual:allow(architecture, forbidden) reason: "port adapter must call the registry // directly for serialization round-trip; a pure domain accessor would lose ordering." use crate::adapters::registry::lookup; ``` -------------------------------- ### Generating and Using a Quality Baseline Source: https://github.com/saschaontour/rustqual/blob/main/book/legacy-adoption.md Generate a baseline quality snapshot using `rustqual --save-baseline` and commit it. In CI, use `rustqual --compare baseline.json --fail-on-regression` to prevent regressions in new code. Regenerate the baseline after significant refactoring. ```bash # Generate the baseline once rustqual --save-baseline baseline.json git add baseline.json git commit -m "Add quality baseline" ``` ```yaml - run: rustqual --compare baseline.json --fail-on-regression ``` ```bash rustqual --save-baseline baseline.json # after refactor lowers the count ``` -------------------------------- ### GitHub Actions Annotation Example Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-output-formats.md This format generates GitHub workflow commands for inline annotations on pull request diffs, indicating errors, warnings, or notices directly in the UI. ```text ::error file=src/order.rs,line=48::IOSP violation: logic=[if (line 50)], calls=[helper (line 53)] ::warning file=src/utils/legacy.rs,line=12::Dead code detected: legacy::unused ::warning file=src/payment.rs,line=88::Stale qual:allow(complexity, max_cyclomatic=20) marker — no finding in window. ``` -------------------------------- ### RustQual Complexity Configuration Source: https://github.com/saschaontour/rustqual/blob/main/book/function-quality.md Shows how to configure complexity thresholds in `rustqual.toml` to control function size, nesting, and other metrics. This allows tailoring quality checks to project needs. ```toml [complexity] enabled = true max_cognitive = 15 max_cyclomatic = 10 max_function_lines = 60 max_nesting_depth = 4 detect_unsafe = true detect_error_handling = true allow_expect = false # set true to permit .expect() but still flag .unwrap() ``` -------------------------------- ### Refactor Parameter Sprawl Example Source: https://github.com/saschaontour/rustqual/blob/main/book/module-quality.md Shows how to refactor a function with a wide signature (parameter sprawl) by introducing a context struct. The 'render' function is improved by accepting a 'RenderOptions' struct. ```rust // SRP-003 fn render(width: u32, height: u32, dpi: u32, theme: Theme, locale: Locale, watermark: Option<&str>) { /* … */ } // Better fn render(opts: &RenderOptions) { /* … */ } ``` -------------------------------- ### Configuration: Test File Length Source: https://github.com/saschaontour/rustqual/blob/main/CHANGELOG.md The '[tests].file_length_baseline' and '[tests].file_length_ceiling' options are replaced by a single '[tests].file_length' setting. ```toml [tests] file_length = 300 ``` -------------------------------- ### Bulk Suppression of Directories Source: https://github.com/saschaontour/rustqual/blob/main/book/legacy-adoption.md Configure `exclude_files` in `rustqual.toml` to skip entire directories like vendored code, generated files, or examples from analysis. These files are entirely ignored by rustqual. ```toml exclude_files = [ "src/legacy/**", "src/generated/**", "examples/**", ] ``` -------------------------------- ### Project Composition Configuration Source: https://github.com/saschaontour/rustqual/blob/main/book/reference-configuration.md Sets up overall project analysis, including excluded files, max suppression ratio, and enabling various analysis modules like complexity, duplicates, SRP, coupling, test quality, and architecture. ```toml exclude_files = ["examples/**"] max_suppression_ratio = 0.05 [complexity] enabled = true [duplicates] enabled = true [srp] enabled = true [coupling] enabled = true [test_quality] enabled = true [architecture] enabled = true [architecture.layers] order = ["domain", "ports", "infrastructure", "application"] unmatched_behavior = "strict_error" [architecture.layers.domain] paths = ["src/domain/**"] # … etc. ``` -------------------------------- ### Generating LCOV Coverage Data for rustqual Source: https://github.com/saschaontour/rustqual/blob/main/book/test-quality.md This command sequence demonstrates how to install cargo-llvm-cov and generate LCOV coverage data, which is required for rustqual's coverage-based checks (TQ-004, TQ-005). ```bash cargo install cargo-llvm-cov cargo llvm-cov --lcov --output-path coverage.lcov rustqual --coverage coverage.lcov ```