# UnitForge Scripts & Utilities This directory contains utility scripts and libraries for the UnitForge project, including centralized color handling for consistent terminal output across all scripts. ## ๐Ÿ“ Files Overview | File | Purpose | Language | |------|---------|----------| | `colors.sh` | Bash color utility library | Bash | | `colors.py` | Python color utility module | Python | | `colors.mk` | Makefile color definitions | Make | | `test-colors.sh` | Color utility test script | Bash | | `README.md` | This documentation | Markdown | ## ๐ŸŽจ Color Utilities ### Why Centralized Colors? Before this refactor, UnitForge had hardcoded ANSI escape codes scattered across multiple shell scripts like: ```bash RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' ``` This approach had several problems: - โŒ **Duplication**: Same color codes repeated in multiple files - โŒ **Inconsistency**: Different scripts used different color palettes - โŒ **Maintenance**: Changes required updating multiple files - โŒ **No fallback**: No graceful degradation for non-color terminals The centralized approach solves these issues: - โœ… **DRY Principle**: Single source of truth for all colors - โœ… **Consistency**: Uniform color palette across the project - โœ… **Maintainability**: Update colors in one place - โœ… **Smart Detection**: Automatic color support detection - โœ… **Graceful Degradation**: Works in any terminal environment ## ๐Ÿš Bash Color Utility (`colors.sh`) ### Basic Usage Source the utility in your shell scripts: ```bash #!/bin/bash # Load centralized color utility SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${SCRIPT_DIR}/scripts/colors.sh" # Use color functions info "Starting process..." success "Operation completed!" warning "Check configuration" error "Something went wrong" ``` ### Available Colors #### Basic Colors ```bash red "Red text" green "Green text" yellow "Yellow text" blue "Blue text" purple "Purple text" cyan "Cyan text" white "White text" gray "Gray text" ``` #### Bright Colors ```bash bright_red "Bright red text" bright_green "Bright green text" bright_blue "Bright blue text" # ... etc ``` #### Status Messages ```bash info "Information message" # โ„น Blue success "Success message" # โœ“ Green warning "Warning message" # โš  Yellow error "Error message" # โœ— Red debug "Debug message" # ๐Ÿ› Gray (only if DEBUG=1) ``` #### Headers and Structure ```bash header "Main Section" # Bold blue with underline subheader "Subsection" # Bold with dash underline box_header "Title" 50 # Fancy box with title box_message "Message" "$GREEN" 40 # Colored message box ``` #### Progress and Status ```bash step 3 10 "Processing files" # [3/10] Processing files status "ok" "File processed" # [ OK ] File processed status "fail" "Connection failed" # [ FAIL ] Connection failed status "warn" "Deprecated feature" # [ WARN ] Deprecated feature status "info" "Available updates" # [ INFO ] Available updates status "skip" "Already exists" # [ SKIP ] Already exists ``` ### Advanced Features #### Color Detection ```bash if supports_color; then echo "Terminal supports colors" else echo "Colors disabled" fi ``` #### Environment Variables - `NO_COLOR=1`: Disable all colors - `DEBUG=1`: Show debug messages - `TERM=dumb`: Automatically disables colors #### Progress Indicators ```bash # Spinner (use with background processes) long_running_command & spinner # Progress bar for i in {1..10}; do progress_bar $i 10 40 sleep 0.5 done ``` ## ๐Ÿ Python Color Utility (`colors.py`) ### Basic Usage Import and use the color functions: ```python #!/usr/bin/env python3 import sys import os # Add scripts directory to path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'scripts')) from colors import info, success, warning, error, header # Use color functions info("Starting process...") success("Operation completed!") warning("Check configuration") error("Something went wrong") ``` ### Available Functions #### Text Coloring ```python from colors import red, green, blue, yellow print(red("Error text")) print(green("Success text")) print(blue("Info text")) print(yellow("Warning text")) ``` #### Status Messages ```python from colors import info, success, warning, error, debug info("Process starting...") # โ„น Blue success("Task completed!") # โœ“ Green warning("Configuration missing") # โš  Yellow error("Connection failed") # โœ— Red debug("Variable state: active") # ๐Ÿ› Gray (if DEBUG env var set) ``` #### Headers and Structure ```python from colors import header, subheader, box_header, box_message, c header("Main Processing Phase") subheader("File Operations") box_header("UnitForge Setup", width=50) box_message("Success!", c.GREEN, width=40) ``` #### Progress and Steps ```python from colors import step, status, progress_bar step(1, 5, "Initializing...") step(2, 5, "Loading configuration...") status("ok", "File loaded successfully") status("fail", "Network connection failed") status("warn", "Using default settings") # Progress bar for i in range(11): progress_bar(i, 10, width=40) time.sleep(0.1) ``` #### Advanced Usage ```python from colors import ColorizedFormatter, c, supports_color # Context manager for colored blocks with ColorizedFormatter(c.GREEN): print("This entire block is green") print("Including multiple lines") # Manual color codes (discouraged - use functions instead) if supports_color(): print(f"{c.BOLD}Bold text{c.NC}") ``` ## ๐Ÿ”ง Makefile Colors (`colors.mk`) ### Usage in Makefiles Include the color definitions: ```make # Include centralized colors include scripts/colors.mk target: $(call info,Starting build process...) @echo -e "$(GREEN)Building project...$(NC)" $(call success,Build completed!) ``` ### Available Functions ```make $(call info,Information message) $(call success,Success message) $(call warning,Warning message) $(call error,Error message) $(call header,Section Title) $(call subheader,Subsection) $(call box_header,Fancy Title) $(call step,3/10,Current step) $(call status,ok,Operation status) ``` ### Color Variables ```make # Use color variables directly @echo -e "$(BLUE)Processing...$(NC)" @echo -e "$(GREEN)โœ“ Complete$(NC)" @echo -e "$(YELLOW)โš  Warning$(NC)" @echo -e "$(RED)โœ— Failed$(NC)" ``` ## ๐Ÿงช Testing Run the color utility test: ```bash # Test all color functions ./scripts/test-colors.sh # Test Python module python scripts/colors.py # Test color detection NO_COLOR=1 ./scripts/test-colors.sh # Should show no colors DEBUG=1 ./scripts/test-colors.sh # Should show debug messages ``` ## ๐ŸŽฏ Migration Guide ### From Hardcoded Colors **Before:** ```bash #!/bin/bash RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' echo -e "${GREEN}โœ“ Success${NC}" echo -e "${RED}โœ— Error${NC}" ``` **After:** ```bash #!/bin/bash source "$(dirname "$0")/scripts/colors.sh" success "Success" error "Error" ``` ### From Individual Color Functions **Before:** ```bash echo_green() { echo -e "\033[0;32m$1\033[0m"; } echo_red() { echo -e "\033[0;31m$1\033[0m"; } ``` **After:** ```bash source "$(dirname "$0")/scripts/colors.sh" # Use built-in green() and red() functions ``` ## ๐Ÿ› ๏ธ Development Guidelines ### Adding New Colors 1. **Add to color definitions** in all three files: - `colors.sh`: Bash export variables - `colors.py`: Python class attributes - `colors.mk`: Makefile variables 2. **Add convenience functions** if needed: ```bash # colors.sh orange() { color_echo "$ORANGE" "$@"; } ``` 3. **Test thoroughly** with different terminal types: ```bash TERM=dumb ./test-colors.sh NO_COLOR=1 ./test-colors.sh ``` ### Best Practices 1. **Always use functions over raw codes**: ```bash # Good success "Operation completed" # Avoid echo -e "${GREEN}โœ“ Operation completed${NC}" ``` 2. **Test color support**: ```bash if supports_color; then # Use colors else # Plain text fallback fi ``` 3. **Provide meaningful status messages**: ```bash # Good status "ok" "Dependencies installed successfully" # Too generic status "ok" "Done" ``` 4. **Use appropriate status types**: - `info`: General information - `success`/`ok`: Successful operations - `warning`/`warn`: Potential issues - `error`/`fail`: Critical failures - `skip`: Skipped operations ## ๐Ÿ”— Integration Examples ### Shell Script Template ```bash #!/bin/bash set -e # Load color utility SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "${SCRIPT_DIR}/scripts/colors.sh" # Script header box_header "My UnitForge Script" # Main process with status updates header "Processing Phase" step 1 3 "Initializing..." if initialize_system; then success "System initialized" else error "Initialization failed" exit 1 fi step 2 3 "Running tasks..." info "Processing files..." # ... task logic ... success "Tasks completed" step 3 3 "Cleanup..." warning "Temporary files will be removed" cleanup_temp_files success "Cleanup complete" # Summary echo box_message "Script completed successfully!" "$GREEN" ``` ### Python Script Template ```python #!/usr/bin/env python3 """UnitForge Python script with color support.""" import sys import os from pathlib import Path # Add scripts to path script_dir = Path(__file__).parent.parent / "scripts" sys.path.insert(0, str(script_dir)) from colors import header, info, success, warning, error, step, box_header def main(): """Main script function.""" box_header("My UnitForge Python Script") header("Processing Phase") step(1, 3, "Initializing...") try: # ... initialization logic ... success("System initialized") except Exception as e: error(f"Initialization failed: {e}") sys.exit(1) step(2, 3, "Running tasks...") info("Processing data...") # ... task logic ... success("Tasks completed") step(3, 3, "Finalizing...") warning("Saving results...") # ... save logic ... success("Results saved") if __name__ == "__main__": main() ``` ## ๐Ÿ“Š Color Reference ### Standard Palette | Color | Bash Function | Python Function | Use Case | |-------|---------------|-----------------|----------| | ๐Ÿ”ด Red | `red()` | `red()` | Errors, failures | | ๐ŸŸข Green | `green()` | `green()` | Success, completion | | ๐ŸŸก Yellow | `yellow()` | `yellow()` | Warnings, cautions | | ๐Ÿ”ต Blue | `blue()` | `blue()` | Information, headers | | ๐ŸŸฃ Purple | `purple()` | `purple()` | Special operations | | ๐Ÿ”ต Cyan | `cyan()` | `cyan()` | Steps, progress | | โšช White | `white()` | `white()` | Emphasis | | โšซ Gray | `gray()` | `gray()` | Debug, minor info | ### Status Indicators | Status | Symbol | Color | Usage | |--------|--------|-------|-------| | `ok`/`success` | โœ“ | Green | Successful operations | | `fail`/`error` | โœ— | Red | Failed operations | | `warn`/`warning` | โš  | Yellow | Warnings, issues | | `info` | โ„น | Blue | Information | | `skip` | โ€ข | Gray | Skipped operations | ## ๐Ÿš€ Future Enhancements - [ ] **Rich progress bars** with animated indicators - [ ] **Color themes** (dark/light mode support) - [ ] **Log level integration** with Python logging - [ ] **JSON output mode** for CI/CD pipelines - [ ] **Color customization** via configuration files --- **UnitForge Color Utilities** - Making terminal output beautiful and consistent! ๐ŸŽจ