👨💻 Developer Guide
Contributing to Guardy - architecture, development workflow, and contribution guidelines
Welcome to the Guardy developer guide! This guide will help you understand Guardy's architecture, set up your development environment, and contribute effectively.
Quick Start
Get Guardy running on your machine in minutes:
# Clone the repository
git clone https://gitlab.com/deepbrain.space/guardy
cd guardy/crates/guardy
# Build the project
cargo build
# Run tests
cargo test
# Install locally for development
cargo install --path crates/guardyPrerequisites
Required
- Rust 1.89 or higher - Guardy uses the latest Rust features
- Git - For version control and testing git hooks
- Cargo - Rust's package manager (comes with Rust)
Optional
- Moon - For task running (recommended for development)
- Just - Command runner for common tasks
- Docker - For CI/CD testing
Recommended: Use mise to manage Rust and other tool versions automatically.
Repository Structure
guardy/
├── crates/
│ ├── guardy/ # Main CLI application
│ │ ├── src/
│ │ │ ├── cli/ # Command-line interface
│ │ │ ├── config/ # Configuration system
│ │ │ ├── git/ # Git operations
│ │ │ ├── hooks/ # Git hooks implementation
│ │ │ ├── scan/ # Secret scanner
│ │ │ ├── sync/ # File synchronization
│ │ │ └── main.rs # Application entry point
│ │ └── Cargo.toml
│ └── supercli/ # Shared CLI utilities
├── sites/
│ └── guardy.dev/ # Documentation site (Next.js)
├── .gitlab-ci.yml # CI/CD configuration
├── Cargo.toml # Workspace configuration
└── README.mdArchitecture Overview
Guardy is built around three main subsystems:
1. Hooks Management
Purpose: Native Rust implementation of git hooks with configuration-driven execution.
Key Components:
- HookExecutor - Executes hook commands and built-in actions
- HookInstaller - Installs/uninstalls git hooks
- BuiltinActions - Pre-configured actions (secret scanning, conventional commits)
- CommandRunner - Parallel and sequential command execution
Design Principles:
- Native performance (no shell wrapper overhead)
- Configuration-driven (YAML-based hook definitions)
- Parallel execution support
- Graceful error handling
Location: crates/guardy/src/hooks/
2. Secret Scanner
Purpose: Multi-threaded secret detection engine with entropy analysis.
Key Components:
- Scanner - Core scanning engine
- PatternLibrary - Secret detection patterns (regex-based)
- EntropyAnalyzer - Statistical analysis for high-entropy strings
- FileProcessor - Parallel file processing
- ResultFormatter - Multiple output formats (text, JSON, CSV, HTML)
Design Principles:
- Multi-threaded for performance
- Smart file filtering (ignore binary, large files, etc.)
- Extensible pattern system
- Low false-positive rate
Location: crates/guardy/src/scan/
3. File Synchronization
Purpose: Protected file sync from remote repositories with drift detection.
Key Components:
- SyncManager - Manages sync operations
- GitSync - Git-based remote file fetching
- DriftDetector - Detects local modifications
- InteractivePrompt - User review interface
- ConflictResolver - Handles file conflicts
Design Principles:
- Safe updates (review changes before applying)
- Git-based versioning
- Selective sync (include/exclude patterns)
- Drift detection
Location: crates/guardy/src/sync/
Using Guardy as a Library
While Guardy is primarily a CLI tool, it can also be used as a Rust library. The public API provides access to:
- Configuration management
- Git operations
- Hook execution
- Secret scanning
- File synchronization
Adding Guardy to Your Project
[dependencies]
guardy = "0.2"Example: Secret Scanner
use guardy::scan::Scanner;
use guardy::config::Config;
// Create a scanner with default config
let config = Config::default();
let scanner = Scanner::new(config);
// Scan a directory
let results = scanner.scan_directory("src/")?;
// Process results
for finding in results {
println!("Found secret in {}: {}", finding.file, finding.pattern);
}Example: Hook Executor
use guardy::hooks::HookExecutor;
// Create a hook executor
let executor = HookExecutor::new();
// Execute a hook
executor.execute("pre-commit", &[]).await?;API Reference
For detailed Rust API documentation, see docs.rs/guardy. Note that guardy.dev is the primary documentation source - docs.rs provides crate-level API reference that links back here for guides and examples.
Configuration System
Guardy uses a hierarchical configuration system with multiple sources:
Configuration Hierarchy
- CLI Arguments (highest priority)
- Environment Variables (
GUARDY_*) - Local Config (
.guardy.yaml) - Parent Configs (recursive lookup)
- Global Config (
~/.config/guardy/config.yaml) - Defaults (lowest priority)
Config Build Macro
Guardy uses a custom config_build! macro to generate configuration structs with automatic merging:
config_build! {
HooksConfig<HooksArgs> {
skip_all: bool => {
cli: |args: &HooksArgs| args.skip_all,
env: "GUARDY_HOOKS_SKIP_ALL",
default: false,
},
parallel: bool => {
cli: |args: &HooksArgs| args.parallel,
env: "GUARDY_HOOKS_PARALLEL",
default: true,
},
// Hook definitions...
}
}Benefits:
- Type-safe configuration
- Automatic CLI/env/file merging
- Clear precedence rules
- Self-documenting
Development Workflow
Setting Up Your Environment
# Clone and build
git clone https://gitlab.com/deepbrain.space/guardy
cd guardy
cargo build
# Run tests
cargo test
# Run locally
cargo run -- hooks install# Install moon
curl -fsSL https://moonrepo.dev/install.sh | bash
# Build project
moon build guardy
# Run tests
moon test guardy
# Run locally
moon run guardy:dev# Install just
cargo install just
# Available commands
just --list
# Build and test
just build
just test
# Run development version
just devRunning Tests
# Run all tests
cargo test
# Run specific test
cargo test test_hook_execution
# Run with output
cargo test -- --nocapture
# Run integration tests only
cargo test --test integration
# Run with coverage
cargo tarpaulin --out HtmlCode Quality
Guardy enforces strict code quality standards:
# Format code
cargo fmt
# Lint code
cargo clippy -- -D warnings
# Check for common issues
cargo check
# Security audit
cargo audit
# Unused dependencies
cargo macheteAll CI checks must pass before merge. Run cargo fmt && cargo clippy before committing.
Debugging
# Enable debug logging
RUST_LOG=debug cargo run -- scan src/
# Trace level (very verbose)
RUST_LOG=trace cargo run -- scan src/
# Module-specific logging
RUST_LOG=guardy::scan=debug cargo run -- scan src/# Build with debug symbols
cargo build
# Run with backtrace
RUST_BACKTRACE=1 cargo run -- scan src/
# Full backtrace
RUST_BACKTRACE=full cargo run -- scan src/Add to .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug Guardy",
"cargo": {
"args": ["build", "--bin=guardy"]
},
"args": ["scan", "src/"],
"cwd": "${workspaceFolder}"
}
]
}Contributing Guidelines
Before You Start
- Check existing issues - Look for related work or discussions
- Open an issue - Discuss your idea before implementing
- Fork the repository - Create your own copy to work on
- Create a branch - Use descriptive branch names (
feature/xyz,fix/abc)
Making Changes
- Write tests - All new features need tests
- Update documentation - Keep docs in sync with code
- Follow conventions - Match existing code style
- Commit messages - Use conventional commits format
Commit Message Format
type(scope): description
[optional body]
[optional footer]Types:
feat:- New featurefix:- Bug fixdocs:- Documentation changestest:- Test additions/changesrefactor:- Code refactoringperf:- Performance improvementschore:- Build/tooling changes
Examples:
feat(scan): add support for custom entropy thresholds
fix(hooks): correctly handle spaces in file paths
docs(cli): update scan command referencePull Request Process
- Update your branch - Rebase on latest
main - Run all checks -
cargo fmt,cargo clippy,cargo test - Update CHANGELOG - Add entry for your changes
- Create MR - Use the GitLab merge request template
- Address feedback - Respond to review comments
- Wait for CI - All CI checks must pass
Review Timeline: Most merge requests are reviewed within 48 hours.
Adding New Features
Adding a New Secret Pattern
- Define the pattern in
crates/guardy/src/scan/static_data/patterns.rs:
Pattern {
id: "my-secret",
name: "My Secret Pattern",
description: "Detects MY_SECRET tokens",
category: "API Keys",
regex: r"MY_SECRET_[A-Z0-9]{32}",
entropy_threshold: Some(0.00001),
keywords: &["MY_SECRET"],
},- Add tests in
crates/guardy/src/scan/tests.rs:
#[test]
fn test_my_secret_pattern() {
let scanner = Scanner::new();
let content = "export MY_SECRET_ABCD1234...";
let results = scanner.scan_content(content);
assert!(results.iter().any(|r| r.pattern_id == "my-secret"));
}Adding a New Hook Type
- Add to hook types in
crates/guardy/src/hooks/types.rs:
pub enum HookType {
// ...existing hooks...
MyNewHook,
}-
Implement execution logic in
crates/guardy/src/hooks/executor.rs -
Add installation logic in
crates/guardy/src/hooks/install.rs -
Document in
sites/guardy.dev/content/docs/hooks/available-hooks.mdx
Adding a CLI Command
- Create command module in
crates/guardy/src/cli/commands/mycommand.rs:
use anyhow::Result;
use clap::Args;
#[derive(Args, Clone)]
pub struct MyCommandArgs {
#[arg(long)]
pub my_option: Option<String>,
}
pub async fn execute(args: MyCommandArgs) -> Result<()> {
// Implementation
Ok(())
}- Register in
crates/guardy/src/cli/commands/mod.rs:
pub mod mycommand;
#[derive(Subcommand)]
pub enum Commands {
// ...existing commands...
MyCommand(mycommand::MyCommandArgs),
}- Add documentation in
sites/guardy.dev/content/docs/cli-reference.mdx
Testing
Unit Tests
Located alongside source files:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_feature() {
// Test implementation
}
}Integration Tests
Located in crates/guardy/tests/:
// tests/integration_test.rs
#[test]
fn test_hooks_workflow() {
// Full workflow test
}Test Utilities
Common test helpers in crates/guardy/src/test_utils.rs:
// Create temporary git repository
let temp_repo = create_test_repo();
// Mock file system
let temp_dir = create_temp_dir();
// Mock configuration
let config = test_config();Release Process
Guardy uses semantic versioning and automated releases:
- Version bump - Update
Cargo.tomlversion - Update CHANGELOG - Document changes
- Create tag -
git tag v1.2.3 - Push tag -
git push origin v1.2.3 - CI builds - Automatic binary builds for all platforms
- GitLab release - Automatic release creation
Documentation
Code Documentation
All public APIs must be documented:
/// Scans files for secrets and credentials
///
/// # Arguments
///
/// * `paths` - Files or directories to scan
/// * `options` - Scanning configuration options
///
/// # Returns
///
/// * `Ok(ScanResults)` - Scan completed successfully
/// * `Err(ScanError)` - Scan failed
///
/// # Examples
///
/// ```
/// let scanner = Scanner::new();
/// let results = scanner.scan(&["src/"], &options)?;
/// ```
pub fn scan(&self, paths: &[PathBuf], options: &ScanOptions) -> Result<ScanResults> {
// Implementation
}User Documentation
Update documentation site in sites/guardy.dev/content/docs/:
cd sites/guardy.dev
# Install dependencies
bun install
# Run development server
bun run dev
# Build for production
bun run buildPerformance Optimization
Profiling
# CPU profiling with flamegraph
cargo flamegraph --bin guardy -- scan src/
# Memory profiling
cargo run --bin guardy --features dhat-heap -- scan src/
# Benchmarking
cargo benchPerformance Tips
- Parallel processing - Use rayon for CPU-bound tasks
- Async I/O - Use tokio for I/O-bound operations
- Memory pools - Reuse allocations where possible
- Smart filtering - Skip unnecessary work early
- Benchmarks - Measure before optimizing
Troubleshooting
Common Issues
# Clean build
cargo clean && cargo build
# Update dependencies
cargo update
# Check Rust version
rustc --version # Should be 1.89+# Run single test with output
cargo test test_name -- --nocapture
# Run tests serially
cargo test -- --test-threads=1
# Check git state
git status# Ensure git is initialized
git init
# Check hooks directory
ls -la .git/hooks/
# Reset hooks
guardy hooks uninstall --yes
guardy hooks installCommunity
Getting Help
- Issues - GitLab Issues
- Discussions - GitLab Discussions
- Matrix - #guardy:matrix.org
Code of Conduct
Guardy follows the Contributor Covenant Code of Conduct.
Be respectful, inclusive, and constructive in all interactions.
Resources
- GitLab Repository - https://gitlab.com/deepbrain.space/guardy
- Documentation Site - https://guardy.dev
- Rust Book - https://doc.rust-lang.org/book/
- Cargo Book - https://doc.rust-lang.org/cargo/
- Clap Documentation - https://docs.rs/clap/latest/clap/
Thank you for contributing to Guardy! Your efforts help make secure development easier for everyone.