Skip to content
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# GitHub Copilot Instructions for Rust Development

**Scope**: These guidelines apply to ALL Rust files (*.rs) in this repository, including:
- `src/` - Main source code
- `bin/` - Binary crates
- `crates/` - Workspace crates
- `examples/` - Example code
- `tests/` - Integration tests
- `benches/` - Benchmarks

## Code Quality and Style Guidelines

### Variable Naming and Declaration
- **Lazy declaration**: Only define variables when you need them, not at the beginning of functions
- **Meaningful names**: Variable names should clearly describe their purpose and content
- **Snake_case**: Use snake_case for variables, functions, and modules
- **PascalCase**: Use PascalCase for types, structs, enums, and traits

### Logging and Output Best Practices
- **Inline variables in macros**: Always inline variables within `info!`, `debug!`, `warn!`, `error!`, and `println!` macros
```rust
// ✅ Good
info!("Processing user {user_id} with status {status}");

// ❌ Bad
info!("Processing user {} with status {}", user_id, status);
```
- **Use structured logging**: Include context and relevant data in log messages
- **Appropriate log levels**: Use the correct log level for different types of messages

### Error Handling
- **Prefer `Result<T, E>`**: Use Result types for error handling instead of panicking
- **Use `anyhow`** for all errors.
- **Propagate errors**: Use `?` operator to propagate errors up the call stack
- **Meaningful error messages**: Provide context about what operation failed and why
- **Avoid unwrap()**: Only use `unwrap()` when you can prove the operation cannot fail

### Memory Management and Performance
- **Prefer borrowing**: Use references (`&T`) instead of owned values when possible
- **Avoid unnecessary clones**: Only clone when ownership transfer is required
- **Use `Cow<str>`** when you might need either borrowed or owned strings
- **Prefer iterators**: Use iterator chains over manual loops when appropriate
- **Avoid premature optimization**: Write clear code first, optimize when needed

### Type Safety and Design
- **Strong typing**: Use newtype patterns for domain-specific types
- **Prefer enums**: Use enums with variants instead of boolean flags or magic numbers
- **Implement standard traits**: Derive or implement `Debug`, `Clone`, `PartialEq` as appropriate
- **Use type-level constants**: Prefer `const` over hardcoded values
- **Validate at boundaries**: Validate input at API boundaries, trust internal data

### Function and Module Design
- **Small functions**: Keep functions focused on a single responsibility
- **Pure functions**: Prefer functions without side effects when possible
- **Clear signatures**: Function signatures should be self-documenting
- **Module organization**: Group related functionality in modules
- **Public API**: Minimize public surface area, prefer private by default

### Testing
- **Unit tests**: Write tests for individual functions and methods
- **Integration tests**: Test module interactions and public APIs
- **Property-based testing**: Use `proptest` for complex invariants
- **Test naming**: Use descriptive test names that explain the scenario
- **Arrange-Act-Assert**: Structure tests with clear setup, execution, and verification

### Documentation
- **Doc comments**: Use `///` for public APIs with examples
- **Module docs**: Document module purpose and usage patterns
- **Examples**: Include code examples in documentation
- **README**: Keep README up-to-date with build and usage instructions

### Async Programming
- **Use `tokio`**: Prefer tokio ecosystem for async runtime and utilities
- **Avoid blocking**: Never use blocking operations in async contexts
- **Structured concurrency**: Use `tokio::select!` and `join!` for concurrent operations
- **Timeout operations**: Add timeouts to network and I/O operations

### Dependencies and Cargo
- **Minimal dependencies**: Only add dependencies you actually need
- **Version pinning**: Use specific versions for production applications
- **Feature flags**: Use cargo features to make dependencies optional
- **Workspace organization**: Use cargo workspaces for multi-crate projects

### Security Best Practices
- **Input validation**: Validate all external input
- **Secure defaults**: Choose secure defaults for configuration
- **Avoid `unsafe`**: Only use unsafe code when absolutely necessary with proper documentation
- **Dependency auditing**: Regularly audit dependencies for security vulnerabilities
- **Secret management**: Never hardcode secrets, use environment variables or secret management

