mirror of
https://github.com/shokinn/hosts-go.git
synced 2025-08-23 08:33:02 +00:00
- Added `internal/core/parser.go` for parsing hosts files, including: - Support for standard entries (IPv4, IPv6, multiple aliases, inline comments) - Handling of comments and disabled entries - Error recovery for malformed lines with warnings - Intelligent formatting with adaptive spacing and column alignment - Backup and atomic write operations for file safety test(parser): Add comprehensive tests for hosts file parsing - Created `tests/parser_test.go` with 54 test cases covering: - Standard entries and comments - Malformed lines and whitespace variations - Round-trip parsing to ensure format preservation - Backup functionality for hosts files docs(progress): Update project progress and next steps - Mark Phase 1 as complete and outline tasks for Phase 2 (TUI implementation) - Highlight completed features and testing coverage
189 lines
7.7 KiB
Markdown
189 lines
7.7 KiB
Markdown
# System Patterns: hosts-go
|
|
|
|
## Architecture Overview
|
|
|
|
The hosts-go application follows a **layered architecture** with clear separation of concerns:
|
|
|
|
```
|
|
┌─────────────────────┐
|
|
│ TUI Layer │ ← Bubble Tea models, views, styles
|
|
├─────────────────────┤
|
|
│ Business Logic │ ← Core domain logic, validation
|
|
├─────────────────────┤
|
|
│ System Interface │ ← File I/O, DNS, permissions
|
|
└─────────────────────┘
|
|
```
|
|
|
|
## Key Technical Decisions
|
|
|
|
### 1. **Bubble Tea Framework**
|
|
- **Why**: Provides mature TUI framework with event-driven architecture
|
|
- **Pattern**: Model-View-Update (MVU) pattern for state management
|
|
- **Components**: Main model orchestrates sub-components (list, detail, modal)
|
|
|
|
### 2. **Internal Package Structure**
|
|
```
|
|
internal/
|
|
├── tui/ # UI layer - Bubble Tea components
|
|
├── core/ # Business logic - domain models and operations
|
|
└── utils/ # Shared utilities - helpers and common functions
|
|
```
|
|
|
|
### 3. **Permission Model**
|
|
- **View mode default**: Read-only access, no sudo required
|
|
- **Edit mode explicit**: User must explicitly enter edit mode
|
|
- **Sudo on demand**: Only request elevated permissions when entering edit mode
|
|
- **Graceful fallback**: Handle permission denied gracefully
|
|
|
|
## Design Patterns in Use
|
|
|
|
### 1. **Model-View-Update (MVU)**
|
|
- **Model**: Application state (entries, selection, mode)
|
|
- **View**: Rendering logic (two-pane layout, styles)
|
|
- **Update**: State transitions based on user input
|
|
|
|
### 2. **Command Pattern**
|
|
- **Edit operations**: Encapsulate modifications as commands
|
|
- **Undo support**: Commands can be reversed
|
|
- **Validation**: Commands validate before execution
|
|
|
|
### 3. **Repository Pattern**
|
|
- **HostsRepository**: Abstract file operations
|
|
- **MockRepository**: In-memory implementation for testing
|
|
- **FileRepository**: Actual `/etc/hosts` file operations
|
|
|
|
### 4. **Observer Pattern**
|
|
- **DNS resolution**: Background updates to IP addresses
|
|
- **File watching**: Detect external changes to hosts file
|
|
- **Status updates**: Notify UI of operation progress
|
|
|
|
## Component Relationships
|
|
|
|
### TUI Components
|
|
```
|
|
MainModel
|
|
├── ListModel (left pane)
|
|
│ ├── Entry selection
|
|
│ ├── Sorting controls
|
|
│ └── Status indicators
|
|
├── DetailModel (right pane)
|
|
│ ├── Entry editing
|
|
│ ├── Form validation
|
|
│ └── DNS resolution
|
|
└── ModalModel (overlays)
|
|
├── Configuration
|
|
├── Confirmations
|
|
└── Error dialogs
|
|
```
|
|
|
|
### Core Business Logic
|
|
```
|
|
Manager
|
|
├── HostsParser (read/write hosts file)
|
|
├── DNSResolver (hostname to IP resolution)
|
|
├── Validator (entry validation)
|
|
└── ConfigManager (user preferences)
|
|
```
|
|
|
|
## Critical Implementation Paths
|
|
|
|
### 1. **File Operations** ✅ IMPLEMENTED
|
|
```go
|
|
// Atomic file updates with backup - COMPLETED
|
|
1. Read current /etc/hosts → backup (✅ BackupHostsFile)
|
|
2. Parse entries → validate changes (✅ ParseHostsContent with warnings)
|
|
3. Write to temporary file → verify (✅ WriteHostsFile with temp files)
|
|
4. Atomic move temp → /etc/hosts (✅ os.Rename for atomic operation)
|
|
5. Remove backup on success (✅ Backup retained for safety)
|
|
```
|
|
|
|
### 2. **Parser Implementation** ✅ IMPLEMENTED
|
|
```go
|
|
// Hosts file parsing with format preservation - COMPLETED
|
|
1. Line-by-line parsing → classify comments vs entries (✅ parseCommentLine)
|
|
2. Regex-based field extraction → handle whitespace variations (✅ regexp.Split)
|
|
3. IP/hostname validation → comprehensive validation (✅ net.ParseIP, validateHostname)
|
|
4. Format style detection → GCD-based spacing analysis (✅ DetectFormattingStyle)
|
|
5. Intelligent formatting → preserve style while improving alignment (✅ FormatHostsFile)
|
|
```
|
|
|
|
### 3. **State Management** (READY FOR IMPLEMENTATION)
|
|
```go
|
|
// Bubble Tea update cycle - READY FOR PHASE 2
|
|
1. User input → Command
|
|
2. Command → State change
|
|
3. State change → View update
|
|
4. View update → Screen render
|
|
```
|
|
|
|
### 4. **DNS Resolution** (PLANNED FOR PHASE 4)
|
|
```go
|
|
// Background IP resolution - FUTURE FEATURE
|
|
1. Extract hostnames from entries
|
|
2. Resolve in background goroutines
|
|
3. Compare resolved vs current IPs
|
|
4. Update UI with resolution status
|
|
5. User chooses whether to update
|
|
```
|
|
|
|
### 5. **Edit Mode Transition** (PLANNED FOR PHASE 3)
|
|
```go
|
|
// Permission elevation - FUTURE FEATURE
|
|
1. User requests edit mode
|
|
2. Check current permissions
|
|
3. Request sudo if needed
|
|
4. Validate file write access
|
|
5. Enable editing controls
|
|
```
|
|
|
|
## Error Handling Strategy
|
|
|
|
### 1. **Graceful Degradation** ✅ IMPLEMENTED
|
|
- **Parser warnings**: Non-fatal errors allow continued processing (✅ ParseWarning system)
|
|
- **Malformed entries**: Invalid lines generate warnings but don't stop parsing (✅ Implemented)
|
|
- **Format preservation**: Unknown formatting preserved while improving known patterns (✅ Implemented)
|
|
|
|
### 2. **Validation Layers** ✅ IMPLEMENTED
|
|
- **IP validation**: IPv4/IPv6 validation using Go's net.ParseIP (✅ Implemented)
|
|
- **Hostname validation**: RFC-compliant validation with detailed error messages (✅ validateHostname)
|
|
- **Entry completeness**: Check for required fields before processing (✅ Implemented)
|
|
|
|
### 3. **Recovery Mechanisms** ✅ IMPLEMENTED
|
|
- **Backup system**: Automatic timestamped backups before any write operation (✅ BackupHostsFile)
|
|
- **Atomic operations**: Temporary files prevent corruption during writes (✅ WriteHostsFile)
|
|
- **Warning aggregation**: Collect and report all issues without stopping (✅ ParseWarning slice)
|
|
- **Round-trip validation**: Ensure parse → format → parse consistency (✅ Tested)
|
|
|
|
### 4. **Future Error Handling** (PLANNED)
|
|
- **File locked**: Show warning, allow retry
|
|
- **DNS failure**: Show cached/manual IP options
|
|
- **State recovery**: Restore UI state after errors
|
|
- **User guidance**: Clear error messages with suggested actions
|
|
|
|
## Testing Architecture
|
|
|
|
### 1. **Unit Tests** ✅ IMPLEMENTED (54 TESTS)
|
|
- **Parser functions**: ParseHostsContent, FormatHostsFile, DetectFormattingStyle (✅ Comprehensive coverage)
|
|
- **Model validation**: HostEntry creation, hostname/IP validation (✅ 44 foundation tests)
|
|
- **Edge cases**: Malformed files, empty files, comment-only files (✅ Extensive edge case testing)
|
|
- **File operations**: Backup functionality, atomic writes (✅ BackupHostsFile tested)
|
|
|
|
### 2. **Test Coverage Achieved**
|
|
- **Standard entries**: IPv4, IPv6, aliases, comments (✅ TestParseHostsFile_StandardEntries)
|
|
- **Comment handling**: Disabled entries vs standalone comments (✅ TestParseHostsFile_CommentsAndDisabled)
|
|
- **Error scenarios**: Invalid IPs, malformed lines, missing data (✅ TestParseHostsFile_MalformedLines)
|
|
- **Whitespace handling**: Tabs, spaces, mixed formatting (✅ TestParseHostsFile_WhitespaceVariations)
|
|
- **Round-trip parsing**: Parse → format → parse consistency (✅ TestWriteHostsFile_RoundTrip)
|
|
- **Format detection**: Tab vs space detection with GCD analysis (✅ TestDetectFormattingStyle)
|
|
|
|
### 3. **Test Patterns** ✅ IMPLEMENTED
|
|
- **Table-driven tests**: Multiple input scenarios for comprehensive coverage (✅ Used extensively)
|
|
- **Helper functions**: parseHostsContent helper for string-based testing (✅ Implemented)
|
|
- **Temporary files**: Safe testing of file operations (✅ TestBackupHostsFile)
|
|
- **Error validation**: Verify specific error messages and warning content (✅ Implemented)
|
|
|
|
### 4. **Future Testing** (PLANNED)
|
|
- **TUI workflows**: Complete user interactions (Phase 2)
|
|
- **Permission scenarios**: Test sudo/non-sudo paths (Phase 3)
|
|
- **Integration tests**: Full application workflows (Phase 3)
|
|
- **Mock interfaces**: Controllable external dependencies (Phase 3)
|