# Contributing to ROM Groomer *Last Updated: June 22, 2025* ## AI Assistant Context This document provides essential context for AI assistants working with the ROM Groomer project. ### Project Purpose ROM Groomer is a bash-based toolkit for managing retro gaming ROM collections. It automates the process of downloading, filtering, organizing, and preparing ROM files for emulation systems. The project emphasizes: - **Automation**: Reduce manual work in ROM collection management - **Organization**: Systematic approach to ROM file structure - **Quality**: 1G1R (One Game One ROM) filtering to eliminate duplicates - **Compatibility**: Support for multiple emulation platforms and frontends ### Core Concepts #### 1G1R (One Game One ROM) A curation philosophy that keeps only the best version of each game, eliminating: - Regional duplicates (prefer USA → English → Other regions) - Revision duplicates (prefer latest revisions) - Format duplicates (prefer optimal formats for emulation) #### Pipeline Stages 1. **Source**: Raw ROM files and archives 2. **Filter**: Apply platform and region filters 3. **Organization**: Final structured ROM collections 4. **Archive**: Backup and historical versions #### Build Scripts Each `build-[system]-[region]-1g1r.sh` script handles: - Downloading ROM sets (via rclone or other sources) - Applying platform-specific filters - Creating 1G1R collections - Organizing files for emulation ### File Naming Conventions ``` build-[system]-[region]-1g1r.sh ``` Where: - `system`: Gaming platform (nes, snes, genesis, etc.) - `region`: Target region (usa, eng, all) - `1g1r`: Indicates One Game One ROM filtering ### Key Scripts Overview #### Core Organization - `nointro-processor.sh`: Enhanced core processor with pre-flight checks - `redump-processor.sh`: Core processor for disc-based systems - `organize-roms.sh`: Main organization logic - `config.sh`: Global configuration settings with DELETE flag initialization - `utils.sh`: Shared utility functions with enhanced path validation - `preflight-checks.sh`: Comprehensive system validation framework #### Platform Builders - `build-*-1g1r.sh`: Platform-specific ROM builders (fixed and enhanced) - `nointro-processor.sh`: No-Intro DAT-based builder with pre-flight checks - `redump-processor.sh`: Redump DAT-based builder #### Utilities - `verify-and-clean-roms-zips.sh`: ROM validation and cleanup - `delete-listfiles.sh`: Enhanced deletion with validation and security - `link-listfiles.sh`: ROM linking functionality - `convert*.sh`: Format conversion utilities - `rclone-myrient.sh`: Remote ROM source management - `preflight-checks.sh`: System dependency and configuration validation ### Development Guidelines #### Code Style - Use bash best practices (set -euo pipefail) - Consistent indentation (2 spaces) - Descriptive variable names - Comment complex logic - Error handling for all operations #### File System Policy - **EMUBASEDIR Containment**: All file operations MUST occur within `${EMUBASEDIR}` (default: `/data/emu`) - **No External Writes**: Never create files, directories, or temporary files outside of EMUBASEDIR - **Temporary Files**: Use `${EMUBASEDIR}/temp/` or subdirectories for all temporary operations - **Permission Compliance**: Respect the EMUBASEDIR permission structure - we have full control within this boundary - **Test Isolation**: All tests must use temporary directories within EMUBASEDIR, never system-wide temp locations - **Security Principle**: This policy prevents accidental system-wide file pollution and ensures clean, contained operations **Examples:** ```bash # ✅ CORRECT - Within EMUBASEDIR TEST_TEMP_DIR="${EMUBASEDIR}/temp/test-$$" WORKING_DIR="${EMUBASEDIR}/stage/processing" # ❌ INCORRECT - Outside EMUBASEDIR TEST_TEMP_DIR="/tmp/test-$$" WORKING_DIR="/var/tmp/processing" ``` #### Script Structure Standards - **Modular Functions**: Break scripts into reusable, testable functions - **Usage Documentation**: Include detailed usage block at the top of each script - **Error Handling**: Robust error handling for all critical operations - **Consistent Formatting**: Maintain consistent spacing, indentation, and formatting - **Header Comments**: Include script purpose, dependencies, and usage examples #### Logging Standards - **Structured Logging**: Route all output through `logger.sh` for consistency - **Debug Information**: Add DEBUG logs before major actions, including variable values - **Aligned Output**: Ensure logs are aligned and color-coded for readability - **Progress Indicators**: Provide visual feedback for long-running operations - **Error Reporting**: Graceful error handling with summary reporting #### Function Design Principles - **Single Responsibility**: Each function should have one clear purpose - **Parameter Validation**: Validate all input parameters - **Return Codes**: Use consistent return codes for success/failure - **Documentation**: Document function parameters and return values - **Testing**: Design functions to be easily testable in isolation #### Testing Approach - Dry-run modes for destructive operations - Validation steps before major operations - Progress indicators for long-running tasks - Comprehensive error messages #### Unit Testing Requirements The project includes a comprehensive unit testing framework to ensure reliability and maintainability: **Implemented Test Infrastructure:** - **Test Framework**: `test-framework.sh` provides assertion functions and safe test environments - **Test Runner**: `run-tests.sh` executes the complete test suite - **Comprehensive Coverage**: 7 test files covering critical functionality - **Safe Execution**: All tests run in isolated temporary directories within EMUBASEDIR - **Security Validation**: Tests verify path security and prevent directory traversal attacks **Test Categories:** - **Function Testing**: Test individual utility functions in isolation (`test-utils.sh`) - **Component Testing**: Test core components like deletion and organization (`test-delete-listfiles.sh`, `test-organize-roms.sh`) - **Integration Testing**: Test complete workflows with realistic scenarios (`test-integration.sh`) - **Pre-flight Testing**: Verify system validation and dependency checks (`test-preflight-checks.sh`) - **Error Handling**: Verify proper error handling and recovery across all components - **Security Testing**: Validate path restrictions and malicious input handling **Running Tests:** ```bash # Complete test suite ./run-tests.sh # Individual test suites ./test-utils.sh # Utility function tests ./test-delete-listfiles.sh # Deletion functionality ./test-organize-roms.sh # ROM organization ./test-integration.sh # End-to-end workflows ./test-preflight-checks.sh # System validation ``` **Test Structure:** ```bash rom-organizer/ ├── run-tests.sh # Main test suite runner ├── test-framework.sh # Testing framework and utilities ├── test-utils.sh # Unit tests for utility functions ├── test-delete-listfiles.sh # Tests for deletion functionality ├── test-organize-roms.sh # Tests for ROM organization ├── test-integration.sh # Integration workflow tests ├── test-preflight-checks.sh # Pre-flight validation tests └── temp/ # Isolated test environments (auto-cleanup) ``` **Testing Standards:** - All new functions must include unit tests - Critical workflows require integration tests - Tests must be isolated and not affect the production system - Test both success and failure scenarios - Security tests must validate path restrictions - Tests run in temporary directories that are automatically cleaned up - Current test coverage: 86% success rate on critical workflows #### Unit Testing Strategy for Build Script Fixes As we fix issues identified by the test suite, each fix MUST include corresponding unit tests to prevent regression: **Required Tests for Every Fix:** - **Before Fix**: Test that demonstrates the problem - **After Fix**: Test that validates the solution - **Regression Prevention**: Test that ensures the problem doesn't return **Test Categories to Expand:** 1. **Build Script Validation Tests** (`test-build-script-naming.sh`) - ✅ **Implemented**: Naming pattern validation - ✅ **Implemented**: Internal reference consistency - ✅ **Implemented**: FILTER variable validation - 🔄 **Active**: Currently fixing issues found by these tests 2. **Build Script Content Tests** (planned: `test-build-script-content.sh`) - Script header completeness and formatting - Required function presence (set_environment, run_processing, display_summary) - Dependency declarations accuracy - Source system and site configurations - Language override implementations 3. **Build Script Functionality Tests** (planned: `test-build-script-functions.sh`) - Environment setup validation - Parameter passing correctness - Error handling behavior - Logging output verification - Return code consistency 4. **Cross-System Consistency Tests** (planned: `test-system-consistency.sh`) - Consistent patterns across all systems - Required variant coverage (all systems have all/eng variants) - USA variant coverage tracking - Source site appropriateness (No-Intro vs Redump vs Extra) 5. **Integration Tests** (expand existing `test-integration.sh`) - End-to-end build script execution (dry-run mode) - Dependency chain validation - Configuration loading verification - Logger integration testing **Test-Driven Fix Process:** ```bash # 1. Write test that demonstrates the problem ./test-build-script-naming.sh # Shows issues # 2. Fix the identified issues # (make corrections to scripts) # 3. Verify tests now pass ./test-build-script-naming.sh # Should pass # 4. Add specific regression tests # (add tests for the specific fixes made) # 5. Run full test suite ./run-tests.sh # Ensure no regressions ``` **Testing Standards for Fixes:** - Every script modification requires corresponding test updates - Tests must be specific enough to catch the exact issue being fixed - Tests should validate both positive cases (correct behavior) and negative cases (error handling) - Performance of test suite should remain under 30 seconds for rapid development feedback #### Configuration Management - All paths and preferences in `config.sh` - Environment-specific overrides supported - Sensible defaults for common setups - Documentation for all configuration options ### Project Structure ``` rom-organizer/ ├── build-*.sh # Platform-specific builders (all fixed and enhanced) ├── config.sh # Main configuration with DELETE flag ├── nointro-processor.sh # Enhanced core processor with pre-flight checks ├── redump-processor.sh # Disc-based system processor ├── organize-roms.sh # Core organization logic ├── utils.sh # Enhanced shared functions with path validation ├── preflight-checks.sh # NEW: Comprehensive system validation ├── delete-listfiles.sh # Enhanced with security and validation ├── link-listfiles.sh # ROM linking functionality ├── verify-*.sh # Validation tools ├── convert*.sh # Format converters ├── run-tests.sh # NEW: Test suite runner ├── test-framework.sh # NEW: Testing framework ├── test-*.sh # NEW: Comprehensive test suites (7 files) ├── archive/ # Backup scripts and legacy files ├── README.md # Project overview and quick start ├── SCRIPTS.md # Complete script reference ├── CONTRIBUTING.md # Development guidelines and context ├── ROADMAP.md # Development plan and priorities ├── ARCHITECTURE.md # System design documentation ├── CHANGELOG.md # Version history and changes └── PRIORITY_FIXES_FINAL_REPORT.md # Recent implementation status ``` ### Common Operations #### Adding New Platform Support 1. Research platform-specific requirements 2. Create `build-[system]-[region]-1g1r.sh` script 3. Add platform to `config.sh` arrays 4. Test with sample ROM set 5. Document platform-specific notes #### Modifying Existing Scripts 1. Understand current workflow 2. Test changes in dry-run mode 3. Validate with known ROM sets 4. Update documentation if needed 5. Consider backward compatibility #### Debugging Issues 1. Check `config.sh` for correct paths 2. Verify source ROM availability 3. Test individual script components 4. Check file permissions and disk space 5. Review log output for errors ### Platform Categories #### No-Intro Systems (Cartridge-based) - Nintendo: NES, SNES, N64, Game Boy family - Sega: Master System, Genesis, Game Gear, 32X - Atari: 2600, 5200, 7800, Jaguar, Lynx - Others: ColecoVision, Vectrex, Neo Geo Pocket #### Redump Systems (Disc-based) - Sony: PlayStation, PSP - Sega: Saturn, Dreamcast, Sega CD - Nintendo: GameCube, Wii - Others: 3DO, PC Engine CD #### Special Cases - 3DS: Encrypted, requires special handling - Nintendo DS: Large collections, complex filtering - MAME: Arcade systems, different organization needs ### External Dependencies #### Required Tools - bash 4.0+ (for associative arrays) - Standard UNIX utilities (find, sort, uniq, etc.) - 7zip (for archive handling) #### Optional Tools - rclone (for remote ROM sources) - chdman (for CHD format conversion) - Platform-specific tools (varies by system) ### Best Practices for AI Assistants #### When Modifying Scripts 1. Read entire script to understand context 2. Preserve existing functionality 3. Follow established patterns 4. Add appropriate error handling 5. Test changes before committing #### When Adding Features 1. Check if similar functionality exists 2. Consider impact on existing workflows 3. Update configuration if needed 4. Document new features 5. Consider backward compatibility #### When Debugging 1. Reproduce issue if possible 2. Check logs and error messages 3. Verify configuration settings 4. Test with minimal ROM sets 5. Provide clear solutions ### Common Pitfalls 1. **Path Issues**: Absolute vs relative paths in scripts 2. **Permissions**: File and directory permissions 3. **Disk Space**: Large ROM collections require significant space 4. **Case Sensitivity**: File systems vary in case handling 5. **Special Characters**: ROM names with special characters 6. **Network Issues**: Remote ROM source availability ### Support Resources - Project documentation in README.md, ROADMAP.md, and ARCHITECTURE.md - Complete script reference in SCRIPTS.md - Testing framework and comprehensive test suites - Recent implementation status in PRIORITY_FIXES_FINAL_REPORT.md - Version history in CHANGELOG.md - Script comments for implementation details - Git history for understanding changes - Issue tracking for known problems ### Contribution Workflow 1. **Understand Requirements**: What problem are we solving? 2. **Research**: Check existing solutions and approaches 3. **Plan**: Outline changes and potential impacts 4. **Implement**: Make changes following project conventions 5. **Test**: Validate changes with the test suite (`./run-tests.sh`) 6. **Document**: Update relevant documentation (especially SCRIPTS.md) 7. **Review**: Consider edge cases and error conditions ### Development Best Practices #### Before Making Changes 1. **Run Tests**: Execute `./run-tests.sh` to ensure current functionality works 2. **Check Pre-flight**: Ensure `./preflight-checks.sh` passes 3. **Review Documentation**: Check SCRIPTS.md and other relevant docs #### After Making Changes 1. **Test Thoroughly**: Run applicable test suites 2. **Update SCRIPTS.md**: Add/modify script entries as needed 3. **Validate Security**: Ensure path validation and security measures are maintained 4. **Check Integration**: Run integration tests to verify end-to-end functionality #### Adding New Scripts 1. **Follow Naming Conventions**: Use established patterns for script names 2. **Include Error Handling**: Implement robust error handling and validation 3. **Add Tests**: Create appropriate unit/integration tests 4. **Update Documentation**: Add entry to SCRIPTS.md with clear description 5. **Include Usage**: Add usage examples and parameter documentation ## Documentation Maintenance ### Updating SCRIPTS.md **IMPORTANT**: Whenever you create, modify, or remove scripts, you must update `SCRIPTS.md` to keep the script reference current. #### When Adding New Scripts: 1. **Categorize Properly**: Place the script in the appropriate category - Core Scripts (config, utils, logging) - Platform-Specific Build Scripts (by manufacturer) - Format Conversion Scripts - Validation & Cleanup Scripts - Remote Source Management - Utility & Helper Scripts - Test & Development Scripts 2. **Follow Naming Conventions**: Ensure new scripts follow established patterns - Build scripts: `build-[system]-[region]-1g1r.sh` - Utility scripts: Descriptive names ending in `.sh` - Test scripts: `test*.sh` pattern 3. **Add Clear Descriptions**: Include a brief but informative description of what the script does 4. **Update Totals**: Update the "Total scripts documented" count at the bottom #### When Modifying Existing Scripts: 1. **Update Descriptions**: If functionality changes significantly, update the script description 2. **Note Dependencies**: If new dependencies are added, update the dependencies section 3. **Version Notes**: Consider adding notes about major changes #### When Removing Scripts: 1. **Remove from SCRIPTS.md**: Delete the script entry from the appropriate category 2. **Update References**: Check for references in other documentation 3. **Update Totals**: Decrease the total script count #### Example Entry Format: ```markdown - **`script-name.sh`** - Brief description of functionality and purpose ``` ### Documentation Standards - **Consistency**: Use the same format and style for all script entries - **Accuracy**: Ensure descriptions accurately reflect current functionality - **Completeness**: Don't leave scripts undocumented - **Timeliness**: Update documentation as part of the same commit that changes scripts This practice ensures that both human contributors and AI assistants can quickly understand the project's scope and find the right tools for any task.