### Code Organization Patterns
- **Builder pattern**: Use for complex object construction
- **RAII**: Leverage Rust's ownership system for resource management
- **Composition over inheritance**: Prefer composition and traits over complex hierarchies
- **Hexagonal architecture**: Separate business logic from external dependencies

### Specific Project Guidelines
- **Post-quantum cryptography**: Always use quantum-resistant algorithms
- **Keystore security**: Validate hex strings and cryptographic parameters
- **Account management**: Use type-safe enums for message types and crypto functions
- **Error context**: Provide meaningful context in error messages for debugging
- **Configuration**: Use strongly-typed configuration with validation

## Code Review Checklist
- [ ] Variable names are descriptive and use snake_case
- [ ] No unnecessary variable declarations
- [ ] Error handling uses Result types appropriately
- [ ] Log messages use inline variable syntax
- [ ] Functions are focused and well-named
- [ ] Tests cover the happy path and error cases
- [ ] Documentation is clear and includes examples
- [ ] No hardcoded values or magic numbers
- [ ] Memory usage is efficient (minimal cloning)
- [ ] Security considerations are addressed

## Performance Considerations
- **Profile before optimizing**: Use `cargo flamegraph` or similar tools
- **Benchmark critical paths**: Use `criterion` for performance testing
- **Memory profiling**: Monitor memory usage in long-running applications
- **Compile-time optimization**: Use const evaluation where possible
- **Zero-cost abstractions**: Leverage Rust's zero-cost abstractions

## Tooling Integration
- **Clippy**: Always run `cargo clippy` and address warnings
- **Rustfmt**: Use `cargo fmt` for consistent code formatting
- **Rust analyzer**: Configure IDE with rust-analyzer for better development experience
- **CI/CD**: Automate testing, linting, and security audits

Remember: Write code that is readable, maintainable, and follows Rust idioms. When in doubt, favor explicitness over cleverness.
179 changes: 179 additions & 0 deletions .github/workflows/code-quality.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
name: Code Quality Checks

on:
push:
branches: [ main, master, develop ]
pull_request:
branches: [ main, master, develop ]

env:
CARGO_TERM_COLOR: always

jobs:
code-quality:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy

- name: Cache cargo registry
uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

- name: Validate copilot-instructions.md compliance
run: |
echo "🤖 Enforcing GitHub Copilot Instructions across ALL Rust files"
echo "📋 Reference: .github/copilot-instructions.md"
echo "🔍 Scanning: src/, bin/, crates/, examples/, tests/, benches/"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

- name: Initialize failure tracking
run: echo "FAILED_CHECKS=" >> $GITHUB_ENV

- name: Check formatting
run: |
echo "1️⃣ Checking code formatting..."
if ! cargo fmt --all -- --check; then
echo "❌ Code formatting check failed"
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} formatting" >> $GITHUB_ENV
else
echo "✅ Code formatting looks good"
fi

- name: Run Clippy
run: |
echo "2️⃣ Running Clippy linter..."
if ! cargo clippy --all-targets --all-features -- -D warnings; then
echo "❌ Clippy check failed"
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} clippy" >> $GITHUB_ENV
else
echo "✅ Clippy check passed"
fi

- name: Run tests
run: |
echo "3️⃣ Running tests..."
if ! cargo test --all-features --verbose; then
echo "❌ Tests failed"
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} tests" >> $GITHUB_ENV
else
echo "✅ All tests passed"
fi

- name: Check for hardcoded values
run: |
echo "4️⃣ Checking for hardcoded magic numbers..."
if grep -r --include="*.rs" -E '\b[0-9]{3,}\b' . --exclude-dir=target && ! grep -r --include="*.rs" 'const.*=' . --exclude-dir=target; then
echo "❌ Found potential magic numbers. Use constants instead."
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} hardcoded-values" >> $GITHUB_ENV
else
echo "✅ No hardcoded values found"
fi

