refactor: move V1 code into v1/ subdirectory
- git mv cmd/ internal/ pkg/ test/ go.mod go.sum Makefile build.sh docs/ v1/ - Create v1/README.md with V1 documentation - Update root README for V1 + V2 structure - V1 still builds (cd v1 && go build ./cmd/hostkeeper) and 105 tests pass - Root is now clean for V2 development
This commit is contained in:
+91
@@ -0,0 +1,91 @@
|
||||
.PHONY: build run test test-short test-coverage clean fmt vet lint install tidy deps verify release help
|
||||
|
||||
# Binary name
|
||||
BINARY_NAME=hostkeeper
|
||||
BUILD_DIR=bin
|
||||
|
||||
# Go parameters
|
||||
GOCMD=go
|
||||
GOBUILD=$(GOCMD) build
|
||||
GOCLEAN=$(GOCMD) clean
|
||||
GOTEST=$(GOCMD) test
|
||||
GOGET=$(GOCMD) get
|
||||
GOFMT=$(GOCMD) fmt
|
||||
GOVET=$(GOCMD) vet
|
||||
|
||||
# Version info
|
||||
VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
||||
BUILD_TIME := $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
LDFLAGS := -X main.version=$(VERSION) -X main.buildTime=$(BUILD_TIME)
|
||||
|
||||
# Default target
|
||||
all: build
|
||||
|
||||
## build: Compile the binary
|
||||
build:
|
||||
$(GOBUILD) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME) ./cmd/hostkeeper
|
||||
|
||||
## run: Build and run
|
||||
run: build
|
||||
./$(BUILD_DIR)/$(BINARY_NAME) $(ARGS)
|
||||
|
||||
## test: Run all tests
|
||||
test:
|
||||
$(GOTEST) ./... -v
|
||||
|
||||
## test-short: Run only short tests
|
||||
test-short:
|
||||
$(GOTEST) ./... -v -short
|
||||
|
||||
## test-coverage: Run tests with coverage report
|
||||
test-coverage:
|
||||
$(GOTEST) ./... -v -coverprofile=coverage.out -covermode=atomic
|
||||
$(GOCMD) tool cover -html=coverage.out -o coverage.html
|
||||
@echo "Coverage report generated: coverage.html"
|
||||
|
||||
## clean: Remove build artifacts
|
||||
clean:
|
||||
$(GOCLEAN)
|
||||
rm -rf $(BUILD_DIR)
|
||||
rm -f coverage.out coverage.html
|
||||
|
||||
## fmt: Format all Go files
|
||||
fmt:
|
||||
$(GOFMT) ./...
|
||||
|
||||
## vet: Run go vet
|
||||
vet:
|
||||
$(GOVET) ./...
|
||||
|
||||
## lint: Run linter (requires golangci-lint)
|
||||
lint:
|
||||
golangci-lint run ./...
|
||||
|
||||
## install: Install the binary to GOPATH/bin
|
||||
install: build
|
||||
$(GOCMD) install ./cmd/hostkeeper
|
||||
|
||||
## tidy: Run go mod tidy
|
||||
tidy:
|
||||
$(GOCMD) mod tidy
|
||||
|
||||
## deps: Download dependencies
|
||||
deps:
|
||||
$(GOCMD) mod download
|
||||
|
||||
## verify: Verify module dependencies
|
||||
verify:
|
||||
$(GOCMD) mod verify
|
||||
|
||||
## release: Build for multiple platforms
|
||||
release: clean
|
||||
mkdir -p $(BUILD_DIR)
|
||||
GOOS=darwin GOARCH=amd64 $(GOBUILD) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-amd64 ./cmd/hostkeeper
|
||||
GOOS=darwin GOARCH=arm64 $(GOBUILD) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-darwin-arm64 ./cmd/hostkeeper
|
||||
GOOS=linux GOARCH=amd64 $(GOBUILD) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-amd64 ./cmd/hostkeeper
|
||||
GOOS=linux GOARCH=arm64 $(GOBUILD) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-linux-arm64 ./cmd/hostkeeper
|
||||
GOOS=windows GOARCH=amd64 $(GOBUILD) -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY_NAME)-windows-amd64.exe ./cmd/hostkeeper
|
||||
|
||||
## help: Show this help
|
||||
help:
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-15s\033[0m %s\n", $$1, $$2}'
|
||||
@@ -0,0 +1,640 @@
|
||||
# Hostkeeper Project State & Handoff Guide
|
||||
|
||||
> **Purpose**: Enable seamless continuation of development by any agent/LLM across sessions
|
||||
>
|
||||
> **Last Updated**: 2025-01-31 (Phase 3 Testing Complete)
|
||||
> **Current Status**: ✅ MVP Complete — Phase 1 Done, Phase 2 Done, Phase 3 Testing Done
|
||||
> **Phase**: Phase 3 (Documentation)
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start for New Agents
|
||||
|
||||
### Immediate Context (Read This First)
|
||||
|
||||
**Project**: Hostkeeper - Cross-platform SSH/SFTP management tool
|
||||
**Tech Stack**: Go 1.21+, Cobra, Bubble Tea, golang.org/x/crypto/ssh
|
||||
**Architecture**: Monolithic CLI with embedded TUI
|
||||
**Current Phase**: MVP Implementation (estimated 3-4 weeks)
|
||||
|
||||
### What's Already Done
|
||||
✅ Complete design documentation (`docs/plans/2024-06-22-hostkeeper-design.md`)
|
||||
✅ Detailed implementation plan (`docs/plans/2024-06-22-hostkeeper-implementation.md`)
|
||||
✅ Git repository initialized
|
||||
✅ Project structure defined
|
||||
✅ **Task 1**: Project setup (go.mod, Makefile, .gitignore, main.go)
|
||||
✅ **Task 2**: Core data models (`internal/models/models.go`) + JSON storage (`pkg/storage/`)
|
||||
✅ **Task 3**: Configuration management (`pkg/config/config.go`)
|
||||
✅ **Task 4**: Error handling framework (`internal/errors/`) + tests passing
|
||||
✅ **Task 5**: SSH client (`pkg/ssh/`) + tests passing
|
||||
✅ **Task 6**: CLI Framework Setup - Cobra root, version, completion (`cmd/hostkeeper/`)
|
||||
✅ **Task 7**: Add command (`cmd/hostkeeper/add.go`) - add hosts with flags/interactive + tests
|
||||
✅ **Task 8**: List command (`cmd/hostkeeper/list.go`) - list/filter/sort hosts + tests
|
||||
✅ **Bug Fix**: Fixed deadlock in JSON storage (RLock within Lock)
|
||||
|
||||
### What's Been Done
|
||||
✅ **Task 13**: Documentation — README, INSTALLATION, USAGE, ARCHITECTURE
|
||||
✅ **Task 14**: Release — CHANGELOG, RELEASE_CHECKLIST, git tag v1.0.0
|
||||
|
||||
**🔥 All 14 MVP tasks complete! Project is ready for deployment.**
|
||||
|
||||
### Post-MVP Fixes
|
||||
✅ TUI layout overhaul: centered border boxes, per-row centering, context-specific footers
|
||||
✅ Status bar removed; keybindings moved inside each tab's border box footer
|
||||
✅ SFTP browser: full-width panes, SFTP-specific keybindings
|
||||
✅ Host list footer: added `Ctrl+E:edit`
|
||||
✅ UUID + timestamps auto-generated in TUI form `submit()` methods
|
||||
✅ UUID + timestamps auto-generated in storage layer (`SaveHost`, `SaveKeyPair`, `SaveSnippet`)
|
||||
✅ Git history cleaned of committed binary; `.gitignore` fixed
|
||||
✅ **host_form_tab.go**: Space/Left/Right passthrough to text input (fixes typing spaces + cursor nav)
|
||||
✅ **tui.go**: Key + snippet list refresh on save/delete
|
||||
✅ **tabs.go**: WindowSizeMsg forwarded to all tabs on resize
|
||||
✅ **sftp_browser_tab.go footer**: Added `Enter/→:open`, `←/Backspace:up`
|
||||
✅ **Form tab footers**: Added `Shift+Tab:prev`, `↑↓:nav`
|
||||
|
||||
### Done: Responsive Layout Overhaul
|
||||
✅ **NEW `responsive.go`**: Shared helpers for adaptive layout (`wrapFooter`, `adaptiveSidePad`, `clampWidth`, `truncateStr`)
|
||||
✅ Footer auto-wraps to multi-line (full labels preserved) — no more overflow on narrow terminals
|
||||
✅ Box width clamped to terminal width across all tabs
|
||||
✅ Host/key/snippet rows truncated with `…` for long names; compact format on narrow screens
|
||||
✅ SFTP panes stack vertically when terminal < 50 cols
|
||||
✅ Tab bar truncates names on overflow
|
||||
✅ Form contentW minimum lowered from 50 to 30 for mobile (Termux)
|
||||
✅ Fixed bug: key_list_tab.go & snippet_list_tab.go dropped last row (`rows[:len(rows)-1]` excluded real data)
|
||||
✅ Breakpoints: compact (<60 cols / mobile), medium (60–100 / tablet), wide (≥100 / desktop)
|
||||
|
||||
### Done: SFTP Stacked Mode Fix
|
||||
✅ **File**: `pkg/tui/sftp_browser_tab.go`
|
||||
✅ Stacked mode (<50 cols): render cuma ACTIVE pane (bukan 2 pane)
|
||||
✅ Pane indicator bar: `[Local] Remote` — active disorot hijau (StatusBarStyle)
|
||||
✅ Side-by-side mode (>=50 cols): tidak diubah, tetap 2 pane
|
||||
✅ Default active pane: Local (bukan Remote)
|
||||
✅ Border height fix: `renderPane` sekarang terima `maxH` parameter, `paneStyle.Height(maxH)` → border selalu konsisten tingginya, tidak naik-turun sesuai scroll
|
||||
✅ Stacked mode: `maxH = t.height - 6` (title + indicator + border + footer)
|
||||
✅ Side-by-side mode: `maxH = t.height - 5` (title + border + footer)
|
||||
|
||||
---
|
||||
|
||||
## 📊 Current Project Status
|
||||
|
||||
### Completion Matrix
|
||||
|
||||
| Component | Status | Notes |
|
||||
|-----------|--------|-------|
|
||||
| **Planning** | ✅ 100% | Design and implementation plans complete |
|
||||
| **Setup** | ✅ 100% | go.mod, Makefile, .gitignore, main.go |
|
||||
| **Core Models** | ✅ 100% | Host, KeyPair, Snippet, AppConfig models + JSON storage |
|
||||
| **Config** | ✅ 100% | Cross-platform config management |
|
||||
| **Errors** | ✅ 100% | AppError + ConnectionError + SSH error handler |
|
||||
| **SSH Client** | ✅ 100% | Password + key auth, Execute, Connect/Close |
|
||||
| **CLI Framework** | ✅ 100% | Cobra root, version, completion commands |
|
||||
| **CLI Commands** | ✅ 100% | All 11 commands: add, list, connect, edit, delete, export, import, tui, completion, version, help |
|
||||
| **TUI** | ✅ 100% | Bubble Tea TUI with host list navigation |
|
||||
| **Testing** | ✅ 100% | All unit + integration tests passing |
|
||||
| **Documentation** | ✅ 100% | README, INSTALLATION, USAGE, ARCHITECTURE guides |
|
||||
|
||||
### Overall Progress: **🎉 100% Complete** (All 14 MVP Tasks Done)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Implementation Task Status
|
||||
|
||||
### Task Breakdown (from implementation plan)
|
||||
|
||||
#### ✅ Task 1: Project Setup and Dependencies
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: CRITICAL (must be first)
|
||||
- **Deliverables**: go.mod, project structure, Makefile
|
||||
- **Files Created**:
|
||||
- `go.mod`, `go.sum` (module: `git.tukangketik.id/swanadiva/hostkeeper`)
|
||||
- `Makefile`, `.gitignore`
|
||||
- `cmd/hostkeeper/main.go`
|
||||
|
||||
#### ✅ Task 2: Core Data Models and Storage Layer
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: CRITICAL
|
||||
- **Deliverables**: Host, KeyPair, Snippet, AppConfig models + JSON storage
|
||||
- **Files Created**:
|
||||
- `internal/models/models.go` — all data models + `DefaultConfig()`
|
||||
- `pkg/storage/storage.go` — Storage interface, ExportData, MergeStrategy
|
||||
- `pkg/storage/json_storage.go` — JSONStorage implementation with file locking
|
||||
|
||||
#### ✅ Task 3: Configuration Management
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Cross-platform config load/save functionality
|
||||
- **Files Created**:
|
||||
- `pkg/config/config.go` — Config struct, OS-aware paths (macOS/Linux/Windows), auto-create defaults
|
||||
|
||||
#### ✅ Task 4: Error Handling Framework
|
||||
- **Status**: ✅ Completed (all tests passing)
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Error types, SSH error handler
|
||||
- **Files Created**:
|
||||
- `internal/errors/errors.go` — AppError type with codes, Unwrap support
|
||||
- `internal/errors/connection_errors.go` — ConnectionError, HandleSSHError, FormatConnectionError
|
||||
- `test/errors_test.go` — 5 test functions, all passing
|
||||
|
||||
#### ✅ Task 5: SSH Client Implementation
|
||||
- **Status**: ✅ Completed (all tests passing)
|
||||
- **Priority**: CRITICAL
|
||||
- **Deliverables**: SSH connection client with auth
|
||||
- **Files Created**:
|
||||
- `pkg/ssh/client.go` — Client struct, Connect, Execute, Close, IsConnected
|
||||
- `pkg/ssh/auth.go` — Password/key/both auth, default key discovery
|
||||
- `test/ssh/ssh_test.go` — 4 test functions, all passing
|
||||
|
||||
#### ✅ Task 6: CLI Framework Setup
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: CRITICAL
|
||||
- **Deliverables**: Cobra framework, basic commands
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/main.go` — Entry point with Execute() function
|
||||
- `cmd/hostkeeper/root.go` — Root command with PersistentPreRunE config init
|
||||
- `cmd/hostkeeper/completion.go` — Shell completion (bash/zsh/fish/powershell)
|
||||
- Includes `version` subcommand and `-v/--verbose`, `--debug` flags
|
||||
|
||||
#### ✅ Task 7: Add Command
|
||||
- **Status**: ✅ Completed (all tests passing)
|
||||
- **Priority**: CRITICAL
|
||||
- **Deliverables**: `add` command for registering hosts
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/add.go` — add host with flags/interactive, password/key auth, groups, tags, notes
|
||||
- `cmd/hostkeeper/add_test.go` — tests for add command (flag parsing, storage integration)
|
||||
|
||||
#### ✅ Task 8: List Command
|
||||
- **Status**: ✅ Completed (all tests passing)
|
||||
- **Priority**: CRITICAL
|
||||
- **Deliverables**: `list` command for displaying hosts
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/list.go` — list hosts with filter (group/tag), sort, table/JSON/wide output formats
|
||||
- `cmd/hostkeeper/list_test.go` — tests for list command (filtering, formatting)
|
||||
|
||||
#### ✅ Task 9: Connect Host Command
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: CRITICAL
|
||||
- **Deliverables**: Connect to saved SSH hosts via native SSH or Go SSH client
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/connect.go` — Connect command with native SSH (default) and direct Go SSH (--direct) modes
|
||||
- `cmd/hostkeeper/connect_test.go` — Tests for command existence, flags, and SSH arg building
|
||||
|
||||
#### ✅ Edit Host Command
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Edit existing SSH host configurations
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/edit.go` — Edit command with flag-based and interactive modes
|
||||
- `cmd/hostkeeper/edit_test.go` — Tests for command existence and flags
|
||||
|
||||
#### ✅ Delete Host Command
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Delete SSH hosts with confirmation prompt
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/delete.go` — Delete command with --force flag to skip confirmation
|
||||
- `cmd/hostkeeper/delete_test.go` — Tests for command existence, alias, and flags
|
||||
|
||||
#### ✅ Task 10: Basic TUI Implementation
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Bubble Tea TUI with host list screen
|
||||
- **Files Created**:
|
||||
- `pkg/tui/tui.go` — TUI model with Init/Update/View (Bubble Tea)
|
||||
- `pkg/tui/host_list.go` — Host list renderer with keyboard navigation
|
||||
- `pkg/tui/tui_test.go` — Tests for TUI initialization and host loading
|
||||
- `cmd/hostkeeper/tui.go` — CLI `tui` command
|
||||
|
||||
#### ✅ Task 11: Export/Import Commands
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Export/import hosts, keys, snippets for backup/transfer
|
||||
- **Files Created**:
|
||||
- `cmd/hostkeeper/export.go` — Export command with JSON format (default) and include-keys flag
|
||||
- `cmd/hostkeeper/import.go` — Import command with replace/merge strategies and dry-run preview
|
||||
- `test/storage/export_import_test.go` — Integration test for export/import round-trip
|
||||
|
||||
#### ✅ Task 12: Build and Testing
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Build system and integration tests
|
||||
- **Files Created/Modified**:
|
||||
- `Makefile` — Added test-coverage, verify targets; updated clean to remove coverage files
|
||||
- `build.sh` — Cross-platform build script with SHA256 checksums
|
||||
- `test/integration/integration_test.go` — End-to-end workflow tests (add, list, get, update, export/import, delete, config)
|
||||
|
||||
#### ✅ Task 13: Documentation
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: README, INSTALLATION, USAGE, ARCHITECTURE guides
|
||||
- **Files Created/Updated**:
|
||||
- `README.md` — Full rewrite with features, quick start, commands, tech info
|
||||
- `docs/INSTALLATION.md` — Cross-platform installation guide
|
||||
- `docs/USAGE.md` — Detailed command usage with examples
|
||||
- `docs/ARCHITECTURE.md` — System architecture overview
|
||||
|
||||
#### ✅ Task 14: Final Testing and Release
|
||||
- **Status**: ✅ Completed
|
||||
- **Priority**: HIGH
|
||||
- **Deliverables**: Release preparation, CHANGELOG, git tag v1.0.0
|
||||
- **Files Created**:
|
||||
- `CHANGELOG.md` — Release changelog
|
||||
- `RELEASE_CHECKLIST.md` — Pre/post-release checklist
|
||||
- **Git Tag**: `v1.0.0`
|
||||
|
||||
---
|
||||
|
||||
## 🗺️ Development Roadmap
|
||||
|
||||
### Current Week Focus
|
||||
**Target**: Complete Tasks 12+ (Build, Testing, Docs, Release)
|
||||
|
||||
### This Sprint
|
||||
- [x] Project setup and dependencies
|
||||
- [x] Core data models and storage
|
||||
- [x] Configuration management
|
||||
- [x] Error handling framework
|
||||
- [x] SSH client implementation
|
||||
- [x] CLI framework setup
|
||||
- [x] Add host command
|
||||
- [x] List hosts command
|
||||
- [x] Connect host command
|
||||
- [x] Edit host command
|
||||
- [x] Delete host command
|
||||
- [x] TUI implementation
|
||||
- [x] Export/Import commands
|
||||
- [x] Build system and integration tests
|
||||
|
||||
### Next Sprint
|
||||
- [ ] SFTP Performance: caching directory listings, batch directory reads
|
||||
- [ ] SFTP File Transfer: download (remote→local), upload (local→remote)
|
||||
- [ ] Phase 2 Priority 2: Security Enhancement (AES-256-GCM, key passphrase, known_hosts)
|
||||
|
||||
### Final Sprint
|
||||
- [ ] Phase 2 Priority 3: UX Polish (configuration profiles, theme customization, enhanced error messages)
|
||||
- [ ] Testing and integration
|
||||
- [ ] Documentation completion
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Technical Stack & Dependencies
|
||||
|
||||
### Go Dependencies
|
||||
```go
|
||||
// Required packages (to be installed in Task 1)
|
||||
github.com/spf13/cobra@latest // CLI framework
|
||||
github.com/spf13/viper@latest // Configuration
|
||||
github.com/charmbracelet/bubbletea // TUI framework
|
||||
github.com/charmbracelet/lipgloss // TUI styling
|
||||
golang.org/x/crypto@latest // SSH/SFTP
|
||||
github.com/google/uuid@latest // UUID generation
|
||||
github.com/joho/godotenv@latest // Environment variables
|
||||
```
|
||||
|
||||
### Build Tools
|
||||
- `make` - Build automation
|
||||
- `go test` - Testing framework
|
||||
- `go fmt` - Code formatting
|
||||
|
||||
### Platform Support
|
||||
- Linux (x86_64, ARM64, ARM)
|
||||
- macOS (x86_64, ARM64)
|
||||
- Windows (x86_64)
|
||||
- Termux/Android (ARM)
|
||||
|
||||
---
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
hostkeeper/
|
||||
├── cmd/
|
||||
│ └── hostkeeper/ # Main application
|
||||
│ ├── main.go # Entry point
|
||||
│ ├── root.go # Root command
|
||||
│ └── *.go # Subcommands
|
||||
├── pkg/
|
||||
│ ├── ssh/ # SSH client
|
||||
│ ├── sftp/ # SFTP client (Phase 2)
|
||||
│ ├── storage/ # Data persistence
|
||||
│ ├── config/ # Configuration
|
||||
│ └── tui/ # Terminal UI
|
||||
├── internal/
|
||||
│ ├── models/ # Data models
|
||||
│ └── errors/ # Error handling
|
||||
├── test/ # Tests
|
||||
├── docs/
|
||||
│ └── plans/ # Design docs
|
||||
├── utils/ # Utilities
|
||||
├── build/ # Build output
|
||||
├── go.mod
|
||||
├── go.sum
|
||||
├── Makefile
|
||||
├── README.md
|
||||
└── PROJECT_STATE.md # THIS FILE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Handoff Procedures
|
||||
|
||||
### For New Agents/LLMs
|
||||
|
||||
#### Step 1: Read This File
|
||||
- **Start here**: This `PROJECT_STATE.md` file
|
||||
- **Then read**: `docs/plans/2024-06-22-hostkeeper-design.md` (architecture)
|
||||
- **Then read**: `docs/plans/2024-06-22-hostkeeper-implementation.md` (tasks)
|
||||
|
||||
#### Step 2: Check Current Status
|
||||
```bash
|
||||
# Check git status
|
||||
git status
|
||||
|
||||
# Check recent commits
|
||||
git log --oneline -5
|
||||
|
||||
# Check what files exist
|
||||
find . -name "*.go" -type f
|
||||
```
|
||||
|
||||
#### Step 3: Determine Next Action
|
||||
1. Look at "Implementation Task Status" above
|
||||
2. Find first incomplete task
|
||||
3. Refer to implementation plan for detailed instructions
|
||||
4. Execute following TDD approach
|
||||
|
||||
#### Step 4: Update This File
|
||||
After completing any task, update the corresponding status section:
|
||||
```markdown
|
||||
#### ✅ Task X: [Task Name]
|
||||
- **Status**: Completed
|
||||
- **Completion Date**: [Date]
|
||||
- **Notes**: [Any important notes]
|
||||
- **Commits**: [Relevant commit hashes]
|
||||
```
|
||||
|
||||
### For Returning Agents
|
||||
|
||||
#### Quick Status Check
|
||||
```bash
|
||||
# What's been done recently?
|
||||
git log --oneline --since="2 weeks ago" | head -10
|
||||
|
||||
# What tests are passing?
|
||||
make test 2>&1 | tail -20
|
||||
|
||||
# What's the current state?
|
||||
go run cmd/hostkeeper/main.go --version
|
||||
```
|
||||
|
||||
#### Resume Work
|
||||
1. Check "Implementation Task Status" in this file
|
||||
2. Find last completed task
|
||||
3. Continue with next incomplete task
|
||||
4. Update status as you progress
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Testing Strategy
|
||||
|
||||
### Test Categories
|
||||
1. **Unit Tests** - Individual component testing
|
||||
2. **Integration Tests** - Cross-component testing
|
||||
3. **E2E Tests** - Full workflow testing
|
||||
|
||||
### Running Tests
|
||||
```bash
|
||||
# All tests
|
||||
make test
|
||||
|
||||
# With coverage
|
||||
make test-coverage
|
||||
|
||||
# Specific package
|
||||
go test ./pkg/storage -v
|
||||
|
||||
# Watch mode (if installed)
|
||||
go test ./... -watch
|
||||
```
|
||||
|
||||
### Current Test Coverage
|
||||
- **Target**: 80%+ coverage
|
||||
- **Current**: ~30% (error handling + SSH client tests passing)
|
||||
- **Priority**: Write tests first (TDD approach)
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Known Issues & Limitations
|
||||
|
||||
### Current Limitations (MVP Scope)
|
||||
- No encryption (Phase 2)
|
||||
- No cloud sync (Phase 3)
|
||||
- No custom terminal emulator (Phase 2)
|
||||
- Basic SFTP only (native client, no TUI)
|
||||
|
||||
### Technical Debt
|
||||
- None yet (project just started)
|
||||
|
||||
### Security Considerations
|
||||
- File permissions must be 0600 for sensitive files
|
||||
- No password/key logging in errors
|
||||
- Memory clearing for sensitive data (Phase 2)
|
||||
|
||||
---
|
||||
|
||||
## 📚 Documentation Index
|
||||
|
||||
### Essential Reading (Priority Order)
|
||||
1. **`PROJECT_STATE.md`** (this file) - Current status and handoff
|
||||
2. **`docs/plans/2024-06-22-hostkeeper-design.md`** - Architecture and design
|
||||
3. **`docs/plans/2024-06-22-hostkeeper-implementation.md`** - Implementation tasks
|
||||
|
||||
### Additional Documentation
|
||||
- `README.md` - Project overview and quick start
|
||||
- `docs/INSTALLATION.md` - Installation guide
|
||||
- `docs/USAGE.md` - Usage documentation
|
||||
- `docs/ARCHITECTURE.md` - Detailed architecture
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Success Criteria
|
||||
|
||||
### MVP Success Metrics
|
||||
- ✅ Can establish SSH connections (via native SSH)
|
||||
- ✅ Can manage multiple hosts
|
||||
- ✅ Can perform SFTP operations
|
||||
- ✅ Can export/import credentials
|
||||
- ✅ Works on all target platforms
|
||||
- ✅ Secure credential storage
|
||||
- ✅ User-friendly error messages
|
||||
|
||||
### Current Progress: 5/7 criteria met (SFTP + encrypted storage deferred to Phase 2)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Version Control Strategy
|
||||
|
||||
### Branch Strategy
|
||||
- `main` - Production code
|
||||
- `feature/*` - Feature branches
|
||||
- `bugfix/*` - Bug fixes
|
||||
|
||||
### Commit Conventions
|
||||
```bash
|
||||
# Feature commits
|
||||
git commit -m "feat: add SSH client implementation"
|
||||
|
||||
# Bug fixes
|
||||
git commit -m "fix: handle connection timeout properly"
|
||||
|
||||
# Documentation
|
||||
git commit -m "docs: update installation guide"
|
||||
|
||||
# Tests
|
||||
git commit -m "test: add SSH client integration tests"
|
||||
```
|
||||
|
||||
### Release Tagging
|
||||
```bash
|
||||
# Format: v[MAJOR].[MINOR].[PATCH]
|
||||
git tag -a v1.0.0 -m "Initial MVP release"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 💻 Development Workflow
|
||||
|
||||
### Getting Started (Fresh Clone)
|
||||
```bash
|
||||
# Clone repository
|
||||
git clone <repo-url>
|
||||
cd hostkeeper
|
||||
|
||||
# Install dependencies
|
||||
go mod download
|
||||
|
||||
# Run tests
|
||||
make test
|
||||
|
||||
# Build project
|
||||
make build
|
||||
|
||||
# Run application
|
||||
./build/hostkeeper --help
|
||||
```
|
||||
|
||||
### Daily Workflow
|
||||
```bash
|
||||
# Pull latest changes
|
||||
git pull origin main
|
||||
|
||||
# Check status (THIS FILE)
|
||||
# Look at "Current Project Status" section
|
||||
|
||||
# Find next task
|
||||
# Look at "Implementation Task Status" section
|
||||
|
||||
# Work on task
|
||||
# Follow implementation plan
|
||||
|
||||
# Test changes
|
||||
make test
|
||||
|
||||
# Commit changes
|
||||
git add .
|
||||
git commit -m "feat: descriptive message"
|
||||
|
||||
# Push changes
|
||||
git push origin main
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Debugging & Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Build Failures
|
||||
```bash
|
||||
# Clean and retry
|
||||
make clean
|
||||
make build
|
||||
|
||||
# Check dependencies
|
||||
go mod verify
|
||||
go mod tidy
|
||||
```
|
||||
|
||||
#### Test Failures
|
||||
```bash
|
||||
# Run with verbose output
|
||||
go test -v ./...
|
||||
|
||||
# Run specific test
|
||||
go test ./test -run TestSpecificFunction
|
||||
```
|
||||
|
||||
#### Import Errors
|
||||
```bash
|
||||
# Verify module structure
|
||||
go mod tidy
|
||||
|
||||
# Check go.mod
|
||||
cat go.mod
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📞 Contact & Support
|
||||
|
||||
### Project Links
|
||||
- Repository: [GitHub URL]
|
||||
- Issues: [GitHub Issues URL]
|
||||
- Discussions: [GitHub Discussions URL]
|
||||
|
||||
### Getting Help
|
||||
1. Check documentation in `docs/`
|
||||
2. Search existing issues
|
||||
3. Create new issue with:
|
||||
- Clear description
|
||||
- Steps to reproduce
|
||||
- Expected vs actual behavior
|
||||
- Environment details
|
||||
|
||||
---
|
||||
|
||||
## 🎓 Learning Resources
|
||||
|
||||
### For New Contributors
|
||||
- Go Documentation: https://golang.org/doc/
|
||||
- Cobra Framework: https://github.com/spf13/cobra
|
||||
- Bubble Tea: https://github.com/charmbracelet/bubbletea
|
||||
- SSH in Go: https://pkg.go.dev/golang.org/x/crypto/ssh
|
||||
|
||||
### Project-Specific
|
||||
- Design decisions: `docs/plans/2024-06-22-hostkeeper-design.md`
|
||||
- Implementation guide: `docs/plans/2024-06-22-hostkeeper-implementation.md`
|
||||
- Code examples: `test/` directory
|
||||
|
||||
---
|
||||
|
||||
## 📊 Progress Tracking
|
||||
|
||||
### Completion Timeline
|
||||
- **Start Date**: 2024-06-22
|
||||
- **Planning Complete**: 2024-06-22 ✅
|
||||
- **Target MVP**: 2024-07-20 (3-4 weeks)
|
||||
- **Current Phase**: MVP Release
|
||||
|
||||
### Milestone Tracking
|
||||
- [x] Milestone 1: Foundation (Tasks 1-6) - Week 1 ✅ COMPLETE
|
||||
- [x] Task 7-9: Add, List, Connect commands ✅ COMPLETE
|
||||
- [x] Edit & Delete commands ✅ COMPLETE
|
||||
- [x] Milestone 2: Core Features (Tasks 7-10) - Week 2-3 ✅ COMPLETE
|
||||
- [x] Milestone 3: Polish & Release (Tasks 11-14) - Week 4 ✅ COMPLETE
|
||||
- [x] **🏆 ALL 14 MVP TASKS COMPLETE** 🏆
|
||||
|
||||
---
|
||||
|
||||
**🔄 Remember**: After completing any task, update the "Implementation Task Status" section above to maintain accurate project state for future agents/sessions.
|
||||
|
||||
**📝 Note**: This file should be updated after every significant development session to ensure continuity across agents and time.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Hostkeeper V1 — CLI/TUI
|
||||
|
||||
> **Status**: FROZEN — no further development.
|
||||
> Pembuatan V2 dilakukan di folder `../app/` dan `../mobile/`.
|
||||
|
||||
Hostkeeper V1 adalah SSH/SFTP management tool berbasis CLI + TUI (Bubble Tea).
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
cd v1
|
||||
make build
|
||||
./hostkeeper tui
|
||||
```
|
||||
|
||||
## Dokumentasi
|
||||
|
||||
- [Architecture](docs/ARCHITECTURE.md)
|
||||
- [Installation](docs/INSTALLATION.md)
|
||||
- [Usage](docs/USAGE.md)
|
||||
- [Test Plan](docs/TEST_PLAN.md)
|
||||
- [Project State](PROJECT_STATE.md)
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Go 1.26+
|
||||
- Cobra (CLI)
|
||||
- Bubble Tea (TUI)
|
||||
- golang.org/x/crypto/ssh
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
cd v1
|
||||
make test
|
||||
# 105 tests passing
|
||||
```
|
||||
@@ -0,0 +1,41 @@
|
||||
# Release Checklist
|
||||
|
||||
## Pre-Release
|
||||
|
||||
- [ ] All tests pass: `make test`
|
||||
- [ ] Test coverage is adequate: `make test-coverage`
|
||||
- [ ] `go vet` passes: `make vet`
|
||||
- [ ] Lint passes: `make lint`
|
||||
- [ ] All platforms build successfully: `./build.sh`
|
||||
- [ ] `CHANGELOG.md` is up to date
|
||||
- [ ] Version is updated in source
|
||||
- [ ] Documentation is current
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] Integration tests pass: `go test ./test/integration/`
|
||||
- [ ] Manual smoke test all commands:
|
||||
- [ ] `hostkeeper add`
|
||||
- [ ] `hostkeeper list`
|
||||
- [ ] `hostkeeper connect`
|
||||
- [ ] `hostkeeper edit`
|
||||
- [ ] `hostkeeper delete`
|
||||
- [ ] `hostkeeper export`
|
||||
- [ ] `hostkeeper import`
|
||||
- [ ] `hostkeeper tui`
|
||||
- [ ] `hostkeeper version`
|
||||
- [ ] `hostkeeper completion`
|
||||
|
||||
## Release
|
||||
|
||||
- [ ] Tag the release: `git tag v1.0.0`
|
||||
- [ ] Push tags: `git push origin --tags`
|
||||
- [ ] Build release binaries: `./build.sh`
|
||||
- [ ] Verify checksums in `build/checksums.txt`
|
||||
- [ ] Create GitHub release with binaries attached
|
||||
- [ ] Post-release announcement (if applicable)
|
||||
|
||||
## Post-Release
|
||||
|
||||
- [ ] Update PROJECT_STATE.md
|
||||
- [ ] Start next milestone planning
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
# Build script for multiple platforms
|
||||
set -e
|
||||
|
||||
VERSION=${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo "dev")}
|
||||
BUILD_DIR=${BUILD_DIR:-"build"}
|
||||
BINARY_NAME="hostkeeper"
|
||||
|
||||
echo "Building Hostkeeper v${VERSION}"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
|
||||
rm -rf ${BUILD_DIR}
|
||||
mkdir -p ${BUILD_DIR}
|
||||
|
||||
platforms=(
|
||||
"linux/amd64"
|
||||
"linux/arm64"
|
||||
"linux/arm"
|
||||
"darwin/amd64"
|
||||
"darwin/arm64"
|
||||
"windows/amd64"
|
||||
)
|
||||
|
||||
for platform in "${platforms[@]}"; do
|
||||
IFS='/' read -r os arch <<< "$platform"
|
||||
|
||||
output_name="${BINARY_NAME}-${os}-${arch}"
|
||||
if [ "$os" = "windows" ]; then
|
||||
output_name="${output_name}.exe"
|
||||
fi
|
||||
|
||||
echo " Building for ${os}/${arch}..."
|
||||
|
||||
GOOS=$os GOARCH=$arch go build \
|
||||
-ldflags "-X main.version=${VERSION} -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
|
||||
-o "${BUILD_DIR}/${output_name}" \
|
||||
./cmd/hostkeeper
|
||||
|
||||
if command -v shasum &> /dev/null; then
|
||||
(cd ${BUILD_DIR} && shasum -a 256 "${output_name}" > "${output_name}.sha256")
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Build complete! Binaries in ${BUILD_DIR}/"
|
||||
echo ""
|
||||
echo "Available binaries:"
|
||||
ls -lh ${BUILD_DIR}/
|
||||
@@ -0,0 +1,295 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
)
|
||||
|
||||
var (
|
||||
addHostname string
|
||||
addPort int
|
||||
addUser string
|
||||
addPassword string
|
||||
addKeyPath string
|
||||
addAuthType string
|
||||
addGroup string
|
||||
addTags []string
|
||||
addNotes string
|
||||
)
|
||||
|
||||
// addCmd represents the add command
|
||||
var addCmd = &cobra.Command{
|
||||
Use: "add [name]",
|
||||
Short: "Add a new SSH host",
|
||||
Long: `Add a new SSH host connection to HostKeeper.
|
||||
|
||||
You can add hosts using flags for quick addition or interactively.
|
||||
|
||||
Examples:
|
||||
# Add host with password authentication
|
||||
hostkeeper add myserver --host 192.168.1.10 --user admin --password mypass
|
||||
|
||||
# Add host with key authentication
|
||||
hostkeeper add myserver --host 192.168.1.10 --user admin --key ~/.ssh/id_rsa
|
||||
|
||||
# Add host with custom port and group
|
||||
hostkeeper add myserver --host 192.168.1.10 --port 2222 --user admin --password mypass --group production
|
||||
|
||||
# Add host interactively
|
||||
hostkeeper add`,
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: runAddHost,
|
||||
}
|
||||
|
||||
func init() {
|
||||
// Flags for add command
|
||||
addCmd.Flags().StringVar(&addHostname, "host", "", "hostname or IP address")
|
||||
addCmd.Flags().IntVar(&addPort, "port", 0, "SSH port (default: 22)")
|
||||
addCmd.Flags().StringVar(&addUser, "user", "", "SSH username")
|
||||
addCmd.Flags().StringVar(&addPassword, "password", "", "SSH password")
|
||||
addCmd.Flags().StringVar(&addKeyPath, "key", "", "path to SSH private key")
|
||||
addCmd.Flags().StringVar(&addAuthType, "auth-type", "", "authentication type: password, key, or both")
|
||||
addCmd.Flags().StringVar(&addGroup, "group", "", "host group for categorization")
|
||||
addCmd.Flags().StringSliceVar(&addTags, "tags", nil, "tags for the host (comma-separated)")
|
||||
addCmd.Flags().StringVar(&addNotes, "notes", "", "notes about this host")
|
||||
|
||||
rootCmd.AddCommand(addCmd)
|
||||
}
|
||||
|
||||
func runAddHost(cmd *cobra.Command, args []string) error {
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Determine host name
|
||||
var name string
|
||||
if len(args) > 0 {
|
||||
name = args[0]
|
||||
}
|
||||
|
||||
// Check if we should use interactive mode
|
||||
interactive := name == "" && addHostname == ""
|
||||
if interactive {
|
||||
return addHostInteractive(cfg)
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if name == "" {
|
||||
return fmt.Errorf("host name is required (provide as argument or use interactive mode)")
|
||||
}
|
||||
if addHostname == "" {
|
||||
return fmt.Errorf("hostname is required (--host flag)")
|
||||
}
|
||||
if addUser == "" {
|
||||
return fmt.Errorf("username is required (--user flag)")
|
||||
}
|
||||
|
||||
// Set default port from config
|
||||
port := addPort
|
||||
if port == 0 {
|
||||
port = cfg.GetAppConfig().DefaultPort
|
||||
}
|
||||
|
||||
// Determine auth type
|
||||
authType := addAuthType
|
||||
if authType == "" {
|
||||
if addKeyPath != "" && addPassword != "" {
|
||||
authType = "both"
|
||||
} else if addKeyPath != "" {
|
||||
authType = "key"
|
||||
} else if addPassword != "" {
|
||||
authType = "password"
|
||||
} else {
|
||||
return fmt.Errorf("authentication is required: provide --password, --key, or both")
|
||||
}
|
||||
}
|
||||
|
||||
// Read key if provided
|
||||
keyContent := ""
|
||||
if addKeyPath != "" {
|
||||
data, err := os.ReadFile(addKeyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read key file: %w", err)
|
||||
}
|
||||
keyContent = string(data)
|
||||
}
|
||||
|
||||
// Create host
|
||||
host := &models.Host{
|
||||
ID: uuid.New().String(),
|
||||
Name: name,
|
||||
Hostname: addHostname,
|
||||
Port: port,
|
||||
Username: addUser,
|
||||
Auth: models.AuthConfig{
|
||||
Type: authType,
|
||||
Password: addPassword,
|
||||
},
|
||||
Group: addGroup,
|
||||
Tags: addTags,
|
||||
Notes: addNotes,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Store key content in password field if key-only auth (as reference)
|
||||
// In a full implementation, this would store the key securely
|
||||
if keyContent != "" {
|
||||
host.Auth.Password = keyContent // Will be moved to secure storage
|
||||
}
|
||||
|
||||
// Initialize storage
|
||||
store, err := newStorage(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
// Save host
|
||||
ctx := context.Background()
|
||||
if err := store.SaveHost(ctx, host); err != nil {
|
||||
return fmt.Errorf("failed to save host: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("✓ Host '%s' added successfully\n", name)
|
||||
fmt.Printf(" Hostname: %s:%d\n", addHostname, port)
|
||||
fmt.Printf(" User: %s\n", addUser)
|
||||
fmt.Printf(" Auth: %s\n", authType)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func addHostInteractive(cfg *config.Config) error {
|
||||
input := bufio.NewReader(os.Stdin)
|
||||
|
||||
fmt.Println("╔══════════════════════════════════════╗")
|
||||
fmt.Println("║ Add New SSH Host ║")
|
||||
fmt.Println("╚══════════════════════════════════════╝")
|
||||
fmt.Println()
|
||||
|
||||
readLine := func(prompt string) string {
|
||||
fmt.Print(prompt)
|
||||
line, _ := input.ReadString('\n')
|
||||
return strings.TrimRight(line, "\n\r")
|
||||
}
|
||||
|
||||
// Get host name
|
||||
name := readLine("Host Name (e.g., myserver): ")
|
||||
if name == "" {
|
||||
return fmt.Errorf("host name is required")
|
||||
}
|
||||
|
||||
// Get hostname
|
||||
hostname := readLine("Hostname or IP (e.g., 192.168.1.10): ")
|
||||
if hostname == "" {
|
||||
return fmt.Errorf("hostname is required")
|
||||
}
|
||||
|
||||
// Get port
|
||||
defaultPort := cfg.GetAppConfig().DefaultPort
|
||||
portInput := readLine(fmt.Sprintf("Port [%d]: ", defaultPort))
|
||||
port := defaultPort
|
||||
if portInput != "" {
|
||||
fmt.Sscanf(portInput, "%d", &port)
|
||||
}
|
||||
|
||||
// Get username
|
||||
username := readLine("Username: ")
|
||||
if username == "" {
|
||||
return fmt.Errorf("username is required")
|
||||
}
|
||||
|
||||
// Get auth type
|
||||
authType := readLine("Auth Type (password/key/both) [password]: ")
|
||||
if authType == "" {
|
||||
authType = "password"
|
||||
}
|
||||
|
||||
// Get password
|
||||
var password string
|
||||
if authType == "password" || authType == "both" {
|
||||
password = readLine("Password: ")
|
||||
}
|
||||
|
||||
// Get key path
|
||||
var keyContent string
|
||||
if authType == "key" || authType == "both" {
|
||||
keyPath := readLine("Path to private key (~/.ssh/id_rsa): ")
|
||||
if keyPath != "" {
|
||||
data, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read key file: %w", err)
|
||||
}
|
||||
keyContent = string(data)
|
||||
}
|
||||
}
|
||||
|
||||
// Get group
|
||||
group := readLine("Group (optional): ")
|
||||
|
||||
// Get tags
|
||||
tagsInput := readLine("Tags (comma-separated, optional): ")
|
||||
var tags []string
|
||||
if tagsInput != "" {
|
||||
tags = strings.Split(tagsInput, ",")
|
||||
for i, t := range tags {
|
||||
tags[i] = strings.TrimSpace(t)
|
||||
}
|
||||
}
|
||||
|
||||
// Get notes
|
||||
notes := readLine("Notes (optional): ")
|
||||
|
||||
// Create host
|
||||
host := &models.Host{
|
||||
ID: uuid.New().String(),
|
||||
Name: name,
|
||||
Hostname: hostname,
|
||||
Port: port,
|
||||
Username: username,
|
||||
Auth: models.AuthConfig{
|
||||
Type: authType,
|
||||
Password: password,
|
||||
},
|
||||
Group: group,
|
||||
Tags: tags,
|
||||
Notes: notes,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if keyContent != "" {
|
||||
host.Auth.Password = keyContent
|
||||
}
|
||||
|
||||
// Initialize storage
|
||||
store, err := newStorage(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
// Save host
|
||||
ctx := context.Background()
|
||||
if err := store.SaveHost(ctx, host); err != nil {
|
||||
return fmt.Errorf("failed to save host: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Printf("✓ Host '%s' added successfully!\n", name)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAddCommandExists(t *testing.T) {
|
||||
if addCmd == nil {
|
||||
t.Fatal("addCmd should not be nil")
|
||||
}
|
||||
|
||||
if addCmd.Use != "add [name]" {
|
||||
t.Errorf("expected Use 'add [name]', got '%s'", addCmd.Use)
|
||||
}
|
||||
|
||||
if addCmd.Short == "" {
|
||||
t.Error("Short description should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddCommandFlags(t *testing.T) {
|
||||
expectedFlags := []string{"host", "port", "user", "password", "key", "auth-type", "group", "tags", "notes"}
|
||||
for _, flagName := range expectedFlags {
|
||||
if addCmd.Flags().Lookup(flagName) == nil {
|
||||
t.Errorf("flag '%s' should be defined", flagName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddCommandValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
hostFlag string
|
||||
userFlag string
|
||||
passFlag string
|
||||
wantError bool
|
||||
errContains string
|
||||
}{
|
||||
{
|
||||
name: "missing hostname",
|
||||
args: []string{"myserver"},
|
||||
userFlag: "admin",
|
||||
passFlag: "pass",
|
||||
wantError: true,
|
||||
errContains: "hostname is required",
|
||||
},
|
||||
{
|
||||
name: "missing username",
|
||||
args: []string{"myserver"},
|
||||
hostFlag: "192.168.1.10",
|
||||
passFlag: "pass",
|
||||
wantError: true,
|
||||
errContains: "username is required",
|
||||
},
|
||||
{
|
||||
name: "missing auth",
|
||||
args: []string{"myserver"},
|
||||
hostFlag: "192.168.1.10",
|
||||
userFlag: "admin",
|
||||
wantError: true,
|
||||
errContains: "authentication is required",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Reset flags
|
||||
addHostname = tt.hostFlag
|
||||
addUser = tt.userFlag
|
||||
addPassword = tt.passFlag
|
||||
addPort = 0
|
||||
addKeyPath = ""
|
||||
addAuthType = ""
|
||||
addGroup = ""
|
||||
addTags = nil
|
||||
addNotes = ""
|
||||
|
||||
// Set HOME to temp dir to avoid polluting real config
|
||||
t.Setenv("HOME", "/tmp/hostkeeper-test-nonexistent")
|
||||
|
||||
err := runAddHost(addCmd, tt.args)
|
||||
|
||||
if tt.wantError && err == nil {
|
||||
t.Errorf("expected error but got none")
|
||||
}
|
||||
if !tt.wantError && err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
if tt.errContains != "" && err != nil {
|
||||
if !contains(err.Error(), tt.errContains) {
|
||||
t.Errorf("error should contain '%s', got '%s'", tt.errContains, err.Error())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion [bash|zsh|fish|powershell]",
|
||||
Short: "Generate shell completion script",
|
||||
Long: `Generate shell completion script for hostkeeper.
|
||||
|
||||
To load completions:
|
||||
|
||||
Bash:
|
||||
$ source <(hostkeeper completion bash)
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
# Linux:
|
||||
$ hostkeeper completion bash > /etc/bash_completion.d/hostkeeper
|
||||
# macOS:
|
||||
$ hostkeeper completion bash > /usr/local/etc/bash_completion.d/hostkeeper
|
||||
|
||||
Zsh:
|
||||
# If shell completion is not already enabled in your environment,
|
||||
# you will need to enable it. You can execute the following once:
|
||||
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ hostkeeper completion zsh > "${fpath[1]}/_hostkeeper"
|
||||
|
||||
# You will need to start a new shell for this setup to take effect.
|
||||
|
||||
fish:
|
||||
$ hostkeeper completion fish | source
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ hostkeeper completion fish > ~/.config/fish/completions/hostkeeper.fish
|
||||
|
||||
PowerShell:
|
||||
PS> hostkeeper completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
# To load completions for every new session, run:
|
||||
PS> hostkeeper completion powershell > hostkeeper.ps1
|
||||
# and source this file from your PowerShell profile.
|
||||
`,
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
|
||||
Args: cobra.ExactValidArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
switch args[0] {
|
||||
case "bash":
|
||||
_ = cmd.Root().GenBashCompletion(os.Stdout)
|
||||
case "zsh":
|
||||
_ = cmd.Root().GenZshCompletion(os.Stdout)
|
||||
case "fish":
|
||||
_ = cmd.Root().GenFishCompletion(os.Stdout, true)
|
||||
case "powershell":
|
||||
_ = cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(completionCmd)
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/errors"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/ssh"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
connectTimeout int
|
||||
connectNative bool
|
||||
)
|
||||
|
||||
// connectCmd represents the connect command
|
||||
var connectCmd = &cobra.Command{
|
||||
Use: "connect <host-name-or-id>",
|
||||
Short: "Connect to a saved SSH host",
|
||||
Long: `Connect to a saved SSH host using stored credentials.
|
||||
|
||||
Examples:
|
||||
# Connect to a host by name
|
||||
hostkeeper connect myserver
|
||||
|
||||
# Connect with a specific timeout
|
||||
hostkeeper connect myserver --timeout 60
|
||||
|
||||
# Use native system SSH instead of Go SSH client
|
||||
hostkeeper connect myserver --native`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: runConnect,
|
||||
}
|
||||
|
||||
func init() {
|
||||
connectCmd.Flags().IntVar(&connectTimeout, "timeout", 30, "Connection timeout in seconds")
|
||||
connectCmd.Flags().BoolVar(&connectNative, "native", false, "Use native system SSH instead of Go SSH client")
|
||||
|
||||
rootCmd.AddCommand(connectCmd)
|
||||
}
|
||||
|
||||
func runConnect(cmd *cobra.Command, args []string) error {
|
||||
hostIdentifier := args[0]
|
||||
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize storage
|
||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Find host by name or ID
|
||||
host, err := findHost(ctx, store, hostIdentifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("Connecting to %s (%s@%s:%d)...\n", host.Name, host.Username, host.Hostname, host.Port)
|
||||
|
||||
// Choose connection method
|
||||
if connectNative {
|
||||
return connectWithNativeSSH(host)
|
||||
}
|
||||
|
||||
return connectDirectSSH(host)
|
||||
}
|
||||
|
||||
// findHost finds a host by ID first, then by name
|
||||
func findHost(ctx context.Context, store storage.Storage, identifier string) (*models.Host, error) {
|
||||
// Try to find by ID first
|
||||
host, err := store.GetHost(ctx, identifier)
|
||||
if err == nil {
|
||||
return host, nil
|
||||
}
|
||||
|
||||
// Try to find by name
|
||||
hosts, err := store.ListHosts(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list hosts: %w", err)
|
||||
}
|
||||
|
||||
for _, h := range hosts {
|
||||
if h.Name == identifier {
|
||||
return h, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Try to find by hostname
|
||||
for _, h := range hosts {
|
||||
if h.Hostname == identifier {
|
||||
return h, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Try to find by ID prefix (short ID match)
|
||||
for _, h := range hosts {
|
||||
if len(h.ID) >= 8 && h.ID[:8] == identifier {
|
||||
return h, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Host not found, provide helpful error
|
||||
msg := fmt.Sprintf("host '%s' not found. Use 'hostkeeper list' to see available hosts", identifier)
|
||||
if strings.Contains(identifier, " ") {
|
||||
msg += fmt.Sprintf("\nHint: if the host name contains spaces, quote it: connect \"%s\"", identifier)
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
|
||||
// connectWithNativeSSH uses the system SSH client
|
||||
func connectWithNativeSSH(host *models.Host) error {
|
||||
sshArgs := buildSSHArgs(host)
|
||||
|
||||
cmd := exec.Command("ssh", sshArgs...)
|
||||
|
||||
// Set up standard I/O for interactive session
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
// Execute SSH command
|
||||
if err := cmd.Run(); err != nil {
|
||||
return errors.HandleSSHError(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// connectDirectSSH uses Go SSH client
|
||||
func connectDirectSSH(host *models.Host) error {
|
||||
timeout := time.Duration(connectTimeout) * time.Second
|
||||
client := ssh.NewClient(host, timeout)
|
||||
|
||||
ctx := context.Background()
|
||||
if err := client.Connect(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
fmt.Printf("Connected to %s (%s@%s:%d)\n", host.Name, host.Username, host.Hostname, host.Port)
|
||||
|
||||
if err := client.Shell(); err != nil {
|
||||
return fmt.Errorf("shell session failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildSSHArgs builds SSH command arguments for the system SSH client
|
||||
func buildSSHArgs(host *models.Host) []string {
|
||||
var args []string
|
||||
|
||||
// Add port if not default
|
||||
if host.Port != 22 && host.Port != 0 {
|
||||
args = append(args, "-p", fmt.Sprintf("%d", host.Port))
|
||||
}
|
||||
|
||||
// Add connection string
|
||||
connectionString := fmt.Sprintf("%s@%s", host.Username, host.Hostname)
|
||||
args = append(args, connectionString)
|
||||
|
||||
return args
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
func TestConnectCommandExists(t *testing.T) {
|
||||
if connectCmd == nil {
|
||||
t.Fatal("connectCmd should not be nil")
|
||||
}
|
||||
|
||||
if connectCmd.Use != "connect <host-name-or-id>" {
|
||||
t.Errorf("expected Use 'connect <host-name-or-id>', got '%s'", connectCmd.Use)
|
||||
}
|
||||
|
||||
if connectCmd.Short == "" {
|
||||
t.Error("Short description should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectCommandFlags(t *testing.T) {
|
||||
expectedFlags := []string{"timeout", "native"}
|
||||
for _, flagName := range expectedFlags {
|
||||
if connectCmd.Flags().Lookup(flagName) == nil {
|
||||
t.Errorf("flag '%s' should be defined", flagName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectArgs(t *testing.T) {
|
||||
if connectCmd.Args == nil {
|
||||
t.Error("Args validator should not be nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSSHArgs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
host *models.Host
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "default port 22",
|
||||
host: &models.Host{
|
||||
Name: "test",
|
||||
Hostname: "192.168.1.1",
|
||||
Port: 22,
|
||||
Username: "admin",
|
||||
},
|
||||
want: []string{"admin@192.168.1.1"},
|
||||
},
|
||||
{
|
||||
name: "non-default port 2222",
|
||||
host: &models.Host{
|
||||
Name: "test",
|
||||
Hostname: "192.168.1.1",
|
||||
Port: 2222,
|
||||
Username: "admin",
|
||||
},
|
||||
want: []string{"-p", "2222", "admin@192.168.1.1"},
|
||||
},
|
||||
{
|
||||
name: "key auth with KeyID",
|
||||
host: &models.Host{
|
||||
Name: "test",
|
||||
Hostname: "10.0.0.1",
|
||||
Port: 22,
|
||||
Username: "root",
|
||||
Auth: models.AuthConfig{
|
||||
Type: "key",
|
||||
KeyID: "~/.ssh/id_rsa",
|
||||
},
|
||||
},
|
||||
want: []string{"root@10.0.0.1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := buildSSHArgs(tt.host)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Errorf("buildSSHArgs() = %v, want %v", got, tt.want)
|
||||
return
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Errorf("buildSSHArgs() = %v, want %v", got, tt.want)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
)
|
||||
|
||||
var deleteForce bool
|
||||
|
||||
// deleteCmd represents the delete command
|
||||
var deleteCmd = &cobra.Command{
|
||||
Use: "delete <host-name-or-id>",
|
||||
Short: "Delete a saved SSH host",
|
||||
Long: `Delete a saved SSH host from HostKeeper.
|
||||
|
||||
You will be prompted for confirmation unless --force is used.
|
||||
|
||||
Examples:
|
||||
# Delete a host with confirmation
|
||||
hostkeeper delete myserver
|
||||
|
||||
# Delete without confirmation
|
||||
hostkeeper delete myserver --force`,
|
||||
Aliases: []string{"rm"},
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: runDeleteHost,
|
||||
}
|
||||
|
||||
func init() {
|
||||
deleteCmd.Flags().BoolVar(&deleteForce, "force", false, "delete without confirmation")
|
||||
|
||||
rootCmd.AddCommand(deleteCmd)
|
||||
}
|
||||
|
||||
func runDeleteHost(cmd *cobra.Command, args []string) error {
|
||||
hostIdentifier := args[0]
|
||||
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
store, err := newStorage(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
host, err := findHost(ctx, store, hostIdentifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Confirm deletion unless --force is used
|
||||
if !deleteForce {
|
||||
fmt.Printf("Are you sure you want to delete host '%s' (%s@%s:%d)? [y/N]: ",
|
||||
host.Name, host.Username, host.Hostname, host.Port)
|
||||
var response string
|
||||
fmt.Scanln(&response)
|
||||
if response != "y" && response != "Y" && response != "yes" {
|
||||
fmt.Println("Deletion cancelled.")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := store.DeleteHost(ctx, host.ID); err != nil {
|
||||
return fmt.Errorf("failed to delete host: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("✓ Host '%s' deleted successfully\n", host.Name)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDeleteCommandExists(t *testing.T) {
|
||||
if deleteCmd == nil {
|
||||
t.Fatal("deleteCmd should not be nil")
|
||||
}
|
||||
|
||||
if deleteCmd.Use != "delete <host-name-or-id>" {
|
||||
t.Errorf("expected Use 'delete <host-name-or-id>', got '%s'", deleteCmd.Use)
|
||||
}
|
||||
|
||||
if deleteCmd.Short == "" {
|
||||
t.Error("Short description should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteCommandFlags(t *testing.T) {
|
||||
expectedFlags := []string{"force"}
|
||||
for _, flagName := range expectedFlags {
|
||||
if deleteCmd.Flags().Lookup(flagName) == nil {
|
||||
t.Errorf("flag '%s' should be defined", flagName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteArgs(t *testing.T) {
|
||||
if deleteCmd.Args == nil {
|
||||
t.Error("Args validator should not be nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
editHostname string
|
||||
editPort int
|
||||
editUser string
|
||||
editPassword string
|
||||
editKeyPath string
|
||||
editAuthType string
|
||||
editGroup string
|
||||
editTags []string
|
||||
editNotes string
|
||||
editName string
|
||||
)
|
||||
|
||||
// editCmd represents the edit command
|
||||
var editCmd = &cobra.Command{
|
||||
Use: "edit <host-name-or-id>",
|
||||
Short: "Edit a saved SSH host",
|
||||
Long: `Edit an existing SSH host configuration in HostKeeper.
|
||||
|
||||
You can update fields using flags or interactively.
|
||||
|
||||
Examples:
|
||||
# Edit hostname and port
|
||||
hostkeeper edit myserver --host 10.0.0.1 --port 2222
|
||||
|
||||
# Change username and auth
|
||||
hostkeeper edit myserver --user root --auth-type key
|
||||
|
||||
# Edit interactively
|
||||
hostkeeper edit myserver`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: runEditHost,
|
||||
}
|
||||
|
||||
func init() {
|
||||
editCmd.Flags().StringVar(&editHostname, "host", "", "new hostname or IP address")
|
||||
editCmd.Flags().IntVar(&editPort, "port", 0, "new SSH port")
|
||||
editCmd.Flags().StringVar(&editUser, "user", "", "new SSH username")
|
||||
editCmd.Flags().StringVar(&editPassword, "password", "", "new SSH password")
|
||||
editCmd.Flags().StringVar(&editKeyPath, "key", "", "new path to SSH private key")
|
||||
editCmd.Flags().StringVar(&editAuthType, "auth-type", "", "new authentication type: password, key, or both")
|
||||
editCmd.Flags().StringVar(&editGroup, "group", "", "new host group")
|
||||
editCmd.Flags().StringSliceVar(&editTags, "tags", nil, "new tags (comma-separated)")
|
||||
editCmd.Flags().StringVar(&editNotes, "notes", "", "new notes")
|
||||
editCmd.Flags().StringVar(&editName, "name", "", "new host name")
|
||||
|
||||
rootCmd.AddCommand(editCmd)
|
||||
}
|
||||
|
||||
func runEditHost(cmd *cobra.Command, args []string) error {
|
||||
hostIdentifier := args[0]
|
||||
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
store, err := newStorage(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
host, err := findHost(ctx, store, hostIdentifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check if any flags were provided
|
||||
flagProvided := cmd.Flags().Changed("host") || cmd.Flags().Changed("port") ||
|
||||
cmd.Flags().Changed("user") || cmd.Flags().Changed("password") ||
|
||||
cmd.Flags().Changed("key") || cmd.Flags().Changed("auth-type") ||
|
||||
cmd.Flags().Changed("group") || cmd.Flags().Changed("tags") ||
|
||||
cmd.Flags().Changed("notes") || cmd.Flags().Changed("name")
|
||||
|
||||
if !flagProvided {
|
||||
return editHostInteractive(cfg, store, host)
|
||||
}
|
||||
|
||||
// Apply flag-based updates
|
||||
if cmd.Flags().Changed("host") {
|
||||
host.Hostname = editHostname
|
||||
}
|
||||
if cmd.Flags().Changed("port") {
|
||||
if editPort > 0 {
|
||||
host.Port = editPort
|
||||
} else {
|
||||
host.Port = cfg.GetAppConfig().DefaultPort
|
||||
}
|
||||
}
|
||||
if cmd.Flags().Changed("user") {
|
||||
host.Username = editUser
|
||||
}
|
||||
if cmd.Flags().Changed("password") {
|
||||
host.Auth.Password = editPassword
|
||||
}
|
||||
if cmd.Flags().Changed("auth-type") {
|
||||
host.Auth.Type = editAuthType
|
||||
}
|
||||
if cmd.Flags().Changed("key") {
|
||||
data, err := os.ReadFile(editKeyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read key file: %w", err)
|
||||
}
|
||||
host.Auth.Password = string(data)
|
||||
}
|
||||
if cmd.Flags().Changed("group") {
|
||||
host.Group = editGroup
|
||||
}
|
||||
if cmd.Flags().Changed("tags") {
|
||||
host.Tags = editTags
|
||||
}
|
||||
if cmd.Flags().Changed("notes") {
|
||||
host.Notes = editNotes
|
||||
}
|
||||
if cmd.Flags().Changed("name") {
|
||||
host.Name = editName
|
||||
}
|
||||
|
||||
host.UpdatedAt = time.Now()
|
||||
|
||||
if err := store.SaveHost(ctx, host); err != nil {
|
||||
return fmt.Errorf("failed to update host: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("✓ Host '%s' updated successfully\n", host.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func editHostInteractive(cfg *config.Config, store *storage.JSONStorage, host *models.Host) error {
|
||||
fmt.Println("╔══════════════════════════════════════╗")
|
||||
fmt.Println("║ Edit SSH Host ║")
|
||||
fmt.Println("╚══════════════════════════════════════╝")
|
||||
fmt.Println()
|
||||
fmt.Println("Press Enter to keep the current value.")
|
||||
fmt.Println()
|
||||
|
||||
// Name
|
||||
fmt.Printf("Host Name [%s]: ", host.Name)
|
||||
var name string
|
||||
fmt.Scanln(&name)
|
||||
if name != "" {
|
||||
host.Name = name
|
||||
}
|
||||
|
||||
// Hostname
|
||||
fmt.Printf("Hostname or IP [%s]: ", host.Hostname)
|
||||
var hostname string
|
||||
fmt.Scanln(&hostname)
|
||||
if hostname != "" {
|
||||
host.Hostname = hostname
|
||||
}
|
||||
|
||||
// Port
|
||||
defaultPort := cfg.GetAppConfig().DefaultPort
|
||||
fmt.Printf("Port [%d]: ", host.Port)
|
||||
var portInput string
|
||||
fmt.Scanln(&portInput)
|
||||
if portInput != "" {
|
||||
fmt.Sscanf(portInput, "%d", &host.Port)
|
||||
} else if host.Port == 0 {
|
||||
host.Port = defaultPort
|
||||
}
|
||||
|
||||
// Username
|
||||
fmt.Printf("Username [%s]: ", host.Username)
|
||||
var username string
|
||||
fmt.Scanln(&username)
|
||||
if username != "" {
|
||||
host.Username = username
|
||||
}
|
||||
|
||||
// Auth type
|
||||
currentAuth := host.Auth.Type
|
||||
if currentAuth == "" {
|
||||
currentAuth = "password"
|
||||
}
|
||||
fmt.Printf("Auth Type (password/key/both) [%s]: ", currentAuth)
|
||||
var authType string
|
||||
fmt.Scanln(&authType)
|
||||
if authType != "" {
|
||||
host.Auth.Type = authType
|
||||
} else {
|
||||
host.Auth.Type = currentAuth
|
||||
}
|
||||
|
||||
// Password
|
||||
if host.Auth.Type == "password" || host.Auth.Type == "both" {
|
||||
prompt := "Password"
|
||||
if host.Auth.Password != "" {
|
||||
prompt += " [********]"
|
||||
}
|
||||
fmt.Printf("%s: ", prompt)
|
||||
var password string
|
||||
fmt.Scanln(&password)
|
||||
if password != "" {
|
||||
host.Auth.Password = password
|
||||
}
|
||||
}
|
||||
|
||||
// Key path
|
||||
if host.Auth.Type == "key" || host.Auth.Type == "both" {
|
||||
fmt.Printf("Path to private key: ")
|
||||
var keyPath string
|
||||
fmt.Scanln(&keyPath)
|
||||
if keyPath != "" {
|
||||
data, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read key file: %w", err)
|
||||
}
|
||||
host.Auth.Password = string(data)
|
||||
}
|
||||
}
|
||||
|
||||
// Group
|
||||
fmt.Printf("Group [%s]: ", host.Group)
|
||||
var group string
|
||||
fmt.Scanln(&group)
|
||||
if group != "" {
|
||||
host.Group = group
|
||||
}
|
||||
|
||||
// Tags
|
||||
currentTags := strings.Join(host.Tags, ",")
|
||||
fmt.Printf("Tags (comma-separated) [%s]: ", currentTags)
|
||||
var tagsInput string
|
||||
fmt.Scanln(&tagsInput)
|
||||
if tagsInput != "" {
|
||||
tags := strings.Split(tagsInput, ",")
|
||||
for i, t := range tags {
|
||||
tags[i] = strings.TrimSpace(t)
|
||||
}
|
||||
host.Tags = tags
|
||||
}
|
||||
|
||||
// Notes
|
||||
fmt.Printf("Notes [%s]: ", host.Notes)
|
||||
var notes string
|
||||
fmt.Scanln(¬es)
|
||||
if notes != "" {
|
||||
host.Notes = notes
|
||||
}
|
||||
|
||||
host.UpdatedAt = time.Now()
|
||||
|
||||
ctx := context.Background()
|
||||
if err := store.SaveHost(ctx, host); err != nil {
|
||||
return fmt.Errorf("failed to update host: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Printf("✓ Host '%s' updated successfully!\n", host.Name)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEditCommandExists(t *testing.T) {
|
||||
if editCmd == nil {
|
||||
t.Fatal("editCmd should not be nil")
|
||||
}
|
||||
|
||||
if editCmd.Use != "edit <host-name-or-id>" {
|
||||
t.Errorf("expected Use 'edit <host-name-or-id>', got '%s'", editCmd.Use)
|
||||
}
|
||||
|
||||
if editCmd.Short == "" {
|
||||
t.Error("Short description should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditCommandFlags(t *testing.T) {
|
||||
expectedFlags := []string{"host", "port", "user", "password", "key", "auth-type", "group", "tags", "notes", "name"}
|
||||
for _, flagName := range expectedFlags {
|
||||
if editCmd.Flags().Lookup(flagName) == nil {
|
||||
t.Errorf("flag '%s' should be defined", flagName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditArgs(t *testing.T) {
|
||||
if editCmd.Args == nil {
|
||||
t.Error("Args validator should not be nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
exportFormat string
|
||||
exportIncludeKeys bool
|
||||
)
|
||||
|
||||
// exportCmd represents the export command
|
||||
var exportCmd = &cobra.Command{
|
||||
Use: "export [filename]",
|
||||
Short: "Export hosts and credentials to file",
|
||||
Long: `Export all saved hosts, SSH keys, snippets to a file for backup or transfer.
|
||||
|
||||
Examples:
|
||||
# Export to default file
|
||||
hostkeeper export my-backup
|
||||
|
||||
# Export with .json extension
|
||||
hostkeeper export my-backup.json`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: runExport,
|
||||
}
|
||||
|
||||
func init() {
|
||||
exportCmd.Flags().StringVar(&exportFormat, "format", "json", "Export format (json)")
|
||||
exportCmd.Flags().BoolVar(&exportIncludeKeys, "include-keys", true, "Include SSH keys in export")
|
||||
|
||||
rootCmd.AddCommand(exportCmd)
|
||||
}
|
||||
|
||||
func runExport(cmd *cobra.Command, args []string) error {
|
||||
filename := args[0]
|
||||
|
||||
if filepath.Ext(filename) != ".json" {
|
||||
filename = filename + ".json"
|
||||
}
|
||||
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
data, err := store.ExportData(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to export data: %w", err)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal export data: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(filename, jsonBytes, 0600); err != nil {
|
||||
return fmt.Errorf("failed to write export file: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Export successful!\n")
|
||||
fmt.Printf(" File: %s\n", filename)
|
||||
fmt.Printf(" Hosts: %d\n", len(data.Hosts))
|
||||
fmt.Printf(" Keys: %d\n", len(data.KeyPairs))
|
||||
fmt.Printf(" Snippets: %d\n", len(data.Snippets))
|
||||
fmt.Printf(" Size: %.2f KB\n", float64(len(jsonBytes))/1024)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
importMergeStrategy string
|
||||
importDryRun bool
|
||||
)
|
||||
|
||||
// importCmd represents the import command
|
||||
var importCmd = &cobra.Command{
|
||||
Use: "import <filename>",
|
||||
Short: "Import hosts and credentials from file",
|
||||
Long: `Import hosts, SSH keys, snippets from a previously exported file.
|
||||
|
||||
Merge strategies:
|
||||
replace Replace all existing data with imported data
|
||||
merge Keep existing data, add only new items
|
||||
|
||||
Examples:
|
||||
# Import with merge (default)
|
||||
hostkeeper import my-backup.json
|
||||
|
||||
# Import replacing all existing data
|
||||
hostkeeper import my-backup.json --strategy replace
|
||||
|
||||
# Preview without importing
|
||||
hostkeeper import my-backup.json --dry-run`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: runImport,
|
||||
}
|
||||
|
||||
func init() {
|
||||
importCmd.Flags().StringVar(&importMergeStrategy, "strategy", "merge", "Merge strategy: replace or merge")
|
||||
importCmd.Flags().BoolVar(&importDryRun, "dry-run", false, "Show what would be imported without actually importing")
|
||||
|
||||
rootCmd.AddCommand(importCmd)
|
||||
}
|
||||
|
||||
func runImport(cmd *cobra.Command, args []string) error {
|
||||
filename := args[0]
|
||||
|
||||
if _, err := os.Stat(filename); os.IsNotExist(err) {
|
||||
return fmt.Errorf("file not found: %s", filename)
|
||||
}
|
||||
|
||||
jsonBytes, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read import file: %w", err)
|
||||
}
|
||||
|
||||
var data storage.ExportData
|
||||
if err := json.Unmarshal(jsonBytes, &data); err != nil {
|
||||
return fmt.Errorf("failed to parse import file: %w", err)
|
||||
}
|
||||
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if importDryRun {
|
||||
return previewImport(&data, filename)
|
||||
}
|
||||
|
||||
// Map strategy string to MergeStrategy type
|
||||
var strategy storage.MergeStrategy
|
||||
switch importMergeStrategy {
|
||||
case "replace":
|
||||
strategy = storage.MergeStrategyReplace
|
||||
case "merge":
|
||||
strategy = storage.MergeStrategyMerge
|
||||
default:
|
||||
return fmt.Errorf("invalid strategy: %s (use 'replace' or 'merge')", importMergeStrategy)
|
||||
}
|
||||
|
||||
if err := store.ImportData(ctx, &data, strategy); err != nil {
|
||||
return fmt.Errorf("failed to import data: %w", err)
|
||||
}
|
||||
|
||||
hosts, _ := store.ListHosts(ctx)
|
||||
keys, _ := store.ListKeyPairs(ctx)
|
||||
snippets, _ := store.ListSnippets(ctx)
|
||||
|
||||
fmt.Printf("Import successful!\n")
|
||||
fmt.Printf(" Strategy: %s\n", importMergeStrategy)
|
||||
fmt.Printf(" Total Hosts: %d\n", len(hosts))
|
||||
fmt.Printf(" Total Keys: %d\n", len(keys))
|
||||
fmt.Printf(" Total Snippets: %d\n", len(snippets))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func previewImport(data *storage.ExportData, filename string) error {
|
||||
fmt.Println("Import Preview (Dry Run)")
|
||||
fmt.Println("------------------------")
|
||||
fmt.Printf("File: %s\n", filename)
|
||||
fmt.Printf("Hosts: %d\n", len(data.Hosts))
|
||||
fmt.Printf("Keys: %d\n", len(data.KeyPairs))
|
||||
fmt.Printf("Snippets: %d\n", len(data.Snippets))
|
||||
fmt.Printf("Strategy: %s\n\n", importMergeStrategy)
|
||||
|
||||
fmt.Println("To perform the import, run:")
|
||||
fmt.Printf(" hostkeeper import %s --strategy %s\n", filename, importMergeStrategy)
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
)
|
||||
|
||||
var (
|
||||
listGroup string
|
||||
listTag string
|
||||
listFormat string
|
||||
listSort string
|
||||
)
|
||||
|
||||
// listCmd represents the list command
|
||||
var listCmd = &cobra.Command{
|
||||
Use: "list",
|
||||
Aliases: []string{"ls"},
|
||||
Short: "List all saved SSH hosts",
|
||||
Long: `List all SSH hosts saved in HostKeeper.
|
||||
|
||||
You can filter by group or tag, and format the output as table or json.
|
||||
|
||||
Examples:
|
||||
# List all hosts
|
||||
hostkeeper list
|
||||
|
||||
# List hosts in a specific group
|
||||
hostkeeper list --group production
|
||||
|
||||
# List hosts with a specific tag
|
||||
hostkeeper list --tag web
|
||||
|
||||
# Output in JSON format
|
||||
hostkeeper list --format json
|
||||
|
||||
# Sort by name
|
||||
hostkeeper list --sort name`,
|
||||
RunE: runListHosts,
|
||||
}
|
||||
|
||||
func init() {
|
||||
listCmd.Flags().StringVar(&listGroup, "group", "", "filter hosts by group")
|
||||
listCmd.Flags().StringVar(&listTag, "tag", "", "filter hosts by tag")
|
||||
listCmd.Flags().StringVar(&listFormat, "format", "table", "output format: table or json")
|
||||
listCmd.Flags().StringVar(&listSort, "sort", "name", "sort by: name, hostname, or group")
|
||||
|
||||
rootCmd.AddCommand(listCmd)
|
||||
}
|
||||
|
||||
func runListHosts(cmd *cobra.Command, args []string) error {
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize storage
|
||||
store, err := newStorage(cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
// Get all hosts
|
||||
ctx := context.Background()
|
||||
hosts, err := store.ListHosts(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list hosts: %w", err)
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
if listGroup != "" {
|
||||
hosts = filterByGroup(hosts, listGroup)
|
||||
}
|
||||
if listTag != "" {
|
||||
hosts = filterByTag(hosts, listTag)
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
sortHosts(hosts, listSort)
|
||||
|
||||
// Output
|
||||
if len(hosts) == 0 {
|
||||
fmt.Println("No hosts found.")
|
||||
fmt.Println()
|
||||
fmt.Println("Add a host with: hostkeeper add [name] --host <hostname> --user <username>")
|
||||
return nil
|
||||
}
|
||||
|
||||
switch listFormat {
|
||||
case "json":
|
||||
return outputJSON(hosts)
|
||||
case "table":
|
||||
return outputTable(hosts)
|
||||
default:
|
||||
return fmt.Errorf("unsupported format: %s (use 'table' or 'json')", listFormat)
|
||||
}
|
||||
}
|
||||
|
||||
func filterByGroup(hosts []*models.Host, group string) []*models.Host {
|
||||
var filtered []*models.Host
|
||||
for _, h := range hosts {
|
||||
if strings.EqualFold(h.Group, group) {
|
||||
filtered = append(filtered, h)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func filterByTag(hosts []*models.Host, tag string) []*models.Host {
|
||||
var filtered []*models.Host
|
||||
for _, h := range hosts {
|
||||
for _, t := range h.Tags {
|
||||
if strings.EqualFold(t, tag) {
|
||||
filtered = append(filtered, h)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
func sortHosts(hosts []*models.Host, sortBy string) {
|
||||
switch sortBy {
|
||||
case "hostname":
|
||||
sort.Slice(hosts, func(i, j int) bool {
|
||||
return hosts[i].Hostname < hosts[j].Hostname
|
||||
})
|
||||
case "group":
|
||||
sort.Slice(hosts, func(i, j int) bool {
|
||||
return hosts[i].Group < hosts[j].Group
|
||||
})
|
||||
default: // "name"
|
||||
sort.Slice(hosts, func(i, j int) bool {
|
||||
return hosts[i].Name < hosts[j].Name
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func shortID(id string) string {
|
||||
if len(id) >= 8 {
|
||||
return id[:8]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func outputTable(hosts []*models.Host) error {
|
||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||
|
||||
fmt.Fprintln(w, "ID\tNAME\tHOSTNAME\tPORT\tUSER\tGROUP\tAUTH\tTAGS")
|
||||
fmt.Fprintln(w, "--\t────\t────────\t────\t────\t─────\t────\t────")
|
||||
|
||||
for _, h := range hosts {
|
||||
tags := strings.Join(h.Tags, ", ")
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%d\t%s\t%s\t%s\t%s\n",
|
||||
shortID(h.ID),
|
||||
h.Name,
|
||||
h.Hostname,
|
||||
h.Port,
|
||||
h.Username,
|
||||
h.Group,
|
||||
h.Auth.Type,
|
||||
tags,
|
||||
)
|
||||
}
|
||||
|
||||
return w.Flush()
|
||||
}
|
||||
|
||||
func outputJSON(hosts []*models.Host) error {
|
||||
fmt.Print("[")
|
||||
for i, h := range hosts {
|
||||
if i > 0 {
|
||||
fmt.Print(",")
|
||||
}
|
||||
fmt.Printf(`{"id":"%s","short_id":"%s","name":"%s","hostname":"%s","port":%d,"username":"%s","group":"%s","auth_type":"%s"}`,
|
||||
h.ID, shortID(h.ID), h.Name, h.Hostname, h.Port, h.Username, h.Group, h.Auth.Type)
|
||||
}
|
||||
fmt.Println("]")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
func TestListCommandExists(t *testing.T) {
|
||||
if listCmd == nil {
|
||||
t.Fatal("listCmd should not be nil")
|
||||
}
|
||||
|
||||
if listCmd.Use != "list" {
|
||||
t.Errorf("expected Use 'list', got '%s'", listCmd.Use)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListCommandFlags(t *testing.T) {
|
||||
expectedFlags := []string{"group", "tag", "format", "sort"}
|
||||
for _, flagName := range expectedFlags {
|
||||
if listCmd.Flags().Lookup(flagName) == nil {
|
||||
t.Errorf("flag '%s' should be defined", flagName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterByGroup(t *testing.T) {
|
||||
hosts := []*models.Host{
|
||||
{Name: "web1", Group: "production"},
|
||||
{Name: "web2", Group: "staging"},
|
||||
{Name: "db1", Group: "production"},
|
||||
{Name: "cache1", Group: "staging"},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
group string
|
||||
wantLen int
|
||||
}{
|
||||
{"production", 2},
|
||||
{"staging", 2},
|
||||
{"nonexistent", 0},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.group, func(t *testing.T) {
|
||||
result := filterByGroup(hosts, tt.group)
|
||||
if len(result) != tt.wantLen {
|
||||
t.Errorf("expected %d hosts for group '%s', got %d", tt.wantLen, tt.group, len(result))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterByTag(t *testing.T) {
|
||||
hosts := []*models.Host{
|
||||
{Name: "web1", Tags: []string{"web", "frontend"}},
|
||||
{Name: "db1", Tags: []string{"database", "backend"}},
|
||||
{Name: "web2", Tags: []string{"web", "frontend"}},
|
||||
{Name: "cache1", Tags: []string{"cache", "backend"}},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
tag string
|
||||
wantLen int
|
||||
}{
|
||||
{"web", 2},
|
||||
{"database", 1},
|
||||
{"backend", 2},
|
||||
{"nonexistent", 0},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.tag, func(t *testing.T) {
|
||||
result := filterByTag(hosts, tt.tag)
|
||||
if len(result) != tt.wantLen {
|
||||
t.Errorf("expected %d hosts for tag '%s', got %d", tt.wantLen, tt.tag, len(result))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSortHosts(t *testing.T) {
|
||||
hosts := []*models.Host{
|
||||
{Name: "zebra", Hostname: "10.0.0.3", Group: "c"},
|
||||
{Name: "alpha", Hostname: "10.0.0.1", Group: "a"},
|
||||
{Name: "mike", Hostname: "10.0.0.2", Group: "b"},
|
||||
}
|
||||
|
||||
// Test sort by name
|
||||
sortHosts(hosts, "name")
|
||||
if hosts[0].Name != "alpha" {
|
||||
t.Errorf("expected first host to be 'alpha' when sorted by name, got '%s'", hosts[0].Name)
|
||||
}
|
||||
|
||||
// Test sort by hostname
|
||||
sortHosts(hosts, "hostname")
|
||||
if hosts[0].Hostname != "10.0.0.1" {
|
||||
t.Errorf("expected first host to have hostname '10.0.0.1' when sorted by hostname, got '%s'", hosts[0].Hostname)
|
||||
}
|
||||
|
||||
// Test sort by group
|
||||
sortHosts(hosts, "group")
|
||||
if hosts[0].Group != "a" {
|
||||
t.Errorf("expected first host to have group 'a' when sorted by group, got '%s'", hosts[0].Group)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "dev"
|
||||
buildTime = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// SSH_ASKPASS support: hostkeeper askpass
|
||||
// Called by the SSH_ASKPASS script we create for key passphrases.
|
||||
if len(os.Args) == 2 && os.Args[1] == "askpass" {
|
||||
fmt.Print(os.Getenv("HK_PASSPHRASE"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := Execute(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
cfgFile string
|
||||
appCfg *config.Config
|
||||
verbose int
|
||||
debug bool
|
||||
passwordFlag string
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "hostkeeper",
|
||||
Short: "Cross-platform SSH/SFTP management tool",
|
||||
Long: `Hostkeeper - Cross-platform SSH/SFTP Management Tool
|
||||
|
||||
A comprehensive SSH/SFTP management tool with secure credential storage,
|
||||
host management, and cross-device sync capabilities.
|
||||
|
||||
Quick Start:
|
||||
hostkeeper add myserver --host 192.168.1.10 --user admin
|
||||
hostkeeper list
|
||||
hostkeeper connect myserver
|
||||
|
||||
For more information, visit the project repository.`,
|
||||
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
// Initialize configuration
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
appCfg = cfg
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is platform-specific app dir)")
|
||||
rootCmd.PersistentFlags().CountVarP(&verbose, "verbose", "v", "verbose output (-v for info, -vv for debug)")
|
||||
rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "enable debug mode")
|
||||
rootCmd.PersistentFlags().StringVar(&passwordFlag, "password", "", "master password for encrypted storage")
|
||||
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
// initConfig reads in config file and ENV variables if set
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Use platform-specific config directory
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
viper.AddConfigPath(cfg.GetConfigDir())
|
||||
viper.SetConfigType("json")
|
||||
viper.SetConfigName("config")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv()
|
||||
|
||||
// Read config file (ignore if not found for first run)
|
||||
_ = viper.ReadInConfig()
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `Print the version and build information for HostKeeper.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("hostkeeper %s (built: %s)\n", version, buildTime)
|
||||
},
|
||||
}
|
||||
|
||||
// Execute runs the root command
|
||||
func Execute() error {
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
|
||||
// newStorage creates a new JSONStorage with the password flag applied
|
||||
func newStorage(cfg *config.Config) (*storage.JSONStorage, error) {
|
||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if passwordFlag != "" {
|
||||
store.SetPassword(passwordFlag)
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/knownhosts"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||
)
|
||||
|
||||
var encryptFlag bool
|
||||
|
||||
// tuiCmd represents the tui command
|
||||
var tuiCmd = &cobra.Command{
|
||||
Use: "tui",
|
||||
Short: "Launch terminal user interface",
|
||||
Long: `Launch an interactive terminal user interface for managing SSH hosts and connections.`,
|
||||
RunE: runTUI,
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(tuiCmd)
|
||||
tuiCmd.Flags().BoolVar(&encryptFlag, "encrypt", false, "Enable AES-256-GCM encryption for sensitive data")
|
||||
}
|
||||
|
||||
func runTUI(cmd *cobra.Command, args []string) error {
|
||||
cfg := appCfg
|
||||
if cfg == nil {
|
||||
var err error
|
||||
cfg, err = config.New()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize config: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||
}
|
||||
|
||||
// Initialize known_hosts
|
||||
kh, err := knownhosts.New(cfg.GetDataDir())
|
||||
if err != nil {
|
||||
fmt.Printf("Warning: failed to load known_hosts: %v\n", err)
|
||||
}
|
||||
|
||||
// Auto-detect encrypted data files
|
||||
needPassword := encryptFlag || store.IsDataEncrypted()
|
||||
|
||||
model := tui.New()
|
||||
model.SetDataDir(cfg.GetDataDir())
|
||||
if kh != nil {
|
||||
model.SetKnownHosts(kh)
|
||||
}
|
||||
|
||||
if needPassword {
|
||||
// Show password prompt first — hosts will be loaded after password is set
|
||||
model.ShowEncryptPrompt()
|
||||
} else {
|
||||
// No encryption — load hosts normally
|
||||
ctx := context.Background()
|
||||
hosts, err := store.ListHosts(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load hosts: %w", err)
|
||||
}
|
||||
model.LoadHosts(hosts)
|
||||
}
|
||||
|
||||
p := tea.NewProgram(model)
|
||||
model.SetProgram(p)
|
||||
if _, err := p.Run(); err != nil {
|
||||
return fmt.Errorf("failed to run TUI: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
# Architecture
|
||||
|
||||
## Overview
|
||||
|
||||
Hostkeeper follows a layered architecture:
|
||||
|
||||
```
|
||||
CLI Layer (cmd/hostkeeper/)
|
||||
|
|
||||
| calls
|
||||
v
|
||||
Application Layer (pkg/)
|
||||
|
|
||||
| calls
|
||||
v
|
||||
Storage Layer (pkg/config/, pkg/storage/)
|
||||
|
|
||||
| reads/writes
|
||||
v
|
||||
File System (~/.config/hostkeeper/)
|
||||
```
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
cmd/hostkeeper/ — CLI commands (Cobra)
|
||||
├── main.go — Entry point
|
||||
├── root.go — Root command setup
|
||||
├── add.go — Add host command
|
||||
├── list.go — List hosts command
|
||||
├── connect.go — Connect command
|
||||
├── edit.go — Edit host command
|
||||
├── delete.go — Delete host command
|
||||
├── export.go — Export command
|
||||
├── import.go — Import command
|
||||
├── tui.go — TUI command entry
|
||||
├── version.go — Version command
|
||||
├── completion.go — Shell completion
|
||||
└── *_test.go — CLI command tests
|
||||
|
||||
pkg/ — Library code
|
||||
├── config/ — Configuration and data directory
|
||||
├── models/ — Data models (Host, Key, Snippet)
|
||||
├── storage/ — File and export/import operations
|
||||
├── errors/ — Error types
|
||||
└── tui/ — TUI implementation (Bubble Tea)
|
||||
|
||||
test/ — Test suites
|
||||
├── integration/ — End-to-end integration tests
|
||||
└── storage/ — Storage tests
|
||||
|
||||
docs/ — Documentation
|
||||
├── plans/ — Design and implementation plans
|
||||
├── INSTALLATION.md
|
||||
├── USAGE.md
|
||||
└── ARCHITECTURE.md
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
### Models (`pkg/models/`)
|
||||
|
||||
The core data structures:
|
||||
|
||||
- **Host** — SSH host with address, credentials, group, tags
|
||||
- **Key** — SSH key metadata
|
||||
- **Snippet** — Reusable connection snippets
|
||||
|
||||
### Configuration (`pkg/config/`)
|
||||
|
||||
Manages application configuration, data directory path, and initialization.
|
||||
|
||||
### Storage (`pkg/storage/`)
|
||||
|
||||
Handles persistent storage:
|
||||
- File-based JSON storage per data type
|
||||
- Export/import with replace and merge strategies
|
||||
- File permission enforcement (0600)
|
||||
|
||||
### CLI Layer (`cmd/hostkeeper/`)
|
||||
|
||||
Each command follows a consistent pattern:
|
||||
1. Parse flags
|
||||
2. Load config and storage
|
||||
3. Execute business logic
|
||||
4. Format output
|
||||
|
||||
### TUI (`pkg/tui/`)
|
||||
|
||||
Bubble Tea model with:
|
||||
- Screen-based navigation (extensible for future screens)
|
||||
- Host list view with styled output
|
||||
- Keyboard-driven interaction
|
||||
|
||||
## Data Flow
|
||||
|
||||
### Adding a Host
|
||||
|
||||
```
|
||||
User → hostkeeper add (flags) → parse args → Host model → storage.SaveHost() → JSON file
|
||||
```
|
||||
|
||||
### Connecting to a Host
|
||||
|
||||
```
|
||||
User → hostkeeper connect <name> → findHost() by ID → resolve key → exec native SSH or Go SSH
|
||||
```
|
||||
|
||||
### Export/Import
|
||||
|
||||
```
|
||||
Export: storage → marshal JSON → write file
|
||||
Import: read file → unmarshal → strategy (merge/replace) → save all
|
||||
```
|
||||
|
||||
## Security
|
||||
|
||||
- Credential files stored with `0600` permissions
|
||||
- SSH key content stored within host credentials
|
||||
- Direct mode uses Go SSH client (no shell, command execution only)
|
||||
- Native SSH mode delegates all terminal handling to system SSH
|
||||
|
||||
## Future Architecture
|
||||
|
||||
- SQLite database for improved query capabilities
|
||||
- Encrypted credential storage (age/gpg)
|
||||
- Configuration encryption
|
||||
- Plugin system for custom authentication methods
|
||||
@@ -0,0 +1,113 @@
|
||||
# Installation Guide
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Go 1.21+** — for building from source
|
||||
- **Git** — for cloning the repository
|
||||
- **Make** — optional, for build automation
|
||||
|
||||
## Installation Methods
|
||||
|
||||
### Method 1: Build from Source
|
||||
|
||||
```bash
|
||||
git clone https://git.tukangketik.id/swanadiva/HostKeeper.git
|
||||
cd hostkeeper
|
||||
make build
|
||||
sudo cp bin/hostkeeper /usr/local/bin/
|
||||
```
|
||||
|
||||
### Method 2: Go Install
|
||||
|
||||
```bash
|
||||
go install git.tukangketik.id/swanadiva/hostkeeper/cmd/hostkeeper@latest
|
||||
```
|
||||
|
||||
This installs to `$GOPATH/bin` or `$HOME/go/bin`.
|
||||
|
||||
### Method 3: Cross-Platform Build
|
||||
|
||||
```bash
|
||||
./build.sh
|
||||
```
|
||||
|
||||
Binaries will be in the `build/` directory with SHA256 checksums.
|
||||
|
||||
## Platform-Specific Instructions
|
||||
|
||||
### macOS
|
||||
|
||||
```bash
|
||||
# Install Go via Homebrew
|
||||
brew install go
|
||||
|
||||
# Build and install
|
||||
git clone https://git.tukangketik.id/swanadiva/HostKeeper.git
|
||||
cd hostkeeper
|
||||
make build
|
||||
cp bin/hostkeeper /usr/local/bin/
|
||||
```
|
||||
|
||||
### Linux (Ubuntu/Debian)
|
||||
|
||||
```bash
|
||||
# Install Go
|
||||
sudo apt update
|
||||
sudo apt install golang git make
|
||||
|
||||
# Build and install
|
||||
git clone https://git.tukangketik.id/swanadiva/HostKeeper.git
|
||||
cd hostkeeper
|
||||
make build
|
||||
sudo cp bin/hostkeeper /usr/local/bin/
|
||||
```
|
||||
|
||||
### Windows
|
||||
|
||||
```powershell
|
||||
# Install Go from https://golang.org/dl/
|
||||
# Clone repository
|
||||
git clone https://git.tukangketik.id/swanadiva/HostKeeper.git
|
||||
cd hostkeeper
|
||||
|
||||
# Build
|
||||
go build -o hostkeeper.exe ./cmd/hostkeeper
|
||||
```
|
||||
|
||||
### Termux (Android)
|
||||
|
||||
```bash
|
||||
pkg install golang git make
|
||||
git clone https://git.tukangketik.id/swanadiva/HostKeeper.git
|
||||
cd hostkeeper
|
||||
make build
|
||||
cp bin/hostkeeper $PREFIX/bin/
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
hostkeeper version
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
hostkeeper dev (built: ...)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Command Not Found
|
||||
|
||||
Ensure the binary is in your PATH:
|
||||
```bash
|
||||
export PATH=$PATH:/usr/local/bin
|
||||
```
|
||||
|
||||
### Build Failures
|
||||
|
||||
```bash
|
||||
make clean
|
||||
make deps
|
||||
make build
|
||||
```
|
||||
@@ -0,0 +1,187 @@
|
||||
# Hostkeeper Test Plan — Phase 3
|
||||
|
||||
> **Created**: 2025-01-31
|
||||
> **Purpose**: Comprehensive test coverage for all packages
|
||||
> **Target Coverage**: 90%+ for all packages
|
||||
|
||||
---
|
||||
|
||||
## Current Coverage Summary
|
||||
|
||||
| Package | Current | Target | Gap |
|
||||
|---------|---------|--------|-----|
|
||||
| `internal/errors` | 100% | 100% | — |
|
||||
| `internal/models` | 91% | 100% | +9% |
|
||||
| `pkg/crypto` | **0%** | **100%** | +100% |
|
||||
| `pkg/knownhosts` | **0%** | **100%** | +100% |
|
||||
| `pkg/ssh` | 60% | 90% | +30% |
|
||||
| `pkg/storage` | 40% | 90% | +50% |
|
||||
| `pkg/config` | 22% | 80% | +58% |
|
||||
| `pkg/tui` | ~40% | 70% | +30% |
|
||||
| `cmd/hostkeeper` | ~40% | 70% | +30% |
|
||||
|
||||
---
|
||||
|
||||
## Test File Structure
|
||||
|
||||
```
|
||||
test/
|
||||
├── crypto/
|
||||
│ └── crypto_test.go (NEW — 17 scenarios)
|
||||
├── knownhosts/
|
||||
│ └── knownhosts_test.go (NEW — 14 scenarios)
|
||||
├── storage/
|
||||
│ ├── export_import_test.go (EXISTING)
|
||||
│ └── json_storage_test.go (NEW — 18 scenarios)
|
||||
├── config/
|
||||
│ └── config_test.go (NEW — 10 scenarios)
|
||||
├── ssh/
|
||||
│ └── ssh_test.go (EXISTING)
|
||||
├── tui/
|
||||
│ ├── theme_test.go (EXISTING)
|
||||
│ ├── error_banner_test.go (EXISTING)
|
||||
│ └── responsive_test.go (NEW — 10 scenarios)
|
||||
├── cmd/
|
||||
│ └── root_test.go (NEW — 8 scenarios)
|
||||
├── errors_test.go (EXISTING)
|
||||
├── models_test.go (EXISTING)
|
||||
└── integration/
|
||||
└── integration_test.go (EXISTING)
|
||||
```
|
||||
|
||||
**Total: 7 new test files, ~87 test scenarios**
|
||||
|
||||
---
|
||||
|
||||
## Scenario Details
|
||||
|
||||
### 1. `test/crypto/crypto_test.go` — CRITICAL
|
||||
|
||||
| # | Scenario | Input | Expected | Priority |
|
||||
|---|----------|-------|----------|----------|
|
||||
| 1.1 | DeriveKey determinism | same password + salt | same key | HIGH |
|
||||
| 1.2 | DeriveKey password variation | different password | different key | HIGH |
|
||||
| 1.3 | DeriveKey salt variation | different salt | different key | HIGH |
|
||||
| 1.4 | DeriveKey empty password | "" | no panic, valid key | MEDIUM |
|
||||
| 1.5 | Encrypt/Decrypt round-trip | "hello world" | decrypt = original | HIGH |
|
||||
| 1.6 | Encrypt empty plaintext | "" | decrypt = "" | MEDIUM |
|
||||
| 1.7 | Encrypt large data | 1MB random bytes | round-trip OK | MEDIUM |
|
||||
| 1.8 | Encrypt unicode | "こんにちは" | round-trip OK | MEDIUM |
|
||||
| 1.9 | Encrypt with newlines | "line1\nline2" | round-trip OK | MEDIUM |
|
||||
| 1.10 | Wrong password | decrypt with wrong pw | ErrDecryptionFailed | HIGH |
|
||||
| 1.11 | Empty password | decrypt with "" | ErrDecryptionFailed | HIGH |
|
||||
| 1.12 | IsEncrypted valid ciphertext | base64 ciphertext | true | HIGH |
|
||||
| 1.13 | IsEncrypted plaintext | "hello" | false | HIGH |
|
||||
| 1.14 | IsEncrypted empty | "" | false | MEDIUM |
|
||||
| 1.15 | HashPassword determinism | same pw | same hash | HIGH |
|
||||
| 1.16 | HashPassword variation | different pw | different hash | HIGH |
|
||||
| 1.17 | Encrypt randomness | same input, 2 calls | different ciphertext | MEDIUM |
|
||||
|
||||
### 2. `test/knownhosts/knownhosts_test.go` — CRITICAL
|
||||
|
||||
| # | Scenario | Input | Expected | Priority |
|
||||
|---|----------|-------|----------|----------|
|
||||
| 2.1 | New creates file | non-existent path | file created | HIGH |
|
||||
| 2.2 | New loads existing | existing file | hosts loaded | HIGH |
|
||||
| 2.3 | Add new host | hostname+port+key | added | HIGH |
|
||||
| 2.4 | Add duplicate | same host twice | no error, no duplicate | HIGH |
|
||||
| 2.5 | Get existing | hostname+port | returns HostKey | HIGH |
|
||||
| 2.6 | Get non-existent | unknown host | nil | MEDIUM |
|
||||
| 2.7 | Remove existing | hostname+port | removed | HIGH |
|
||||
| 2.8 | Remove non-existent | unknown host | no error | MEDIUM |
|
||||
| 2.9 | Verify unknown | new host | (false, nil) TOFU | HIGH |
|
||||
| 2.10 | Verify known match | correct key | (true, hostKey) | HIGH |
|
||||
| 2.11 | Verify known mismatch | wrong key | (false, hostKey) MITM | HIGH |
|
||||
| 2.12 | HostKeyCallback | autoAdd=true | adds unknown hosts | HIGH |
|
||||
| 2.13 | Persistence | Add → Save → New → Get | found | HIGH |
|
||||
| 2.14 | Corrupted file | invalid JSON | error | MEDIUM |
|
||||
|
||||
### 3. `test/storage/json_storage_test.go` — HIGH
|
||||
|
||||
| # | Scenario | Input | Expected | Priority |
|
||||
|---|----------|-------|----------|----------|
|
||||
| 3.1 | SaveKeyPair | valid KeyPair | success | HIGH |
|
||||
| 3.2 | ListKeyPairs | after save | returns saved | HIGH |
|
||||
| 3.3 | GetKeyPair found | by ID | returns KeyPair | HIGH |
|
||||
| 3.4 | GetKeyPair not found | unknown ID | error | MEDIUM |
|
||||
| 3.5 | DeleteKeyPair | by ID | removed | HIGH |
|
||||
| 3.6 | DeleteKeyPair not found | unknown ID | no error | MEDIUM |
|
||||
| 3.7 | SaveSnippet | valid Snippet | success | HIGH |
|
||||
| 3.8 | ListSnippets | after save | returns saved | HIGH |
|
||||
| 3.9 | GetSnippet found | by ID | returns Snippet | HIGH |
|
||||
| 3.10 | GetSnippet not found | unknown ID | error | MEDIUM |
|
||||
| 3.11 | DeleteSnippet | by ID | removed | HIGH |
|
||||
| 3.12 | DeleteSnippet not found | unknown ID | no error | MEDIUM |
|
||||
| 3.13 | SetPassword + SaveHost | encrypted storage | file encrypted | HIGH |
|
||||
| 3.14 | IsDataEncrypted | encrypted file | true | HIGH |
|
||||
| 3.15 | Wrong password load | decrypt with wrong pw | error | HIGH |
|
||||
| 3.16 | MergeStrategyMerge | import with merge | keeps existing + adds new | HIGH |
|
||||
| 3.17 | MergeStrategyReplace | import with replace | overwrites all | HIGH |
|
||||
| 3.18 | SaveHost empty ID | host with "" ID | generates UUID | MEDIUM |
|
||||
|
||||
### 4. `test/config/config_test.go` — MEDIUM
|
||||
|
||||
| # | Scenario | Input | Expected | Priority |
|
||||
|---|----------|-------|----------|----------|
|
||||
| 4.1 | New first run | no config file | creates default | HIGH |
|
||||
| 4.2 | New existing | valid config file | loads config | HIGH |
|
||||
| 4.3 | Save | modify + save | persists | HIGH |
|
||||
| 4.4 | UpdateAppConfig | change theme | saved | HIGH |
|
||||
| 4.5 | GetConfigDir | — | valid path | MEDIUM |
|
||||
| 4.6 | GetDataDir | — | valid path | MEDIUM |
|
||||
| 4.7 | GetConfigFilePath | — | ends with config.json | MEDIUM |
|
||||
| 4.8 | GetHostsFilePath | — | ends with hosts.json | MEDIUM |
|
||||
| 4.9 | GetKeysFilePath | — | ends with keys.json | MEDIUM |
|
||||
| 4.10 | GetSnippetsFilePath | — | ends with snippets.json | MEDIUM |
|
||||
|
||||
### 5. `test/tui/responsive_test.go` — MEDIUM
|
||||
|
||||
| # | Scenario | Input | Expected | Priority |
|
||||
|---|----------|-------|----------|----------|
|
||||
| 5.1 | WrapFooter short | short string | single line | MEDIUM |
|
||||
| 5.2 | WrapFooter long | long string | multi-line | MEDIUM |
|
||||
| 5.3 | WrapFooter empty | "" | "" | LOW |
|
||||
| 5.4 | ClampWidth over | width > max | clamped to max | MEDIUM |
|
||||
| 5.5 | ClampWidth under | width < min | clamped to min | MEDIUM |
|
||||
| 5.6 | ClampWidth in range | min < width < max | unchanged | MEDIUM |
|
||||
| 5.7 | TruncateStr short | short string | unchanged | MEDIUM |
|
||||
| 5.8 | TruncateStr long | long string | truncated + … | MEDIUM |
|
||||
| 5.9 | TruncateStr empty | "" | "" | LOW |
|
||||
| 5.10 | TruncateStr unicode | "こんにちは世界" | correct width | MEDIUM |
|
||||
|
||||
### 6. `test/cmd/root_test.go` — MEDIUM
|
||||
|
||||
| # | Scenario | Input | Expected | Priority |
|
||||
|---|----------|-------|----------|----------|
|
||||
| 6.1 | RootCmd execute | no args | no error | HIGH |
|
||||
| 6.2 | Version flag | --version | shows version | MEDIUM |
|
||||
| 6.3 | FindHost by ID | host ID | returns host | HIGH |
|
||||
| 6.4 | FindHost by name | host name | returns host | HIGH |
|
||||
| 6.5 | FindHost by hostname | IP/hostname | returns host | HIGH |
|
||||
| 6.6 | FindHost not found | unknown | error | MEDIUM |
|
||||
| 6.7 | NewStorage no password | --password="" | unencrypted | MEDIUM |
|
||||
| 6.8 | NewStorage with password | --password="x" | encrypted | HIGH |
|
||||
|
||||
---
|
||||
|
||||
## Execution Order
|
||||
|
||||
```
|
||||
Phase 3, Sprint 1: Security-Critical (pkg/crypto, pkg/knownhosts)
|
||||
Phase 3, Sprint 2: Core (pkg/storage, pkg/config)
|
||||
Phase 3, Sprint 3: UI + CLI (pkg/tui, cmd/hostkeeper)
|
||||
Phase 3, Sprint 4: Integration + Final
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Success Criteria
|
||||
|
||||
- [ ] All tests pass (`go test ./test/...`)
|
||||
- [ ] Coverage >= 90% for `pkg/crypto`
|
||||
- [ ] Coverage >= 90% for `pkg/knownhosts`
|
||||
- [ ] Coverage >= 80% for `pkg/storage`
|
||||
- [ ] Coverage >= 70% for `pkg/config`
|
||||
- [ ] Coverage >= 60% for `pkg/tui`
|
||||
- [ ] No race conditions (`go test -race ./test/...`)
|
||||
- [ ] Build clean (`go build ./...`)
|
||||
@@ -0,0 +1,151 @@
|
||||
# Usage Guide
|
||||
|
||||
## Host Management
|
||||
|
||||
### Add a Host
|
||||
|
||||
Interactive mode:
|
||||
```bash
|
||||
hostkeeper add
|
||||
```
|
||||
|
||||
With flags:
|
||||
```bash
|
||||
hostkeeper add myserver --host 192.168.1.10 --user admin --password mypass
|
||||
hostkeeper add myserver --host 10.0.0.1 --port 2222 --user root --key ~/.ssh/id_rsa
|
||||
hostkeeper add webserver --host example.com --user deploy --password secret --group production --tags web,frontend
|
||||
```
|
||||
|
||||
Flags:
|
||||
- `--host` — hostname or IP address
|
||||
- `--port` — SSH port (default: 22)
|
||||
- `--user` — SSH username
|
||||
- `--password` — SSH password
|
||||
- `--key` — path to SSH private key
|
||||
- `--auth-type` — authentication type (password, key, both)
|
||||
- `--group` — host group for categorization
|
||||
- `--tags` — comma-separated tags
|
||||
- `--notes` — notes about the host
|
||||
|
||||
### List Hosts
|
||||
|
||||
```bash
|
||||
hostkeeper list
|
||||
hostkeeper ls # alias
|
||||
```
|
||||
|
||||
Filter by group or tag:
|
||||
```bash
|
||||
hostkeeper list --group production
|
||||
hostkeeper list --tag web
|
||||
```
|
||||
|
||||
Output formats:
|
||||
```bash
|
||||
hostkeeper list --format table # default
|
||||
hostkeeper list --format json
|
||||
```
|
||||
|
||||
Sort options:
|
||||
```bash
|
||||
hostkeeper list --sort name # default
|
||||
hostkeeper list --sort hostname
|
||||
hostkeeper list --sort group
|
||||
```
|
||||
|
||||
### Connect to a Host
|
||||
|
||||
Connect using system SSH (default, full interactive terminal):
|
||||
```bash
|
||||
hostkeeper connect myserver
|
||||
```
|
||||
|
||||
Connect with Go SSH client (direct mode, no interactive shell):
|
||||
```bash
|
||||
hostkeeper connect myserver --direct
|
||||
```
|
||||
|
||||
Custom timeout:
|
||||
```bash
|
||||
hostkeeper connect myserver --timeout 60
|
||||
```
|
||||
|
||||
### Edit a Host
|
||||
|
||||
Interactive mode:
|
||||
```bash
|
||||
hostkeeper edit myserver
|
||||
```
|
||||
|
||||
With flags (only update what you specify):
|
||||
```bash
|
||||
hostkeeper edit myserver --host 10.0.0.1 --port 2222
|
||||
hostkeeper edit myserver --user root --name myserver-renamed
|
||||
hostkeeper edit myserver --group staging --tags backend
|
||||
```
|
||||
|
||||
### Delete a Host
|
||||
|
||||
With confirmation prompt:
|
||||
```bash
|
||||
hostkeeper delete myserver
|
||||
hostkeeper rm myserver # alias
|
||||
```
|
||||
|
||||
Skip confirmation:
|
||||
```bash
|
||||
hostkeeper delete myserver --force
|
||||
```
|
||||
|
||||
## Data Management
|
||||
|
||||
### Export
|
||||
|
||||
Export all hosts, keys, and snippets to a JSON file:
|
||||
```bash
|
||||
hostkeeper export backup
|
||||
hostkeeper export backup.json
|
||||
```
|
||||
|
||||
### Import
|
||||
|
||||
Import from a previously exported JSON file:
|
||||
```bash
|
||||
hostkeeper import backup.json # merge (default)
|
||||
hostkeeper import backup.json --strategy replace
|
||||
hostkeeper import backup.json --dry-run # preview only
|
||||
```
|
||||
|
||||
Merge strategies:
|
||||
- `merge` — keep existing data, add new items (default)
|
||||
- `replace` — replace all existing data with imported data
|
||||
|
||||
## TUI Interface
|
||||
|
||||
Launch the interactive terminal UI:
|
||||
```bash
|
||||
hostkeeper tui
|
||||
```
|
||||
|
||||
Navigation:
|
||||
- `↑`/`k` — move up
|
||||
- `↓`/`j` — move down
|
||||
- `Enter` — select host
|
||||
- `q` — quit
|
||||
|
||||
## Shell Completion
|
||||
|
||||
Generate shell completion scripts:
|
||||
```bash
|
||||
hostkeeper completion bash > /etc/bash_completion.d/hostkeeper
|
||||
hostkeeper completion zsh > /usr/local/share/zsh/site-functions/_hostkeeper
|
||||
hostkeeper completion fish > ~/.config/fish/completions/hostkeeper.fish
|
||||
hostkeeper completion powershell > hostkeeper.ps1
|
||||
```
|
||||
|
||||
## Global Flags
|
||||
|
||||
- `--config` — path to custom config file
|
||||
- `-v`/`--verbose` — verbose output (-v for info, -vv for debug)
|
||||
- `--debug` — enable debug mode
|
||||
- `--help` — display help
|
||||
@@ -0,0 +1,51 @@
|
||||
module git.tukangketik.id/swanadiva/hostkeeper
|
||||
|
||||
go 1.26.4
|
||||
|
||||
require (
|
||||
github.com/charmbracelet/bubbles v1.0.0
|
||||
github.com/charmbracelet/bubbletea v1.3.10
|
||||
github.com/charmbracelet/lipgloss v1.1.0
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/pkg/sftp v1.13.7
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/viper v1.21.0
|
||||
golang.org/x/crypto v0.53.0
|
||||
golang.org/x/term v0.44.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/atotto/clipboard v0.1.4 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.1 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.6 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.9.0 // indirect
|
||||
github.com/clipperhouse/stringish v0.1.1 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.5.0 // indirect
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.19 // indirect
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,156 @@
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||
github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
|
||||
github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=
|
||||
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
|
||||
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
|
||||
github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=
|
||||
github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=
|
||||
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
|
||||
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
|
||||
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
|
||||
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
|
||||
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
||||
github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=
|
||||
github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=
|
||||
github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
|
||||
github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
|
||||
github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
|
||||
github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
||||
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
|
||||
github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
|
||||
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pkg/sftp v1.13.7 h1:uv+I3nNJvlKZIQGSr8JVQLNHFU9YhhNpvC14Y6KgmSM=
|
||||
github.com/pkg/sftp v1.13.7/go.mod h1:KMKI0t3T6hfA+lTR/ssZdunHo+uwq7ghoN09/FSu3DY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
|
||||
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,105 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ConnectionError represents SSH connection errors with helpful hints
|
||||
type ConnectionError struct {
|
||||
Type string // "auth", "network", "timeout", "config", "unknown"
|
||||
Message string
|
||||
Details string
|
||||
Hints []string
|
||||
}
|
||||
|
||||
// Error implements the error interface
|
||||
func (e *ConnectionError) Error() string {
|
||||
return fmt.Sprintf("Connection Error (%s): %s\nDetails: %s", e.Type, e.Message, e.Details)
|
||||
}
|
||||
|
||||
// NewConnectionError creates a new ConnectionError
|
||||
func NewConnectionError(errType, message, details string, hints []string) *ConnectionError {
|
||||
return &ConnectionError{
|
||||
Type: errType,
|
||||
Message: message,
|
||||
Details: details,
|
||||
Hints: hints,
|
||||
}
|
||||
}
|
||||
|
||||
// HandleSSHError processes SSH errors and returns user-friendly errors
|
||||
func HandleSSHError(err error) *ConnectionError {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
errStr := err.Error()
|
||||
|
||||
switch {
|
||||
case strings.Contains(errStr, "connection refused"):
|
||||
return &ConnectionError{
|
||||
Type: "network",
|
||||
Message: "Cannot connect to server",
|
||||
Details: errStr,
|
||||
Hints: []string{"Check if server is running", "Verify firewall rules", "Confirm hostname and port"},
|
||||
}
|
||||
|
||||
case strings.Contains(errStr, "authentication failed"), strings.Contains(errStr, "unable to authenticate"):
|
||||
return &ConnectionError{
|
||||
Type: "auth",
|
||||
Message: "Authentication failed",
|
||||
Details: errStr,
|
||||
Hints: []string{"Verify username and password", "Check SSH key is loaded", "Test with native SSH client"},
|
||||
}
|
||||
|
||||
case strings.Contains(errStr, "timeout"), strings.Contains(errStr, "timed out"):
|
||||
return &ConnectionError{
|
||||
Type: "timeout",
|
||||
Message: "Connection timeout",
|
||||
Details: errStr,
|
||||
Hints: []string{"Check network connectivity", "Try increasing timeout", "Verify server is reachable"},
|
||||
}
|
||||
|
||||
case strings.Contains(errStr, "no such host"), strings.Contains(errStr, "hostname"):
|
||||
return &ConnectionError{
|
||||
Type: "config",
|
||||
Message: "Invalid hostname",
|
||||
Details: errStr,
|
||||
Hints: []string{"Verify hostname spelling", "Check DNS resolution", "Try IP address instead"},
|
||||
}
|
||||
|
||||
case strings.Contains(errStr, "permission denied"):
|
||||
return &ConnectionError{
|
||||
Type: "auth",
|
||||
Message: "Permission denied",
|
||||
Details: errStr,
|
||||
Hints: []string{"Check user permissions on server", "Verify account is not locked", "Check authentication method"},
|
||||
}
|
||||
|
||||
default:
|
||||
return &ConnectionError{
|
||||
Type: "unknown",
|
||||
Message: "Connection failed",
|
||||
Details: errStr,
|
||||
Hints: []string{"Check host configuration", "Verify network settings", "Test with standard SSH client"},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FormatConnectionError formats connection error for user-friendly display
|
||||
func FormatConnectionError(err *ConnectionError) string {
|
||||
var output strings.Builder
|
||||
|
||||
output.WriteString(fmt.Sprintf("❌ Connection Error: %s\n\n", err.Message))
|
||||
output.WriteString(fmt.Sprintf("Details: %s\n\n", err.Details))
|
||||
|
||||
if len(err.Hints) > 0 {
|
||||
output.WriteString("Possible solutions:\n")
|
||||
for i, hint := range err.Hints {
|
||||
output.WriteString(fmt.Sprintf(" %d. %s\n", i+1, hint))
|
||||
}
|
||||
}
|
||||
|
||||
return output.String()
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Error codes
|
||||
const (
|
||||
ErrHostNotFound = "HOST_NOT_FOUND"
|
||||
ErrAuthFailed = "AUTH_FAILED"
|
||||
ErrConnectionTimeout = "CONNECTION_TIMEOUT"
|
||||
ErrInvalidConfig = "INVALID_CONFIG"
|
||||
ErrKeyNotFound = "KEY_NOT_FOUND"
|
||||
ErrPermissionDenied = "PERMISSION_DENIED"
|
||||
ErrFileCorrupted = "FILE_CORRUPTED"
|
||||
ErrInvalidCredentials = "INVALID_CREDENTIALS"
|
||||
)
|
||||
|
||||
// AppError represents an application error with code, message, cause, and hints
|
||||
type AppError struct {
|
||||
Code string
|
||||
Message string
|
||||
Cause error
|
||||
Hints []string
|
||||
}
|
||||
|
||||
// Error implements the error interface
|
||||
func (e *AppError) Error() string {
|
||||
if e.Cause != nil {
|
||||
return fmt.Sprintf("[%s] %s: %v", e.Code, e.Message, e.Cause)
|
||||
}
|
||||
return fmt.Sprintf("[%s] %s", e.Code, e.Message)
|
||||
}
|
||||
|
||||
// Unwrap returns the underlying cause for use with errors.Is/errors.As
|
||||
func (e *AppError) Unwrap() error {
|
||||
return e.Cause
|
||||
}
|
||||
|
||||
// NewAppError creates a new application error
|
||||
func NewAppError(code, message string, cause error, hints []string) *AppError {
|
||||
return &AppError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
Cause: cause,
|
||||
Hints: hints,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Host represents an SSH host connection configuration
|
||||
type Host struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Hostname string `json:"hostname"`
|
||||
Port int `json:"port"`
|
||||
Username string `json:"username"`
|
||||
Auth AuthConfig `json:"auth"`
|
||||
Group string `json:"group,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
}
|
||||
|
||||
// AuthConfig represents authentication configuration
|
||||
type AuthConfig struct {
|
||||
Type string `json:"type"` // "password", "key", "both"
|
||||
Password string `json:"password,omitempty"`
|
||||
KeyID string `json:"key_id,omitempty"` // Reference to KeyPair ID
|
||||
}
|
||||
|
||||
// KeyPair represents an SSH key pair
|
||||
type KeyPair struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"` // "rsa", "ed25519", "ecdsa"
|
||||
PrivateKey string `json:"private_key"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
Passphrase string `json:"passphrase,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Snippet represents a command snippet
|
||||
type Snippet struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Command string `json:"command"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Tags []string `json:"tags,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// Profile represents a named configuration profile
|
||||
type Profile struct {
|
||||
Name string `json:"name"`
|
||||
Theme string `json:"theme"`
|
||||
DefaultGroup string `json:"default_group,omitempty"`
|
||||
DefaultAuth string `json:"default_auth,omitempty"` // "password", "key", "both"
|
||||
Editor string `json:"editor,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
}
|
||||
|
||||
// AppConfig represents the application configuration
|
||||
type AppConfig struct {
|
||||
Version string `json:"version"`
|
||||
DefaultPort int `json:"default_port"`
|
||||
ConnectionTimeout int `json:"connection_timeout"` // in seconds
|
||||
Theme string `json:"theme"`
|
||||
Editor string `json:"editor"`
|
||||
AutoSync bool `json:"auto_sync"`
|
||||
SyncProvider string `json:"sync_provider,omitempty"`
|
||||
|
||||
// Profiles
|
||||
Profiles []Profile `json:"profiles,omitempty"`
|
||||
ActiveProfile string `json:"active_profile,omitempty"`
|
||||
|
||||
// Security
|
||||
EncryptionEnabled bool `json:"encryption_enabled"`
|
||||
PasswordHash string `json:"password_hash,omitempty"` // SHA-256 hash for verification
|
||||
KnownHostsFile string `json:"known_hosts_file,omitempty"`
|
||||
}
|
||||
|
||||
// KnownHost represents a verified host key
|
||||
type KnownHost struct {
|
||||
Hostname string `json:"hostname"`
|
||||
Port int `json:"port"`
|
||||
KeyType string `json:"key_type"` // "ssh-rsa", "ssh-ed25519", etc.
|
||||
KeyHash string `json:"key_hash"` // Base64-encoded host key
|
||||
AddedAt time.Time `json:"added_at"`
|
||||
}
|
||||
|
||||
// DefaultConfig returns the default application configuration
|
||||
func DefaultConfig() *AppConfig {
|
||||
return &AppConfig{
|
||||
Version: "1.0.0",
|
||||
DefaultPort: 22,
|
||||
ConnectionTimeout: 30,
|
||||
Theme: "dark",
|
||||
Editor: "vim",
|
||||
AutoSync: false,
|
||||
EncryptionEnabled: false,
|
||||
Profiles: []Profile{
|
||||
{
|
||||
Name: "default",
|
||||
Theme: "dark",
|
||||
},
|
||||
},
|
||||
ActiveProfile: "default",
|
||||
}
|
||||
}
|
||||
|
||||
// GetProfile returns a profile by name
|
||||
func (c *AppConfig) GetProfile(name string) *Profile {
|
||||
for i := range c.Profiles {
|
||||
if c.Profiles[i].Name == name {
|
||||
return &c.Profiles[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveProfile returns the active profile
|
||||
func (c *AppConfig) GetActiveProfile() *Profile {
|
||||
return c.GetProfile(c.ActiveProfile)
|
||||
}
|
||||
|
||||
// AddProfile adds a new profile
|
||||
func (c *AppConfig) AddProfile(p Profile) {
|
||||
c.Profiles = append(c.Profiles, p)
|
||||
}
|
||||
|
||||
// RemoveProfile removes a profile by name
|
||||
func (c *AppConfig) RemoveProfile(name string) {
|
||||
for i := range c.Profiles {
|
||||
if c.Profiles[i].Name == name {
|
||||
c.Profiles = append(c.Profiles[:i], c.Profiles[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
// Config manages application configuration and paths
|
||||
type Config struct {
|
||||
appName string
|
||||
configDir string
|
||||
dataDir string
|
||||
appConfig *models.AppConfig
|
||||
}
|
||||
|
||||
// New creates a new Config instance
|
||||
func New() (*Config, error) {
|
||||
appName := "hostkeeper"
|
||||
|
||||
configDir, err := getConfigDir(appName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get config directory: %w", err)
|
||||
}
|
||||
|
||||
dataDir := filepath.Join(configDir, "data")
|
||||
|
||||
c := &Config{
|
||||
appName: appName,
|
||||
configDir: configDir,
|
||||
dataDir: dataDir,
|
||||
}
|
||||
|
||||
// Create directories
|
||||
if err := os.MkdirAll(configDir, 0700); err != nil {
|
||||
return nil, fmt.Errorf("failed to create config directory: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(dataDir, 0700); err != nil {
|
||||
return nil, fmt.Errorf("failed to create data directory: %w", err)
|
||||
}
|
||||
|
||||
// Load or create config
|
||||
if err := c.load(); err != nil {
|
||||
return nil, fmt.Errorf("failed to load config: %w", err)
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// getConfigDir returns the OS-appropriate config directory for the app
|
||||
func getConfigDir(appName string) (string, error) {
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, "Library", "Application Support", appName), nil
|
||||
case "linux":
|
||||
if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
|
||||
return filepath.Join(xdg, appName), nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, ".config", appName), nil
|
||||
case "windows":
|
||||
appData := os.Getenv("APPDATA")
|
||||
if appData != "" {
|
||||
return filepath.Join(appData, appName), nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, "AppData", "Roaming", appName), nil
|
||||
default:
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, "."+appName), nil
|
||||
}
|
||||
}
|
||||
|
||||
// load reads the config file, or creates a default one if it doesn't exist
|
||||
func (c *Config) load() error {
|
||||
configPath := c.GetConfigFilePath()
|
||||
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
// Create default config
|
||||
c.appConfig = models.DefaultConfig()
|
||||
return c.Save()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
c.appConfig = models.DefaultConfig()
|
||||
if err := json.Unmarshal(data, c.appConfig); err != nil {
|
||||
return fmt.Errorf("failed to parse config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save writes the current configuration to disk
|
||||
func (c *Config) Save() error {
|
||||
configPath := c.GetConfigFilePath()
|
||||
|
||||
data, err := json.MarshalIndent(c.appConfig, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal config: %w", err)
|
||||
}
|
||||
|
||||
return os.WriteFile(configPath, data, 0600)
|
||||
}
|
||||
|
||||
// GetAppConfig returns the application configuration
|
||||
func (c *Config) GetAppConfig() *models.AppConfig {
|
||||
return c.appConfig
|
||||
}
|
||||
|
||||
// UpdateAppConfig updates the application configuration
|
||||
func (c *Config) UpdateAppConfig(cfg *models.AppConfig) error {
|
||||
c.appConfig = cfg
|
||||
return c.Save()
|
||||
}
|
||||
|
||||
// GetConfigDir returns the configuration directory path
|
||||
func (c *Config) GetConfigDir() string {
|
||||
return c.configDir
|
||||
}
|
||||
|
||||
// GetDataDir returns the data directory path
|
||||
func (c *Config) GetDataDir() string {
|
||||
return c.dataDir
|
||||
}
|
||||
|
||||
// GetConfigFilePath returns the full path to the config JSON file
|
||||
func (c *Config) GetConfigFilePath() string {
|
||||
return filepath.Join(c.configDir, "config.json")
|
||||
}
|
||||
|
||||
// GetHostsFilePath returns the full path to the hosts JSON file
|
||||
func (c *Config) GetHostsFilePath() string {
|
||||
return filepath.Join(c.dataDir, "hosts.json")
|
||||
}
|
||||
|
||||
// GetKeysFilePath returns the full path to the keys JSON file
|
||||
func (c *Config) GetKeysFilePath() string {
|
||||
return filepath.Join(c.dataDir, "keys.json")
|
||||
}
|
||||
|
||||
// GetSnippetsFilePath returns the full path to the snippets JSON file
|
||||
func (c *Config) GetSnippetsFilePath() string {
|
||||
return filepath.Join(c.dataDir, "snippets.json")
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
const (
|
||||
KeyLength = 32 // AES-256
|
||||
SaltLength = 16
|
||||
Iterations = 100000
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidPassword = errors.New("invalid password")
|
||||
ErrDecryptionFailed = errors.New("decryption failed — wrong password or corrupted data")
|
||||
)
|
||||
|
||||
// DeriveKey derives an AES-256 key from a password using PBKDF2
|
||||
func DeriveKey(password string, salt []byte) []byte {
|
||||
return pbkdf2.Key([]byte(password), salt, Iterations, KeyLength, sha256.New)
|
||||
}
|
||||
|
||||
// Encrypt encrypts plaintext using AES-256-GCM with a password
|
||||
func Encrypt(plaintext []byte, password string) (string, error) {
|
||||
salt := make([]byte, SaltLength)
|
||||
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
key := DeriveKey(password, salt)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
aesGCM, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
nonce := make([]byte, aesGCM.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
|
||||
|
||||
// Format: base64(salt + nonce + ciphertext)
|
||||
result := make([]byte, 0, len(salt)+len(nonce)+len(ciphertext))
|
||||
result = append(result, salt...)
|
||||
result = append(result, nonce...)
|
||||
result = append(result, ciphertext...)
|
||||
|
||||
return base64.StdEncoding.EncodeToString(result), nil
|
||||
}
|
||||
|
||||
// Decrypt decrypts ciphertext using AES-256-GCM with a password
|
||||
func Decrypt(encoded string, password string) ([]byte, error) {
|
||||
data, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
if len(data) < SaltLength+12 { // 12 = minimum nonce size for GCM
|
||||
return nil, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
salt := data[:SaltLength]
|
||||
data = data[SaltLength:]
|
||||
|
||||
key := DeriveKey(password, salt)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
aesGCM, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
nonceSize := aesGCM.NonceSize()
|
||||
if len(data) < nonceSize {
|
||||
return nil, ErrDecryptionFailed
|
||||
}
|
||||
|
||||
nonce := data[:nonceSize]
|
||||
ciphertext := data[nonceSize:]
|
||||
|
||||
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidPassword
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
// IsEncrypted checks if a string looks like base64-encoded encrypted data
|
||||
func IsEncrypted(data string) bool {
|
||||
decoded, err := base64.StdEncoding.DecodeString(data)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// Minimum: 16 (salt) + 12 (nonce) + 16 (min ciphertext) = 44 bytes
|
||||
return len(decoded) >= 44
|
||||
}
|
||||
|
||||
// HashPassword creates a SHA-256 hash of a password for verification
|
||||
func HashPassword(password string) string {
|
||||
h := sha256.Sum256([]byte(password))
|
||||
return base64.StdEncoding.EncodeToString(h[:])
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package knownhosts
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
cryptossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// KnownHosts manages the known_hosts file
|
||||
type KnownHosts struct {
|
||||
path string
|
||||
hosts map[string]*HostKey // key = "hostname:port"
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// HostKey represents a stored host key
|
||||
type HostKey struct {
|
||||
Hostname string `json:"hostname"`
|
||||
Port int `json:"port"`
|
||||
KeyType string `json:"key_type"`
|
||||
KeyData string `json:"key_data"` // Base64-encoded raw key
|
||||
AddedAt time.Time `json:"added_at"`
|
||||
}
|
||||
|
||||
// New creates a new KnownHosts manager
|
||||
func New(dataDir string) (*KnownHosts, error) {
|
||||
path := filepath.Join(dataDir, "known_hosts")
|
||||
kh := &KnownHosts{
|
||||
path: path,
|
||||
hosts: make(map[string]*HostKey),
|
||||
}
|
||||
|
||||
if err := kh.load(); err != nil {
|
||||
// File doesn't exist yet, that's OK
|
||||
if !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return kh, nil
|
||||
}
|
||||
|
||||
// Load reads the known_hosts file
|
||||
func (kh *KnownHosts) load() error {
|
||||
kh.mu.Lock()
|
||||
defer kh.mu.Unlock()
|
||||
|
||||
data, err := os.ReadFile(kh.path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var hosts []*HostKey
|
||||
if err := json.Unmarshal(data, &hosts); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, h := range hosts {
|
||||
key := fmt.Sprintf("%s:%d", h.Hostname, h.Port)
|
||||
kh.hosts[key] = h
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Save writes the known_hosts file
|
||||
func (kh *KnownHosts) Save() error {
|
||||
kh.mu.Lock()
|
||||
defer kh.mu.Unlock()
|
||||
|
||||
return kh.saveInternal()
|
||||
}
|
||||
|
||||
// saveInternal writes the known_hosts file without locking (caller must hold lock)
|
||||
func (kh *KnownHosts) saveInternal() error {
|
||||
var hosts []*HostKey
|
||||
for _, h := range kh.hosts {
|
||||
hosts = append(hosts, h)
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(hosts, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(kh.path, data, 0600)
|
||||
}
|
||||
|
||||
// Verify checks if a host key is known and matches
|
||||
func (kh *KnownHosts) Verify(hostname string, port int, remoteKey cryptossh.PublicKey) (bool, *HostKey) {
|
||||
kh.mu.RLock()
|
||||
defer kh.mu.RUnlock()
|
||||
|
||||
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||
stored, ok := kh.hosts[key]
|
||||
if !ok {
|
||||
return false, nil // Unknown host
|
||||
}
|
||||
|
||||
// Compare key type and data
|
||||
remoteType := remoteKey.Type()
|
||||
remoteData := base64.StdEncoding.EncodeToString(remoteKey.Marshal())
|
||||
|
||||
if stored.KeyType != remoteType || stored.KeyData != remoteData {
|
||||
return false, stored // Key mismatch — potential MITM
|
||||
}
|
||||
|
||||
return true, stored // Key matches
|
||||
}
|
||||
|
||||
// Add stores a new host key
|
||||
func (kh *KnownHosts) Add(hostname string, port int, remoteKey cryptossh.PublicKey) error {
|
||||
kh.mu.Lock()
|
||||
defer kh.mu.Unlock()
|
||||
|
||||
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||
kh.hosts[key] = &HostKey{
|
||||
Hostname: hostname,
|
||||
Port: port,
|
||||
KeyType: remoteKey.Type(),
|
||||
KeyData: base64.StdEncoding.EncodeToString(remoteKey.Marshal()),
|
||||
AddedAt: time.Now(),
|
||||
}
|
||||
|
||||
return kh.saveInternal()
|
||||
}
|
||||
|
||||
// Remove removes a host key
|
||||
func (kh *KnownHosts) Remove(hostname string, port int) error {
|
||||
kh.mu.Lock()
|
||||
defer kh.mu.Unlock()
|
||||
|
||||
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||
delete(kh.hosts, key)
|
||||
|
||||
return kh.saveInternal()
|
||||
}
|
||||
|
||||
// Get returns the stored host key for a given host
|
||||
func (kh *KnownHosts) Get(hostname string, port int) *HostKey {
|
||||
kh.mu.RLock()
|
||||
defer kh.mu.RUnlock()
|
||||
|
||||
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||
return kh.hosts[key]
|
||||
}
|
||||
|
||||
// HostKeyCallback returns a crypto/ssh HostKeyCallback for use in SSH config
|
||||
func (kh *KnownHosts) HostKeyCallback(autoAdd bool) cryptossh.HostKeyCallback {
|
||||
return func(hostname string, remote net.Addr, remoteKey cryptossh.PublicKey) error {
|
||||
// Extract port from address
|
||||
_, portStr, err := net.SplitHostPort(remote.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse address: %w", err)
|
||||
}
|
||||
|
||||
port := 22
|
||||
fmt.Sscanf(portStr, "%d", &port)
|
||||
|
||||
// Check if host is known
|
||||
matches, stored := kh.Verify(hostname, port, remoteKey)
|
||||
if matches {
|
||||
return nil // Key matches, connection OK
|
||||
}
|
||||
|
||||
if stored == nil {
|
||||
// Unknown host — auto-add if enabled
|
||||
if autoAdd {
|
||||
if err := kh.Add(hostname, port, remoteKey); err != nil {
|
||||
return fmt.Errorf("failed to add host key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("host key not found for %s:%d — run 'hostkeeper trust %s' to add", hostname, port, hostname)
|
||||
}
|
||||
|
||||
// Key mismatch — potential MITM attack
|
||||
return fmt.Errorf("WARNING: host key mismatch for %s:%d!\n"+
|
||||
"Stored key type: %s\n"+
|
||||
"Remote key type: %s\n"+
|
||||
"This could indicate a MITM attack.\n"+
|
||||
"Run 'hostkeeper trust --remove %s' and try again.",
|
||||
hostname, port, stored.KeyType, remoteKey.Type(), hostname)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
cryptossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// getAuthMethods returns SSH authentication methods based on host config
|
||||
func (c *Client) getAuthMethods() ([]cryptossh.AuthMethod, error) {
|
||||
var authMethods []cryptossh.AuthMethod
|
||||
|
||||
switch c.host.Auth.Type {
|
||||
case "password":
|
||||
if c.host.Auth.Password == "" {
|
||||
return nil, fmt.Errorf("password auth requires password")
|
||||
}
|
||||
authMethods = append(authMethods, cryptossh.Password(c.host.Auth.Password))
|
||||
|
||||
case "key":
|
||||
signer, err := c.getKeySigner()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to setup key authentication: %w", err)
|
||||
}
|
||||
authMethods = append(authMethods, cryptossh.PublicKeys(signer))
|
||||
|
||||
case "both":
|
||||
// Try password first
|
||||
if c.host.Auth.Password != "" {
|
||||
authMethods = append(authMethods, cryptossh.Password(c.host.Auth.Password))
|
||||
}
|
||||
// Then try key
|
||||
signer, err := c.getKeySigner()
|
||||
if err == nil {
|
||||
authMethods = append(authMethods, cryptossh.PublicKeys(signer))
|
||||
}
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported authentication type: %s", c.host.Auth.Type)
|
||||
}
|
||||
|
||||
if len(authMethods) == 0 {
|
||||
return nil, fmt.Errorf("no authentication methods configured")
|
||||
}
|
||||
|
||||
return authMethods, nil
|
||||
}
|
||||
|
||||
// getKeySigner returns an SSH signer for key-based authentication
|
||||
//
|
||||
// Phase 1: Loads key from KeyID as a file path, or from common SSH key locations
|
||||
// Phase 2: Will integrate with the storage layer for encrypted key storage
|
||||
func (c *Client) getKeySigner() (cryptossh.Signer, error) {
|
||||
var keyPath string
|
||||
|
||||
if c.host.Auth.KeyID != "" {
|
||||
// If KeyID looks like a path, use it directly
|
||||
if strings.HasPrefix(c.host.Auth.KeyID, "/") || strings.HasPrefix(c.host.Auth.KeyID, "~") {
|
||||
keyPath = expandPath(c.host.Auth.KeyID)
|
||||
} else {
|
||||
// Try ~/.ssh/<keyID>
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get home directory: %w", err)
|
||||
}
|
||||
keyPath = filepath.Join(home, ".ssh", c.host.Auth.KeyID)
|
||||
}
|
||||
} else {
|
||||
// Fall back to default key locations
|
||||
keyPath = getDefaultKeyPath()
|
||||
}
|
||||
|
||||
// Read the key file
|
||||
keyData, err := os.ReadFile(keyPath) //nolint:gosec
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read key file %s: %w", keyPath, err)
|
||||
}
|
||||
|
||||
// Parse the key (support passphrase-protected keys)
|
||||
var signer cryptossh.Signer
|
||||
if c.host.Auth.Password != "" {
|
||||
signer, err = cryptossh.ParsePrivateKeyWithPassphrase(keyData, []byte(c.host.Auth.Password))
|
||||
} else if c.passphraseCallback != nil {
|
||||
// Try without passphrase first
|
||||
signer, err = cryptossh.ParsePrivateKey(keyData)
|
||||
if err != nil && strings.Contains(err.Error(), "encrypted") {
|
||||
// Key is encrypted, prompt for passphrase
|
||||
passphrase := c.passphraseCallback()
|
||||
if passphrase != "" {
|
||||
signer, err = cryptossh.ParsePrivateKeyWithPassphrase(keyData, []byte(passphrase))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
signer, err = cryptossh.ParsePrivateKey(keyData)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse private key: %w", err)
|
||||
}
|
||||
|
||||
return signer, nil
|
||||
}
|
||||
|
||||
// getDefaultKeyPath returns the first existing default SSH key path
|
||||
func getDefaultKeyPath() string {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
candidates := []string{
|
||||
"id_ed25519",
|
||||
"id_rsa",
|
||||
"id_ecdsa",
|
||||
"id_dsa",
|
||||
}
|
||||
|
||||
for _, name := range candidates {
|
||||
path := filepath.Join(home, ".ssh", name)
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// expandPath expands ~ to the home directory
|
||||
func expandPath(path string) string {
|
||||
if strings.HasPrefix(path, "~/") {
|
||||
home, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
return filepath.Join(home, path[2:])
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package ssh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/errors"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
cryptossh "golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
// Client represents an SSH client
|
||||
type Client struct {
|
||||
host *models.Host
|
||||
timeout time.Duration
|
||||
client *cryptossh.Client
|
||||
config *cryptossh.ClientConfig
|
||||
hostKeyCallback cryptossh.HostKeyCallback
|
||||
passphraseCallback func() string // called to get passphrase for encrypted keys
|
||||
}
|
||||
|
||||
// NewClient creates a new SSH client
|
||||
func NewClient(host *models.Host, timeout time.Duration) *Client {
|
||||
return &Client{
|
||||
host: host,
|
||||
timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
// SetHostKeyCallback sets the host key verification callback
|
||||
func (c *Client) SetHostKeyCallback(cb cryptossh.HostKeyCallback) {
|
||||
c.hostKeyCallback = cb
|
||||
}
|
||||
|
||||
// SetPassphraseCallback sets the callback for getting key passphrases
|
||||
func (c *Client) SetPassphraseCallback(cb func() string) {
|
||||
c.passphraseCallback = cb
|
||||
}
|
||||
|
||||
// Connect establishes an SSH connection
|
||||
func (c *Client) Connect(ctx context.Context) error {
|
||||
// Create SSH configuration
|
||||
if err := c.setupConfig(); err != nil {
|
||||
return fmt.Errorf("failed to setup SSH config: %w", err)
|
||||
}
|
||||
|
||||
// Create connection context with timeout
|
||||
connCtx, cancel := context.WithTimeout(ctx, c.timeout)
|
||||
defer cancel()
|
||||
|
||||
// Establish TCP connection
|
||||
address := fmt.Sprintf("%s:%d", c.host.Hostname, c.host.Port)
|
||||
conn, err := c.dialTCP(connCtx, address)
|
||||
if err != nil {
|
||||
return errors.HandleSSHError(err)
|
||||
}
|
||||
|
||||
// Establish SSH connection over TCP
|
||||
sshConn, chans, reqs, err := cryptossh.NewClientConn(conn, address, c.config)
|
||||
if err != nil {
|
||||
conn.Close()
|
||||
return errors.HandleSSHError(err)
|
||||
}
|
||||
|
||||
c.client = cryptossh.NewClient(sshConn, chans, reqs)
|
||||
return nil
|
||||
}
|
||||
|
||||
// dialTCP establishes a TCP connection
|
||||
func (c *Client) dialTCP(ctx context.Context, address string) (net.Conn, error) {
|
||||
d := net.Dialer{}
|
||||
return d.DialContext(ctx, "tcp", address)
|
||||
}
|
||||
|
||||
// setupConfig creates SSH client configuration
|
||||
func (c *Client) setupConfig() error {
|
||||
hostKeyCallback := cryptossh.InsecureIgnoreHostKey()
|
||||
if c.hostKeyCallback != nil {
|
||||
hostKeyCallback = c.hostKeyCallback
|
||||
}
|
||||
|
||||
config := &cryptossh.ClientConfig{
|
||||
User: c.host.Username,
|
||||
HostKeyCallback: hostKeyCallback,
|
||||
Timeout: c.timeout,
|
||||
}
|
||||
|
||||
// Configure authentication methods
|
||||
authMethods, err := c.getAuthMethods()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to setup authentication: %w", err)
|
||||
}
|
||||
|
||||
config.Auth = authMethods
|
||||
c.config = config
|
||||
return nil
|
||||
}
|
||||
|
||||
// Execute runs a command on the remote server
|
||||
func (c *Client) Execute(_ context.Context, cmd string) (string, error) {
|
||||
if c.client == nil {
|
||||
return "", fmt.Errorf("not connected to server")
|
||||
}
|
||||
|
||||
session, err := c.client.NewSession()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create session: %w", err)
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
output, err := session.CombinedOutput(cmd)
|
||||
if err != nil {
|
||||
return string(output), fmt.Errorf("command execution failed: %w", err)
|
||||
}
|
||||
|
||||
return string(output), nil
|
||||
}
|
||||
|
||||
// Shell opens an interactive shell session
|
||||
func (c *Client) Shell() error {
|
||||
if c.client == nil {
|
||||
return fmt.Errorf("not connected to server")
|
||||
}
|
||||
|
||||
session, err := c.client.NewSession()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create session: %w", err)
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
// Get current terminal state
|
||||
fd := int(os.Stdin.Fd())
|
||||
oldState, err := term.MakeRaw(fd)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to set raw terminal: %w", err)
|
||||
}
|
||||
defer term.Restore(fd, oldState)
|
||||
|
||||
// Set up terminal modes
|
||||
modes := cryptossh.TerminalModes{
|
||||
cryptossh.ECHO: 1,
|
||||
cryptossh.TTY_OP_ISPEED: 14400,
|
||||
cryptossh.TTY_OP_OSPEED: 14400,
|
||||
}
|
||||
|
||||
// Get terminal size
|
||||
width, height, err := term.GetSize(fd)
|
||||
if err != nil {
|
||||
width = 80
|
||||
height = 24
|
||||
}
|
||||
|
||||
// Request PTY
|
||||
if err := session.RequestPty("xterm-256color", height, width, modes); err != nil {
|
||||
return fmt.Errorf("failed to request PTY: %w", err)
|
||||
}
|
||||
|
||||
// Handle window changes
|
||||
sigwinch := make(chan os.Signal, 1)
|
||||
signal.Notify(sigwinch, os.Signal(syscall.SIGWINCH))
|
||||
go func() {
|
||||
for range sigwinch {
|
||||
w, h, err := term.GetSize(fd)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
session.WindowChange(h, w)
|
||||
}
|
||||
}()
|
||||
defer signal.Stop(sigwinch)
|
||||
|
||||
// Link I/O
|
||||
session.Stdin = os.Stdin
|
||||
session.Stdout = os.Stdout
|
||||
session.Stderr = os.Stderr
|
||||
|
||||
// Start shell
|
||||
if err := session.Shell(); err != nil {
|
||||
return fmt.Errorf("failed to start shell: %w", err)
|
||||
}
|
||||
|
||||
// Wait for shell to exit
|
||||
if err := session.Wait(); err != nil {
|
||||
if exitErr, ok := err.(*cryptossh.ExitError); ok {
|
||||
if exitErr.ExitStatus() != 0 {
|
||||
return fmt.Errorf("shell exited with status %d", exitErr.ExitStatus())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("shell session error: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the SSH connection
|
||||
func (c *Client) Close() error {
|
||||
if c.client != nil {
|
||||
return c.client.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetClient returns the underlying SSH client
|
||||
func (c *Client) GetClient() *cryptossh.Client {
|
||||
return c.client
|
||||
}
|
||||
|
||||
// IsConnected returns true if the client has an active connection
|
||||
func (c *Client) IsConnected() bool {
|
||||
return c.client != nil
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/crypto"
|
||||
)
|
||||
|
||||
// JSONStorage implements Storage interface using JSON files
|
||||
type JSONStorage struct {
|
||||
dataDir string
|
||||
password string // master password for encryption (empty = no encryption)
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewJSONStorage creates a new JSON storage instance
|
||||
func NewJSONStorage(dataDir string) (*JSONStorage, error) {
|
||||
if err := os.MkdirAll(dataDir, 0700); err != nil {
|
||||
return nil, fmt.Errorf("failed to create data directory: %w", err)
|
||||
}
|
||||
|
||||
s := &JSONStorage{dataDir: dataDir}
|
||||
|
||||
if err := s.ensureDataFiles(); err != nil {
|
||||
return nil, fmt.Errorf("failed to initialize data files: %w", err)
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// SetPassword sets the master password for encryption/decryption
|
||||
func (s *JSONStorage) SetPassword(password string) {
|
||||
s.password = password
|
||||
}
|
||||
|
||||
// GetPassword returns the current master password
|
||||
func (s *JSONStorage) GetPassword() string {
|
||||
return s.password
|
||||
}
|
||||
|
||||
// IsEncrypted returns whether encryption is enabled
|
||||
func (s *JSONStorage) IsEncrypted() bool {
|
||||
return s.password != ""
|
||||
}
|
||||
|
||||
// IsDataEncrypted checks if the data files are actually encrypted
|
||||
func (s *JSONStorage) IsDataEncrypted() bool {
|
||||
path := filepath.Join(s.dataDir, "hosts.json")
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return crypto.IsEncrypted(string(data))
|
||||
}
|
||||
|
||||
func (s *JSONStorage) ensureDataFiles() error {
|
||||
files := map[string]string{
|
||||
"hosts.json": "hosts",
|
||||
"keys.json": "key_pairs",
|
||||
"snippets.json": "snippets",
|
||||
}
|
||||
|
||||
for file, key := range files {
|
||||
path := filepath.Join(s.dataDir, file)
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
data := map[string]interface{}{key: []interface{}{}}
|
||||
dataBytes, _ := json.MarshalIndent(data, "", " ")
|
||||
if err := os.WriteFile(path, dataBytes, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============ Host Operations ============
|
||||
|
||||
func (s *JSONStorage) getHostsPath() string {
|
||||
return filepath.Join(s.dataDir, "hosts.json")
|
||||
}
|
||||
|
||||
func (s *JSONStorage) ListHosts(ctx context.Context) ([]*models.Host, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.listHostsInternal()
|
||||
}
|
||||
|
||||
// listHostsInternal reads hosts WITHOUT locking (caller must hold lock)
|
||||
func (s *JSONStorage) listHostsInternal() ([]*models.Host, error) {
|
||||
var data struct {
|
||||
Hosts []*models.Host `json:"hosts"`
|
||||
}
|
||||
|
||||
if err := s.readJSON(s.getHostsPath(), &data); err != nil {
|
||||
return nil, fmt.Errorf("failed to read hosts: %w", err)
|
||||
}
|
||||
|
||||
return data.Hosts, nil
|
||||
}
|
||||
|
||||
func (s *JSONStorage) GetHost(ctx context.Context, id string) (*models.Host, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
hosts, err := s.listHostsInternal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, host := range hosts {
|
||||
if host.ID == id {
|
||||
return host, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("host not found: %s", id)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) SaveHost(ctx context.Context, host *models.Host) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if host.ID == "" {
|
||||
host.ID = uuid.New().String()
|
||||
}
|
||||
if host.CreatedAt.IsZero() {
|
||||
host.CreatedAt = time.Now()
|
||||
}
|
||||
host.UpdatedAt = time.Now()
|
||||
|
||||
hosts, err := s.listHostsInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
found := false
|
||||
for i, h := range hosts {
|
||||
if h.ID == host.ID {
|
||||
hosts[i] = host
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
hosts = append(hosts, host)
|
||||
}
|
||||
|
||||
return s.replaceHosts(hosts)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) DeleteHost(ctx context.Context, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
hosts, err := s.listHostsInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, host := range hosts {
|
||||
if host.ID == id {
|
||||
hosts = append(hosts[:i], hosts[i+1:]...)
|
||||
return s.replaceHosts(hosts)
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("host not found: %s", id)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) replaceHosts(hosts []*models.Host) error {
|
||||
var data struct {
|
||||
Hosts []*models.Host `json:"hosts"`
|
||||
}
|
||||
data.Hosts = hosts
|
||||
|
||||
bytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal hosts: %w", err)
|
||||
}
|
||||
|
||||
// Encrypt if password is set
|
||||
if s.password != "" {
|
||||
encrypted, err := crypto.Encrypt(bytes, s.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encrypt hosts: %w", err)
|
||||
}
|
||||
bytes = []byte(encrypted)
|
||||
}
|
||||
|
||||
return os.WriteFile(s.getHostsPath(), bytes, 0600)
|
||||
}
|
||||
|
||||
// ============ KeyPair Operations ============
|
||||
|
||||
func (s *JSONStorage) getKeysPath() string {
|
||||
return filepath.Join(s.dataDir, "keys.json")
|
||||
}
|
||||
|
||||
func (s *JSONStorage) ListKeyPairs(ctx context.Context) ([]*models.KeyPair, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.listKeyPairsInternal()
|
||||
}
|
||||
|
||||
// listKeyPairsInternal reads key pairs WITHOUT locking (caller must hold lock)
|
||||
func (s *JSONStorage) listKeyPairsInternal() ([]*models.KeyPair, error) {
|
||||
var data struct {
|
||||
KeyPairs []*models.KeyPair `json:"key_pairs"`
|
||||
}
|
||||
|
||||
if err := s.readJSON(s.getKeysPath(), &data); err != nil {
|
||||
return nil, fmt.Errorf("failed to read key pairs: %w", err)
|
||||
}
|
||||
|
||||
return data.KeyPairs, nil
|
||||
}
|
||||
|
||||
func (s *JSONStorage) GetKeyPair(ctx context.Context, id string) (*models.KeyPair, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
keys, err := s.listKeyPairsInternal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
if key.ID == id {
|
||||
return key, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("key pair not found: %s", id)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) SaveKeyPair(ctx context.Context, keyPair *models.KeyPair) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if keyPair.ID == "" {
|
||||
keyPair.ID = uuid.New().String()
|
||||
}
|
||||
if keyPair.CreatedAt.IsZero() {
|
||||
keyPair.CreatedAt = time.Now()
|
||||
}
|
||||
keyPair.UpdatedAt = time.Now()
|
||||
|
||||
keys, err := s.listKeyPairsInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
found := false
|
||||
for i, k := range keys {
|
||||
if k.ID == keyPair.ID {
|
||||
keys[i] = keyPair
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
keys = append(keys, keyPair)
|
||||
}
|
||||
|
||||
return s.replaceKeyPairs(keys)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) DeleteKeyPair(ctx context.Context, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
keys, err := s.listKeyPairsInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, key := range keys {
|
||||
if key.ID == id {
|
||||
keys = append(keys[:i], keys[i+1:]...)
|
||||
return s.replaceKeyPairs(keys)
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("key pair not found: %s", id)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) replaceKeyPairs(keys []*models.KeyPair) error {
|
||||
var data struct {
|
||||
KeyPairs []*models.KeyPair `json:"key_pairs"`
|
||||
}
|
||||
data.KeyPairs = keys
|
||||
|
||||
bytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal key pairs: %w", err)
|
||||
}
|
||||
|
||||
// Encrypt if password is set
|
||||
if s.password != "" {
|
||||
encrypted, err := crypto.Encrypt(bytes, s.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encrypt key pairs: %w", err)
|
||||
}
|
||||
bytes = []byte(encrypted)
|
||||
}
|
||||
|
||||
return os.WriteFile(s.getKeysPath(), bytes, 0600)
|
||||
}
|
||||
|
||||
// ============ Snippet Operations ============
|
||||
|
||||
func (s *JSONStorage) getSnippetsPath() string {
|
||||
return filepath.Join(s.dataDir, "snippets.json")
|
||||
}
|
||||
|
||||
func (s *JSONStorage) ListSnippets(ctx context.Context) ([]*models.Snippet, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
return s.listSnippetsInternal()
|
||||
}
|
||||
|
||||
// listSnippetsInternal reads snippets WITHOUT locking (caller must hold lock)
|
||||
func (s *JSONStorage) listSnippetsInternal() ([]*models.Snippet, error) {
|
||||
var data struct {
|
||||
Snippets []*models.Snippet `json:"snippets"`
|
||||
}
|
||||
|
||||
if err := s.readJSON(s.getSnippetsPath(), &data); err != nil {
|
||||
return nil, fmt.Errorf("failed to read snippets: %w", err)
|
||||
}
|
||||
|
||||
return data.Snippets, nil
|
||||
}
|
||||
|
||||
func (s *JSONStorage) GetSnippet(ctx context.Context, id string) (*models.Snippet, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
snippets, err := s.listSnippetsInternal()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, snippet := range snippets {
|
||||
if snippet.ID == id {
|
||||
return snippet, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("snippet not found: %s", id)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) SaveSnippet(ctx context.Context, snippet *models.Snippet) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if snippet.ID == "" {
|
||||
snippet.ID = uuid.New().String()
|
||||
}
|
||||
if snippet.CreatedAt.IsZero() {
|
||||
snippet.CreatedAt = time.Now()
|
||||
}
|
||||
snippet.UpdatedAt = time.Now()
|
||||
|
||||
snippets, err := s.listSnippetsInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
found := false
|
||||
for i, sn := range snippets {
|
||||
if sn.ID == snippet.ID {
|
||||
snippets[i] = snippet
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
snippets = append(snippets, snippet)
|
||||
}
|
||||
|
||||
return s.replaceSnippets(snippets)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) DeleteSnippet(ctx context.Context, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
snippets, err := s.listSnippetsInternal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for i, snippet := range snippets {
|
||||
if snippet.ID == id {
|
||||
snippets = append(snippets[:i], snippets[i+1:]...)
|
||||
return s.replaceSnippets(snippets)
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("snippet not found: %s", id)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) replaceSnippets(snippets []*models.Snippet) error {
|
||||
var data struct {
|
||||
Snippets []*models.Snippet `json:"snippets"`
|
||||
}
|
||||
data.Snippets = snippets
|
||||
|
||||
bytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal snippets: %w", err)
|
||||
}
|
||||
|
||||
// Encrypt if password is set
|
||||
if s.password != "" {
|
||||
encrypted, err := crypto.Encrypt(bytes, s.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encrypt snippets: %w", err)
|
||||
}
|
||||
bytes = []byte(encrypted)
|
||||
}
|
||||
|
||||
return os.WriteFile(s.getSnippetsPath(), bytes, 0600)
|
||||
}
|
||||
|
||||
// ============ Export/Import ============
|
||||
|
||||
func (s *JSONStorage) ExportData(ctx context.Context) (*ExportData, error) {
|
||||
hosts, err := s.ListHosts(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keys, err := s.ListKeyPairs(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
snippets, err := s.ListSnippets(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &ExportData{
|
||||
Hosts: hosts,
|
||||
KeyPairs: keys,
|
||||
Snippets: snippets,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *JSONStorage) ImportData(ctx context.Context, data *ExportData, strategy MergeStrategy) error {
|
||||
switch strategy {
|
||||
case MergeStrategyReplace:
|
||||
if err := s.replaceHosts(data.Hosts); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.replaceKeyPairs(data.KeyPairs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.replaceSnippets(data.Snippets); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
case MergeStrategyMerge:
|
||||
if err := s.mergeHosts(ctx, data.Hosts); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.mergeKeyPairs(ctx, data.KeyPairs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.mergeSnippets(ctx, data.Snippets); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
default:
|
||||
return fmt.Errorf("unknown merge strategy: %s", strategy)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *JSONStorage) mergeHosts(ctx context.Context, newHosts []*models.Host) error {
|
||||
existingHosts, err := s.ListHosts(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingIDs := make(map[string]bool)
|
||||
for _, host := range existingHosts {
|
||||
existingIDs[host.ID] = true
|
||||
}
|
||||
|
||||
for _, newHost := range newHosts {
|
||||
if !existingIDs[newHost.ID] {
|
||||
existingHosts = append(existingHosts, newHost)
|
||||
}
|
||||
}
|
||||
|
||||
return s.replaceHosts(existingHosts)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) mergeKeyPairs(ctx context.Context, newKeys []*models.KeyPair) error {
|
||||
existingKeys, err := s.ListKeyPairs(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingIDs := make(map[string]bool)
|
||||
for _, key := range existingKeys {
|
||||
existingIDs[key.ID] = true
|
||||
}
|
||||
|
||||
for _, newKey := range newKeys {
|
||||
if !existingIDs[newKey.ID] {
|
||||
existingKeys = append(existingKeys, newKey)
|
||||
}
|
||||
}
|
||||
|
||||
return s.replaceKeyPairs(existingKeys)
|
||||
}
|
||||
|
||||
func (s *JSONStorage) mergeSnippets(ctx context.Context, newSnippets []*models.Snippet) error {
|
||||
existingSnippets, err := s.ListSnippets(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existingIDs := make(map[string]bool)
|
||||
for _, snippet := range existingSnippets {
|
||||
existingIDs[snippet.ID] = true
|
||||
}
|
||||
|
||||
for _, newSnippet := range newSnippets {
|
||||
if !existingIDs[newSnippet.ID] {
|
||||
existingSnippets = append(existingSnippets, newSnippet)
|
||||
}
|
||||
}
|
||||
|
||||
return s.replaceSnippets(existingSnippets)
|
||||
}
|
||||
|
||||
// ============ Helpers ============
|
||||
|
||||
func (s *JSONStorage) readJSON(path string, v interface{}) error {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Decrypt if password is set and data looks encrypted
|
||||
if s.password != "" && crypto.IsEncrypted(string(data)) {
|
||||
decrypted, err := crypto.Decrypt(string(data), s.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("decryption failed: %w", err)
|
||||
}
|
||||
data = decrypted
|
||||
}
|
||||
|
||||
return json.Unmarshal(data, v)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
// Storage defines the interface for data persistence
|
||||
type Storage interface {
|
||||
// Host operations
|
||||
ListHosts(ctx context.Context) ([]*models.Host, error)
|
||||
GetHost(ctx context.Context, id string) (*models.Host, error)
|
||||
SaveHost(ctx context.Context, host *models.Host) error
|
||||
DeleteHost(ctx context.Context, id string) error
|
||||
|
||||
// KeyPair operations
|
||||
ListKeyPairs(ctx context.Context) ([]*models.KeyPair, error)
|
||||
GetKeyPair(ctx context.Context, id string) (*models.KeyPair, error)
|
||||
SaveKeyPair(ctx context.Context, keyPair *models.KeyPair) error
|
||||
DeleteKeyPair(ctx context.Context, id string) error
|
||||
|
||||
// Snippet operations
|
||||
ListSnippets(ctx context.Context) ([]*models.Snippet, error)
|
||||
GetSnippet(ctx context.Context, id string) (*models.Snippet, error)
|
||||
SaveSnippet(ctx context.Context, snippet *models.Snippet) error
|
||||
DeleteSnippet(ctx context.Context, id string) error
|
||||
|
||||
// Export/Import
|
||||
ExportData(ctx context.Context) (*ExportData, error)
|
||||
ImportData(ctx context.Context, data *ExportData, strategy MergeStrategy) error
|
||||
}
|
||||
|
||||
// ExportData represents the data structure for export/import
|
||||
type ExportData struct {
|
||||
Hosts []*models.Host `json:"hosts"`
|
||||
KeyPairs []*models.KeyPair `json:"key_pairs"`
|
||||
Snippets []*models.Snippet `json:"snippets"`
|
||||
}
|
||||
|
||||
// MergeStrategy defines how imported data is merged with existing data
|
||||
type MergeStrategy string
|
||||
|
||||
const (
|
||||
// MergeStrategyReplace replaces all existing data with imported data
|
||||
MergeStrategyReplace MergeStrategy = "replace"
|
||||
// MergeStrategyMerge keeps existing data and adds only new items
|
||||
MergeStrategyMerge MergeStrategy = "merge"
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
// ErrorSeverity indicates the level of an error message
|
||||
type ErrorSeverity int
|
||||
|
||||
const (
|
||||
SevError ErrorSeverity = iota
|
||||
SevWarning
|
||||
SevInfo
|
||||
)
|
||||
|
||||
// ErrorBanner displays a structured error message with title, details, and hints
|
||||
type ErrorBanner struct {
|
||||
Title string
|
||||
Detail string
|
||||
Hints []string
|
||||
Severity ErrorSeverity
|
||||
AutoDismiss bool
|
||||
DismissAfter time.Duration
|
||||
createdAt time.Time
|
||||
visible bool
|
||||
}
|
||||
|
||||
// NewErrorBanner creates a new error banner with the given severity
|
||||
func NewErrorBanner(severity ErrorSeverity) *ErrorBanner {
|
||||
return &ErrorBanner{
|
||||
Severity: severity,
|
||||
AutoDismiss: true,
|
||||
DismissAfter: 5 * time.Second,
|
||||
visible: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Show displays the error banner with the given message
|
||||
func (b *ErrorBanner) Show(title, detail string, hints ...string) {
|
||||
b.Title = title
|
||||
b.Detail = detail
|
||||
b.Hints = hints
|
||||
b.visible = true
|
||||
b.createdAt = time.Now()
|
||||
}
|
||||
|
||||
// Hide hides the error banner
|
||||
func (b *ErrorBanner) Hide() {
|
||||
b.visible = false
|
||||
}
|
||||
|
||||
// IsVisible returns whether the banner is currently visible
|
||||
func (b *ErrorBanner) IsVisible() bool {
|
||||
return b.visible
|
||||
}
|
||||
|
||||
// Update checks if auto-dismiss time has elapsed
|
||||
func (b *ErrorBanner) Update() {
|
||||
if b.visible && b.AutoDismiss && time.Since(b.createdAt) > b.DismissAfter {
|
||||
b.visible = false
|
||||
}
|
||||
}
|
||||
|
||||
// View renders the error banner
|
||||
func (b *ErrorBanner) View(width int) string {
|
||||
if !b.visible {
|
||||
return ""
|
||||
}
|
||||
|
||||
var (
|
||||
titleStyle lipgloss.Style
|
||||
borderColor lipgloss.Color
|
||||
prefix string
|
||||
)
|
||||
|
||||
switch b.Severity {
|
||||
case SevError:
|
||||
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ea6962")).Bold(true)
|
||||
borderColor = lipgloss.Color("#ea6962")
|
||||
prefix = "✖"
|
||||
case SevWarning:
|
||||
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#d8a657")).Bold(true)
|
||||
borderColor = lipgloss.Color("#d8a657")
|
||||
prefix = "⚠"
|
||||
case SevInfo:
|
||||
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#7daea3")).Bold(true)
|
||||
borderColor = lipgloss.Color("#7daea3")
|
||||
prefix = "ℹ"
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
|
||||
// Title line with prefix
|
||||
sb.WriteString(titleStyle.Render(fmt.Sprintf("%s %s", prefix, b.Title)))
|
||||
|
||||
// Detail line
|
||||
if b.Detail != "" {
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(strings.Repeat(" ", len(prefix)+1))
|
||||
detailStyle := lipgloss.NewStyle().Foreground(activeTheme.Fg)
|
||||
sb.WriteString(detailStyle.Render(b.Detail))
|
||||
}
|
||||
|
||||
// Hints
|
||||
if len(b.Hints) > 0 {
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(strings.Repeat(" ", len(prefix)+1))
|
||||
hintStyle := lipgloss.NewStyle().Foreground(activeTheme.FgMute)
|
||||
sb.WriteString(hintStyle.Render("Hints:"))
|
||||
for i, hint := range b.Hints {
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(strings.Repeat(" ", len(prefix)+2))
|
||||
sb.WriteString(hintStyle.Render(fmt.Sprintf("%d. %s", i+1, hint)))
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap in a styled box
|
||||
borderStyle := lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(borderColor).
|
||||
Padding(0, 1).
|
||||
Width(min(width-2, 80))
|
||||
|
||||
return borderStyle.Render(sb.String())
|
||||
}
|
||||
|
||||
// min returns the smaller of two integers
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
type formMode int
|
||||
|
||||
const (
|
||||
formModeAdd formMode = iota
|
||||
formModeEdit
|
||||
)
|
||||
|
||||
type fieldID int
|
||||
|
||||
const (
|
||||
fieldName fieldID = iota
|
||||
fieldHostname
|
||||
fieldPort
|
||||
fieldUsername
|
||||
fieldAuthType
|
||||
fieldPassword
|
||||
fieldGroup
|
||||
fieldTags
|
||||
fieldNotes
|
||||
fieldCount
|
||||
)
|
||||
|
||||
var fieldLabels = map[fieldID]string{
|
||||
fieldName: "Name",
|
||||
fieldHostname: "Hostname",
|
||||
fieldPort: "Port",
|
||||
fieldUsername: "Username",
|
||||
fieldAuthType: "Auth Type",
|
||||
fieldPassword: "Password",
|
||||
fieldGroup: "Group",
|
||||
fieldTags: "Tags",
|
||||
fieldNotes: "Notes",
|
||||
}
|
||||
|
||||
// HostFormTab is a tab for adding/editing hosts
|
||||
type HostFormTab struct {
|
||||
mode formMode
|
||||
editing *models.Host
|
||||
dataDir string
|
||||
|
||||
inputs []textinput.Model
|
||||
focus fieldID
|
||||
width int
|
||||
height int
|
||||
|
||||
err error
|
||||
saved bool
|
||||
}
|
||||
|
||||
// NewAddHostFormTab creates a new host add form tab
|
||||
func NewAddHostFormTab(dataDir string) *HostFormTab {
|
||||
return newHostFormTab(formModeAdd, nil, dataDir)
|
||||
}
|
||||
|
||||
// NewEditHostFormTab creates a new host edit form tab
|
||||
func NewEditHostFormTab(host *models.Host, dataDir string) *HostFormTab {
|
||||
return newHostFormTab(formModeEdit, host, dataDir)
|
||||
}
|
||||
|
||||
func newHostFormTab(mode formMode, host *models.Host, dataDir string) *HostFormTab {
|
||||
inputs := make([]textinput.Model, fieldCount)
|
||||
|
||||
for i := range inputs {
|
||||
inputs[i] = textinput.New()
|
||||
inputs[i].Prompt = ""
|
||||
}
|
||||
|
||||
inputs[fieldName].Placeholder = "My Server"
|
||||
inputs[fieldHostname].Placeholder = "192.168.1.1 or server.example.com"
|
||||
inputs[fieldPort].Placeholder = "22"
|
||||
inputs[fieldPort].SetValue("22")
|
||||
inputs[fieldUsername].Placeholder = "root"
|
||||
inputs[fieldAuthType].SetValue("password")
|
||||
inputs[fieldPassword].EchoMode = textinput.EchoPassword
|
||||
inputs[fieldPassword].Placeholder = "Enter password"
|
||||
inputs[fieldGroup].Placeholder = "production"
|
||||
inputs[fieldTags].Placeholder = "web,backend"
|
||||
inputs[fieldNotes].Placeholder = "Optional notes..."
|
||||
|
||||
if mode == formModeEdit && host != nil {
|
||||
inputs[fieldName].SetValue(host.Name)
|
||||
inputs[fieldHostname].SetValue(host.Hostname)
|
||||
inputs[fieldPort].SetValue(strconv.Itoa(host.Port))
|
||||
inputs[fieldUsername].SetValue(host.Username)
|
||||
inputs[fieldAuthType].SetValue(host.Auth.Type)
|
||||
if host.Auth.Password != "" {
|
||||
inputs[fieldPassword].SetValue(host.Auth.Password)
|
||||
}
|
||||
inputs[fieldGroup].SetValue(host.Group)
|
||||
inputs[fieldTags].SetValue(strings.Join(host.Tags, ","))
|
||||
inputs[fieldNotes].SetValue(host.Notes)
|
||||
}
|
||||
|
||||
inputs[fieldName].Focus()
|
||||
inputs[fieldName].Prompt = "> "
|
||||
|
||||
return &HostFormTab{
|
||||
mode: mode,
|
||||
editing: host,
|
||||
dataDir: dataDir,
|
||||
inputs: inputs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *HostFormTab) Name() string {
|
||||
if t.mode == formModeEdit {
|
||||
return "Edit: " + t.editing.Name
|
||||
}
|
||||
return "Add Host"
|
||||
}
|
||||
|
||||
func (t *HostFormTab) Init() tea.Cmd {
|
||||
return textinput.Blink
|
||||
}
|
||||
|
||||
func (t *HostFormTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
if t.saved {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
t.width = msg.Width
|
||||
t.height = msg.Height
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
return t, func() tea.Msg { return closeFormMsg{} }
|
||||
|
||||
case "enter":
|
||||
if t.focus == fieldAuthType {
|
||||
t.toggleAuthType()
|
||||
return t, nil
|
||||
}
|
||||
if t.focus == fieldCount-1 {
|
||||
return t.submit()
|
||||
}
|
||||
t.nextField()
|
||||
|
||||
case " ", "left", "right":
|
||||
if t.focus == fieldAuthType {
|
||||
t.toggleAuthType()
|
||||
return t, nil
|
||||
}
|
||||
// pass through to text input (allow typing spaces, cursor nav)
|
||||
var cmd tea.Cmd
|
||||
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||
return t, cmd
|
||||
|
||||
case "tab", "down":
|
||||
t.nextField()
|
||||
|
||||
case "shift+tab", "up":
|
||||
t.prevField()
|
||||
|
||||
case "ctrl+s":
|
||||
return t.submit()
|
||||
|
||||
default:
|
||||
if t.focus == fieldAuthType {
|
||||
// ignore typing on auth type field
|
||||
return t, nil
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||
return t, cmd
|
||||
}
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (t *HostFormTab) nextField() {
|
||||
t.inputs[t.focus].Blur()
|
||||
t.inputs[t.focus].Prompt = ""
|
||||
t.focus++
|
||||
if t.focus >= fieldCount {
|
||||
t.focus = fieldCount - 1
|
||||
}
|
||||
t.inputs[t.focus].Focus()
|
||||
t.inputs[t.focus].Prompt = "> "
|
||||
}
|
||||
|
||||
func (t *HostFormTab) prevField() {
|
||||
t.inputs[t.focus].Blur()
|
||||
t.inputs[t.focus].Prompt = ""
|
||||
t.focus--
|
||||
if t.focus < 0 {
|
||||
t.focus = 0
|
||||
}
|
||||
t.inputs[t.focus].Focus()
|
||||
t.inputs[t.focus].Prompt = "> "
|
||||
}
|
||||
|
||||
func cycleAuthType(current string) string {
|
||||
switch current {
|
||||
case "password":
|
||||
return "key"
|
||||
case "key":
|
||||
return "password"
|
||||
default:
|
||||
return "password"
|
||||
}
|
||||
}
|
||||
|
||||
func (t *HostFormTab) toggleAuthType() {
|
||||
current := t.inputs[fieldAuthType].Value()
|
||||
t.inputs[fieldAuthType].SetValue(cycleAuthType(current))
|
||||
}
|
||||
|
||||
func (t *HostFormTab) submit() (Tab, tea.Cmd) {
|
||||
name := t.inputs[fieldName].Value()
|
||||
hostname := t.inputs[fieldHostname].Value()
|
||||
username := t.inputs[fieldUsername].Value()
|
||||
|
||||
if name == "" || hostname == "" || username == "" {
|
||||
t.err = fmt.Errorf("name, hostname, and username are required")
|
||||
return t, nil
|
||||
}
|
||||
|
||||
port := 22
|
||||
if p := t.inputs[fieldPort].Value(); p != "" {
|
||||
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
|
||||
port = parsed
|
||||
}
|
||||
}
|
||||
|
||||
authType := t.inputs[fieldAuthType].Value()
|
||||
if authType == "" {
|
||||
authType = "password"
|
||||
}
|
||||
|
||||
var tags []string
|
||||
if tagStr := t.inputs[fieldTags].Value(); tagStr != "" {
|
||||
for _, tag := range strings.Split(tagStr, ",") {
|
||||
if trimmed := strings.TrimSpace(tag); trimmed != "" {
|
||||
tags = append(tags, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var host *models.Host
|
||||
if t.mode == formModeEdit && t.editing != nil {
|
||||
host = t.editing
|
||||
host.Name = name
|
||||
host.Hostname = hostname
|
||||
host.Port = port
|
||||
host.Username = username
|
||||
host.Auth.Type = authType
|
||||
host.Auth.Password = t.inputs[fieldPassword].Value()
|
||||
host.Group = t.inputs[fieldGroup].Value()
|
||||
host.Tags = tags
|
||||
host.Notes = t.inputs[fieldNotes].Value()
|
||||
} else {
|
||||
host = &models.Host{
|
||||
ID: uuid.New().String(),
|
||||
Name: name,
|
||||
Hostname: hostname,
|
||||
Port: port,
|
||||
Username: username,
|
||||
Auth: models.AuthConfig{
|
||||
Type: authType,
|
||||
Password: t.inputs[fieldPassword].Value(),
|
||||
},
|
||||
Group: t.inputs[fieldGroup].Value(),
|
||||
Tags: tags,
|
||||
Notes: t.inputs[fieldNotes].Value(),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
t.saved = true
|
||||
return t, saveHostCmd(host, t.dataDir)
|
||||
}
|
||||
|
||||
func (t *HostFormTab) View() string {
|
||||
contentW := t.width - 12
|
||||
if contentW < 30 {
|
||||
contentW = 30
|
||||
}
|
||||
if contentW > 70 {
|
||||
contentW = 70
|
||||
}
|
||||
|
||||
var inner strings.Builder
|
||||
|
||||
title := "Add New Host"
|
||||
if t.mode == formModeEdit {
|
||||
title = "Edit Host"
|
||||
}
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(title)))
|
||||
inner.WriteString("\n\n")
|
||||
|
||||
if t.err != nil {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||
inner.WriteString("\n\n")
|
||||
}
|
||||
|
||||
for i := fieldID(0); i < fieldCount; i++ {
|
||||
input := t.inputs[i]
|
||||
|
||||
label := fieldLabels[i]
|
||||
style := SubtitleStyle
|
||||
if i == t.focus {
|
||||
style = HighlightStyle
|
||||
}
|
||||
inner.WriteString(style.Render(label + ":"))
|
||||
inner.WriteString("\n")
|
||||
|
||||
if i == fieldAuthType {
|
||||
current := input.Value()
|
||||
pills := []string{"password", "key"}
|
||||
var parts []string
|
||||
for _, p := range pills {
|
||||
if p == current {
|
||||
if i == t.focus {
|
||||
parts = append(parts, SelectedStyle.Render(" "+p+" "))
|
||||
} else {
|
||||
parts = append(parts, TagStyle.Render(" "+p+" "))
|
||||
}
|
||||
} else {
|
||||
parts = append(parts, SubtitleStyle.Render(" "+p+" "))
|
||||
}
|
||||
}
|
||||
inner.WriteString(" ")
|
||||
inner.WriteString(strings.Join(parts, " "))
|
||||
inner.WriteString("\n")
|
||||
if i == t.focus {
|
||||
inner.WriteString(" " + InfoStyle.Render("Space/←/→ to toggle"))
|
||||
}
|
||||
inner.WriteString("\n\n")
|
||||
} else {
|
||||
renderedInput := input.View()
|
||||
inner.WriteString(" ")
|
||||
inner.WriteString(renderedInput)
|
||||
inner.WriteString("\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
inner.WriteString("\n")
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close Tab:next Shift+Tab:prev ↑↓:nav Enter:next Ctrl+S:save Esc:cancel"
|
||||
footerWrapped := wrapFooter(footerText, contentW)
|
||||
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
|
||||
box := BorderStyle.Render(inner.String())
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (t *HostFormTab) Close() {}
|
||||
@@ -0,0 +1,266 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
// HostListTab is the host list tab
|
||||
type HostListTab struct {
|
||||
hosts []*models.Host
|
||||
selectedIndex int
|
||||
err error
|
||||
width int
|
||||
height int
|
||||
}
|
||||
|
||||
// NewHostListTab creates a new host list tab
|
||||
func NewHostListTab() *HostListTab {
|
||||
return &HostListTab{
|
||||
selectedIndex: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Init initializes the tab
|
||||
func (t *HostListTab) Init() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Name returns the tab name
|
||||
func (t *HostListTab) Name() string {
|
||||
return "Hosts"
|
||||
}
|
||||
|
||||
// Update handles messages for the host list
|
||||
func (t *HostListTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
t.width = msg.Width
|
||||
t.height = msg.Height
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "up", "k":
|
||||
if t.selectedIndex > 0 {
|
||||
t.selectedIndex--
|
||||
}
|
||||
|
||||
case "down", "j":
|
||||
if t.selectedIndex < len(t.hosts)-1 {
|
||||
t.selectedIndex++
|
||||
}
|
||||
|
||||
case "enter", " ":
|
||||
if len(t.hosts) > 0 {
|
||||
host := t.hosts[t.selectedIndex]
|
||||
return t, func() tea.Msg {
|
||||
return sshConnectToMsg{host: host}
|
||||
}
|
||||
}
|
||||
|
||||
case "ctrl+n":
|
||||
return t, func() tea.Msg {
|
||||
return openHostFormMsg{}
|
||||
}
|
||||
|
||||
case "ctrl+e", "e":
|
||||
if len(t.hosts) > 0 {
|
||||
host := t.hosts[t.selectedIndex]
|
||||
return t, func() tea.Msg {
|
||||
return openHostFormMsg{editing: host}
|
||||
}
|
||||
}
|
||||
|
||||
case "ctrl+f":
|
||||
if len(t.hosts) > 0 {
|
||||
host := t.hosts[t.selectedIndex]
|
||||
return t, func() tea.Msg {
|
||||
return openSFTPMsg{host: host}
|
||||
}
|
||||
}
|
||||
|
||||
case "ctrl+k":
|
||||
return t, func() tea.Msg {
|
||||
return openKeyListMsg{}
|
||||
}
|
||||
|
||||
case "ctrl+p":
|
||||
return t, func() tea.Msg {
|
||||
return openSnippetListMsg{}
|
||||
}
|
||||
|
||||
case "q", "ctrl+c":
|
||||
return t, func() tea.Msg {
|
||||
return quitMsg{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// View renders the host list — responsive layout
|
||||
func (t *HostListTab) View() string {
|
||||
var b strings.Builder
|
||||
|
||||
// Error display
|
||||
if t.err != nil {
|
||||
b.WriteString(ErrorStyle.Render(fmt.Sprintf(" Error: %v ", t.err)))
|
||||
b.WriteString("\n")
|
||||
t.err = nil
|
||||
}
|
||||
|
||||
if len(t.hosts) == 0 {
|
||||
msg := SubtitleStyle.Render("(no connections — press Ctrl+N to add)")
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, msg))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Scrolling
|
||||
availH := t.height - 10
|
||||
if availH < 1 {
|
||||
availH = 1
|
||||
}
|
||||
maxHosts := availH
|
||||
if maxHosts > len(t.hosts) {
|
||||
maxHosts = len(t.hosts)
|
||||
}
|
||||
|
||||
start := t.selectedIndex - maxHosts/2
|
||||
if start < 0 {
|
||||
start = 0
|
||||
}
|
||||
if start+maxHosts > len(t.hosts) {
|
||||
start = len(t.hosts) - maxHosts
|
||||
}
|
||||
|
||||
// Responsive width calculation
|
||||
sidePad := adaptiveSidePad(t.width)
|
||||
titlePlain := "Connection List"
|
||||
|
||||
// Measure content rows to determine natural box width
|
||||
widestContent := lipgloss.Width(titlePlain)
|
||||
for i := start; i < start+maxHosts; i++ {
|
||||
host := t.hosts[i]
|
||||
raw := fmt.Sprintf(" %-12s %-18s :%d", host.Name, host.Hostname, host.Port)
|
||||
if w := lipgloss.Width(raw); w > widestContent {
|
||||
widestContent = w
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp box to terminal width
|
||||
targetW := clampWidth(widestContent+sidePad*2, t.width)
|
||||
innerW := targetW - sidePad*2
|
||||
if innerW < 1 {
|
||||
innerW = 1
|
||||
}
|
||||
|
||||
// Build rows with adaptive format
|
||||
type styledRow struct {
|
||||
text string
|
||||
plain string
|
||||
}
|
||||
var rows []styledRow
|
||||
|
||||
for i := start; i < start+maxHosts; i++ {
|
||||
host := t.hosts[i]
|
||||
var raw string
|
||||
if innerW >= 35 {
|
||||
raw = fmt.Sprintf(" %-12s %-18s :%d", host.Name, host.Hostname, host.Port)
|
||||
} else {
|
||||
raw = fmt.Sprintf(" %s %s:%d", host.Name, host.Hostname, host.Port)
|
||||
}
|
||||
if lipgloss.Width(raw) > innerW {
|
||||
raw = truncateStr(raw, innerW)
|
||||
}
|
||||
|
||||
var styled string
|
||||
if i == t.selectedIndex {
|
||||
styled = lipgloss.NewStyle().
|
||||
Foreground(gbFg).
|
||||
Background(gbBgSel).
|
||||
Bold(true).
|
||||
Render("▸ " + strings.TrimLeft(raw, " "))
|
||||
} else {
|
||||
styled = lipgloss.NewStyle().Foreground(gbFg).Render(raw)
|
||||
}
|
||||
rows = append(rows, styledRow{text: styled, plain: raw})
|
||||
}
|
||||
|
||||
// Footer (wrapped to fit innerW)
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Enter:SSH Ctrl+N:add Ctrl+E:edit Ctrl+F:SFTP Ctrl+K:keys Ctrl+P:snippets q:quit"
|
||||
footerWrapped := wrapFooter(footerText, innerW)
|
||||
|
||||
// Title
|
||||
title := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(titlePlain)
|
||||
|
||||
var content strings.Builder
|
||||
|
||||
content.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, title))
|
||||
content.WriteString("\n\n")
|
||||
|
||||
for _, r := range rows {
|
||||
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, r.text)
|
||||
content.WriteString(line)
|
||||
content.WriteString("\n")
|
||||
}
|
||||
content.WriteString("\n")
|
||||
|
||||
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||
content.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
content.WriteString("\n")
|
||||
}
|
||||
|
||||
box := BorderStyle.Render(content.String())
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Close is a no-op for host list tab
|
||||
func (t *HostListTab) Close() {}
|
||||
|
||||
// SetHosts sets the host list
|
||||
func (t *HostListTab) SetHosts(hosts []*models.Host) {
|
||||
t.hosts = hosts
|
||||
if len(hosts) > 0 && t.selectedIndex >= len(hosts) {
|
||||
t.selectedIndex = len(hosts) - 1
|
||||
}
|
||||
}
|
||||
|
||||
// Hosts returns the host list
|
||||
func (t *HostListTab) Hosts() []*models.Host {
|
||||
return t.hosts
|
||||
}
|
||||
|
||||
// SelectedIndex returns the selected index
|
||||
func (t *HostListTab) SelectedIndex() int {
|
||||
return t.selectedIndex
|
||||
}
|
||||
|
||||
// FindHostListTab finds the first HostListTab in a list of tabs
|
||||
func FindHostListTab(tabs []Tab) *HostListTab {
|
||||
for _, tab := range tabs {
|
||||
if ht, ok := tab.(*HostListTab); ok {
|
||||
return ht
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// formatTagsForTUI formats tags for TUI display
|
||||
func formatTagsForTUI(tags []string) string {
|
||||
if len(tags) == 0 {
|
||||
return ""
|
||||
}
|
||||
var formatted []string
|
||||
for _, tag := range tags {
|
||||
formatted = append(formatted, "["+tag+"]")
|
||||
}
|
||||
return strings.Join(formatted, " ")
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
type keyFormMode int
|
||||
|
||||
const (
|
||||
keyFormAdd keyFormMode = iota
|
||||
keyFormEdit
|
||||
)
|
||||
|
||||
type keyFieldID int
|
||||
|
||||
const (
|
||||
keyFieldName keyFieldID = iota
|
||||
keyFieldType
|
||||
keyFieldPrivateKey
|
||||
keyFieldPassphrase
|
||||
keyFieldCount
|
||||
)
|
||||
|
||||
var keyFieldLabels = map[keyFieldID]string{
|
||||
keyFieldName: "Name",
|
||||
keyFieldType: "Type (rsa/ed25519/ecdsa)",
|
||||
keyFieldPrivateKey: "Private Key (PEM)",
|
||||
keyFieldPassphrase: "Passphrase",
|
||||
}
|
||||
|
||||
// KeyFormTab is a tab for adding/editing SSH key pairs
|
||||
type KeyFormTab struct {
|
||||
mode keyFormMode
|
||||
editing *models.KeyPair
|
||||
dataDir string
|
||||
|
||||
inputs []textinput.Model
|
||||
focus keyFieldID
|
||||
width int
|
||||
height int
|
||||
|
||||
err error
|
||||
saved bool
|
||||
}
|
||||
|
||||
func NewAddKeyFormTab(dataDir string) *KeyFormTab {
|
||||
return newKeyFormTab(keyFormAdd, nil, dataDir)
|
||||
}
|
||||
|
||||
func NewEditKeyFormTab(key *models.KeyPair, dataDir string) *KeyFormTab {
|
||||
return newKeyFormTab(keyFormEdit, key, dataDir)
|
||||
}
|
||||
|
||||
func newKeyFormTab(mode keyFormMode, key *models.KeyPair, dataDir string) *KeyFormTab {
|
||||
inputs := make([]textinput.Model, keyFieldCount)
|
||||
for i := range inputs {
|
||||
inputs[i] = textinput.New()
|
||||
inputs[i].Prompt = ""
|
||||
}
|
||||
|
||||
inputs[keyFieldName].Placeholder = "My SSH Key"
|
||||
inputs[keyFieldType].Placeholder = "ed25519"
|
||||
inputs[keyFieldType].SetValue("ed25519")
|
||||
inputs[keyFieldPrivateKey].Placeholder = "-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||
inputs[keyFieldPassphrase].Placeholder = "Optional passphrase"
|
||||
|
||||
if mode == keyFormEdit && key != nil {
|
||||
inputs[keyFieldName].SetValue(key.Name)
|
||||
inputs[keyFieldType].SetValue(key.Type)
|
||||
inputs[keyFieldPrivateKey].SetValue(key.PrivateKey)
|
||||
inputs[keyFieldPassphrase].SetValue(key.Passphrase)
|
||||
}
|
||||
|
||||
inputs[keyFieldName].Focus()
|
||||
inputs[keyFieldName].Prompt = "> "
|
||||
|
||||
return &KeyFormTab{
|
||||
mode: mode,
|
||||
editing: key,
|
||||
dataDir: dataDir,
|
||||
inputs: inputs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) Name() string {
|
||||
if t.mode == keyFormEdit {
|
||||
return "Edit Key"
|
||||
}
|
||||
return "Add Key"
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) Init() tea.Cmd {
|
||||
return textinput.Blink
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
if t.saved {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
t.width = msg.Width
|
||||
t.height = msg.Height
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
return t, func() tea.Msg { return closeFormMsg{} }
|
||||
|
||||
case "enter":
|
||||
if t.focus == keyFieldCount-1 {
|
||||
return t.submit()
|
||||
}
|
||||
t.nextField()
|
||||
|
||||
case "tab", "down":
|
||||
t.nextField()
|
||||
|
||||
case "shift+tab", "up":
|
||||
t.prevField()
|
||||
|
||||
case "ctrl+s":
|
||||
return t.submit()
|
||||
|
||||
default:
|
||||
var cmd tea.Cmd
|
||||
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||
return t, cmd
|
||||
}
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) nextField() {
|
||||
t.inputs[t.focus].Blur()
|
||||
t.inputs[t.focus].Prompt = ""
|
||||
t.focus++
|
||||
if t.focus >= keyFieldCount {
|
||||
t.focus = keyFieldCount - 1
|
||||
}
|
||||
t.inputs[t.focus].Focus()
|
||||
t.inputs[t.focus].Prompt = "> "
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) prevField() {
|
||||
t.inputs[t.focus].Blur()
|
||||
t.inputs[t.focus].Prompt = ""
|
||||
t.focus--
|
||||
if t.focus < 0 {
|
||||
t.focus = 0
|
||||
}
|
||||
t.inputs[t.focus].Focus()
|
||||
t.inputs[t.focus].Prompt = "> "
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) submit() (Tab, tea.Cmd) {
|
||||
name := t.inputs[keyFieldName].Value()
|
||||
privateKey := t.inputs[keyFieldPrivateKey].Value()
|
||||
|
||||
if name == "" || privateKey == "" {
|
||||
t.err = fmt.Errorf("name and private key are required")
|
||||
return t, nil
|
||||
}
|
||||
|
||||
var key *models.KeyPair
|
||||
if t.mode == keyFormEdit && t.editing != nil {
|
||||
key = t.editing
|
||||
key.Name = name
|
||||
key.Type = t.inputs[keyFieldType].Value()
|
||||
key.PrivateKey = privateKey
|
||||
key.Passphrase = t.inputs[keyFieldPassphrase].Value()
|
||||
} else {
|
||||
key = &models.KeyPair{
|
||||
ID: uuid.New().String(),
|
||||
Name: name,
|
||||
Type: t.inputs[keyFieldType].Value(),
|
||||
PrivateKey: privateKey,
|
||||
Passphrase: t.inputs[keyFieldPassphrase].Value(),
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
t.saved = true
|
||||
return t, saveKeyCmd(key, t.dataDir)
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) View() string {
|
||||
contentW := t.width - 12
|
||||
if contentW < 30 {
|
||||
contentW = 30
|
||||
}
|
||||
if contentW > 70 {
|
||||
contentW = 70
|
||||
}
|
||||
|
||||
var inner strings.Builder
|
||||
|
||||
title := "Add SSH Key"
|
||||
if t.mode == keyFormEdit {
|
||||
title = "Edit SSH Key"
|
||||
}
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(title)))
|
||||
inner.WriteString("\n\n")
|
||||
|
||||
if t.err != nil {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||
inner.WriteString("\n\n")
|
||||
}
|
||||
|
||||
for i := keyFieldID(0); i < keyFieldCount; i++ {
|
||||
input := t.inputs[i]
|
||||
label := keyFieldLabels[i]
|
||||
style := SubtitleStyle
|
||||
if i == t.focus {
|
||||
style = HighlightStyle
|
||||
}
|
||||
inner.WriteString(style.Render(label + ":"))
|
||||
inner.WriteString("\n ")
|
||||
inner.WriteString(input.View())
|
||||
inner.WriteString("\n\n")
|
||||
}
|
||||
|
||||
inner.WriteString("\n")
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close Tab:next Shift+Tab:prev ↑↓:nav Enter:next Ctrl+S:save Esc:cancel"
|
||||
footerWrapped := wrapFooter(footerText, contentW)
|
||||
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
|
||||
box := BorderStyle.Render(inner.String())
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) Close() {}
|
||||
@@ -0,0 +1,267 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
type keyListState int
|
||||
|
||||
const (
|
||||
keyListLoading keyListState = iota
|
||||
keyListReady
|
||||
keyListError
|
||||
)
|
||||
|
||||
// KeyListTab displays and manages SSH key pairs
|
||||
type KeyListTab struct {
|
||||
dataDir string
|
||||
keys []*models.KeyPair
|
||||
selected int
|
||||
state keyListState
|
||||
err error
|
||||
width int
|
||||
height int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewKeyListTab(dataDir string) *KeyListTab {
|
||||
return &KeyListTab{
|
||||
dataDir: dataDir,
|
||||
state: keyListLoading,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *KeyListTab) Name() string { return "SSH Keys" }
|
||||
|
||||
func (t *KeyListTab) Init() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(t.dataDir)
|
||||
if err != nil {
|
||||
return keyListLoadedMsg{err: err}
|
||||
}
|
||||
keys, err := store.ListKeyPairs(context.Background())
|
||||
if err != nil {
|
||||
return keyListLoadedMsg{err: err}
|
||||
}
|
||||
return keyListLoadedMsg{keys: keys}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *KeyListTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
t.mu.Lock()
|
||||
t.width = msg.Width
|
||||
t.height = msg.Height
|
||||
t.mu.Unlock()
|
||||
|
||||
case keyListLoadedMsg:
|
||||
t.mu.Lock()
|
||||
if msg.err != nil {
|
||||
t.state = keyListError
|
||||
t.err = msg.err
|
||||
} else {
|
||||
t.state = keyListReady
|
||||
t.keys = msg.keys
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case saveKeyResultMsg:
|
||||
return t, t.Init()
|
||||
|
||||
case deleteKeyResultMsg:
|
||||
if msg.err != nil {
|
||||
t.mu.Lock()
|
||||
t.err = msg.err
|
||||
t.mu.Unlock()
|
||||
}
|
||||
return t, t.Init()
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "up", "k":
|
||||
t.mu.Lock()
|
||||
if t.selected > 0 {
|
||||
t.selected--
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case "down", "j":
|
||||
t.mu.Lock()
|
||||
if t.selected < len(t.keys)-1 {
|
||||
t.selected++
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case "ctrl+n":
|
||||
return t, func() tea.Msg { return openKeyFormMsg{} }
|
||||
|
||||
case "ctrl+e":
|
||||
t.mu.Lock()
|
||||
keys := t.keys
|
||||
idx := t.selected
|
||||
t.mu.Unlock()
|
||||
if len(keys) > 0 && idx >= 0 && idx < len(keys) {
|
||||
return t, func() tea.Msg { return openKeyFormMsg{editing: keys[idx]} }
|
||||
}
|
||||
|
||||
case "delete", "d":
|
||||
t.mu.Lock()
|
||||
keys := t.keys
|
||||
idx := t.selected
|
||||
t.mu.Unlock()
|
||||
if len(keys) > 0 && idx >= 0 && idx < len(keys) {
|
||||
return t, deleteKeyCmd(keys[idx].ID, t.dataDir)
|
||||
}
|
||||
|
||||
case "esc":
|
||||
return t, func() tea.Msg { return closeFormMsg{} }
|
||||
}
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (t *KeyListTab) View() string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if t.state == keyListLoading {
|
||||
return lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Loading keys..."))
|
||||
}
|
||||
if t.state == keyListError {
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||
b.WriteString("\n")
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Press Esc to go back")))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type styledRow struct {
|
||||
text string
|
||||
plain string
|
||||
}
|
||||
|
||||
titlePlain := "SSH Key Pairs"
|
||||
|
||||
// Build content rows
|
||||
var rows []styledRow
|
||||
if t.err != nil {
|
||||
errLine := fmt.Sprintf("Error: %v", t.err)
|
||||
rows = append(rows, styledRow{text: ErrorStyle.Render(errLine), plain: errLine})
|
||||
}
|
||||
|
||||
if len(t.keys) == 0 {
|
||||
empty := "No SSH keys stored."
|
||||
hint := "Press Ctrl+N to add a new key."
|
||||
rows = append(rows, styledRow{text: SubtitleStyle.Render(empty), plain: empty})
|
||||
rows = append(rows, styledRow{text: SubtitleStyle.Render(hint), plain: hint})
|
||||
} else {
|
||||
for i, key := range t.keys {
|
||||
var plain string
|
||||
if key.Type != "" {
|
||||
plain = fmt.Sprintf(" %s (%s)", key.Name, key.Type)
|
||||
} else {
|
||||
plain = fmt.Sprintf(" %s", key.Name)
|
||||
}
|
||||
var styled string
|
||||
if i == t.selected {
|
||||
styled = lipgloss.NewStyle().
|
||||
Foreground(gbFg).
|
||||
Background(gbBgSel).
|
||||
Bold(true).
|
||||
Render("▸ " + strings.TrimLeft(plain, " "))
|
||||
} else {
|
||||
styled = lipgloss.NewStyle().Foreground(gbFg).Render(plain)
|
||||
}
|
||||
rows = append(rows, styledRow{text: styled, plain: plain})
|
||||
}
|
||||
}
|
||||
|
||||
// Responsive width
|
||||
sidePad := adaptiveSidePad(t.width)
|
||||
widestContent := lipgloss.Width(titlePlain)
|
||||
for _, r := range rows {
|
||||
if w := lipgloss.Width(r.plain); w > widestContent {
|
||||
widestContent = w
|
||||
}
|
||||
}
|
||||
targetW := clampWidth(widestContent+sidePad*2, t.width)
|
||||
innerW := targetW - sidePad*2
|
||||
if innerW < 1 {
|
||||
innerW = 1
|
||||
}
|
||||
|
||||
// Footer (wrapped)
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Ctrl+N:add Ctrl+E:edit D:delete Esc:back"
|
||||
footerWrapped := wrapFooter(footerText, innerW)
|
||||
|
||||
// Render
|
||||
var inner strings.Builder
|
||||
titleStyled := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(titlePlain)
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, titleStyled))
|
||||
inner.WriteString("\n\n")
|
||||
|
||||
for _, r := range rows {
|
||||
plain := r.plain
|
||||
if lipgloss.Width(plain) > innerW {
|
||||
plain = truncateStr(plain, innerW)
|
||||
}
|
||||
styled := r.text
|
||||
if lipgloss.Width(r.plain) > innerW {
|
||||
styled = truncateStr(r.text, innerW)
|
||||
}
|
||||
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, styled)
|
||||
inner.WriteString(line)
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
inner.WriteString("\n")
|
||||
|
||||
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
|
||||
box := BorderStyle.Render(inner.String())
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (t *KeyListTab) Close() {}
|
||||
|
||||
// SetKeys updates the key list data directly (used for refresh)
|
||||
func (t *KeyListTab) SetKeys(keys []*models.KeyPair) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.state = keyListReady
|
||||
t.keys = keys
|
||||
}
|
||||
|
||||
// FindKeyListTab finds the first KeyListTab in a list of tabs
|
||||
func FindKeyListTab(tabs []Tab) *KeyListTab {
|
||||
for _, tab := range tabs {
|
||||
if kt, ok := tab.(*KeyListTab); ok {
|
||||
return kt
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keyListLoadedMsg carries the loaded key list
|
||||
type keyListLoadedMsg struct {
|
||||
keys []*models.KeyPair
|
||||
err error
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
// quitMsg signals the TUI to exit
|
||||
type quitMsg struct{}
|
||||
|
||||
// sshConnectToMsg signals the TUI to connect to a host via native SSH
|
||||
type sshConnectToMsg struct {
|
||||
host *models.Host
|
||||
}
|
||||
|
||||
// sshExitMsg signals that a native SSH session has ended
|
||||
type sshExitMsg struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// openHostFormMsg signals the TUI to open a host form tab
|
||||
type openHostFormMsg struct {
|
||||
editing *models.Host // nil for add mode
|
||||
}
|
||||
|
||||
// closeFormMsg signals the TUI to close the active form tab
|
||||
type closeFormMsg struct{}
|
||||
|
||||
// saveHostMsg is produced when the form needs to save a host
|
||||
type saveHostMsg struct {
|
||||
host *models.Host
|
||||
dataDir string
|
||||
}
|
||||
|
||||
// saveHostResultMsg is produced after a save attempt
|
||||
type saveHostResultMsg struct {
|
||||
host *models.Host
|
||||
err error
|
||||
}
|
||||
|
||||
// openSFTPMsg signals the TUI to open an SFTP browser tab
|
||||
type openSFTPMsg struct {
|
||||
host *models.Host
|
||||
}
|
||||
|
||||
// loadedHostsMsg is produced after reloading hosts from storage
|
||||
type loadedHostsMsg struct {
|
||||
hosts []*models.Host
|
||||
}
|
||||
|
||||
// Key management messages
|
||||
type openKeyListMsg struct{}
|
||||
|
||||
type openKeyFormMsg struct {
|
||||
editing *models.KeyPair
|
||||
}
|
||||
|
||||
type saveKeyMsg struct {
|
||||
key *models.KeyPair
|
||||
dataDir string
|
||||
}
|
||||
|
||||
type saveKeyResultMsg struct {
|
||||
key *models.KeyPair
|
||||
err error
|
||||
}
|
||||
|
||||
type deleteKeyMsg struct {
|
||||
id string
|
||||
dataDir string
|
||||
}
|
||||
|
||||
type deleteKeyResultMsg struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// Snippet management messages
|
||||
type openSnippetListMsg struct{}
|
||||
|
||||
type openSnippetFormMsg struct {
|
||||
editing *models.Snippet
|
||||
}
|
||||
|
||||
type saveSnippetMsg struct {
|
||||
snippet *models.Snippet
|
||||
dataDir string
|
||||
}
|
||||
|
||||
type saveSnippetResultMsg struct {
|
||||
snippet *models.Snippet
|
||||
err error
|
||||
}
|
||||
|
||||
type deleteSnippetMsg struct {
|
||||
id string
|
||||
dataDir string
|
||||
}
|
||||
|
||||
type deleteSnippetResultMsg struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// saveKeyCmd creates a command that saves a key pair to storage
|
||||
func saveKeyCmd(key *models.KeyPair, dataDir string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(dataDir)
|
||||
if err != nil {
|
||||
return saveKeyResultMsg{err: err}
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := store.SaveKeyPair(ctx, key); err != nil {
|
||||
return saveKeyResultMsg{err: err}
|
||||
}
|
||||
return saveKeyResultMsg{key: key}
|
||||
}
|
||||
}
|
||||
|
||||
// deleteKeyCmd creates a command that deletes a key pair
|
||||
func deleteKeyCmd(id, dataDir string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(dataDir)
|
||||
if err != nil {
|
||||
return deleteKeyResultMsg{err: err}
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := store.DeleteKeyPair(ctx, id); err != nil {
|
||||
return deleteKeyResultMsg{err: err}
|
||||
}
|
||||
return deleteKeyResultMsg{}
|
||||
}
|
||||
}
|
||||
|
||||
// saveSnippetCmd creates a command that saves a snippet to storage
|
||||
func saveSnippetCmd(snippet *models.Snippet, dataDir string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(dataDir)
|
||||
if err != nil {
|
||||
return saveSnippetResultMsg{err: err}
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := store.SaveSnippet(ctx, snippet); err != nil {
|
||||
return saveSnippetResultMsg{err: err}
|
||||
}
|
||||
return saveSnippetResultMsg{snippet: snippet}
|
||||
}
|
||||
}
|
||||
|
||||
// deleteSnippetCmd creates a command that deletes a snippet
|
||||
func deleteSnippetCmd(id, dataDir string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(dataDir)
|
||||
if err != nil {
|
||||
return deleteSnippetResultMsg{err: err}
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := store.DeleteSnippet(ctx, id); err != nil {
|
||||
return deleteSnippetResultMsg{err: err}
|
||||
}
|
||||
return deleteSnippetResultMsg{}
|
||||
}
|
||||
}
|
||||
|
||||
// saveHostCmd creates a command that saves a host to storage
|
||||
func saveHostCmd(host *models.Host, dataDir string) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(dataDir)
|
||||
if err != nil {
|
||||
return saveHostResultMsg{err: err}
|
||||
}
|
||||
ctx := context.Background()
|
||||
if err := store.SaveHost(ctx, host); err != nil {
|
||||
return saveHostResultMsg{err: err}
|
||||
}
|
||||
return saveHostResultMsg{host: host}
|
||||
}
|
||||
}
|
||||
|
||||
// openEncryptPromptMsg shows the encryption setup prompt
|
||||
type openEncryptPromptMsg struct{}
|
||||
@@ -0,0 +1,218 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
// passwordPromptMode determines what the password prompt is for
|
||||
type passwordPromptMode int
|
||||
|
||||
const (
|
||||
// passwordModeSetup — first time enabling encryption, ask for new password
|
||||
passwordModeSetup passwordPromptMode = iota
|
||||
// passwordModeUnlock — encryption already enabled, ask for existing password
|
||||
passwordModeUnlock
|
||||
)
|
||||
|
||||
// PasswordPromptTab shows a password prompt for encryption setup or unlock
|
||||
type PasswordPromptTab struct {
|
||||
mode passwordPromptMode
|
||||
inputs []textinput.Model
|
||||
focus int
|
||||
width int
|
||||
height int
|
||||
err error
|
||||
dataDir string
|
||||
onComplete func(password string) // called with password on success
|
||||
}
|
||||
|
||||
// NewPasswordPromptTab creates a new password prompt tab
|
||||
func NewPasswordPromptTab(mode passwordPromptMode, dataDir string, onComplete func(string)) *PasswordPromptTab {
|
||||
p := &PasswordPromptTab{
|
||||
mode: mode,
|
||||
dataDir: dataDir,
|
||||
onComplete: onComplete,
|
||||
}
|
||||
|
||||
// Password field
|
||||
passwordInput := textinput.New()
|
||||
passwordInput.Placeholder = "Enter master password"
|
||||
passwordInput.EchoMode = textinput.EchoPassword
|
||||
passwordInput.EchoCharacter = '•'
|
||||
passwordInput.Focus()
|
||||
|
||||
// Confirm password field (only for setup mode)
|
||||
confirmInput := textinput.New()
|
||||
confirmInput.Placeholder = "Confirm password"
|
||||
confirmInput.EchoMode = textinput.EchoPassword
|
||||
confirmInput.EchoCharacter = '•'
|
||||
|
||||
if mode == passwordModeSetup {
|
||||
p.inputs = []textinput.Model{passwordInput, confirmInput}
|
||||
} else {
|
||||
p.inputs = []textinput.Model{passwordInput}
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *PasswordPromptTab) Name() string {
|
||||
if p.mode == passwordModeSetup {
|
||||
return "Setup Encryption"
|
||||
}
|
||||
return "Unlock Storage"
|
||||
}
|
||||
|
||||
func (p *PasswordPromptTab) Init() tea.Cmd {
|
||||
return textinput.Blink
|
||||
}
|
||||
|
||||
func (p *PasswordPromptTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
p.width = msg.Width
|
||||
p.height = msg.Height
|
||||
return p, nil
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "tab", "down":
|
||||
p.focus++
|
||||
if p.focus >= len(p.inputs) {
|
||||
p.focus = 0
|
||||
}
|
||||
for i := range p.inputs {
|
||||
if i == p.focus {
|
||||
p.inputs[i].Focus()
|
||||
} else {
|
||||
p.inputs[i].Blur()
|
||||
}
|
||||
}
|
||||
return p, nil
|
||||
|
||||
case "shift+tab", "up":
|
||||
p.focus--
|
||||
if p.focus < 0 {
|
||||
p.focus = len(p.inputs) - 1
|
||||
}
|
||||
for i := range p.inputs {
|
||||
if i == p.focus {
|
||||
p.inputs[i].Focus()
|
||||
} else {
|
||||
p.inputs[i].Blur()
|
||||
}
|
||||
}
|
||||
return p, nil
|
||||
|
||||
case "enter":
|
||||
password := p.inputs[0].Value()
|
||||
if password == "" {
|
||||
p.err = fmt.Errorf("password cannot be empty")
|
||||
return p, nil
|
||||
}
|
||||
|
||||
if p.mode == passwordModeSetup && len(p.inputs) > 1 {
|
||||
confirm := p.inputs[1].Value()
|
||||
if password != confirm {
|
||||
p.err = fmt.Errorf("passwords do not match")
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Success — call onComplete
|
||||
if p.onComplete != nil {
|
||||
p.onComplete(password)
|
||||
}
|
||||
return p, func() tea.Msg { return passwordSetMsg{} }
|
||||
|
||||
case "esc":
|
||||
// Cancel — go back or quit
|
||||
return p, func() tea.Msg { return closeFormMsg{} }
|
||||
|
||||
default:
|
||||
// Update current input
|
||||
var cmd tea.Cmd
|
||||
p.inputs[p.focus], cmd = p.inputs[p.focus].Update(msg)
|
||||
return p, cmd
|
||||
}
|
||||
}
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *PasswordPromptTab) Close() {
|
||||
// Nothing to clean up
|
||||
}
|
||||
|
||||
func (p *PasswordPromptTab) View() string {
|
||||
var b strings.Builder
|
||||
|
||||
title := "Setup Master Password"
|
||||
if p.mode == passwordModeUnlock {
|
||||
title = "Enter Master Password"
|
||||
}
|
||||
|
||||
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||
AppTitleStyle.Render(title)))
|
||||
b.WriteString("\n\n")
|
||||
|
||||
if p.mode == passwordModeSetup {
|
||||
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Encrypt all sensitive data (passwords, keys) with AES-256")))
|
||||
b.WriteString("\n")
|
||||
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("You will need this password to access your data")))
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
|
||||
// Input fields
|
||||
contentW := p.width - 8
|
||||
if contentW > 60 {
|
||||
contentW = 60
|
||||
}
|
||||
|
||||
box := lipgloss.NewStyle().
|
||||
Border(lipgloss.RoundedBorder()).
|
||||
BorderForeground(lipgloss.Color("62")).
|
||||
Padding(1, 2).
|
||||
Width(contentW)
|
||||
|
||||
var fields strings.Builder
|
||||
for i, input := range p.inputs {
|
||||
label := "Password:"
|
||||
if i == 1 {
|
||||
label = "Confirm:"
|
||||
}
|
||||
fields.WriteString(SubtitleStyle.Render(" " + label))
|
||||
fields.WriteString("\n")
|
||||
fields.WriteString(input.View())
|
||||
fields.WriteString("\n\n")
|
||||
}
|
||||
|
||||
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center, box.Render(fields.String())))
|
||||
|
||||
if p.err != nil {
|
||||
b.WriteString("\n")
|
||||
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||
ErrorStyle.Render(p.err.Error())))
|
||||
}
|
||||
|
||||
// Footer
|
||||
footerText := "Enter:confirm Esc:cancel Tab:next field"
|
||||
b.WriteString("\n\n")
|
||||
for _, line := range strings.Split(wrapFooter(footerText, p.width), "\n") {
|
||||
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// passwordSetMsg is sent when password is successfully set
|
||||
type passwordSetMsg struct {
|
||||
password string
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
// Responsive breakpoints
|
||||
const (
|
||||
widthCompact = 60 // mobile / Termux
|
||||
widthMedium = 100 // tablet
|
||||
)
|
||||
|
||||
// boxOverhead is the horizontal chars consumed by BorderStyle (border 2 + padding 4)
|
||||
const boxOverhead = 6
|
||||
|
||||
// wrapFooter wraps a footer string into multiple lines that fit availW.
|
||||
// Words are split on double-space separators (" ") and grouped greedily.
|
||||
// Returns the wrapped string with "\n" line breaks.
|
||||
func wrapFooter(text string, availW int) string {
|
||||
if availW < 1 {
|
||||
availW = 1
|
||||
}
|
||||
if lipgloss.Width(text) <= availW {
|
||||
return text
|
||||
}
|
||||
|
||||
words := strings.Split(text, " ")
|
||||
var lines []string
|
||||
var current strings.Builder
|
||||
|
||||
for _, word := range words {
|
||||
word = strings.TrimSpace(word)
|
||||
if word == "" {
|
||||
continue
|
||||
}
|
||||
if current.Len() == 0 {
|
||||
current.WriteString(word)
|
||||
} else if current.Len()+2+lipgloss.Width(word) <= availW {
|
||||
current.WriteString(" ")
|
||||
current.WriteString(word)
|
||||
} else {
|
||||
lines = append(lines, current.String())
|
||||
current.Reset()
|
||||
current.WriteString(word)
|
||||
}
|
||||
}
|
||||
if current.Len() > 0 {
|
||||
lines = append(lines, current.String())
|
||||
}
|
||||
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// adaptiveSidePad returns horizontal padding based on terminal width.
|
||||
// wide: 6, medium: 3, compact: 1
|
||||
func adaptiveSidePad(termWidth int) int {
|
||||
switch {
|
||||
case termWidth < widthCompact:
|
||||
return 1
|
||||
case termWidth < widthMedium:
|
||||
return 3
|
||||
default:
|
||||
return 6
|
||||
}
|
||||
}
|
||||
|
||||
// clampWidth clamps a target box width to fit within the terminal.
|
||||
// Reserves boxOverhead for border+padding. Enforces a minimum of 20.
|
||||
func clampWidth(target, termWidth int) int {
|
||||
maxW := termWidth - boxOverhead
|
||||
if maxW < 20 {
|
||||
maxW = 20
|
||||
}
|
||||
if target > maxW {
|
||||
return maxW
|
||||
}
|
||||
if target < 20 {
|
||||
return 20
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// truncateStr truncates a string to maxLen with an ellipsis character.
|
||||
func truncateStr(s string, maxLen int) string {
|
||||
if maxLen < 1 {
|
||||
return ""
|
||||
}
|
||||
if lipgloss.Width(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
if maxLen <= 1 {
|
||||
return "…"
|
||||
}
|
||||
runes := []rune(s)
|
||||
var result []rune
|
||||
resultW := 0
|
||||
for _, r := range runes {
|
||||
rw := lipgloss.Width(string(r))
|
||||
if resultW+rw > maxLen-1 {
|
||||
break
|
||||
}
|
||||
result = append(result, r)
|
||||
resultW += rw
|
||||
}
|
||||
return string(result) + "…"
|
||||
}
|
||||
|
||||
// Exported wrappers for testing
|
||||
|
||||
// WrapFooter wraps a footer string into multiple lines that fit availW
|
||||
func WrapFooter(text string, availW int) string {
|
||||
return wrapFooter(text, availW)
|
||||
}
|
||||
|
||||
// ClampWidth clamps a target box width to fit within the terminal
|
||||
func ClampWidth(target, termWidth int) int {
|
||||
return clampWidth(target, termWidth)
|
||||
}
|
||||
|
||||
// TruncateStr truncates a string to maxLen with an ellipsis character
|
||||
func TruncateStr(s string, maxLen int) string {
|
||||
return truncateStr(s, maxLen)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,259 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
type snippetFormMode int
|
||||
|
||||
const (
|
||||
snippetFormAdd snippetFormMode = iota
|
||||
snippetFormEdit
|
||||
)
|
||||
|
||||
type snippetFieldID int
|
||||
|
||||
const (
|
||||
snippetFieldName snippetFieldID = iota
|
||||
snippetFieldCommand
|
||||
snippetFieldDescription
|
||||
snippetFieldTags
|
||||
snippetFieldCount
|
||||
)
|
||||
|
||||
var snippetFieldLabels = map[snippetFieldID]string{
|
||||
snippetFieldName: "Name",
|
||||
snippetFieldCommand: "Command",
|
||||
snippetFieldDescription: "Description",
|
||||
snippetFieldTags: "Tags (comma-separated)",
|
||||
}
|
||||
|
||||
// SnippetFormTab is a tab for adding/editing command snippets
|
||||
type SnippetFormTab struct {
|
||||
mode snippetFormMode
|
||||
editing *models.Snippet
|
||||
dataDir string
|
||||
|
||||
inputs []textinput.Model
|
||||
focus snippetFieldID
|
||||
width int
|
||||
height int
|
||||
|
||||
err error
|
||||
saved bool
|
||||
}
|
||||
|
||||
func NewAddSnippetFormTab(dataDir string) *SnippetFormTab {
|
||||
return newSnippetFormTab(snippetFormAdd, nil, dataDir)
|
||||
}
|
||||
|
||||
func NewEditSnippetFormTab(snippet *models.Snippet, dataDir string) *SnippetFormTab {
|
||||
return newSnippetFormTab(snippetFormEdit, snippet, dataDir)
|
||||
}
|
||||
|
||||
func newSnippetFormTab(mode snippetFormMode, sn *models.Snippet, dataDir string) *SnippetFormTab {
|
||||
inputs := make([]textinput.Model, snippetFieldCount)
|
||||
for i := range inputs {
|
||||
inputs[i] = textinput.New()
|
||||
inputs[i].Prompt = ""
|
||||
}
|
||||
|
||||
inputs[snippetFieldName].Placeholder = "Check logs"
|
||||
inputs[snippetFieldCommand].Placeholder = "journalctl -u nginx --no-pager -n 100"
|
||||
inputs[snippetFieldDescription].Placeholder = "View last 100 nginx log entries"
|
||||
inputs[snippetFieldTags].Placeholder = "nginx,logs,troubleshooting"
|
||||
|
||||
if mode == snippetFormEdit && sn != nil {
|
||||
inputs[snippetFieldName].SetValue(sn.Name)
|
||||
inputs[snippetFieldCommand].SetValue(sn.Command)
|
||||
inputs[snippetFieldDescription].SetValue(sn.Description)
|
||||
inputs[snippetFieldTags].SetValue(strings.Join(sn.Tags, ","))
|
||||
}
|
||||
|
||||
inputs[snippetFieldName].Focus()
|
||||
inputs[snippetFieldName].Prompt = "> "
|
||||
|
||||
return &SnippetFormTab{
|
||||
mode: mode,
|
||||
editing: sn,
|
||||
dataDir: dataDir,
|
||||
inputs: inputs,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) Name() string {
|
||||
if t.mode == snippetFormEdit {
|
||||
return "Edit Snippet"
|
||||
}
|
||||
return "Add Snippet"
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) Init() tea.Cmd {
|
||||
return textinput.Blink
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
if t.saved {
|
||||
return t, nil
|
||||
}
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
t.width = msg.Width
|
||||
t.height = msg.Height
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
return t, func() tea.Msg { return closeFormMsg{} }
|
||||
|
||||
case "enter":
|
||||
if t.focus == snippetFieldCount-1 {
|
||||
return t.submit()
|
||||
}
|
||||
t.nextField()
|
||||
|
||||
case "tab", "down":
|
||||
t.nextField()
|
||||
|
||||
case "shift+tab", "up":
|
||||
t.prevField()
|
||||
|
||||
case "ctrl+s":
|
||||
return t.submit()
|
||||
|
||||
default:
|
||||
var cmd tea.Cmd
|
||||
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||
return t, cmd
|
||||
}
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) nextField() {
|
||||
t.inputs[t.focus].Blur()
|
||||
t.inputs[t.focus].Prompt = ""
|
||||
t.focus++
|
||||
if t.focus >= snippetFieldCount {
|
||||
t.focus = snippetFieldCount - 1
|
||||
}
|
||||
t.inputs[t.focus].Focus()
|
||||
t.inputs[t.focus].Prompt = "> "
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) prevField() {
|
||||
t.inputs[t.focus].Blur()
|
||||
t.inputs[t.focus].Prompt = ""
|
||||
t.focus--
|
||||
if t.focus < 0 {
|
||||
t.focus = 0
|
||||
}
|
||||
t.inputs[t.focus].Focus()
|
||||
t.inputs[t.focus].Prompt = "> "
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) submit() (Tab, tea.Cmd) {
|
||||
name := t.inputs[snippetFieldName].Value()
|
||||
command := t.inputs[snippetFieldCommand].Value()
|
||||
|
||||
if name == "" || command == "" {
|
||||
t.err = fmt.Errorf("name and command are required")
|
||||
return t, nil
|
||||
}
|
||||
|
||||
var tags []string
|
||||
if tagStr := t.inputs[snippetFieldTags].Value(); tagStr != "" {
|
||||
for _, tag := range strings.Split(tagStr, ",") {
|
||||
if trimmed := strings.TrimSpace(tag); trimmed != "" {
|
||||
tags = append(tags, trimmed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var sn *models.Snippet
|
||||
if t.mode == snippetFormEdit && t.editing != nil {
|
||||
sn = t.editing
|
||||
sn.Name = name
|
||||
sn.Command = command
|
||||
sn.Description = t.inputs[snippetFieldDescription].Value()
|
||||
sn.Tags = tags
|
||||
} else {
|
||||
sn = &models.Snippet{
|
||||
ID: uuid.New().String(),
|
||||
Name: name,
|
||||
Command: command,
|
||||
Description: t.inputs[snippetFieldDescription].Value(),
|
||||
Tags: tags,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
t.saved = true
|
||||
return t, saveSnippetCmd(sn, t.dataDir)
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) View() string {
|
||||
contentW := t.width - 12
|
||||
if contentW < 30 {
|
||||
contentW = 30
|
||||
}
|
||||
if contentW > 70 {
|
||||
contentW = 70
|
||||
}
|
||||
|
||||
var inner strings.Builder
|
||||
|
||||
title := "Add Snippet"
|
||||
if t.mode == snippetFormEdit {
|
||||
title = "Edit Snippet"
|
||||
}
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(title)))
|
||||
inner.WriteString("\n\n")
|
||||
|
||||
if t.err != nil {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||
inner.WriteString("\n\n")
|
||||
}
|
||||
|
||||
for i := snippetFieldID(0); i < snippetFieldCount; i++ {
|
||||
input := t.inputs[i]
|
||||
label := snippetFieldLabels[i]
|
||||
style := SubtitleStyle
|
||||
if i == t.focus {
|
||||
style = HighlightStyle
|
||||
}
|
||||
inner.WriteString(style.Render(label + ":"))
|
||||
inner.WriteString("\n ")
|
||||
inner.WriteString(input.View())
|
||||
inner.WriteString("\n\n")
|
||||
}
|
||||
|
||||
inner.WriteString("\n")
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close Tab:next Shift+Tab:prev ↑↓:nav Enter:next Ctrl+S:save Esc:cancel"
|
||||
footerWrapped := wrapFooter(footerText, contentW)
|
||||
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
|
||||
box := BorderStyle.Render(inner.String())
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) Close() {}
|
||||
@@ -0,0 +1,262 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
type snippetListState int
|
||||
|
||||
const (
|
||||
snippetListLoading snippetListState = iota
|
||||
snippetListReady
|
||||
snippetListError
|
||||
)
|
||||
|
||||
// SnippetListTab displays and manages command snippets
|
||||
type SnippetListTab struct {
|
||||
dataDir string
|
||||
snippets []*models.Snippet
|
||||
selected int
|
||||
state snippetListState
|
||||
err error
|
||||
width int
|
||||
height int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewSnippetListTab(dataDir string) *SnippetListTab {
|
||||
return &SnippetListTab{
|
||||
dataDir: dataDir,
|
||||
state: snippetListLoading,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SnippetListTab) Name() string { return "Snippets" }
|
||||
|
||||
func (t *SnippetListTab) Init() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(t.dataDir)
|
||||
if err != nil {
|
||||
return snippetListLoadedMsg{err: err}
|
||||
}
|
||||
snippets, err := store.ListSnippets(context.Background())
|
||||
if err != nil {
|
||||
return snippetListLoadedMsg{err: err}
|
||||
}
|
||||
return snippetListLoadedMsg{snippets: snippets}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SnippetListTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
t.mu.Lock()
|
||||
t.width = msg.Width
|
||||
t.height = msg.Height
|
||||
t.mu.Unlock()
|
||||
|
||||
case snippetListLoadedMsg:
|
||||
t.mu.Lock()
|
||||
if msg.err != nil {
|
||||
t.state = snippetListError
|
||||
t.err = msg.err
|
||||
} else {
|
||||
t.state = snippetListReady
|
||||
t.snippets = msg.snippets
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case saveSnippetResultMsg:
|
||||
return t, t.Init()
|
||||
|
||||
case deleteSnippetResultMsg:
|
||||
if msg.err != nil {
|
||||
t.mu.Lock()
|
||||
t.err = msg.err
|
||||
t.mu.Unlock()
|
||||
}
|
||||
return t, t.Init()
|
||||
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
case "up", "k":
|
||||
t.mu.Lock()
|
||||
if t.selected > 0 {
|
||||
t.selected--
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case "down", "j":
|
||||
t.mu.Lock()
|
||||
if t.selected < len(t.snippets)-1 {
|
||||
t.selected++
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case "ctrl+n":
|
||||
return t, func() tea.Msg { return openSnippetFormMsg{} }
|
||||
|
||||
case "ctrl+e":
|
||||
t.mu.Lock()
|
||||
snippets := t.snippets
|
||||
idx := t.selected
|
||||
t.mu.Unlock()
|
||||
if len(snippets) > 0 && idx >= 0 && idx < len(snippets) {
|
||||
return t, func() tea.Msg { return openSnippetFormMsg{editing: snippets[idx]} }
|
||||
}
|
||||
|
||||
case "delete", "d":
|
||||
t.mu.Lock()
|
||||
snippets := t.snippets
|
||||
idx := t.selected
|
||||
t.mu.Unlock()
|
||||
if len(snippets) > 0 && idx >= 0 && idx < len(snippets) {
|
||||
return t, deleteSnippetCmd(snippets[idx].ID, t.dataDir)
|
||||
}
|
||||
|
||||
case "esc":
|
||||
return t, func() tea.Msg { return closeFormMsg{} }
|
||||
}
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (t *SnippetListTab) View() string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if t.state == snippetListLoading {
|
||||
return lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Loading snippets..."))
|
||||
}
|
||||
if t.state == snippetListError {
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||
b.WriteString("\n")
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Press Esc to go back")))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type styledRow struct {
|
||||
text string
|
||||
plain string
|
||||
}
|
||||
|
||||
titlePlain := "Command Snippets"
|
||||
|
||||
var rows []styledRow
|
||||
if t.err != nil {
|
||||
errLine := fmt.Sprintf("Error: %v", t.err)
|
||||
rows = append(rows, styledRow{text: ErrorStyle.Render(errLine), plain: errLine})
|
||||
}
|
||||
|
||||
if len(t.snippets) == 0 {
|
||||
empty := "No snippets stored."
|
||||
hint := "Press Ctrl+N to add a new snippet."
|
||||
rows = append(rows, styledRow{text: SubtitleStyle.Render(empty), plain: empty})
|
||||
rows = append(rows, styledRow{text: SubtitleStyle.Render(hint), plain: hint})
|
||||
} else {
|
||||
for i, sn := range t.snippets {
|
||||
var plain string
|
||||
if sn.Description != "" {
|
||||
plain = fmt.Sprintf(" %s — %s", sn.Name, sn.Description)
|
||||
} else {
|
||||
plain = fmt.Sprintf(" %s", sn.Name)
|
||||
}
|
||||
var styled string
|
||||
if i == t.selected {
|
||||
styled = lipgloss.NewStyle().
|
||||
Foreground(gbFg).
|
||||
Background(gbBgSel).
|
||||
Bold(true).
|
||||
Render("▸ " + strings.TrimLeft(plain, " "))
|
||||
} else {
|
||||
styled = lipgloss.NewStyle().Foreground(gbFg).Render(plain)
|
||||
}
|
||||
rows = append(rows, styledRow{text: styled, plain: plain})
|
||||
}
|
||||
}
|
||||
|
||||
// Responsive width
|
||||
sidePad := adaptiveSidePad(t.width)
|
||||
widestContent := lipgloss.Width(titlePlain)
|
||||
for _, r := range rows {
|
||||
if w := lipgloss.Width(r.plain); w > widestContent {
|
||||
widestContent = w
|
||||
}
|
||||
}
|
||||
targetW := clampWidth(widestContent+sidePad*2, t.width)
|
||||
innerW := targetW - sidePad*2
|
||||
if innerW < 1 {
|
||||
innerW = 1
|
||||
}
|
||||
|
||||
// Footer (wrapped)
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Ctrl+N:add Ctrl+E:edit D:delete Esc:back"
|
||||
footerWrapped := wrapFooter(footerText, innerW)
|
||||
|
||||
// Render
|
||||
var inner strings.Builder
|
||||
titleStyled := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(titlePlain)
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, titleStyled))
|
||||
inner.WriteString("\n\n")
|
||||
|
||||
for _, r := range rows {
|
||||
styled := r.text
|
||||
if lipgloss.Width(r.plain) > innerW {
|
||||
styled = truncateStr(r.text, innerW)
|
||||
}
|
||||
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, styled)
|
||||
inner.WriteString(line)
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
inner.WriteString("\n")
|
||||
|
||||
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
|
||||
box := BorderStyle.Render(inner.String())
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (t *SnippetListTab) Close() {}
|
||||
|
||||
// SetSnippets updates the snippet list data directly (used for refresh)
|
||||
func (t *SnippetListTab) SetSnippets(snippets []*models.Snippet) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.state = snippetListReady
|
||||
t.snippets = snippets
|
||||
}
|
||||
|
||||
// FindSnippetListTab finds the first SnippetListTab in a list of tabs
|
||||
func FindSnippetListTab(tabs []Tab) *SnippetListTab {
|
||||
for _, tab := range tabs {
|
||||
if st, ok := tab.(*SnippetListTab); ok {
|
||||
return st
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// snippetListLoadedMsg carries the loaded snippet list
|
||||
type snippetListLoadedMsg struct {
|
||||
snippets []*models.Snippet
|
||||
err error
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
// sshConnectCmd builds and runs a native SSH command via tea.ExecProcess.
|
||||
// Password auth: sshpass -e ssh user@host (SSHPASS env)
|
||||
// Key auth: ssh -i <tmpfile> user@host (SSH_ASKPASS for passphrase)
|
||||
//
|
||||
// Must return tea.ExecProcess directly (NOT wrapped in another closure)
|
||||
// so Bubble Tea can execute the process command correctly.
|
||||
func sshConnectCmd(host *models.Host, dataDir string) tea.Cmd {
|
||||
port := host.Port
|
||||
if port == 0 {
|
||||
port = 22
|
||||
}
|
||||
portStr := strconv.Itoa(port)
|
||||
target := fmt.Sprintf("%s@%s", host.Username, host.Hostname)
|
||||
ctrlSock := fmt.Sprintf("/tmp/hk-%s", host.ID)
|
||||
env := os.Environ()
|
||||
|
||||
// Common SSH args
|
||||
sshArgs := []string{
|
||||
"-p", portStr,
|
||||
"-o", "StrictHostKeyChecking=accept-new",
|
||||
"-o", "ServerAliveInterval=60",
|
||||
"-o", "ServerAliveCountMax=3",
|
||||
"-S", ctrlSock,
|
||||
"-o", "ControlMaster=auto",
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
exec.Command("ssh", "-S", ctrlSock, "-O", "exit", target).Run()
|
||||
}
|
||||
|
||||
switch host.Auth.Type {
|
||||
case "password":
|
||||
allArgs := append([]string{"-e", "ssh"}, sshArgs...)
|
||||
allArgs = append(allArgs, target)
|
||||
cmd := exec.Command("sshpass", allArgs...)
|
||||
cmd.Env = append(env, "SSHPASS="+host.Auth.Password)
|
||||
return tea.ExecProcess(cmd, func(err error) tea.Msg {
|
||||
cleanup()
|
||||
return sshExitMsg{err: err}
|
||||
})
|
||||
|
||||
case "key":
|
||||
keyContent, err := loadKeyContent(host, dataDir)
|
||||
if err != nil {
|
||||
return errorCmd(fmt.Errorf("load key: %w", err))
|
||||
}
|
||||
tmpFile, err := os.CreateTemp("", "hk-key-*")
|
||||
if err != nil {
|
||||
return errorCmd(fmt.Errorf("create temp key: %w", err))
|
||||
}
|
||||
tmpPath := tmpFile.Name()
|
||||
if _, err := tmpFile.Write([]byte(keyContent)); err != nil {
|
||||
tmpFile.Close()
|
||||
os.Remove(tmpPath)
|
||||
return errorCmd(fmt.Errorf("write temp key: %w", err))
|
||||
}
|
||||
tmpFile.Close()
|
||||
os.Chmod(tmpPath, 0600)
|
||||
|
||||
keyArgs := append([]string{"-i", tmpPath}, sshArgs...)
|
||||
keyArgs = append(keyArgs, target)
|
||||
cmd := exec.Command("ssh", keyArgs...)
|
||||
|
||||
if host.Auth.Password != "" {
|
||||
self, err := os.Executable()
|
||||
if err == nil {
|
||||
script := fmt.Sprintf("#!/bin/sh\nexec %q askpass\n", self)
|
||||
f, err := os.CreateTemp("", "hk-askpass-*.sh")
|
||||
if err == nil {
|
||||
f.WriteString(script)
|
||||
f.Close()
|
||||
os.Chmod(f.Name(), 0700)
|
||||
env = append(env,
|
||||
"HK_PASSPHRASE="+host.Auth.Password,
|
||||
"SSH_ASKPASS="+f.Name(),
|
||||
"SSH_ASKPASS_REQUIRE=force",
|
||||
)
|
||||
if os.Getenv("DISPLAY") == "" {
|
||||
env = append(env, "DISPLAY=:0")
|
||||
}
|
||||
if setsid, err := exec.LookPath("setsid"); err == nil {
|
||||
newArgs := append([]string{"ssh"}, keyArgs...)
|
||||
cmd = exec.Command(setsid, newArgs...)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cmd.Env = env
|
||||
return tea.ExecProcess(cmd, func(err error) tea.Msg {
|
||||
os.Remove(tmpPath)
|
||||
cleanup()
|
||||
return sshExitMsg{err: err}
|
||||
})
|
||||
|
||||
default:
|
||||
return errorCmd(fmt.Errorf("unsupported auth type: %s", host.Auth.Type))
|
||||
}
|
||||
}
|
||||
|
||||
// errorCmd returns a Cmd that sends an sshExitMsg with the given error.
|
||||
func errorCmd(err error) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return sshExitMsg{err: err}
|
||||
}
|
||||
}
|
||||
|
||||
// loadKeyContent reads the private key content for a host
|
||||
func loadKeyContent(host *models.Host, dataDir string) (string, error) {
|
||||
if host.Auth.KeyID == "" {
|
||||
return "", fmt.Errorf("key auth requires key_id")
|
||||
}
|
||||
store, err := storage.NewJSONStorage(dataDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
keyPair, err := store.GetKeyPair(context.Background(), host.Auth.KeyID)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load key %s: %w", host.Auth.KeyID, err)
|
||||
}
|
||||
return keyPair.PrivateKey, nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package tui
|
||||
|
||||
import "github.com/charmbracelet/lipgloss"
|
||||
|
||||
// Gruvbox Material Dark Hard palette — warm, soft, easy on eyes
|
||||
var (
|
||||
gbFg = lipgloss.Color("#d4be98") // primary text
|
||||
gbFgMute = lipgloss.Color("#7c6f64") // secondary/hints
|
||||
gbBgSel = lipgloss.Color("#45403d") // cursor row bg
|
||||
gbRed = lipgloss.Color("#ea6962") // error/destructive
|
||||
gbOrange = lipgloss.Color("#e78a4e") // section headers
|
||||
gbYellow = lipgloss.Color("#d8a657") // accent/titles
|
||||
gbGreen = lipgloss.Color("#a9b665") // active pane/success
|
||||
gbAqua = lipgloss.Color("#89b482") // interactive keys
|
||||
gbBlue = lipgloss.Color("#7daea3")
|
||||
gbPurple = lipgloss.Color("#d3869b")
|
||||
gbBorder = lipgloss.Color("#504945") // subtle border
|
||||
)
|
||||
|
||||
// Component styles
|
||||
var (
|
||||
TabActiveStyle = lipgloss.NewStyle().Background(gbYellow).Foreground(lipgloss.Color("#1d2021")).Bold(true).Padding(0, 2)
|
||||
TabInactiveStyle = lipgloss.NewStyle().Background(gbBorder).Foreground(gbFgMute).Padding(0, 2)
|
||||
TabBarStyle = lipgloss.NewStyle().Background(lipgloss.Color("#1d2021"))
|
||||
StatusBarStyle = lipgloss.NewStyle().Background(gbGreen).Foreground(lipgloss.Color("#1d2021")).Padding(0, 1)
|
||||
AppTitleStyle = lipgloss.NewStyle().Foreground(gbYellow).Bold(true)
|
||||
HighlightStyle = lipgloss.NewStyle().Foreground(gbOrange).Bold(true)
|
||||
SelectedStyle = lipgloss.NewStyle().Foreground(gbFg).Background(gbBgSel).Bold(true).Padding(0, 1)
|
||||
ErrorStyle = lipgloss.NewStyle().Foreground(gbRed).Bold(true)
|
||||
SuccessStyle = lipgloss.NewStyle().Foreground(gbGreen).Bold(true)
|
||||
InfoStyle = lipgloss.NewStyle().Foreground(gbAqua)
|
||||
SubtitleStyle = lipgloss.NewStyle().Foreground(gbFgMute)
|
||||
HostNameStyle = lipgloss.NewStyle().Foreground(gbYellow).Bold(true)
|
||||
HostDetailStyle = lipgloss.NewStyle().Foreground(gbFgMute)
|
||||
TagStyle = lipgloss.NewStyle().Foreground(gbGreen)
|
||||
TitleStyle = AppTitleStyle
|
||||
SectionStyle = lipgloss.NewStyle().Foreground(gbOrange).Bold(true)
|
||||
BorderStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbBorder).Padding(1, 2)
|
||||
)
|
||||
|
||||
// TabWidth returns the width of the tab bar content
|
||||
func TabBarWidth(totalWidth int) int {
|
||||
if totalWidth < 10 {
|
||||
return totalWidth
|
||||
}
|
||||
return totalWidth - 2
|
||||
}
|
||||
|
||||
// Pane styles for dual-pane layout
|
||||
var (
|
||||
StylePaneActive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbGreen).Padding(0, 1)
|
||||
StylePaneInactive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbBorder).Padding(0, 1)
|
||||
)
|
||||
|
||||
// Host card styles
|
||||
var (
|
||||
HostCardStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbBorder).Padding(0, 1)
|
||||
HostCardActiveStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbGreen).Padding(0, 1)
|
||||
)
|
||||
@@ -0,0 +1,231 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
// Tab represents a single tab in the TUI
|
||||
type Tab interface {
|
||||
Init() tea.Cmd
|
||||
Update(tea.Msg) (Tab, tea.Cmd)
|
||||
View() string
|
||||
Name() string
|
||||
// Close is called when the tab is removed; implement for cleanup (e.g. disconnect SSH)
|
||||
Close()
|
||||
}
|
||||
|
||||
// TabManager manages multiple tabs
|
||||
type TabManager struct {
|
||||
tabs []Tab
|
||||
active int
|
||||
width int
|
||||
height int
|
||||
}
|
||||
|
||||
// NewTabManager creates a new TabManager with an initial tab
|
||||
func NewTabManager(initial Tab) *TabManager {
|
||||
return &TabManager{
|
||||
tabs: []Tab{initial},
|
||||
active: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Active returns the currently active tab
|
||||
func (tm *TabManager) Active() Tab {
|
||||
if len(tm.tabs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tm.tabs[tm.active]
|
||||
}
|
||||
|
||||
// Add adds a new tab, switches to it, and returns its init command
|
||||
func (tm *TabManager) Add(tab Tab) tea.Cmd {
|
||||
tm.tabs = append(tm.tabs, tab)
|
||||
tm.active = len(tm.tabs) - 1
|
||||
|
||||
// Forward current terminal size so new tabs know their dimensions
|
||||
if tm.width > 0 && tm.height > 0 {
|
||||
updated, _ := tab.Update(tea.WindowSizeMsg{Width: tm.width, Height: tm.height})
|
||||
tm.tabs[tm.active] = updated
|
||||
}
|
||||
|
||||
return tab.Init()
|
||||
}
|
||||
|
||||
// Close removes the tab at index and returns the active tab
|
||||
func (tm *TabManager) Close(index int) Tab {
|
||||
if index < 0 || index >= len(tm.tabs) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Call Close for cleanup (e.g. disconnect SSH)
|
||||
tm.tabs[index].Close()
|
||||
|
||||
tm.tabs = append(tm.tabs[:index], tm.tabs[index+1:]...)
|
||||
|
||||
if len(tm.tabs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if tm.active >= len(tm.tabs) {
|
||||
tm.active = len(tm.tabs) - 1
|
||||
}
|
||||
return tm.tabs[tm.active]
|
||||
}
|
||||
|
||||
// CloseActive closes the active tab
|
||||
func (tm *TabManager) CloseActive() Tab {
|
||||
if len(tm.tabs) <= 1 {
|
||||
return nil
|
||||
}
|
||||
return tm.Close(tm.active)
|
||||
}
|
||||
|
||||
// Next switches to the next tab
|
||||
func (tm *TabManager) Next() {
|
||||
if len(tm.tabs) <= 1 {
|
||||
return
|
||||
}
|
||||
tm.active = (tm.active + 1) % len(tm.tabs)
|
||||
}
|
||||
|
||||
// Prev switches to the previous tab
|
||||
func (tm *TabManager) Prev() {
|
||||
if len(tm.tabs) <= 1 {
|
||||
return
|
||||
}
|
||||
tm.active--
|
||||
if tm.active < 0 {
|
||||
tm.active = len(tm.tabs) - 1
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of tabs
|
||||
func (tm *TabManager) Len() int {
|
||||
return len(tm.tabs)
|
||||
}
|
||||
|
||||
// SetSize updates the terminal size for the tab manager
|
||||
func (tm *TabManager) SetSize(width, height int) {
|
||||
tm.width = width
|
||||
tm.height = height
|
||||
}
|
||||
|
||||
// Init initializes all tabs
|
||||
func (tm *TabManager) Init() tea.Cmd {
|
||||
var cmds []tea.Cmd
|
||||
for _, t := range tm.tabs {
|
||||
if cmd := t.Init(); cmd != nil {
|
||||
cmds = append(cmds, cmd)
|
||||
}
|
||||
}
|
||||
return tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
// Update sends a message to the active tab
|
||||
func (tm *TabManager) Update(msg tea.Msg) (tea.Cmd, error) {
|
||||
if len(tm.tabs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Handle tab-level keys
|
||||
if keyMsg, ok := msg.(tea.KeyMsg); ok {
|
||||
switch keyMsg.String() {
|
||||
case "ctrl+tab":
|
||||
tm.Next()
|
||||
return nil, nil
|
||||
case "shift+tab":
|
||||
tm.Prev()
|
||||
return nil, nil
|
||||
case "ctrl+q":
|
||||
if closed := tm.CloseActive(); closed != nil {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle window resize — forward to ALL tabs
|
||||
if wsMsg, ok := msg.(tea.WindowSizeMsg); ok {
|
||||
tm.SetSize(wsMsg.Width, wsMsg.Height)
|
||||
for i, t := range tm.tabs {
|
||||
updated, _ := t.Update(msg)
|
||||
tm.tabs[i] = updated
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
updated, cmd := tm.tabs[tm.active].Update(msg)
|
||||
tm.tabs[tm.active] = updated
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
// View renders the tab bar and active tab content
|
||||
func (tm *TabManager) View() string {
|
||||
if len(tm.tabs) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
|
||||
// Render tab bar
|
||||
b.WriteString(renderTabBar(tm))
|
||||
|
||||
// Render active tab content
|
||||
content := tm.tabs[tm.active].View()
|
||||
if content != "" {
|
||||
b.WriteString("\n")
|
||||
b.WriteString(content)
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// renderTabBar renders the top tab bar (responsive: truncates names on overflow)
|
||||
func renderTabBar(tm *TabManager) string {
|
||||
if len(tm.tabs) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
const cellPad = 4 // Padding(0,2) per tab = 2 left + 2 right
|
||||
|
||||
availW := tm.width - 2
|
||||
if availW < 1 {
|
||||
availW = 1
|
||||
}
|
||||
|
||||
// Measure total width and decide if truncation is needed
|
||||
totalW := 0
|
||||
for _, tab := range tm.tabs {
|
||||
totalW += lipgloss.Width(tab.Name()) + cellPad
|
||||
}
|
||||
|
||||
maxNameW := 0
|
||||
if totalW > availW {
|
||||
perTab := availW / len(tm.tabs)
|
||||
maxNameW = perTab - cellPad
|
||||
if maxNameW < 1 {
|
||||
maxNameW = 1
|
||||
}
|
||||
}
|
||||
|
||||
var cells []string
|
||||
for i, tab := range tm.tabs {
|
||||
name := tab.Name()
|
||||
if maxNameW > 0 && lipgloss.Width(name) > maxNameW {
|
||||
name = truncateStr(name, maxNameW)
|
||||
}
|
||||
if i == tm.active {
|
||||
cells = append(cells, TabActiveStyle.Render(name))
|
||||
} else {
|
||||
cells = append(cells, TabInactiveStyle.Render(name))
|
||||
}
|
||||
}
|
||||
|
||||
bar := strings.Join(cells, "")
|
||||
return TabBarStyle.Render(bar)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package tui
|
||||
|
||||
import "github.com/charmbracelet/lipgloss"
|
||||
|
||||
// Theme defines a complete color palette for the TUI
|
||||
type Theme struct {
|
||||
Name string
|
||||
Fg lipgloss.Color
|
||||
FgMute lipgloss.Color
|
||||
Bg lipgloss.Color
|
||||
BgSel lipgloss.Color
|
||||
Red lipgloss.Color
|
||||
Orange lipgloss.Color
|
||||
Yellow lipgloss.Color
|
||||
Green lipgloss.Color
|
||||
Aqua lipgloss.Color
|
||||
Blue lipgloss.Color
|
||||
Purple lipgloss.Color
|
||||
Border lipgloss.Color
|
||||
TabBg lipgloss.Color
|
||||
}
|
||||
|
||||
// Predefined themes
|
||||
var (
|
||||
ThemeDark = Theme{
|
||||
Name: "dark",
|
||||
Fg: lipgloss.Color("#d4be98"),
|
||||
FgMute: lipgloss.Color("#7c6f64"),
|
||||
Bg: lipgloss.Color("#1d2021"),
|
||||
BgSel: lipgloss.Color("#45403d"),
|
||||
Red: lipgloss.Color("#ea6962"),
|
||||
Orange: lipgloss.Color("#e78a4e"),
|
||||
Yellow: lipgloss.Color("#d8a657"),
|
||||
Green: lipgloss.Color("#a9b665"),
|
||||
Aqua: lipgloss.Color("#89b482"),
|
||||
Blue: lipgloss.Color("#7daea3"),
|
||||
Purple: lipgloss.Color("#d3869b"),
|
||||
Border: lipgloss.Color("#504945"),
|
||||
TabBg: lipgloss.Color("#1d2021"),
|
||||
}
|
||||
|
||||
ThemeLight = Theme{
|
||||
Name: "light",
|
||||
Fg: lipgloss.Color("#3c3836"),
|
||||
FgMute: lipgloss.Color("#7c6f64"),
|
||||
Bg: lipgloss.Color("#f2e5bc"),
|
||||
BgSel: lipgloss.Color("#d5c4a1"),
|
||||
Red: lipgloss.Color("#cc241d"),
|
||||
Orange: lipgloss.Color("#d65d0e"),
|
||||
Yellow: lipgloss.Color("#d79921"),
|
||||
Green: lipgloss.Color("#98971a"),
|
||||
Aqua: lipgloss.Color("#689d6a"),
|
||||
Blue: lipgloss.Color("#458588"),
|
||||
Purple: lipgloss.Color("#b16286"),
|
||||
Border: lipgloss.Color("#a89984"),
|
||||
TabBg: lipgloss.Color("#f2e5bc"),
|
||||
}
|
||||
|
||||
ThemeDracula = Theme{
|
||||
Name: "dracula",
|
||||
Fg: lipgloss.Color("#f8f8f2"),
|
||||
FgMute: lipgloss.Color("#6272a4"),
|
||||
Bg: lipgloss.Color("#282a36"),
|
||||
BgSel: lipgloss.Color("#44475a"),
|
||||
Red: lipgloss.Color("#ff5555"),
|
||||
Orange: lipgloss.Color("#ffb86c"),
|
||||
Yellow: lipgloss.Color("#f1fa8c"),
|
||||
Green: lipgloss.Color("#50fa7b"),
|
||||
Aqua: lipgloss.Color("#8be9fd"),
|
||||
Blue: lipgloss.Color("#6272a4"),
|
||||
Purple: lipgloss.Color("#bd93f9"),
|
||||
Border: lipgloss.Color("#44475a"),
|
||||
TabBg: lipgloss.Color("#282a36"),
|
||||
}
|
||||
)
|
||||
|
||||
// Themes is the registry of all available themes
|
||||
var Themes = map[string]Theme{
|
||||
"dark": ThemeDark,
|
||||
"light": ThemeLight,
|
||||
"dracula": ThemeDracula,
|
||||
}
|
||||
|
||||
// activeTheme holds the currently active theme
|
||||
var activeTheme = ThemeDark
|
||||
|
||||
// GetTheme returns a theme by name, defaults to dark
|
||||
func GetTheme(name string) Theme {
|
||||
if t, ok := Themes[name]; ok {
|
||||
return t
|
||||
}
|
||||
return ThemeDark
|
||||
}
|
||||
|
||||
// SetTheme applies a theme by name and updates all component styles
|
||||
func SetTheme(name string) {
|
||||
theme := GetTheme(name)
|
||||
activeTheme = theme
|
||||
applyTheme(theme)
|
||||
}
|
||||
|
||||
// GetActiveTheme returns the currently active theme
|
||||
func GetActiveTheme() Theme {
|
||||
return activeTheme
|
||||
}
|
||||
|
||||
// applyTheme updates all component styles from the given theme
|
||||
func applyTheme(t Theme) {
|
||||
// Palette aliases
|
||||
gbFg = t.Fg
|
||||
gbFgMute = t.FgMute
|
||||
gbBgSel = t.BgSel
|
||||
gbRed = t.Red
|
||||
gbOrange = t.Orange
|
||||
gbYellow = t.Yellow
|
||||
gbGreen = t.Green
|
||||
gbAqua = t.Aqua
|
||||
gbBlue = t.Blue
|
||||
gbPurple = t.Purple
|
||||
gbBorder = t.Border
|
||||
|
||||
// Component styles
|
||||
TabActiveStyle = lipgloss.NewStyle().Background(t.Yellow).Foreground(t.Bg).Bold(true).Padding(0, 2)
|
||||
TabInactiveStyle = lipgloss.NewStyle().Background(t.Border).Foreground(t.FgMute).Padding(0, 2)
|
||||
TabBarStyle = lipgloss.NewStyle().Background(t.TabBg)
|
||||
StatusBarStyle = lipgloss.NewStyle().Background(t.Green).Foreground(t.Bg).Padding(0, 1)
|
||||
AppTitleStyle = lipgloss.NewStyle().Foreground(t.Yellow).Bold(true)
|
||||
HighlightStyle = lipgloss.NewStyle().Foreground(t.Orange).Bold(true)
|
||||
SelectedStyle = lipgloss.NewStyle().Foreground(t.Fg).Background(t.BgSel).Bold(true).Padding(0, 1)
|
||||
ErrorStyle = lipgloss.NewStyle().Foreground(t.Red).Bold(true)
|
||||
SuccessStyle = lipgloss.NewStyle().Foreground(t.Green).Bold(true)
|
||||
InfoStyle = lipgloss.NewStyle().Foreground(t.Aqua)
|
||||
SubtitleStyle = lipgloss.NewStyle().Foreground(t.FgMute)
|
||||
HostNameStyle = lipgloss.NewStyle().Foreground(t.Yellow).Bold(true)
|
||||
HostDetailStyle = lipgloss.NewStyle().Foreground(t.FgMute)
|
||||
TagStyle = lipgloss.NewStyle().Foreground(t.Green)
|
||||
TitleStyle = AppTitleStyle
|
||||
SectionStyle = lipgloss.NewStyle().Foreground(t.Orange).Bold(true)
|
||||
BorderStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Border).Padding(1, 2)
|
||||
|
||||
// Pane styles
|
||||
StylePaneActive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Green).Padding(0, 1)
|
||||
StylePaneInactive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Border).Padding(0, 1)
|
||||
|
||||
// Host card styles
|
||||
HostCardStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Border).Padding(0, 1)
|
||||
HostCardActiveStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Green).Padding(0, 1)
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/knownhosts"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
// Screen represents different TUI screens (deprecated, use tabs)
|
||||
type Screen int
|
||||
|
||||
const (
|
||||
ScreenHostList Screen = iota
|
||||
ScreenConnection
|
||||
ScreenSettings
|
||||
)
|
||||
|
||||
// Model represents the main TUI model
|
||||
type Model struct {
|
||||
tabs *TabManager
|
||||
CurrentScreen Screen // deprecated, kept for backward compat
|
||||
Hosts []*models.Host // deprecated
|
||||
SelectedIndex int // deprecated
|
||||
Error error
|
||||
Quit bool
|
||||
dataDir string
|
||||
program *tea.Program
|
||||
|
||||
// Security
|
||||
storagePassword string
|
||||
knownHosts *knownhosts.KnownHosts
|
||||
showEncryptPrompt bool
|
||||
}
|
||||
|
||||
// New creates a new TUI model
|
||||
func New() *Model {
|
||||
hostList := NewHostListTab()
|
||||
tm := NewTabManager(hostList)
|
||||
|
||||
return &Model{
|
||||
tabs: tm,
|
||||
CurrentScreen: ScreenHostList,
|
||||
SelectedIndex: 0,
|
||||
Quit: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Init initializes the TUI
|
||||
func (m *Model) Init() tea.Cmd {
|
||||
if m.showEncryptPrompt {
|
||||
// Show password prompt tab
|
||||
tab := NewPasswordPromptTab(passwordModeSetup, m.dataDir, func(password string) {
|
||||
m.storagePassword = password
|
||||
})
|
||||
cmd := m.tabs.Add(tab)
|
||||
m.showEncryptPrompt = false
|
||||
return cmd
|
||||
}
|
||||
return m.tabs.Init()
|
||||
}
|
||||
|
||||
// SetProgram stores a reference to the tea.Program for sending messages from goroutines
|
||||
func (m *Model) SetProgram(p *tea.Program) {
|
||||
m.program = p
|
||||
}
|
||||
|
||||
// SetStoragePassword sets the master password for encrypted storage
|
||||
func (m *Model) SetStoragePassword(password string) {
|
||||
m.storagePassword = password
|
||||
}
|
||||
|
||||
// SetKnownHosts sets the known_hosts manager for host key verification
|
||||
func (m *Model) SetKnownHosts(kh *knownhosts.KnownHosts) {
|
||||
m.knownHosts = kh
|
||||
}
|
||||
|
||||
// ShowEncryptPrompt sets a flag to show the encryption setup prompt on first render
|
||||
func (m *Model) ShowEncryptPrompt() {
|
||||
m.showEncryptPrompt = true
|
||||
}
|
||||
|
||||
// Update handles messages and updates the model
|
||||
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
// Only hard quit on ctrl+c (let tabs handle q)
|
||||
if msg.String() == "ctrl+c" {
|
||||
m.Quit = true
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
case quitMsg:
|
||||
m.Quit = true
|
||||
return m, tea.Quit
|
||||
|
||||
case sshConnectToMsg:
|
||||
return m, tea.Batch(tea.ClearScreen, sshConnectCmd(msg.host, m.dataDir))
|
||||
|
||||
case sshExitMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
}
|
||||
return m, tea.ClearScreen
|
||||
|
||||
case openHostFormMsg:
|
||||
var tab Tab
|
||||
if msg.editing != nil {
|
||||
tab = NewEditHostFormTab(msg.editing, m.dataDir)
|
||||
} else {
|
||||
tab = NewAddHostFormTab(m.dataDir)
|
||||
}
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case passwordSetMsg:
|
||||
// Password was set — store it and load hosts
|
||||
m.storagePassword = msg.password
|
||||
|
||||
// Load hosts with the password
|
||||
store, err := storage.NewJSONStorage(m.dataDir)
|
||||
if err == nil {
|
||||
store.SetPassword(msg.password)
|
||||
ctx := context.Background()
|
||||
hosts, loadErr := store.ListHosts(ctx)
|
||||
if loadErr == nil {
|
||||
m.Hosts = hosts
|
||||
// Update host list tab if it exists
|
||||
if hl, ok := m.tabs.Active().(*HostListTab); ok {
|
||||
hl.SetHosts(hosts)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close the password prompt tab
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case openEncryptPromptMsg:
|
||||
// Show password setup prompt
|
||||
tab := NewPasswordPromptTab(passwordModeSetup, m.dataDir, func(password string) {
|
||||
m.storagePassword = password
|
||||
})
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case openSFTPMsg:
|
||||
tab := NewSFTPBrowserTab(msg.host, m.dataDir)
|
||||
if m.program != nil {
|
||||
tab.SetProgram(m.program)
|
||||
}
|
||||
if m.storagePassword != "" {
|
||||
tab.SetStoragePassword(m.storagePassword)
|
||||
}
|
||||
if m.knownHosts != nil {
|
||||
tab.SetPassphraseCallback(func() string {
|
||||
// TODO: prompt for passphrase in TUI
|
||||
return ""
|
||||
})
|
||||
}
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case openKeyListMsg:
|
||||
tab := NewKeyListTab(m.dataDir)
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case openSnippetListMsg:
|
||||
tab := NewSnippetListTab(m.dataDir)
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case openKeyFormMsg:
|
||||
var tab Tab
|
||||
if msg.editing != nil {
|
||||
tab = NewEditKeyFormTab(msg.editing, m.dataDir)
|
||||
} else {
|
||||
tab = NewAddKeyFormTab(m.dataDir)
|
||||
}
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case openSnippetFormMsg:
|
||||
var tab Tab
|
||||
if msg.editing != nil {
|
||||
tab = NewEditSnippetFormTab(msg.editing, m.dataDir)
|
||||
} else {
|
||||
tab = NewAddSnippetFormTab(m.dataDir)
|
||||
}
|
||||
cmd := m.tabs.Add(tab)
|
||||
return m, cmd
|
||||
|
||||
case closeFormMsg:
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case saveHostResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
return m, nil
|
||||
}
|
||||
// Close the form tab, switch back to host list
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
// Reload hosts
|
||||
return m, func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(m.dataDir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
hosts, err := store.ListHosts(context.Background())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return loadedHostsMsg{hosts: hosts}
|
||||
}
|
||||
|
||||
case loadedHostsMsg:
|
||||
m.LoadHosts(msg.hosts)
|
||||
|
||||
case saveKeyResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
return m, nil
|
||||
}
|
||||
// Close form tab and switch back to list
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
// Reload keys
|
||||
return m, func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(m.dataDir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
keys, err := store.ListKeyPairs(context.Background())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return keyListLoadedMsg{keys: keys}
|
||||
}
|
||||
|
||||
case deleteKeyResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
}
|
||||
// Reload keys
|
||||
return m, func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(m.dataDir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
keys, err := store.ListKeyPairs(context.Background())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return keyListLoadedMsg{keys: keys}
|
||||
}
|
||||
|
||||
case keyListLoadedMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
return m, nil
|
||||
}
|
||||
if kt := FindKeyListTab(m.tabs.tabs); kt != nil {
|
||||
kt.SetKeys(msg.keys)
|
||||
}
|
||||
|
||||
case saveSnippetResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
return m, nil
|
||||
}
|
||||
// Close form tab and switch back to list
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
// Reload snippets
|
||||
return m, func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(m.dataDir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
snippets, err := store.ListSnippets(context.Background())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return snippetListLoadedMsg{snippets: snippets}
|
||||
}
|
||||
|
||||
case deleteSnippetResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
}
|
||||
// Reload snippets
|
||||
return m, func() tea.Msg {
|
||||
store, err := storage.NewJSONStorage(m.dataDir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
snippets, err := store.ListSnippets(context.Background())
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return snippetListLoadedMsg{snippets: snippets}
|
||||
}
|
||||
|
||||
case snippetListLoadedMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
return m, nil
|
||||
}
|
||||
if st := FindSnippetListTab(m.tabs.tabs); st != nil {
|
||||
st.SetSnippets(msg.snippets)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
cmd, err := m.tabs.Update(msg)
|
||||
if err != nil {
|
||||
m.Error = err
|
||||
}
|
||||
|
||||
// Sync deprecated fields
|
||||
if ht := FindHostListTab(m.tabs.tabs); ht != nil {
|
||||
m.Hosts = ht.Hosts()
|
||||
m.SelectedIndex = ht.SelectedIndex()
|
||||
}
|
||||
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// View renders the TUI
|
||||
func (m *Model) View() string {
|
||||
if m.Quit {
|
||||
m.tabs = nil
|
||||
return "Thanks for using hostkeeper!\n"
|
||||
}
|
||||
|
||||
if m.tabs == nil || m.tabs.Len() == 0 {
|
||||
return "No tabs open. Press 'q' to quit.\n"
|
||||
}
|
||||
|
||||
// Pass error to host list tab for display
|
||||
if m.Error != nil {
|
||||
if ht := FindHostListTab(m.tabs.tabs); ht != nil {
|
||||
ht.err = m.Error
|
||||
}
|
||||
m.Error = nil
|
||||
}
|
||||
|
||||
return m.tabs.View()
|
||||
}
|
||||
|
||||
// LoadHosts loads hosts into the TUI model
|
||||
func (m *Model) LoadHosts(hosts []*models.Host) {
|
||||
if m.tabs == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if ht := FindHostListTab(m.tabs.tabs); ht != nil {
|
||||
ht.SetHosts(hosts)
|
||||
m.Hosts = hosts
|
||||
}
|
||||
}
|
||||
|
||||
// SetDataDir sets the data directory for SSH connections
|
||||
func (m *Model) SetDataDir(dir string) {
|
||||
m.dataDir = dir
|
||||
}
|
||||
|
||||
// TabManager returns the underlying tab manager
|
||||
func (m *Model) TabManager() *TabManager {
|
||||
return m.tabs
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTUIInitialization(t *testing.T) {
|
||||
ui := New()
|
||||
if ui == nil {
|
||||
t.Fatal("Failed to initialize TUI")
|
||||
}
|
||||
|
||||
if ui.tabs == nil {
|
||||
t.Fatal("expected tabs manager to be initialized")
|
||||
}
|
||||
|
||||
if ui.tabs.Len() != 1 {
|
||||
t.Errorf("expected 1 tab, got %d", ui.tabs.Len())
|
||||
}
|
||||
|
||||
if ui.Quit {
|
||||
t.Error("expected Quit to be false")
|
||||
}
|
||||
|
||||
// Should have a HostListTab by default
|
||||
ht := FindHostListTab(ui.tabs.tabs)
|
||||
if ht == nil {
|
||||
t.Error("expected HostListTab to be the initial tab")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTUILoadHosts(t *testing.T) {
|
||||
ui := New()
|
||||
if ui == nil {
|
||||
t.Fatal("Failed to initialize TUI")
|
||||
}
|
||||
|
||||
ui.LoadHosts(nil)
|
||||
if ui.Hosts != nil {
|
||||
t.Error("expected Hosts to be nil")
|
||||
}
|
||||
|
||||
// Should still have a valid tab manager
|
||||
if ui.tabs == nil {
|
||||
t.Fatal("expected tabs manager to be valid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTabManagerBasic(t *testing.T) {
|
||||
tm := NewTabManager(NewHostListTab())
|
||||
if tm.Len() != 1 {
|
||||
t.Errorf("expected 1 tab, got %d", tm.Len())
|
||||
}
|
||||
|
||||
if tm.Active() == nil {
|
||||
t.Fatal("expected active tab")
|
||||
}
|
||||
|
||||
if tm.Active().Name() != "Hosts" {
|
||||
t.Errorf("expected 'Hosts', got '%s'", tm.Active().Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTabManagerNavigation(t *testing.T) {
|
||||
tm := NewTabManager(NewHostListTab())
|
||||
|
||||
// Add a second tab
|
||||
second := NewHostListTab()
|
||||
tm.Add(second)
|
||||
if tm.Len() != 2 {
|
||||
t.Errorf("expected 2 tabs, got %d", tm.Len())
|
||||
}
|
||||
|
||||
// Active should now be the last added tab
|
||||
if tm.active != 1 {
|
||||
t.Errorf("expected active index 1, got %d", tm.active)
|
||||
}
|
||||
|
||||
// Previous
|
||||
tm.Prev()
|
||||
if tm.active != 0 {
|
||||
t.Errorf("expected active index 0 after Prev, got %d", tm.active)
|
||||
}
|
||||
|
||||
// Next
|
||||
tm.Next()
|
||||
if tm.active != 1 {
|
||||
t.Errorf("expected active index 1 after Next, got %d", tm.active)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTabManagerClose(t *testing.T) {
|
||||
tm := NewTabManager(NewHostListTab())
|
||||
second := NewHostListTab()
|
||||
tm.Add(second)
|
||||
tm.Add(NewHostListTab())
|
||||
|
||||
// Close active (last tab)
|
||||
closed := tm.CloseActive()
|
||||
if closed == nil {
|
||||
t.Error("expected closed tab to be returned")
|
||||
}
|
||||
|
||||
if tm.Len() != 2 {
|
||||
t.Errorf("expected 2 tabs after close, got %d", tm.Len())
|
||||
}
|
||||
|
||||
// Close all tabs except last
|
||||
tm.Close(0)
|
||||
if tm.Len() != 1 {
|
||||
t.Errorf("expected 1 tab after close, got %d", tm.Len())
|
||||
}
|
||||
|
||||
// Should not close the last tab via CloseActive (returns nil)
|
||||
result := tm.CloseActive()
|
||||
if result != nil {
|
||||
t.Error("expected nil when trying to close the last tab")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
)
|
||||
|
||||
func tempDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.MkdirTemp("", "config-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
return dir
|
||||
}
|
||||
|
||||
// 4.1 New first run — creates default config
|
||||
func TestNewFirstRun(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
|
||||
// Override HOME to use temp dir
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
t.Fatalf("New failed: %v", err)
|
||||
}
|
||||
if cfg == nil {
|
||||
t.Fatal("New should return non-nil Config")
|
||||
}
|
||||
|
||||
appCfg := cfg.GetAppConfig()
|
||||
if appCfg == nil {
|
||||
t.Fatal("GetAppConfig should return non-nil")
|
||||
}
|
||||
if appCfg.Version != "1.0.0" {
|
||||
t.Errorf("Version = %q, want %q", appCfg.Version, "1.0.0")
|
||||
}
|
||||
if appCfg.Theme != "dark" {
|
||||
t.Errorf("Theme = %q, want %q", appCfg.Theme, "dark")
|
||||
}
|
||||
}
|
||||
|
||||
// 4.3 Save
|
||||
func TestSave(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
appCfg := cfg.GetAppConfig()
|
||||
appCfg.Theme = "light"
|
||||
|
||||
err := cfg.Save()
|
||||
if err != nil {
|
||||
t.Fatalf("Save failed: %v", err)
|
||||
}
|
||||
|
||||
// Reload and verify
|
||||
cfg2, _ := config.New()
|
||||
if cfg2.GetAppConfig().Theme != "light" {
|
||||
t.Errorf("After Save, Theme = %q, want %q", cfg2.GetAppConfig().Theme, "light")
|
||||
}
|
||||
}
|
||||
|
||||
// 4.4 UpdateAppConfig
|
||||
func TestUpdateAppConfig(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
appCfg := cfg.GetAppConfig()
|
||||
appCfg.Theme = "dracula"
|
||||
appCfg.DefaultPort = 2222
|
||||
|
||||
err := cfg.UpdateAppConfig(appCfg)
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateAppConfig failed: %v", err)
|
||||
}
|
||||
|
||||
// Reload and verify
|
||||
cfg2, _ := config.New()
|
||||
if cfg2.GetAppConfig().Theme != "dracula" {
|
||||
t.Errorf("After UpdateAppConfig, Theme = %q, want %q", cfg2.GetAppConfig().Theme, "dracula")
|
||||
}
|
||||
if cfg2.GetAppConfig().DefaultPort != 2222 {
|
||||
t.Errorf("After UpdateAppConfig, DefaultPort = %d, want 2222", cfg2.GetAppConfig().DefaultPort)
|
||||
}
|
||||
}
|
||||
|
||||
// 4.5 GetConfigDir
|
||||
func TestGetConfigDir(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
configDir := cfg.GetConfigDir()
|
||||
if configDir == "" {
|
||||
t.Error("GetConfigDir should return non-empty path")
|
||||
}
|
||||
if !filepath.IsAbs(configDir) {
|
||||
t.Errorf("GetConfigDir should return absolute path, got %q", configDir)
|
||||
}
|
||||
}
|
||||
|
||||
// 4.6 GetDataDir
|
||||
func TestGetDataDir(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
dataDir := cfg.GetDataDir()
|
||||
if dataDir == "" {
|
||||
t.Error("GetDataDir should return non-empty path")
|
||||
}
|
||||
if !filepath.IsAbs(dataDir) {
|
||||
t.Errorf("GetDataDir should return absolute path, got %q", dataDir)
|
||||
}
|
||||
}
|
||||
|
||||
// 4.7 GetConfigFilePath
|
||||
func TestGetConfigFilePath(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
path := cfg.GetConfigFilePath()
|
||||
if filepath.Base(path) != "config.json" {
|
||||
t.Errorf("GetConfigFilePath should end with config.json, got %q", path)
|
||||
}
|
||||
}
|
||||
|
||||
// 4.8 GetHostsFilePath
|
||||
func TestGetHostsFilePath(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
path := cfg.GetHostsFilePath()
|
||||
if filepath.Base(path) != "hosts.json" {
|
||||
t.Errorf("GetHostsFilePath should end with hosts.json, got %q", path)
|
||||
}
|
||||
}
|
||||
|
||||
// 4.9 GetKeysFilePath
|
||||
func TestGetKeysFilePath(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
path := cfg.GetKeysFilePath()
|
||||
if filepath.Base(path) != "keys.json" {
|
||||
t.Errorf("GetKeysFilePath should end with keys.json, got %q", path)
|
||||
}
|
||||
}
|
||||
|
||||
// 4.10 GetSnippetsFilePath
|
||||
func TestGetSnippetsFilePath(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
origHome := os.Getenv("HOME")
|
||||
os.Setenv("HOME", dir)
|
||||
defer os.Setenv("HOME", origHome)
|
||||
|
||||
cfg, _ := config.New()
|
||||
path := cfg.GetSnippetsFilePath()
|
||||
if filepath.Base(path) != "snippets.json" {
|
||||
t.Errorf("GetSnippetsFilePath should end with snippets.json, got %q", path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package crypto_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/crypto"
|
||||
)
|
||||
|
||||
// 1.1 DeriveKey determinism — same password + salt → same key
|
||||
func TestDeriveKeyDeterminism(t *testing.T) {
|
||||
salt := []byte("1234567890123456")
|
||||
key1 := crypto.DeriveKey("password", salt)
|
||||
key2 := crypto.DeriveKey("password", salt)
|
||||
if !bytes.Equal(key1, key2) {
|
||||
t.Error("DeriveKey should return same key for same password + salt")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.2 DeriveKey password variation — different password → different key
|
||||
func TestDeriveKeyPasswordVariation(t *testing.T) {
|
||||
salt := []byte("1234567890123456")
|
||||
key1 := crypto.DeriveKey("password1", salt)
|
||||
key2 := crypto.DeriveKey("password2", salt)
|
||||
if bytes.Equal(key1, key2) {
|
||||
t.Error("DeriveKey should return different keys for different passwords")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.3 DeriveKey salt variation — different salt → different key
|
||||
func TestDeriveKeySaltVariation(t *testing.T) {
|
||||
key1 := crypto.DeriveKey("password", []byte("1234567890123456"))
|
||||
key2 := crypto.DeriveKey("password", []byte("6543210987654321"))
|
||||
if bytes.Equal(key1, key2) {
|
||||
t.Error("DeriveKey should return different keys for different salts")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.4 DeriveKey empty password — no panic, valid key length
|
||||
func TestDeriveKeyEmptyPassword(t *testing.T) {
|
||||
salt := []byte("1234567890123456")
|
||||
key := crypto.DeriveKey("", salt)
|
||||
if len(key) != crypto.KeyLength {
|
||||
t.Errorf("DeriveKey with empty password should return %d bytes, got %d", crypto.KeyLength, len(key))
|
||||
}
|
||||
}
|
||||
|
||||
// 1.5 Encrypt/Decrypt round-trip
|
||||
func TestEncryptDecryptRoundTrip(t *testing.T) {
|
||||
plaintext := []byte("hello world")
|
||||
encoded, err := crypto.Encrypt(plaintext, "mypassword")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
decoded, err := crypto.Decrypt(encoded, "mypassword")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt failed: %v", err)
|
||||
}
|
||||
if !bytes.Equal(plaintext, decoded) {
|
||||
t.Errorf("Round-trip failed: got %q, want %q", decoded, plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
// 1.6 Encrypt empty plaintext
|
||||
func TestEncryptDecryptEmpty(t *testing.T) {
|
||||
plaintext := []byte("")
|
||||
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
decoded, err := crypto.Decrypt(encoded, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt failed: %v", err)
|
||||
}
|
||||
if len(decoded) != 0 {
|
||||
t.Errorf("Expected empty plaintext, got %d bytes", len(decoded))
|
||||
}
|
||||
}
|
||||
|
||||
// 1.7 Encrypt large data (1MB)
|
||||
func TestEncryptDecryptLargeData(t *testing.T) {
|
||||
plaintext := make([]byte, 1024*1024)
|
||||
if _, err := rand.Read(plaintext); err != nil {
|
||||
t.Fatalf("Failed to generate random data: %v", err)
|
||||
}
|
||||
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
decoded, err := crypto.Decrypt(encoded, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt failed: %v", err)
|
||||
}
|
||||
if !bytes.Equal(plaintext, decoded) {
|
||||
t.Error("Large data round-trip failed")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.8 Encrypt unicode
|
||||
func TestEncryptDecryptUnicode(t *testing.T) {
|
||||
plaintext := []byte("こんにちは世界 🌍")
|
||||
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
decoded, err := crypto.Decrypt(encoded, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt failed: %v", err)
|
||||
}
|
||||
if !bytes.Equal(plaintext, decoded) {
|
||||
t.Errorf("Unicode round-trip failed: got %q, want %q", decoded, plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
// 1.9 Encrypt with newlines
|
||||
func TestEncryptDecryptNewlines(t *testing.T) {
|
||||
plaintext := []byte("line1\nline2\nline3")
|
||||
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
decoded, err := crypto.Decrypt(encoded, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt failed: %v", err)
|
||||
}
|
||||
if !bytes.Equal(plaintext, decoded) {
|
||||
t.Errorf("Newlines round-trip failed: got %q, want %q", decoded, plaintext)
|
||||
}
|
||||
}
|
||||
|
||||
// 1.10 Wrong password → error
|
||||
func TestDecryptWrongPassword(t *testing.T) {
|
||||
plaintext := []byte("secret data")
|
||||
encoded, err := crypto.Encrypt(plaintext, "correct-password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
_, err = crypto.Decrypt(encoded, "wrong-password")
|
||||
if err == nil {
|
||||
t.Error("Decrypt with wrong password should return error")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.11 Empty password → error
|
||||
func TestDecryptEmptyPassword(t *testing.T) {
|
||||
plaintext := []byte("secret data")
|
||||
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
_, err = crypto.Decrypt(encoded, "")
|
||||
if err == nil {
|
||||
t.Error("Decrypt with empty password should return error")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.12 IsEncrypted valid ciphertext
|
||||
func TestIsEncryptedValid(t *testing.T) {
|
||||
encoded, err := crypto.Encrypt([]byte("test"), "password")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt failed: %v", err)
|
||||
}
|
||||
if !crypto.IsEncrypted(encoded) {
|
||||
t.Error("IsEncrypted should return true for valid ciphertext")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.13 IsEncrypted plaintext
|
||||
func TestIsEncryptedPlaintext(t *testing.T) {
|
||||
if crypto.IsEncrypted("hello world") {
|
||||
t.Error("IsEncrypted should return false for plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.14 IsEncrypted empty
|
||||
func TestIsEncryptedEmpty(t *testing.T) {
|
||||
if crypto.IsEncrypted("") {
|
||||
t.Error("IsEncrypted should return false for empty string")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.15 HashPassword determinism
|
||||
func TestHashPasswordDeterminism(t *testing.T) {
|
||||
hash1 := crypto.HashPassword("mypassword")
|
||||
hash2 := crypto.HashPassword("mypassword")
|
||||
if hash1 != hash2 {
|
||||
t.Error("HashPassword should return same hash for same password")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.16 HashPassword variation
|
||||
func TestHashPasswordVariation(t *testing.T) {
|
||||
hash1 := crypto.HashPassword("password1")
|
||||
hash2 := crypto.HashPassword("password2")
|
||||
if hash1 == hash2 {
|
||||
t.Error("HashPassword should return different hashes for different passwords")
|
||||
}
|
||||
}
|
||||
|
||||
// 1.17 Encrypt randomness — same input → different ciphertext
|
||||
func TestEncryptRandomness(t *testing.T) {
|
||||
plaintext := []byte("same input")
|
||||
encoded1, _ := crypto.Encrypt(plaintext, "password")
|
||||
encoded2, _ := crypto.Encrypt(plaintext, "password")
|
||||
if encoded1 == encoded2 {
|
||||
t.Error("Encrypt should produce different ciphertext each time (random salt)")
|
||||
}
|
||||
}
|
||||
|
||||
// Verify constants
|
||||
func TestConstants(t *testing.T) {
|
||||
if crypto.KeyLength != 32 {
|
||||
t.Errorf("KeyLength = %d, want 32", crypto.KeyLength)
|
||||
}
|
||||
if crypto.SaltLength != 16 {
|
||||
t.Errorf("SaltLength = %d, want 16", crypto.SaltLength)
|
||||
}
|
||||
if crypto.Iterations != 100000 {
|
||||
t.Errorf("Iterations = %d, want 100000", crypto.Iterations)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify error variables
|
||||
func TestErrorVars(t *testing.T) {
|
||||
if crypto.ErrInvalidPassword == nil {
|
||||
t.Error("ErrInvalidPassword should not be nil")
|
||||
}
|
||||
if crypto.ErrDecryptionFailed == nil {
|
||||
t.Error("ErrDecryptionFailed should not be nil")
|
||||
}
|
||||
if !strings.Contains(crypto.ErrDecryptionFailed.Error(), "decryption failed") {
|
||||
t.Error("ErrDecryptionFailed message should contain 'decryption failed'")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package errors_test
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
apperrors "git.tukangketik.id/swanadiva/hostkeeper/internal/errors"
|
||||
)
|
||||
|
||||
func TestAppError(t *testing.T) {
|
||||
cause := stderrors.New("underlying issue")
|
||||
appErr := apperrors.NewAppError(
|
||||
apperrors.ErrAuthFailed,
|
||||
"Authentication failed",
|
||||
cause,
|
||||
[]string{"Check credentials", "Verify key permissions"},
|
||||
)
|
||||
|
||||
if appErr.Code != apperrors.ErrAuthFailed {
|
||||
t.Errorf("Expected code '%s', got '%s'", apperrors.ErrAuthFailed, appErr.Code)
|
||||
}
|
||||
|
||||
if len(appErr.Hints) != 2 {
|
||||
t.Errorf("Expected 2 hints, got %d", len(appErr.Hints))
|
||||
}
|
||||
|
||||
// Test error message is non-empty
|
||||
if appErr.Error() == "" {
|
||||
t.Error("Expected non-empty error message")
|
||||
}
|
||||
|
||||
// Test Unwrap
|
||||
if !stderrors.Is(appErr, cause) {
|
||||
t.Error("Expected errors.Is to match the cause via Unwrap")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionError(t *testing.T) {
|
||||
connErr := apperrors.NewConnectionError(
|
||||
"auth",
|
||||
"Authentication failed",
|
||||
"ssh: handshake failed",
|
||||
[]string{"Check credentials", "Verify key permissions"},
|
||||
)
|
||||
|
||||
if connErr.Type != "auth" {
|
||||
t.Errorf("Expected type 'auth', got '%s'", connErr.Type)
|
||||
}
|
||||
|
||||
if len(connErr.Hints) != 2 {
|
||||
t.Errorf("Expected 2 hints, got %d", len(connErr.Hints))
|
||||
}
|
||||
|
||||
if connErr.Error() == "" {
|
||||
t.Error("Expected non-empty error message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSSHError(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inputErr error
|
||||
expectedType string
|
||||
}{
|
||||
{
|
||||
name: "connection refused",
|
||||
inputErr: stderrors.New("dial tcp: connection refused"),
|
||||
expectedType: "network",
|
||||
},
|
||||
{
|
||||
name: "authentication failed",
|
||||
inputErr: stderrors.New("ssh: handshake failed: ssh: unable to authenticate"),
|
||||
expectedType: "auth",
|
||||
},
|
||||
{
|
||||
name: "timeout",
|
||||
inputErr: stderrors.New("dial tcp: connection timed out"),
|
||||
expectedType: "timeout",
|
||||
},
|
||||
{
|
||||
name: "no such host",
|
||||
inputErr: stderrors.New("dial tcp: lookup: no such host"),
|
||||
expectedType: "config",
|
||||
},
|
||||
{
|
||||
name: "permission denied",
|
||||
inputErr: stderrors.New("ssh: permission denied"),
|
||||
expectedType: "auth",
|
||||
},
|
||||
{
|
||||
name: "unknown error",
|
||||
inputErr: stderrors.New("something went wrong"),
|
||||
expectedType: "unknown",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
connErr := apperrors.HandleSSHError(tt.inputErr)
|
||||
if connErr == nil {
|
||||
t.Fatal("Expected non-nil ConnectionError")
|
||||
}
|
||||
if connErr.Type != tt.expectedType {
|
||||
t.Errorf("Expected type '%s', got '%s'", tt.expectedType, connErr.Type)
|
||||
}
|
||||
if len(connErr.Hints) == 0 {
|
||||
t.Error("Expected at least one hint")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSSHErrorNil(t *testing.T) {
|
||||
result := apperrors.HandleSSHError(nil)
|
||||
if result != nil {
|
||||
t.Error("Expected nil for nil input")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatConnectionError(t *testing.T) {
|
||||
connErr := apperrors.NewConnectionError(
|
||||
"auth",
|
||||
"Authentication failed",
|
||||
"ssh: handshake failed",
|
||||
[]string{"Check credentials", "Verify key permissions"},
|
||||
)
|
||||
|
||||
output := apperrors.FormatConnectionError(connErr)
|
||||
|
||||
if output == "" {
|
||||
t.Error("Expected non-empty formatted output")
|
||||
}
|
||||
|
||||
if !strings.Contains(output, "Authentication failed") {
|
||||
t.Error("Expected output to contain error message")
|
||||
}
|
||||
|
||||
if !strings.Contains(output, "Possible solutions") {
|
||||
t.Error("Expected output to contain hints section")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
func TestIntegrationWorkflow(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
store, err := storage.NewJSONStorage(tempDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Test 1: Add hosts
|
||||
t.Run("AddHosts", func(t *testing.T) {
|
||||
testHost := &models.Host{
|
||||
ID: "integration-test-1",
|
||||
Name: "Integration Test Server",
|
||||
Hostname: "test.example.com",
|
||||
Port: 22,
|
||||
Username: "testuser",
|
||||
Auth: models.AuthConfig{Type: "password", Password: "testpass"},
|
||||
Tags: []string{"test", "integration"},
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := store.SaveHost(ctx, testHost); err != nil {
|
||||
t.Errorf("Failed to save host: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 2: List hosts
|
||||
t.Run("ListHosts", func(t *testing.T) {
|
||||
hosts, err := store.ListHosts(ctx)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to list hosts: %v", err)
|
||||
}
|
||||
|
||||
if len(hosts) != 1 {
|
||||
t.Errorf("Expected 1 host, got %d", len(hosts))
|
||||
}
|
||||
})
|
||||
|
||||
// Test 3: Get host
|
||||
t.Run("GetHost", func(t *testing.T) {
|
||||
host, err := store.GetHost(ctx, "integration-test-1")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to get host: %v", err)
|
||||
}
|
||||
|
||||
if host.Name != "Integration Test Server" {
|
||||
t.Errorf("Expected name 'Integration Test Server', got '%s'", host.Name)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 4: Update host
|
||||
t.Run("UpdateHost", func(t *testing.T) {
|
||||
host, err := store.GetHost(ctx, "integration-test-1")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to get host: %v", err)
|
||||
}
|
||||
|
||||
host.Name = "Updated Test Server"
|
||||
if err := store.SaveHost(ctx, host); err != nil {
|
||||
t.Errorf("Failed to update host: %v", err)
|
||||
}
|
||||
|
||||
updated, err := store.GetHost(ctx, "integration-test-1")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to get updated host: %v", err)
|
||||
}
|
||||
|
||||
if updated.Name != "Updated Test Server" {
|
||||
t.Errorf("Update failed: expected 'Updated Test Server', got '%s'", updated.Name)
|
||||
}
|
||||
})
|
||||
|
||||
// Test 5: Export/Import
|
||||
t.Run("ExportImport", func(t *testing.T) {
|
||||
exportData, err := store.ExportData(ctx)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to export: %v", err)
|
||||
}
|
||||
|
||||
if exportData == nil {
|
||||
t.Error("Exported data is nil")
|
||||
return
|
||||
}
|
||||
|
||||
if len(exportData.Hosts) != 1 {
|
||||
t.Errorf("Expected 1 host in export, got %d", len(exportData.Hosts))
|
||||
}
|
||||
|
||||
importDir := t.TempDir()
|
||||
importStore, err := storage.NewJSONStorage(importDir)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to create import storage: %v", err)
|
||||
}
|
||||
|
||||
if err := importStore.ImportData(ctx, exportData, storage.MergeStrategyReplace); err != nil {
|
||||
t.Errorf("Failed to import: %v", err)
|
||||
}
|
||||
|
||||
importedHosts, err := importStore.ListHosts(ctx)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to list imported hosts: %v", err)
|
||||
}
|
||||
|
||||
if len(importedHosts) != 1 {
|
||||
t.Errorf("Expected 1 imported host, got %d", len(importedHosts))
|
||||
}
|
||||
})
|
||||
|
||||
// Test 6: Delete host
|
||||
t.Run("DeleteHost", func(t *testing.T) {
|
||||
if err := store.DeleteHost(ctx, "integration-test-1"); err != nil {
|
||||
t.Errorf("Failed to delete host: %v", err)
|
||||
}
|
||||
|
||||
hosts, err := store.ListHosts(ctx)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to list hosts after deletion: %v", err)
|
||||
}
|
||||
|
||||
if len(hosts) != 0 {
|
||||
t.Errorf("Expected 0 hosts after deletion, got %d", len(hosts))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfigIntegration(t *testing.T) {
|
||||
cfg, err := config.New()
|
||||
if err != nil {
|
||||
t.Errorf("Failed to load/create config: %v", err)
|
||||
}
|
||||
|
||||
if cfg.GetAppConfig().DefaultPort != 22 {
|
||||
t.Errorf("Expected default port 22, got %d", cfg.GetAppConfig().DefaultPort)
|
||||
}
|
||||
|
||||
if cfg.GetAppConfig().ConnectionTimeout != 30 {
|
||||
t.Errorf("Expected default timeout 30, got %d", cfg.GetAppConfig().ConnectionTimeout)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package knownhosts_test
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
cryptossh "golang.org/x/crypto/ssh"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/knownhosts"
|
||||
)
|
||||
|
||||
func tempDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.MkdirTemp("", "knownhosts-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
return dir
|
||||
}
|
||||
|
||||
func generateTestKey(t *testing.T) cryptossh.PublicKey {
|
||||
t.Helper()
|
||||
pubKey, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
sshPubKey, err := cryptossh.NewPublicKey(pubKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create SSH public key: %v", err)
|
||||
}
|
||||
return sshPubKey
|
||||
}
|
||||
|
||||
func generateTestKey2(t *testing.T) cryptossh.PublicKey {
|
||||
t.Helper()
|
||||
pubKey, _, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to generate key: %v", err)
|
||||
}
|
||||
sshPubKey, err := cryptossh.NewPublicKey(pubKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create SSH public key: %v", err)
|
||||
}
|
||||
return sshPubKey
|
||||
}
|
||||
|
||||
// 2.1 New creates file on first call
|
||||
func TestNewCreatesFile(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
kh, err := knownhosts.New(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("New failed: %v", err)
|
||||
}
|
||||
if kh == nil {
|
||||
t.Fatal("New should return non-nil KnownHosts")
|
||||
}
|
||||
// File should be created after first Add+Save
|
||||
}
|
||||
|
||||
// 2.2 New loads existing
|
||||
func TestNewLoadsExisting(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
// Create and add a host
|
||||
kh1, _ := knownhosts.New(dir)
|
||||
_ = kh1.Add("example.com", 22, key)
|
||||
|
||||
// Load again
|
||||
kh2, err := knownhosts.New(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("New failed: %v", err)
|
||||
}
|
||||
stored := kh2.Get("example.com", 22)
|
||||
if stored == nil {
|
||||
t.Fatal("Should load existing host from file")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.3 Add new host
|
||||
func TestAddNewHost(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
err := kh.Add("example.com", 22, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Add failed: %v", err)
|
||||
}
|
||||
|
||||
stored := kh.Get("example.com", 22)
|
||||
if stored == nil {
|
||||
t.Fatal("Get should return the added host")
|
||||
}
|
||||
if stored.Hostname != "example.com" {
|
||||
t.Errorf("Hostname = %q, want %q", stored.Hostname, "example.com")
|
||||
}
|
||||
if stored.Port != 22 {
|
||||
t.Errorf("Port = %d, want 22", stored.Port)
|
||||
}
|
||||
}
|
||||
|
||||
// 2.4 Add duplicate — no error, no duplicate
|
||||
func TestAddDuplicate(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
_ = kh.Add("example.com", 22, key)
|
||||
err := kh.Add("example.com", 22, key)
|
||||
if err != nil {
|
||||
t.Fatalf("Add duplicate should not error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 2.5 Get existing host
|
||||
func TestGetExisting(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
_ = kh.Add("example.com", 22, key)
|
||||
|
||||
stored := kh.Get("example.com", 22)
|
||||
if stored == nil {
|
||||
t.Fatal("Get should return existing host")
|
||||
}
|
||||
if stored.Hostname != "example.com" {
|
||||
t.Errorf("Hostname = %q, want %q", stored.Hostname, "example.com")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.6 Get non-existent host
|
||||
func TestGetNonExistent(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
kh, _ := knownhosts.New(dir)
|
||||
|
||||
stored := kh.Get("unknown.com", 22)
|
||||
if stored != nil {
|
||||
t.Error("Get should return nil for non-existent host")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.7 Remove existing host
|
||||
func TestRemoveExisting(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
_ = kh.Add("example.com", 22, key)
|
||||
|
||||
err := kh.Remove("example.com", 22)
|
||||
if err != nil {
|
||||
t.Fatalf("Remove failed: %v", err)
|
||||
}
|
||||
|
||||
stored := kh.Get("example.com", 22)
|
||||
if stored != nil {
|
||||
t.Error("Get should return nil after Remove")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.8 Remove non-existent host — no error
|
||||
func TestRemoveNonExistent(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
kh, _ := knownhosts.New(dir)
|
||||
|
||||
err := kh.Remove("unknown.com", 22)
|
||||
if err != nil {
|
||||
t.Fatalf("Remove non-existent should not error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 2.9 Verify unknown host — (false, nil) TOFU
|
||||
func TestVerifyUnknown(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
matches, stored := kh.Verify("unknown.com", 22, key)
|
||||
if matches {
|
||||
t.Error("Verify should return false for unknown host")
|
||||
}
|
||||
if stored != nil {
|
||||
t.Error("Verify should return nil HostKey for unknown host")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.10 Verify known host, matching key — (true, hostKey)
|
||||
func TestVerifyKnownMatch(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
_ = kh.Add("example.com", 22, key)
|
||||
|
||||
matches, stored := kh.Verify("example.com", 22, key)
|
||||
if !matches {
|
||||
t.Error("Verify should return true for matching key")
|
||||
}
|
||||
if stored == nil {
|
||||
t.Error("Verify should return stored HostKey")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.11 Verify known host, mismatched key — (false, hostKey) MITM
|
||||
func TestVerifyKnownMismatch(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key1 := generateTestKey(t)
|
||||
key2 := generateTestKey2(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
_ = kh.Add("example.com", 22, key1)
|
||||
|
||||
matches, stored := kh.Verify("example.com", 22, key2)
|
||||
if matches {
|
||||
t.Error("Verify should return false for mismatched key (MITM)")
|
||||
}
|
||||
if stored == nil {
|
||||
t.Error("Verify should return stored HostKey for mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.12 HostKeyCallback — autoAdd=true adds unknown hosts
|
||||
func TestHostKeyCallbackAutoAdd(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh, _ := knownhosts.New(dir)
|
||||
callback := kh.HostKeyCallback(true)
|
||||
|
||||
// Simulate host key check via callback
|
||||
// HostKeyCallback expects net.Addr, so we create a fake one
|
||||
addr := &fakeAddr{addr: "192.168.1.1:22"}
|
||||
err := callback("example.com", addr, key)
|
||||
if err != nil {
|
||||
t.Fatalf("HostKeyCallback with autoAdd failed: %v", err)
|
||||
}
|
||||
|
||||
// Verify host was added
|
||||
stored := kh.Get("example.com", 22)
|
||||
if stored == nil {
|
||||
t.Error("HostKeyCallback should add unknown host when autoAdd=true")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.13 Persistence — Add → Save → New → Get
|
||||
func TestPersistence(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
key := generateTestKey(t)
|
||||
|
||||
kh1, _ := knownhosts.New(dir)
|
||||
_ = kh1.Add("example.com", 22, key)
|
||||
|
||||
// Create new instance from same directory
|
||||
kh2, err := knownhosts.New(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("New failed: %v", err)
|
||||
}
|
||||
stored := kh2.Get("example.com", 22)
|
||||
if stored == nil {
|
||||
t.Fatal("Host should persist across New() calls")
|
||||
}
|
||||
}
|
||||
|
||||
// 2.14 Corrupted file → error
|
||||
func TestCorruptedFile(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
path := filepath.Join(dir, "known_hosts")
|
||||
_ = os.WriteFile(path, []byte("not valid json {{{"), 0600)
|
||||
|
||||
_, err := knownhosts.New(dir)
|
||||
if err == nil {
|
||||
t.Error("New should return error for corrupted file")
|
||||
}
|
||||
}
|
||||
|
||||
// fakeAddr implements net.Addr for testing
|
||||
type fakeAddr struct {
|
||||
addr string
|
||||
}
|
||||
|
||||
func (f *fakeAddr) Network() string { return "tcp" }
|
||||
func (f *fakeAddr) String() string { return f.addr }
|
||||
@@ -0,0 +1,80 @@
|
||||
package errors_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
func TestDefaultConfig(t *testing.T) {
|
||||
config := models.DefaultConfig()
|
||||
|
||||
if config.Version != "1.0.0" {
|
||||
t.Errorf("Version = %q, want %q", config.Version, "1.0.0")
|
||||
}
|
||||
if config.DefaultPort != 22 {
|
||||
t.Errorf("DefaultPort = %d, want 22", config.DefaultPort)
|
||||
}
|
||||
if config.ConnectionTimeout != 30 {
|
||||
t.Errorf("ConnectionTimeout = %d, want 30", config.ConnectionTimeout)
|
||||
}
|
||||
if config.Theme != "dark" {
|
||||
t.Errorf("Theme = %q, want %q", config.Theme, "dark")
|
||||
}
|
||||
if len(config.Profiles) != 1 {
|
||||
t.Errorf("Profiles has %d items, want 1", len(config.Profiles))
|
||||
}
|
||||
if config.ActiveProfile != "default" {
|
||||
t.Errorf("ActiveProfile = %q, want %q", config.ActiveProfile, "default")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppConfigProfiles(t *testing.T) {
|
||||
config := models.DefaultConfig()
|
||||
|
||||
// Test GetProfile
|
||||
profile := config.GetProfile("default")
|
||||
if profile == nil {
|
||||
t.Fatal("GetProfile(default) returned nil")
|
||||
}
|
||||
if profile.Name != "default" {
|
||||
t.Errorf("Profile.Name = %q, want %q", profile.Name, "default")
|
||||
}
|
||||
|
||||
// Test GetProfile for non-existent profile
|
||||
profile = config.GetProfile("nonexistent")
|
||||
if profile != nil {
|
||||
t.Error("GetProfile(nonexistent) should return nil")
|
||||
}
|
||||
|
||||
// Test GetActiveProfile
|
||||
profile = config.GetActiveProfile()
|
||||
if profile == nil {
|
||||
t.Fatal("GetActiveProfile() returned nil")
|
||||
}
|
||||
if profile.Name != "default" {
|
||||
t.Errorf("Active profile Name = %q, want %q", profile.Name, "default")
|
||||
}
|
||||
|
||||
// Test AddProfile
|
||||
newProfile := models.Profile{
|
||||
Name: "work",
|
||||
Theme: "light",
|
||||
}
|
||||
config.AddProfile(newProfile)
|
||||
if len(config.Profiles) != 2 {
|
||||
t.Errorf("After AddProfile, Profiles has %d items, want 2", len(config.Profiles))
|
||||
}
|
||||
|
||||
// Test RemoveProfile
|
||||
config.RemoveProfile("work")
|
||||
if len(config.Profiles) != 1 {
|
||||
t.Errorf("After RemoveProfile, Profiles has %d items, want 1", len(config.Profiles))
|
||||
}
|
||||
|
||||
// Test RemoveProfile for non-existent profile
|
||||
config.RemoveProfile("nonexistent")
|
||||
if len(config.Profiles) != 1 {
|
||||
t.Errorf("After RemoveProfile(nonexistent), Profiles has %d items, want 1", len(config.Profiles))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package ssh_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/ssh"
|
||||
)
|
||||
|
||||
func TestNewClient(t *testing.T) {
|
||||
host := &models.Host{
|
||||
ID: "test-host",
|
||||
Name: "Test Server",
|
||||
Hostname: "localhost",
|
||||
Port: 22,
|
||||
Username: "testuser",
|
||||
Auth: models.AuthConfig{
|
||||
Type: "password",
|
||||
Password: "testpass",
|
||||
},
|
||||
}
|
||||
|
||||
client := ssh.NewClient(host, 30*time.Second)
|
||||
if client == nil {
|
||||
t.Fatal("Failed to create SSH client")
|
||||
}
|
||||
|
||||
if client.IsConnected() {
|
||||
t.Error("Expected client to not be connected initially")
|
||||
}
|
||||
|
||||
// Close should be safe even when not connected
|
||||
if err := client.Close(); err != nil {
|
||||
t.Errorf("Expected nil error on close when not connected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectFailure(t *testing.T) {
|
||||
// Test connecting to a non-existent server
|
||||
host := &models.Host{
|
||||
ID: "test-host",
|
||||
Name: "Non-existent Server",
|
||||
Hostname: "127.0.0.1",
|
||||
Port: 9999, // Port that's likely not running SSH
|
||||
Username: "testuser",
|
||||
Auth: models.AuthConfig{
|
||||
Type: "password",
|
||||
Password: "testpass",
|
||||
},
|
||||
}
|
||||
|
||||
client := ssh.NewClient(host, 2*time.Second)
|
||||
ctx := context.Background()
|
||||
err := client.Connect(ctx)
|
||||
|
||||
// We expect connection to fail
|
||||
if err == nil {
|
||||
t.Log("Connection succeeded (unexpected - SSH server may be running on port 9999)")
|
||||
_ = client.Close()
|
||||
} else {
|
||||
t.Logf("Connection failed as expected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteWithoutConnection(t *testing.T) {
|
||||
host := &models.Host{
|
||||
ID: "test-host",
|
||||
Name: "Test Server",
|
||||
Hostname: "localhost",
|
||||
Port: 22,
|
||||
Username: "testuser",
|
||||
Auth: models.AuthConfig{
|
||||
Type: "password",
|
||||
Password: "testpass",
|
||||
},
|
||||
}
|
||||
|
||||
client := ssh.NewClient(host, 30*time.Second)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := client.Execute(ctx, "echo hello")
|
||||
if err == nil {
|
||||
t.Error("Expected error when executing command without connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetClient(t *testing.T) {
|
||||
host := &models.Host{
|
||||
ID: "test-host",
|
||||
Name: "Test Server",
|
||||
Hostname: "localhost",
|
||||
Port: 22,
|
||||
Username: "testuser",
|
||||
Auth: models.AuthConfig{
|
||||
Type: "password",
|
||||
Password: "testpass",
|
||||
},
|
||||
}
|
||||
|
||||
client := ssh.NewClient(host, 30*time.Second)
|
||||
if client.GetClient() != nil {
|
||||
t.Error("Expected nil underlying client before connecting")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package storage_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
func TestExportImport(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
|
||||
store, err := storage.NewJSONStorage(tempDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create storage: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
testHost := &models.Host{
|
||||
ID: "test-host-1",
|
||||
Name: "Test Server",
|
||||
Hostname: "192.168.1.100",
|
||||
Port: 22,
|
||||
Username: "admin",
|
||||
Auth: models.AuthConfig{Type: "password"},
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
if err := store.SaveHost(ctx, testHost); err != nil {
|
||||
t.Fatalf("Failed to save host: %v", err)
|
||||
}
|
||||
|
||||
exportedData, err := store.ExportData(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to export data: %v", err)
|
||||
}
|
||||
|
||||
if exportedData == nil {
|
||||
t.Fatal("Exported data is nil")
|
||||
}
|
||||
|
||||
if len(exportedData.Hosts) != 1 {
|
||||
t.Fatalf("Expected 1 host, got %d", len(exportedData.Hosts))
|
||||
}
|
||||
|
||||
// Simulate writing to file and reading back
|
||||
jsonBytes, err := json.Marshal(exportedData)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to marshal export data: %v", err)
|
||||
}
|
||||
|
||||
var importedData storage.ExportData
|
||||
if err := json.Unmarshal(jsonBytes, &importedData); err != nil {
|
||||
t.Fatalf("Failed to unmarshal export data: %v", err)
|
||||
}
|
||||
|
||||
importDir := t.TempDir()
|
||||
importStore, err := storage.NewJSONStorage(importDir)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create import storage: %v", err)
|
||||
}
|
||||
|
||||
if err := importStore.ImportData(ctx, &importedData, storage.MergeStrategyReplace); err != nil {
|
||||
t.Fatalf("Failed to import data: %v", err)
|
||||
}
|
||||
|
||||
importedHosts, err := importStore.ListHosts(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to list imported hosts: %v", err)
|
||||
}
|
||||
|
||||
if len(importedHosts) != 1 {
|
||||
t.Errorf("Expected 1 imported host, got %d", len(importedHosts))
|
||||
}
|
||||
|
||||
if importedHosts[0].Name != testHost.Name {
|
||||
t.Errorf("Expected host name '%s', got '%s'", testHost.Name, importedHosts[0].Name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package storage_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
func tempDir(t *testing.T) string {
|
||||
t.Helper()
|
||||
dir, err := os.MkdirTemp("", "storage-test-*")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create temp dir: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
return dir
|
||||
}
|
||||
|
||||
// ============ KeyPair CRUD ============
|
||||
|
||||
// 3.1 SaveKeyPair
|
||||
func TestSaveKeyPair(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
kp := &models.KeyPair{
|
||||
Name: "my-key",
|
||||
Type: "ed25519",
|
||||
PrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----",
|
||||
}
|
||||
|
||||
err := store.SaveKeyPair(ctx, kp)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveKeyPair failed: %v", err)
|
||||
}
|
||||
if kp.ID == "" {
|
||||
t.Error("SaveKeyPair should generate UUID")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.2 ListKeyPairs
|
||||
func TestListKeyPairs(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
kp := &models.KeyPair{Name: "key1", Type: "ed25519", PrivateKey: "test-key-data"}
|
||||
_ = store.SaveKeyPair(ctx, kp)
|
||||
|
||||
keys, err := store.ListKeyPairs(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListKeyPairs failed: %v", err)
|
||||
}
|
||||
if len(keys) != 1 {
|
||||
t.Errorf("ListKeyPairs returned %d keys, want 1", len(keys))
|
||||
}
|
||||
}
|
||||
|
||||
// 3.3 GetKeyPair found
|
||||
func TestGetKeyPairFound(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
kp := &models.KeyPair{Name: "key1", Type: "ed25519", PrivateKey: "test-key-data"}
|
||||
_ = store.SaveKeyPair(ctx, kp)
|
||||
|
||||
found, err := store.GetKeyPair(ctx, kp.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetKeyPair failed: %v", err)
|
||||
}
|
||||
if found.Name != "key1" {
|
||||
t.Errorf("Name = %q, want %q", found.Name, "key1")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.4 GetKeyPair not found
|
||||
func TestGetKeyPairNotFound(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := store.GetKeyPair(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("GetKeyPair should return error for non-existent ID")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.5 DeleteKeyPair
|
||||
func TestDeleteKeyPair(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
kp := &models.KeyPair{Name: "key1", Type: "ed25519", PrivateKey: "test-key-data"}
|
||||
_ = store.SaveKeyPair(ctx, kp)
|
||||
|
||||
err := store.DeleteKeyPair(ctx, kp.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteKeyPair failed: %v", err)
|
||||
}
|
||||
|
||||
keys, _ := store.ListKeyPairs(ctx)
|
||||
if len(keys) != 0 {
|
||||
t.Errorf("ListKeyPairs after delete returned %d keys, want 0", len(keys))
|
||||
}
|
||||
}
|
||||
|
||||
// 3.6 DeleteKeyPair not found
|
||||
func TestDeleteKeyPairNotFound(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
err := store.DeleteKeyPair(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("DeleteKeyPair should return error for non-existent ID")
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Snippet CRUD ============
|
||||
|
||||
// 3.7 SaveSnippet
|
||||
func TestSaveSnippet(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
snippet := &models.Snippet{
|
||||
Name: "deploy-script",
|
||||
Command: "deploy.sh",
|
||||
Description: "deployment script",
|
||||
}
|
||||
|
||||
err := store.SaveSnippet(ctx, snippet)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveSnippet failed: %v", err)
|
||||
}
|
||||
if snippet.ID == "" {
|
||||
t.Error("SaveSnippet should generate UUID")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.8 ListSnippets
|
||||
func TestListSnippets(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
snippet := &models.Snippet{Name: "s1", Command: "cmd1", Description: "desc1"}
|
||||
_ = store.SaveSnippet(ctx, snippet)
|
||||
|
||||
snippets, err := store.ListSnippets(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSnippets failed: %v", err)
|
||||
}
|
||||
if len(snippets) != 1 {
|
||||
t.Errorf("ListSnippets returned %d snippets, want 1", len(snippets))
|
||||
}
|
||||
}
|
||||
|
||||
// 3.9 GetSnippet found
|
||||
func TestGetSnippetFound(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
snippet := &models.Snippet{Name: "s1", Command: "cmd1", Description: "desc1"}
|
||||
_ = store.SaveSnippet(ctx, snippet)
|
||||
|
||||
found, err := store.GetSnippet(ctx, snippet.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetSnippet failed: %v", err)
|
||||
}
|
||||
if found.Name != "s1" {
|
||||
t.Errorf("Name = %q, want %q", found.Name, "s1")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.10 GetSnippet not found
|
||||
func TestGetSnippetNotFound(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := store.GetSnippet(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("GetSnippet should return error for non-existent ID")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.11 DeleteSnippet
|
||||
func TestDeleteSnippet(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
snippet := &models.Snippet{Name: "s1", Command: "cmd1", Description: "desc1"}
|
||||
_ = store.SaveSnippet(ctx, snippet)
|
||||
|
||||
err := store.DeleteSnippet(ctx, snippet.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteSnippet failed: %v", err)
|
||||
}
|
||||
|
||||
snippets, _ := store.ListSnippets(ctx)
|
||||
if len(snippets) != 0 {
|
||||
t.Errorf("ListSnippets after delete returned %d snippets, want 0", len(snippets))
|
||||
}
|
||||
}
|
||||
|
||||
// 3.12 DeleteSnippet not found
|
||||
func TestDeleteSnippetNotFound(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
err := store.DeleteSnippet(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("DeleteSnippet should return error for non-existent ID")
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Encryption ============
|
||||
|
||||
// 3.13 SetPassword + SaveHost → encrypted on disk
|
||||
func TestEncryptionSaveHost(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
store.SetPassword("test-password-123")
|
||||
ctx := context.Background()
|
||||
|
||||
host := &models.Host{
|
||||
Name: "encrypted-host",
|
||||
Hostname: "192.168.1.100",
|
||||
Port: 22,
|
||||
Username: "admin",
|
||||
}
|
||||
err := store.SaveHost(ctx, host)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveHost with encryption failed: %v", err)
|
||||
}
|
||||
|
||||
// Read raw file — should be base64 ciphertext
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "hosts.json"))
|
||||
if string(data) == "" {
|
||||
t.Fatal("hosts.json should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.14 IsDataEncrypted
|
||||
func TestIsDataEncrypted(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
|
||||
// Before encryption — not encrypted
|
||||
if store.IsDataEncrypted() {
|
||||
t.Error("IsDataEncrypted should be false before SetPassword")
|
||||
}
|
||||
|
||||
// After encryption
|
||||
store.SetPassword("test-password-123")
|
||||
ctx := context.Background()
|
||||
host := &models.Host{Name: "h1", Hostname: "1.2.3.4", Port: 22, Username: "u"}
|
||||
_ = store.SaveHost(ctx, host)
|
||||
|
||||
if !store.IsDataEncrypted() {
|
||||
t.Error("IsDataEncrypted should be true after SaveHost with password")
|
||||
}
|
||||
}
|
||||
|
||||
// 3.15 Wrong password → error on load
|
||||
func TestEncryptionWrongPassword(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
store.SetPassword("correct-password")
|
||||
ctx := context.Background()
|
||||
|
||||
host := &models.Host{Name: "h1", Hostname: "1.2.3.4", Port: 22, Username: "u"}
|
||||
_ = store.SaveHost(ctx, host)
|
||||
|
||||
// Try loading with wrong password
|
||||
store2, _ := storage.NewJSONStorage(dir)
|
||||
store2.SetPassword("wrong-password")
|
||||
_, err := store2.ListHosts(ctx)
|
||||
if err == nil {
|
||||
t.Error("ListHosts with wrong password should return error")
|
||||
}
|
||||
}
|
||||
|
||||
// ============ MergeStrategy ============
|
||||
|
||||
// 3.16 MergeStrategyMerge
|
||||
func TestMergeStrategyMerge(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
// Add existing host
|
||||
existing := &models.Host{ID: "host-1", Name: "existing", Hostname: "1.1.1.1", Port: 22, Username: "u"}
|
||||
_ = store.SaveHost(ctx, existing)
|
||||
|
||||
// Import with merge — new host should be added, existing kept
|
||||
importData := &storage.ExportData{
|
||||
Hosts: []*models.Host{
|
||||
{ID: "host-2", Name: "imported", Hostname: "2.2.2.2", Port: 22, Username: "u"},
|
||||
},
|
||||
}
|
||||
err := store.ImportData(ctx, importData, storage.MergeStrategyMerge)
|
||||
if err != nil {
|
||||
t.Fatalf("ImportData with merge failed: %v", err)
|
||||
}
|
||||
|
||||
hosts, _ := store.ListHosts(ctx)
|
||||
if len(hosts) != 2 {
|
||||
t.Errorf("After merge, got %d hosts, want 2", len(hosts))
|
||||
}
|
||||
}
|
||||
|
||||
// 3.17 MergeStrategyReplace
|
||||
func TestMergeStrategyReplace(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
// Add existing host
|
||||
existing := &models.Host{ID: "host-1", Name: "existing", Hostname: "1.1.1.1", Port: 22, Username: "u"}
|
||||
_ = store.SaveHost(ctx, existing)
|
||||
|
||||
// Import with replace — existing should be overwritten
|
||||
importData := &storage.ExportData{
|
||||
Hosts: []*models.Host{
|
||||
{ID: "host-2", Name: "new", Hostname: "2.2.2.2", Port: 22, Username: "u"},
|
||||
},
|
||||
}
|
||||
err := store.ImportData(ctx, importData, storage.MergeStrategyReplace)
|
||||
if err != nil {
|
||||
t.Fatalf("ImportData with replace failed: %v", err)
|
||||
}
|
||||
|
||||
hosts, _ := store.ListHosts(ctx)
|
||||
if len(hosts) != 1 {
|
||||
t.Errorf("After replace, got %d hosts, want 1", len(hosts))
|
||||
}
|
||||
if hosts[0].ID != "host-2" {
|
||||
t.Errorf("After replace, host ID = %q, want %q", hosts[0].ID, "host-2")
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Edge Cases ============
|
||||
|
||||
// 3.18 SaveHost empty ID → generates UUID
|
||||
func TestSaveHostEmptyID(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
ctx := context.Background()
|
||||
|
||||
host := &models.Host{Name: "no-id", Hostname: "1.2.3.4", Port: 22, Username: "u"}
|
||||
err := store.SaveHost(ctx, host)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveHost failed: %v", err)
|
||||
}
|
||||
if host.ID == "" {
|
||||
t.Error("SaveHost should generate UUID for empty ID")
|
||||
}
|
||||
}
|
||||
|
||||
// GetPassword / IsEncrypted
|
||||
func TestPasswordMethods(t *testing.T) {
|
||||
dir := tempDir(t)
|
||||
store, _ := storage.NewJSONStorage(dir)
|
||||
|
||||
if store.IsEncrypted() {
|
||||
t.Error("IsEncrypted should be false initially")
|
||||
}
|
||||
if store.GetPassword() != "" {
|
||||
t.Error("GetPassword should be empty initially")
|
||||
}
|
||||
|
||||
store.SetPassword("test123")
|
||||
if !store.IsEncrypted() {
|
||||
t.Error("IsEncrypted should be true after SetPassword")
|
||||
}
|
||||
if store.GetPassword() != "test123" {
|
||||
t.Errorf("GetPassword = %q, want %q", store.GetPassword(), "test123")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package tui_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||
)
|
||||
|
||||
func TestErrorBannerShowHide(t *testing.T) {
|
||||
banner := tui.NewErrorBanner(tui.SevError)
|
||||
|
||||
// Initially not visible
|
||||
if banner.IsVisible() {
|
||||
t.Error("Banner should not be visible initially")
|
||||
}
|
||||
|
||||
// Show the banner
|
||||
banner.Show("Test Error", "Something went wrong", "Check logs", "Restart app")
|
||||
if !banner.IsVisible() {
|
||||
t.Error("Banner should be visible after Show()")
|
||||
}
|
||||
|
||||
// Verify content
|
||||
if banner.Title != "Test Error" {
|
||||
t.Errorf("Title = %q, want %q", banner.Title, "Test Error")
|
||||
}
|
||||
if banner.Detail != "Something went wrong" {
|
||||
t.Errorf("Detail = %q, want %q", banner.Detail, "Something went wrong")
|
||||
}
|
||||
if len(banner.Hints) != 2 {
|
||||
t.Errorf("Hints has %d items, want 2", len(banner.Hints))
|
||||
}
|
||||
|
||||
// Hide the banner
|
||||
banner.Hide()
|
||||
if banner.IsVisible() {
|
||||
t.Error("Banner should not be visible after Hide()")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorBannerAutoDismiss(t *testing.T) {
|
||||
banner := tui.NewErrorBanner(tui.SevWarning)
|
||||
banner.AutoDismiss = true
|
||||
banner.DismissAfter = 100 * time.Millisecond
|
||||
|
||||
banner.Show("Test Warning", "Something")
|
||||
if !banner.IsVisible() {
|
||||
t.Error("Banner should be visible after Show()")
|
||||
}
|
||||
|
||||
// Wait for auto-dismiss
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
banner.Update()
|
||||
|
||||
if banner.IsVisible() {
|
||||
t.Error("Banner should be auto-dismissed after delay")
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorBannerSeverity(t *testing.T) {
|
||||
tests := []struct {
|
||||
severity tui.ErrorSeverity
|
||||
name string
|
||||
}{
|
||||
{tui.SevError, "error"},
|
||||
{tui.SevWarning, "warning"},
|
||||
{tui.SevInfo, "info"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
banner := tui.NewErrorBanner(tt.severity)
|
||||
if banner.Severity != tt.severity {
|
||||
t.Errorf("NewErrorBanner(%v).Severity = %v, want %v", tt.name, banner.Severity, tt.severity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorBannerView(t *testing.T) {
|
||||
banner := tui.NewErrorBanner(tui.SevError)
|
||||
banner.Show("Error Title", "Error detail", "Hint 1", "Hint 2")
|
||||
|
||||
// Test that View returns non-empty string
|
||||
output := banner.View(80)
|
||||
if output == "" {
|
||||
t.Error("View() returned empty string")
|
||||
}
|
||||
|
||||
// Test that View returns empty string when not visible
|
||||
banner.Hide()
|
||||
output = banner.View(80)
|
||||
if output != "" {
|
||||
t.Error("View() should return empty string when not visible")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package tui_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||
)
|
||||
|
||||
// 5.1 WrapFooter short — single line
|
||||
func TestWrapFooterShort(t *testing.T) {
|
||||
result := tui.WrapFooter("short footer", 80)
|
||||
if result != "short footer" {
|
||||
t.Errorf("WrapFooter short = %q, want %q", result, "short footer")
|
||||
}
|
||||
}
|
||||
|
||||
// 5.2 WrapFooter long — multi-line
|
||||
func TestWrapFooterLong(t *testing.T) {
|
||||
// Footer longer than 30 chars should wrap
|
||||
footer := "key1 key2 key3 key4 key5 key6 key7 key8 key9 key10"
|
||||
result := tui.WrapFooter(footer, 30)
|
||||
if result == footer {
|
||||
t.Error("WrapFooter should wrap long footer")
|
||||
}
|
||||
}
|
||||
|
||||
// 5.3 WrapFooter empty
|
||||
func TestWrapFooterEmpty(t *testing.T) {
|
||||
result := tui.WrapFooter("", 80)
|
||||
if result != "" {
|
||||
t.Errorf("WrapFooter empty = %q, want %q", result, "")
|
||||
}
|
||||
}
|
||||
|
||||
// 5.4 ClampWidth over max
|
||||
func TestClampWidthOver(t *testing.T) {
|
||||
result := tui.ClampWidth(200, 80)
|
||||
if result > 74 { // 80 - 6 (boxOverhead)
|
||||
t.Errorf("ClampWidth(200, 80) = %d, should be <= 74", result)
|
||||
}
|
||||
}
|
||||
|
||||
// 5.5 ClampWidth under min
|
||||
func TestClampWidthUnder(t *testing.T) {
|
||||
result := tui.ClampWidth(5, 80)
|
||||
if result < 20 {
|
||||
t.Errorf("ClampWidth(5, 80) = %d, should be >= 20", result)
|
||||
}
|
||||
}
|
||||
|
||||
// 5.6 ClampWidth in range
|
||||
func TestClampWidthInRange(t *testing.T) {
|
||||
result := tui.ClampWidth(50, 80)
|
||||
if result != 50 {
|
||||
t.Errorf("ClampWidth(50, 80) = %d, want 50", result)
|
||||
}
|
||||
}
|
||||
|
||||
// 5.7 TruncateStr short
|
||||
func TestTruncateStrShort(t *testing.T) {
|
||||
result := tui.TruncateStr("hello", 20)
|
||||
if result != "hello" {
|
||||
t.Errorf("TruncateStr short = %q, want %q", result, "hello")
|
||||
}
|
||||
}
|
||||
|
||||
// 5.8 TruncateStr long
|
||||
func TestTruncateStrLong(t *testing.T) {
|
||||
result := tui.TruncateStr("this is a very long string that should be truncated", 10)
|
||||
if result == "this is a very long string that should be truncated" {
|
||||
t.Error("TruncateStr should truncate long string")
|
||||
}
|
||||
if len(result) > 12 { // 11 content + 1 ellipsis
|
||||
t.Errorf("TruncateStr result too long: %d chars", len(result))
|
||||
}
|
||||
}
|
||||
|
||||
// 5.9 TruncateStr empty
|
||||
func TestTruncateStrEmpty(t *testing.T) {
|
||||
result := tui.TruncateStr("", 20)
|
||||
if result != "" {
|
||||
t.Errorf("TruncateStr empty = %q, want %q", result, "")
|
||||
}
|
||||
}
|
||||
|
||||
// 5.10 TruncateStr unicode
|
||||
func TestTruncateStrUnicode(t *testing.T) {
|
||||
result := tui.TruncateStr("こんにちは世界", 5)
|
||||
if result == "こんにちは世界" {
|
||||
t.Error("TruncateStr should truncate unicode string")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package tui_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||
)
|
||||
|
||||
func TestGetTheme(t *testing.T) {
|
||||
// Test getting existing themes
|
||||
tests := []struct {
|
||||
name string
|
||||
expected string
|
||||
}{
|
||||
{"dark", "dark"},
|
||||
{"light", "light"},
|
||||
{"dracula", "dracula"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
theme := tui.GetTheme(tt.name)
|
||||
if theme.Name != tt.expected {
|
||||
t.Errorf("GetTheme(%q) = %q, want %q", tt.name, theme.Name, tt.expected)
|
||||
}
|
||||
}
|
||||
|
||||
// Test getting non-existing theme defaults to dark
|
||||
theme := tui.GetTheme("nonexistent")
|
||||
if theme.Name != "dark" {
|
||||
t.Errorf("GetTheme(nonexistent) = %q, want %q", theme.Name, "dark")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTheme(t *testing.T) {
|
||||
// Set theme to light
|
||||
tui.SetTheme("light")
|
||||
active := tui.GetActiveTheme()
|
||||
if active.Name != "light" {
|
||||
t.Errorf("After SetTheme(light), GetActiveTheme() = %q, want %q", active.Name, "light")
|
||||
}
|
||||
|
||||
// Set theme back to dark
|
||||
tui.SetTheme("dark")
|
||||
active = tui.GetActiveTheme()
|
||||
if active.Name != "dark" {
|
||||
t.Errorf("After SetTheme(dark), GetActiveTheme() = %q, want %q", active.Name, "dark")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetActiveTheme(t *testing.T) {
|
||||
// Default should be dark
|
||||
active := tui.GetActiveTheme()
|
||||
if active.Name != "dark" {
|
||||
t.Errorf("GetActiveTheme() = %q, want %q", active.Name, "dark")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThemeRegistry(t *testing.T) {
|
||||
// Test that all themes are registered
|
||||
expectedThemes := []string{"dark", "light", "dracula"}
|
||||
for _, name := range expectedThemes {
|
||||
if _, ok := tui.Themes[name]; !ok {
|
||||
t.Errorf("Theme %q not found in Themes map", name)
|
||||
}
|
||||
}
|
||||
|
||||
// Test theme count
|
||||
if len(tui.Themes) != 3 {
|
||||
t.Errorf("Themes map has %d entries, want 3", len(tui.Themes))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user