- Fixed Bootstrap bg-dark class to use better contrasting color - Added comprehensive text-muted contrast fixes for various contexts - Improved dark theme colors for better accessibility - Fixed CSS inheritance issues for code elements in dark contexts - All color choices meet WCAG AA contrast requirements
497 lines
11 KiB
Markdown
497 lines
11 KiB
Markdown
# 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! 🎨
|