- name: Check variable naming conventions
run: |
echo "5️⃣ Checking variable naming conventions..."
if grep -r --include="*.rs" -E 'let\s+[a-z]*[aeiou]*[bcdfghjklmnpqrstvwxyz]{3,}[aeiou]*[bcdfghjklmnpqrstvwxyz]\s*=' . --exclude-dir=target | grep -E '(usr|addr|cfg|mgr|ctx|impl|proc)'; then
echo "❌ Found potential abbreviations in variable names"
echo "Use full descriptive names as per copilot-instructions.md"
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} variable-naming" >> $GITHUB_ENV
else
echo "✅ Variable naming looks good"
fi

- name: Check for inline variables in macros
run: |
echo "6️⃣ Checking log macro formatting..."
violations=$(grep -r --include="*.rs" -E '(info!|debug!|warn!|error!|println!)\s*\([^)]*\{\}' . --exclude-dir=target | \
grep -v -E '\w+\.\w+\(\)' || true)
if [ -n "$violations" ]; then
echo "❌ Found {} placeholders in log macros. Use inline variables instead."
echo "$violations"
echo "Example: info!(\"User {user_id} status {status}\") instead of info!(\"User {} status {}\", user_id, status)"
echo "Note: Function calls like variable.method() are allowed as exceptions"
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} log-macros" >> $GITHUB_ENV
else
echo "✅ Log macro usage looks good"
fi

- name: Check for unwrap() usage
run: |
echo "7️⃣ Checking unwrap() usage..."
unwrap_count=$(grep -r --include="*.rs" '\.unwrap()' . --exclude-dir=target | wc -l || true)
if [ "$unwrap_count" -gt 10 ]; then
echo "❌ Found $unwrap_count instances of .unwrap(). Consider using proper error handling."
echo "See copilot-instructions.md for error handling best practices"
grep -r --include="*.rs" '\.unwrap()' . --exclude-dir=target | head -10
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} unwrap-usage" >> $GITHUB_ENV
else
echo "✅ Unwrap usage is reasonable ($unwrap_count instances)"
fi

- name: Check for lazy variable declaration
run: |
echo "8️⃣ Checking variable declaration patterns..."
# Look for functions with multiple let statements at the beginning
if grep -r --include="*.rs" -A 10 'fn.*{' . --exclude-dir=target | grep -E 'let.*=.*;\s*$' | grep -E 'let.*=.*;\s*let.*=.*;\s*let.*=.*;'; then
echo "❌ Found potential early variable declarations. Declare variables when needed."
echo "See copilot-instructions.md for lazy declaration guidelines"
echo "FAILED_CHECKS=${{ env.FAILED_CHECKS }} lazy-declaration" >> $GITHUB_ENV
else
echo "✅ Variable declarations look appropriately lazy"
fi

- name: Check for TODO/FIXME comments
run: |
echo "Checking for TODO/FIXME comments..."
todo_count=$(grep -r --include="*.rs" -E '(TODO|FIXME|XXX|HACK)' . --exclude-dir=target | wc -l || true)
if [ "$todo_count" -gt 0 ]; then
echo "⚠️ Found $todo_count TODO/FIXME comments:"
grep -r --include="*.rs" -E '(TODO|FIXME|XXX|HACK)' . --exclude-dir=target | head -5
echo "Consider addressing these before merging"
else
echo "✅ No TODO/FIXME comments found"
fi

- name: Final validation result
run: |
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ -n "${{ env.FAILED_CHECKS }}" ]; then
echo "❌ Code quality checks FAILED for:${{ env.FAILED_CHECKS }}"
echo "Please fix the issues above and re-run the workflow"
exit 1
else
echo "✅ All code quality checks PASSED!"
echo "Code follows all guidelines from copilot-instructions.md"
fi

security-audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Run security audit
run: cargo audit

performance-check:
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: Install cargo-bloat
run: cargo install cargo-bloat
- name: Check binary size
run: |
cargo build --release
cargo bloat --release --crates
Loading