The Rust-specific analysis hooks, rust-code-analyzer and rust performance analyzer, automate code quality and performance improvements by analyzing only the files changed in a branch. These hooks are designed to ensure that all optimizations are safe, measurable, and maintainable, while preserving public APIs and existing functionality.
Identifying Changed Files#
Both hooks use the command git --no-pager diff --name-only origin/main to identify which files have changed compared to the main branch. This approach ensures that only files relevant to the current changeset are analyzed, reducing noise and focusing improvements where they are most needed. The hooks typically monitor Rust source files (.rs), Cargo.toml, and related build files [libmagic-rs rust-code-analyzer] [libmagic-rs rust-perf-optimizer].
Analysis Prompts and Focus Areas#
rust-code-analyzer#
This hook analyzes changed files for code quality issues across eight categories: Code Smells, Design Patterns, Best Practices, Readability, Maintainability, Performance, Type Safety, and Error Handling. The analysis prompt instructs the tool to:
- Remove dead or unreachable code.
- Split oversized internal functions (without changing public APIs).
- Eliminate duplicate code blocks.
- Replace blocking I/O with async equivalents in async contexts.
- Fix clippy warnings and follow Rust edition conventions.
- Improve naming, add rustdoc comments to public APIs, and add code examples.
- Extract internal modules, add missing error context, and improve documentation.
- Eliminate unnecessary
.clone()calls and optimize memory allocations. - Strengthen type constraints and reduce unnecessary nesting.
- Add context to errors and ensure no silent failures.
Only mechanical, non-breaking improvements are applied automatically. Any changes that could affect public APIs, introduce significant overhead, or alter existing behavior are deferred for manual review [libmagic-rs rust-code-analyzer].
Example Safe Edits#
// Remove dead code
#[allow(dead_code)]
fn unused_function() {} // Remove entirely
// Add error context
.map_err(|e| format!("Error: {}", e))
// becomes:
.with_context(|| "Failed to process configuration")
// Replace blocking I/O in async
std::fs::read_to_string(path)
// becomes:
tokio::fs::read_to_string(path).await
// Eliminate unnecessary clones
let name = item.name.clone();
process_string(name);
// becomes:
process_string(&item.name);
// Add rustdoc to public APIs
pub fn process_data(data: &str) -> Result<String> {
// becomes:
/// Processes the input data and returns a formatted result.
///
/// # Examples
/// ```
/// let result = process_data("input")?;
/// ```
pub fn process_data(data: &str) -> Result<String> {
rust performance analyzer#
This hook analyzes changed files for runtime performance characteristics, focusing on algorithmic complexity, allocation behavior, async patterns, I/O efficiency, data structures, caching, error handling, logging costs, memory footprint, and instrumentation opportunities. The analysis prompt directs the tool to:
- Remove unnecessary
.clone()calls. - Add
Vec::with_capacity()when the size is known. - Replace
format!in loops withpush_str. - Hoist constant computations out of loops.
- Add early returns for empty inputs.
- Use iterators instead of collecting to
Vec. - Replace blocking I/O with async equivalents.
- Add tracing guards for expensive logging.
All optimizations must preserve correctness, maintain public API compatibility, and respect security constraints. The tool provides before/after code examples, estimates performance impact, and considers maintainability trade-offs. Only clearly safe micro-optimizations are applied automatically [libmagic-rs rust-perf-optimizer] [StringyMcStringFace rust-perf-analyzer].
Validation and Safety#
After applying changes, both hooks run validation commands (just lint and just test). If any change causes a lint or test failure, the change is reverted and deferred for manual review. The hooks never change public function signatures or visibility, never introduce unsafe code, and never break existing functionality. If an optimization is uncertain, it is deferred rather than applied automatically. Code clarity is always prioritized over micro-optimizations.
Interpreting and Acting on Analysis Results#
The output from these hooks includes:
- A summary of files analyzed.
- A count and description of safe edits or optimizations applied.
- A list of deferred items with reasons for deferral.
- Items requiring manual approval.
- Descriptions of applied changes and their rationale.
- Performance impact estimates (for performance analyzer).
- Recommended next steps.
Example output format:
## Code Quality Analysis Summary
**Files Analyzed**: [list of changed files]
**Safe Edits Applied**: [count]
**Items Deferred**: [count]
**Approval Required**: [count]
### Applied Changes
- [file]: [description of change and rationale]
### Deferred Items
- [file]: [reason for deferral]
### Requires Approval
- [file]: [quality concern requiring human review]
### Quality Assessment
[Overall code quality assessment]
### Next Steps
[Recommended follow-up actions]
When reviewing results, focus on the rationale for each change, especially deferred or approval-required items. For deferred items, review the reasons and determine if manual intervention is needed. For applied changes, verify that all tests and lints pass and that public APIs remain stable. Use the recommended next steps to guide further manual improvements or code review.
Best Practices#
- Regularly review deferred and approval-required items to ensure no important issues are overlooked.
- Use the hooks as part of your CI/CD pipeline to automate safe improvements and catch regressions early.
- Prioritize code clarity and maintainability over aggressive micro-optimizations.
- Always validate changes with linting and testing before merging.
These hooks provide a robust, automated foundation for maintaining high code quality and performance in Rust projects, while ensuring that all changes are safe, measurable, and easy to review.