Compare commits
28 Commits
v1.0.0
..
9b27388455
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b27388455 | |||
| e5d32bd22e | |||
| 4af555c135 | |||
| f9b2337612 | |||
| 7f197b9e3a | |||
| c7568e0bf4 | |||
| 2442920616 | |||
| 5b456104e8 | |||
| daa20ac72b | |||
| 79f3917a66 | |||
| 53db03814e | |||
| c957a97cdb | |||
| 7b06793002 | |||
| b319f44c3e | |||
| 43858dda87 | |||
| 94ec00c303 | |||
| 3dc482e353 | |||
| 809ac1d2e8 | |||
| 98dfc1c79c | |||
| 5d9e38f8db | |||
| c5cc3bd711 | |||
| e8c451ed56 | |||
| e99a6ac347 | |||
| 9c1bbd4eac | |||
| 933ee48f3f | |||
| b3878de9af | |||
| 513492e6ee | |||
| 1869cff590 |
+1
-1
@@ -39,4 +39,4 @@ Thumbs.db
|
||||
*.local.json
|
||||
|
||||
# Build output
|
||||
dist/
|
||||
dist/hostkeeper
|
||||
|
||||
+18
-31
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -174,52 +175,47 @@ func runAddHost(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
func addHostInteractive(cfg *config.Config) error {
|
||||
reader := strings.NewReader("")
|
||||
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
|
||||
fmt.Print("Host Name (e.g., myserver): ")
|
||||
var name string
|
||||
fmt.Fscanln(reader)
|
||||
fmt.Scanln(&name)
|
||||
name := readLine("Host Name (e.g., myserver): ")
|
||||
if name == "" {
|
||||
return fmt.Errorf("host name is required")
|
||||
}
|
||||
|
||||
// Get hostname
|
||||
fmt.Print("Hostname or IP (e.g., 192.168.1.10): ")
|
||||
var hostname string
|
||||
fmt.Scanln(&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
|
||||
fmt.Printf("Port [%d]: ", defaultPort)
|
||||
var portInput string
|
||||
fmt.Scanln(&portInput)
|
||||
portInput := readLine(fmt.Sprintf("Port [%d]: ", defaultPort))
|
||||
port := defaultPort
|
||||
if portInput != "" {
|
||||
fmt.Sscanf(portInput, "%d", &port)
|
||||
}
|
||||
|
||||
// Get username
|
||||
fmt.Print("Username: ")
|
||||
var username string
|
||||
fmt.Scanln(&username)
|
||||
username := readLine("Username: ")
|
||||
if username == "" {
|
||||
return fmt.Errorf("username is required")
|
||||
}
|
||||
|
||||
// Get auth type
|
||||
fmt.Print("Auth Type (password/key/both) [password]: ")
|
||||
var authType string
|
||||
fmt.Scanln(&authType)
|
||||
authType := readLine("Auth Type (password/key/both) [password]: ")
|
||||
if authType == "" {
|
||||
authType = "password"
|
||||
}
|
||||
@@ -227,16 +223,13 @@ func addHostInteractive(cfg *config.Config) error {
|
||||
// Get password
|
||||
var password string
|
||||
if authType == "password" || authType == "both" {
|
||||
fmt.Print("Password: ")
|
||||
fmt.Scanln(&password)
|
||||
password = readLine("Password: ")
|
||||
}
|
||||
|
||||
// Get key path
|
||||
var keyContent string
|
||||
if authType == "key" || authType == "both" {
|
||||
fmt.Print("Path to private key (~/.ssh/id_rsa): ")
|
||||
var keyPath string
|
||||
fmt.Scanln(&keyPath)
|
||||
keyPath := readLine("Path to private key (~/.ssh/id_rsa): ")
|
||||
if keyPath != "" {
|
||||
data, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
@@ -247,14 +240,10 @@ func addHostInteractive(cfg *config.Config) error {
|
||||
}
|
||||
|
||||
// Get group
|
||||
fmt.Print("Group (optional): ")
|
||||
var group string
|
||||
fmt.Scanln(&group)
|
||||
group := readLine("Group (optional): ")
|
||||
|
||||
// Get tags
|
||||
fmt.Print("Tags (comma-separated, optional): ")
|
||||
var tagsInput string
|
||||
fmt.Scanln(&tagsInput)
|
||||
tagsInput := readLine("Tags (comma-separated, optional): ")
|
||||
var tags []string
|
||||
if tagsInput != "" {
|
||||
tags = strings.Split(tagsInput, ",")
|
||||
@@ -264,9 +253,7 @@ func addHostInteractive(cfg *config.Config) error {
|
||||
}
|
||||
|
||||
// Get notes
|
||||
fmt.Print("Notes (optional): ")
|
||||
var notes string
|
||||
fmt.Scanln(¬es)
|
||||
notes := readLine("Notes (optional): ")
|
||||
|
||||
// Create host
|
||||
host := &models.Host{
|
||||
|
||||
+33
-12
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -18,14 +19,14 @@ import (
|
||||
|
||||
var (
|
||||
connectTimeout int
|
||||
connectDirect bool
|
||||
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 native SSH client with stored credentials.
|
||||
Long: `Connect to a saved SSH host using stored credentials.
|
||||
|
||||
Examples:
|
||||
# Connect to a host by name
|
||||
@@ -34,15 +35,15 @@ Examples:
|
||||
# Connect with a specific timeout
|
||||
hostkeeper connect myserver --timeout 60
|
||||
|
||||
# Use Go SSH client (direct mode) instead of system SSH
|
||||
hostkeeper connect myserver --direct`,
|
||||
# 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(&connectDirect, "direct", false, "Use direct SSH instead of native client")
|
||||
connectCmd.Flags().BoolVar(&connectNative, "native", false, "Use native system SSH instead of Go SSH client")
|
||||
|
||||
rootCmd.AddCommand(connectCmd)
|
||||
}
|
||||
@@ -76,11 +77,11 @@ func runConnect(cmd *cobra.Command, args []string) error {
|
||||
fmt.Printf("Connecting to %s (%s@%s:%d)...\n", host.Name, host.Username, host.Hostname, host.Port)
|
||||
|
||||
// Choose connection method
|
||||
if connectDirect {
|
||||
return connectDirectSSH(host)
|
||||
if connectNative {
|
||||
return connectWithNativeSSH(host)
|
||||
}
|
||||
|
||||
return connectWithNativeSSH(host)
|
||||
return connectDirectSSH(host)
|
||||
}
|
||||
|
||||
// findHost finds a host by ID first, then by name
|
||||
@@ -103,8 +104,26 @@ func findHost(ctx context.Context, store storage.Storage, identifier string) (*m
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
return nil, fmt.Errorf("host '%s' not found. Use 'hostkeeper list' to see available hosts", identifier)
|
||||
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
|
||||
@@ -137,9 +156,11 @@ func connectDirectSSH(host *models.Host) error {
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
fmt.Printf("Connected to %s\n", host.Name)
|
||||
fmt.Println("Interactive shell not yet implemented in direct mode")
|
||||
fmt.Println("Use --direct=false (default) for native SSH experience")
|
||||
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
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestConnectCommandExists(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestConnectCommandFlags(t *testing.T) {
|
||||
expectedFlags := []string{"timeout", "direct"}
|
||||
expectedFlags := []string{"timeout", "native"}
|
||||
for _, flagName := range expectedFlags {
|
||||
if connectCmd.Flags().Lookup(flagName) == nil {
|
||||
t.Errorf("flag '%s' should be defined", flagName)
|
||||
|
||||
+13
-5
@@ -150,15 +150,23 @@ func sortHosts(hosts []*models.Host, sortBy string) {
|
||||
}
|
||||
}
|
||||
|
||||
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, "NAME\tHOSTNAME\tPORT\tUSER\tGROUP\tAUTH\tTAGS")
|
||||
fmt.Fprintln(w, "────\t────────\t────\t────\t─────\t────\t────")
|
||||
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%d\t%s\t%s\t%s\t%s\n",
|
||||
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,
|
||||
@@ -178,8 +186,8 @@ func outputJSON(hosts []*models.Host) error {
|
||||
if i > 0 {
|
||||
fmt.Print(",")
|
||||
}
|
||||
fmt.Printf(`{"id":"%s","name":"%s","hostname":"%s","port":%d,"username":"%s","group":"%s","auth_type":"%s"}`,
|
||||
h.ID, h.Name, h.Hostname, h.Port, h.Username, h.Group, h.Auth.Type)
|
||||
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
|
||||
|
||||
@@ -11,6 +11,13 @@ var (
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
@@ -46,6 +46,7 @@ func runTUI(cmd *cobra.Command, args []string) error {
|
||||
}
|
||||
|
||||
model := tui.New()
|
||||
model.SetDataDir(cfg.GetDataDir())
|
||||
model.LoadHosts(hosts)
|
||||
|
||||
p := tea.NewProgram(model)
|
||||
|
||||
@@ -12,8 +12,11 @@ Hostkeeper is a cross-platform SSH/SFTP management tool written in Go, inspired
|
||||
|
||||
### Key Design Decisions
|
||||
|
||||
- **Architecture:** Monolithic CLI with embedded TUI (Progressive enhancement approach)
|
||||
- **Interface:** Hybrid - CLI commands + TUI for management tasks
|
||||
- **Architecture:** TUI-first with native SSH delegation — interactive SSH via `tea.ExecProcess` (zero lag, native terminal), SFTP/browsing via in-process Go
|
||||
- **Interface:** TUI for management + native fullscreen SSH when connecting; CLI for quick tasks and automation
|
||||
- **SSH Strategy:** Delegate to native `ssh` binary via `tea.ExecProcess` (same approach as tamagosh) — eliminates lag from Go buffering, enables full terminal capability
|
||||
- **SFTP Strategy:** Use `github.com/pkg/sftp` via Go (in-process) — file operations don't need real-time echo, so Go integration works well
|
||||
- **Color Theme:** Gruvbox Material Dark Hard palette (`#d4be98`, `#a9b665`, `#e78a4e`, `#504945`) — soft, easy on eyes
|
||||
- **Storage:** JSON/YAML files (Phase 1), encrypted storage (Phase 2)
|
||||
- **Platform:** Cross-platform (Linux, macOS, Windows, Termux/Android)
|
||||
- **Sync:** Manual export/import (Phase 1), cloud sync (future)
|
||||
@@ -104,11 +107,12 @@ Hostkeeper is a cross-platform SSH/SFTP management tool written in Go, inspired
|
||||
|
||||
### Key Design Principles
|
||||
|
||||
1. **Single Source of Truth** - All data stored in JSON/YAML files
|
||||
2. **Command-First** - TUI is wrapper for core commands
|
||||
1. **Single Source of Truth** - All data stored in JSON files
|
||||
2. **TUI-First** - TUI is the primary interface; CLI commands serve quick tasks and scripting
|
||||
3. **Layered Architecture** - UI → Business Logic → Storage
|
||||
4. **Cross-Platform** - Pure Go, no OS-specific dependencies
|
||||
5. **Encrypt-Ready** - Structure prepared for encryption upgrade
|
||||
6. **Orange Theme** - Distinct orange color palette to visually separate Hostkeeper from the native terminal, signaling the user is inside the application environment
|
||||
|
||||
---
|
||||
|
||||
@@ -143,22 +147,53 @@ hostkeeper completion # Shell completion setup
|
||||
|
||||
### 2. TUI Layer (Interactive Interface)
|
||||
|
||||
**Framework:** Bubble Tea (recommended for modern, maintainable TUI)
|
||||
**Framework:** Bubble Tea (event-driven TUI) + Lipgloss (styling)
|
||||
|
||||
**Main Screens:**
|
||||
- **Host List:** Grid/List view with status indicators
|
||||
- **Connection Manager:** Active connections, quick actions
|
||||
- **SFTP Browser:** Dual-pane file browser (Phase 2)
|
||||
- **Key Manager:** SSH keys list, import/export, generate
|
||||
- **Snippet Manager:** Command snippets with variables
|
||||
- **Settings:** Config management, preferences
|
||||
**Theme:** Gruvbox Material Dark Hard palette (`#d4be98`, `#a9b665`, `#e78a4e`, `#504945`, `#ea6962`) — soft, warm, easy on eyes over long sessions
|
||||
|
||||
**TUI Features:**
|
||||
- Event-driven architecture
|
||||
- Responsive layout
|
||||
- Keyboard navigation
|
||||
- Mouse support (optional)
|
||||
- Quick actions (`/` search, `n` new, `Ctrl+S` SFTP, etc.)
|
||||
#### Tab System Architecture
|
||||
|
||||
```
|
||||
┌─ Hosts ──── SFTP:server1 ── Keys ── Snippets ────────────────┐
|
||||
│ │
|
||||
│ [content of active tab — host list, SFTP browser, etc.] │
|
||||
│ │
|
||||
├───────────────────────────────────────────────────────────────┤
|
||||
│ Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Enter:SSH /:search │
|
||||
└───────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Tab Types:**
|
||||
- **HostsTab** — Host list with search, filter, sort, keyboard navigation
|
||||
- **SFTPTab** — Dual-pane (local ↔ remote) file browser with upload/download/delete/rename
|
||||
- **KeysTab** — SSH key management (list, add, edit, delete)
|
||||
- **SnippetsTab** — Command snippets management
|
||||
|
||||
**SSH Connect (NOT a tab — fullscreen native SSH delegation):**
|
||||
- User selects host → presses Enter
|
||||
- TUI exits alt-screen, runs `tea.ExecProcess` → native `ssh` binary takes over terminal directly
|
||||
- Zero lag: native SSH handles PTY, echo, resize, signals — no Go buffering
|
||||
- On SSH exit → TUI resumes, returns to host list
|
||||
- Password auth via `sshpass -e` (SSHPASS env var)
|
||||
- Key auth via `ssh -i <keypath>` (passphrase via SSH_ASKPASS if needed)
|
||||
- User can install `tmux` on server for session persistence (optional)
|
||||
|
||||
**Rationale:** In-process SSH (golang.org/x/crypto/ssh with goroutine I/O) introduces ~6 layers of buffering between keystroke and echo. Delegating to native `ssh` via `tea.ExecProcess` eliminates all Go overhead from the real-time I/O path, giving a native-terminal experience.
|
||||
|
||||
**Keyboard Navigation:**
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| `Ctrl+Tab` / `Shift+Tab` | Cycle tabs forward/backward |
|
||||
| `Ctrl+N` | Add new host |
|
||||
| `Ctrl+E` | Edit selected host |
|
||||
| `Ctrl+F` | Open SFTP browser for selected host |
|
||||
| `Ctrl+K` | SSH Keys management |
|
||||
| `Ctrl+P` | Snippets management |
|
||||
| `Enter` | SSH into selected host (fullscreen native SSH) |
|
||||
| `↑` / `↓` | Navigate lists |
|
||||
| `D` / `Delete` | Delete selected item |
|
||||
| `Ctrl+Q` | Close current tab |
|
||||
| `q` | Quit Hostkeeper |
|
||||
|
||||
---
|
||||
|
||||
@@ -661,26 +696,24 @@ Continue anyway? [y/N]
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Enhanced Features (4-6 weeks)
|
||||
### Phase 2: TUI Overhaul & Enhanced Features (4-6 weeks)
|
||||
|
||||
**TUI Enhancement:**
|
||||
- Rich TUI interface for all operations
|
||||
- Dual-pane SFTP browser
|
||||
- Key management UI
|
||||
- Snippet manager
|
||||
- Connection snippets execution
|
||||
**Priority 1 — TUI Overhaul (Completed):**
|
||||
- Tab system with Gruvbox Material theme (TabManager, tab bar, keyboard shortcuts)
|
||||
- Native SSH delegation via `tea.ExecProcess` (zero-lag fullscreen SSH, inspired by tamagosh)
|
||||
- TUI forms for add/edit hosts
|
||||
- Dual-pane SFTP browser (local ↔ remote) with upload/download/delete/rename
|
||||
- Key & snippet management in TUI
|
||||
|
||||
**Security Enhancement:**
|
||||
- AES-256 encryption for storage
|
||||
- Master password protection
|
||||
- Secure credential export/import
|
||||
- Enhanced error messages
|
||||
**Priority 2 — Security Enhancement:**
|
||||
- AES-256-GCM encryption for secrets file (inspired by tamagosh)
|
||||
- Key passphrase support via SSH_ASKPASS
|
||||
- Known_hosts verification for SFTP connections
|
||||
|
||||
**User Experience:**
|
||||
- Shell completion
|
||||
**Priority 3 — UX Polish:**
|
||||
- Configuration profiles
|
||||
- Theme support
|
||||
- Keyboard shortcuts
|
||||
- Theme customization
|
||||
- Enhanced error messages in TUI
|
||||
|
||||
---
|
||||
|
||||
@@ -694,8 +727,6 @@ Continue anyway? [y/N]
|
||||
|
||||
**Advanced Terminal:**
|
||||
- Custom terminal emulator
|
||||
- Multiple session management
|
||||
- Tab support
|
||||
- Advanced text selection
|
||||
|
||||
**Integration:**
|
||||
@@ -762,10 +793,10 @@ Continue anyway? [y/N]
|
||||
### Phase 2 Success Metrics
|
||||
|
||||
- ✅ Rich TUI interface for all operations
|
||||
- ✅ Encrypted credential storage
|
||||
- ✅ Dual-pane SFTP browser
|
||||
- ✅ Zero-lag SSH via native binary delegation
|
||||
- ✅ Dual-pane SFTP browser (local ↔ remote)
|
||||
- ✅ Shell completion and documentation
|
||||
- ✅ Enhanced user experience
|
||||
- ✅ Enhanced user experience with Gruvbox palette
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
**Tech Stack:** Go 1.21+, Cobra (CLI framework), Bubble Tea (TUI), golang.org/x/crypto/ssh, Viper (config management), JSON/YAML storage
|
||||
|
||||
**Current Status**: Planning Complete → Ready for Implementation (Check PROJECT_STATE.md for latest updates)
|
||||
**Current Status**: Phase 2 Complete — SSH rewritten with native `ssh` delegation, dual-pane SFTP browser, Gruvbox theme. Next: security encryption + VT emulator multi-session.
|
||||
|
||||
---
|
||||
|
||||
@@ -4662,11 +4662,263 @@ git tag -a v1.0.0 -m "Initial MVP release with core SSH management features"
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: TUI Overhaul & Enhanced Features
|
||||
|
||||
### Task 15: TUI Tab Framework & Orange Theme
|
||||
|
||||
**Files:**
|
||||
- Create: `pkg/tui/tabs.go` — TabManager, tab bar renderer
|
||||
- Create: `pkg/tui/styles.go` — All lipgloss styles (orange palette)
|
||||
- Modify: `pkg/tui/tui.go` — Integrate TabManager, replace single-screen with tab routing
|
||||
|
||||
**Step 1: Create styles.go**
|
||||
|
||||
```go
|
||||
// pkg/tui/styles.go
|
||||
package tui
|
||||
|
||||
import "github.com/charmbracelet/lipgloss"
|
||||
|
||||
// Orange theme palette
|
||||
var (
|
||||
OrangePrimary = lipgloss.Color("#FF6B00")
|
||||
OrangeSecondary = lipgloss.Color("#FF9F43")
|
||||
OrangeLight = lipgloss.Color("#FFB800")
|
||||
DarkBg = lipgloss.Color("#1A1A1A")
|
||||
LightBg = lipgloss.Color("#2D2D2D")
|
||||
TextPrimary = lipgloss.Color("#FFFFFF")
|
||||
TextSecondary = lipgloss.Color("#AAAAAA")
|
||||
)
|
||||
|
||||
// Component styles
|
||||
var (
|
||||
TabActiveStyle = lipgloss.NewStyle().Background(OrangePrimary).Foreground(DarkBg).Bold(true).Padding(0, 2)
|
||||
TabInactiveStyle = lipgloss.NewStyle().Background(LightBg).Foreground(TextSecondary).Padding(0, 2)
|
||||
TabBarStyle = lipgloss.NewStyle().Background(DarkBg)
|
||||
StatusBarStyle = lipgloss.NewStyle().Background(OrangePrimary).Foreground(DarkBg).Padding(0, 1)
|
||||
TitleStyle = lipgloss.NewStyle().Foreground(OrangeSecondary).Bold(true)
|
||||
HighlightStyle = lipgloss.NewStyle().Foreground(OrangePrimary).Bold(true)
|
||||
SelectedStyle = lipgloss.NewStyle().Foreground(DarkBg).Background(OrangePrimary).Padding(0, 1)
|
||||
)
|
||||
```
|
||||
|
||||
**Step 2: Create tabs.go — TabManager**
|
||||
|
||||
Core structure:
|
||||
- `Tab` interface with `Init()`, `Update(msg)`, `View()`, `Name() string`
|
||||
- `TabManager` holds slice of tabs + active index
|
||||
- Tab bar rendered via `TabActiveStyle` / `TabInactiveStyle`
|
||||
- Keybind routing: tab-level keys (Ctrl+Tab, Ctrl+Q, Ctrl+N) vs tab-content keys
|
||||
|
||||
```go
|
||||
type Tab interface {
|
||||
Init() tea.Cmd
|
||||
Update(tea.Msg) (Tab, tea.Cmd)
|
||||
View() string
|
||||
Name() string
|
||||
}
|
||||
|
||||
type TabManager struct {
|
||||
tabs []Tab
|
||||
active int
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3: Modify tui.go**
|
||||
|
||||
Replace `CurrentScreen Screen` with `*TabManager`. Init creates default `HostsTab`. Update delegates to `TabManager.Update()`. View renders tab bar + active tab view + status bar.
|
||||
|
||||
**Step 4: Verify**
|
||||
|
||||
```bash
|
||||
make build
|
||||
./bin/hostkeeper tui
|
||||
```
|
||||
|
||||
Expected: Tab bar visible at top with "Hosts" tab, orange theme, status bar at bottom. Keyboard navigation works (Ctrl+Tab cycles tabs if multiple exist).
|
||||
|
||||
---
|
||||
|
||||
### Task 16: SSH Session Tab (Multi-Session)
|
||||
|
||||
**Files:**
|
||||
- Create: `pkg/tui/session.go` — SessionTab with live SSH terminal
|
||||
|
||||
**Architecture:**
|
||||
```
|
||||
┌─ Hosts ── Server Nico ── Web Prod ────────────────┐
|
||||
│ │
|
||||
│ $ htop │
|
||||
│ $ cd /var/log │
|
||||
│ $ tail -f syslog │
|
||||
│ │
|
||||
│ [live SSH session output] │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ Connected to Server Nico — Ctrl+Q to disconnect │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**SessionTab struct:**
|
||||
```go
|
||||
type SessionTab struct {
|
||||
host *models.Host
|
||||
client *ssh.Client // Go SSH client
|
||||
pty *ssh.Session
|
||||
width int
|
||||
height int
|
||||
input chan string // keyboard input → SSH stdin
|
||||
output chan string // SSH stdout → TUI render
|
||||
done chan struct{}
|
||||
}
|
||||
```
|
||||
|
||||
**Key flows:**
|
||||
1. User selects host in HostsTab → Enter → open SessionTab
|
||||
2. SessionTab connects via Go SSH client (auto-auth with stored password)
|
||||
3. Start PTY → 2 goroutines: stdin pump, stdout pump
|
||||
4. Keyboard input in TUI → `input` channel → SSH stdin
|
||||
5. SSH stdout → `output` channel → TUI render (via tea.Batch)
|
||||
6. Window resize → `msg tea.WindowSizeMsg` → SSH WindowChange
|
||||
7. Ctrl+Q → close session → remove tab → back to HostsTab
|
||||
8. Multiple sessions = multiple tabs, each with its own goroutines
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
make build
|
||||
./bin/hostkeeper tui
|
||||
# Select a host → Enter → SSH session tab opens
|
||||
# Ctrl+Tab to switch between session and host list
|
||||
# Ctrl+Q to close session
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 17: TUI Host Forms (Add/Edit)
|
||||
|
||||
**Files:**
|
||||
- Create: `pkg/tui/host_form.go`
|
||||
|
||||
**Form fields:**
|
||||
- Name (text input)
|
||||
- Hostname/IP (text input)
|
||||
- Port (number input, default 22)
|
||||
- Username (text input)
|
||||
- Auth Type (select: password/key/both)
|
||||
- Password (text input, masked)
|
||||
- Key (file selector or paste)
|
||||
- Group (text input)
|
||||
- Tags (text input, comma-separated)
|
||||
- Notes (textarea)
|
||||
|
||||
**Implementation:**
|
||||
- Use Bubble Tea `textinput` model for each field
|
||||
- Tab/Shift+Tab to cycle fields
|
||||
- Enter on last field → submit → save via storage
|
||||
- Edit mode: pre-populate fields from existing host
|
||||
- Cancel (Escape) → back to HostsTab without saving
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
make build
|
||||
./bin/hostkeeper tui
|
||||
# HostsTab → press 'a' or Ctrl+N → form opens
|
||||
# Fill fields → Enter → host saved → back to HostsTab
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 18: TUI SFTP Browser
|
||||
|
||||
**Files:**
|
||||
- Create: `pkg/tui/sftp_browser.go`
|
||||
|
||||
**Layout:**
|
||||
```
|
||||
┌─ Hosts ── Server Nico ── SFTP ────────────────────┐
|
||||
│ /var/www/ │
|
||||
│ ──────────────────────────────────────────────── │
|
||||
│ 📁 . <DIR> │
|
||||
│ 📁 .. <DIR> │
|
||||
│ 📁 html <DIR> 2026-01-15 │
|
||||
│ 📄 index.html 4.2 KB 2026-01-15 │
|
||||
│ 📄 config.php 1.1 KB 2026-01-14 │
|
||||
│ 📁 assets <DIR> 2026-01-10 │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ ↑↓:nav Enter:open u:upload d:download q:close │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Implementation:**
|
||||
- Reuse SSH connection from SessionTab (or create new one)
|
||||
- `golang.org/x/crypto/ssh` + `github.com/pkg/sftp` for SFTP operations
|
||||
- File list sorted: dirs first, then files alphabetically
|
||||
- Upload: local file picker (current directory) → remote path
|
||||
- Download: selected file → local directory
|
||||
- Navigation: Enter opens directory, Backspace goes up
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
make build
|
||||
./bin/hostkeeper tui
|
||||
# SFTP tab → browse files → upload/download
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 19: TUI Key & Snippet Management
|
||||
|
||||
**Files:**
|
||||
- Create: `pkg/tui/key_list.go`
|
||||
- Create: `pkg/tui/snippet_list.go`
|
||||
|
||||
**Key List Tab:**
|
||||
- List all saved SSH keys with name, type, fingerprint
|
||||
- Select key → view details (public key, comment)
|
||||
- Actions: generate new key, import from file, delete
|
||||
- Generate: select type (RSA 4096, ED25519, ECDSA), optional passphrase
|
||||
|
||||
**Snippet List Tab:**
|
||||
- List saved command snippets
|
||||
- Select → preview command
|
||||
- Execute snippet on connected host
|
||||
- Create/edit snippets with name, command, description
|
||||
- Variable substitution: `{{hostname}}`, `{{user}}`, `{{port}}`
|
||||
|
||||
**Verify:**
|
||||
```bash
|
||||
make build
|
||||
./bin/hostkeeper tui
|
||||
# Keys tab → list/generate/import
|
||||
# Snippets tab → list/create/execute
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Advanced Features (Future)
|
||||
|
||||
**Cloud Sync:**
|
||||
- User account system
|
||||
- Encrypted cloud storage
|
||||
- Real-time multi-device sync
|
||||
- Conflict resolution
|
||||
|
||||
**Advanced Terminal:**
|
||||
- Custom terminal emulator
|
||||
- Advanced text selection
|
||||
|
||||
**Integration:**
|
||||
- Web UI (optional)
|
||||
- API access
|
||||
- Plugin system
|
||||
- Third-party integrations
|
||||
|
||||
---
|
||||
|
||||
## 📋 Summary
|
||||
|
||||
This implementation plan provides a comprehensive roadmap for building the Hostkeeper MVP with:
|
||||
|
||||
### ✅ Completed Components
|
||||
### ✅ Completed Components (MVP)
|
||||
|
||||
1. **Project Foundation** - Go modules, dependencies, build system
|
||||
2. **Core Data Models** - Host, Key, Snippet, Config models
|
||||
@@ -4681,25 +4933,29 @@ This implementation plan provides a comprehensive roadmap for building the Hostk
|
||||
11. **Build System** - Cross-platform compilation
|
||||
12. **Documentation** - Installation and usage guides
|
||||
|
||||
### 🎯 MVP Success Criteria
|
||||
### 📋 Phase 2 Completed (TUI Overhaul)
|
||||
|
||||
- ✅ Can establish SSH connections to remote servers
|
||||
1. **Task 15** — Tab Framework & Gruvbox Theme
|
||||
2. **Task 16** — SSH Session Rewrite (native `ssh` via `tea.ExecProcess`, zero-lag)
|
||||
3. **Task 17** — TUI Host Forms (add/edit)
|
||||
4. **Task 18** — Dual-pane SFTP Browser (local ↔ remote)
|
||||
5. **Task 19** — TUI Key & Snippet Management
|
||||
|
||||
### 🎯 Success Criteria
|
||||
|
||||
- ✅ Native `ssh` binary delegation via `tea.ExecProcess` — zero lag, full terminal capability
|
||||
- ✅ Dual-pane SFTP browser (inspired by tamagosh/Midnight Commander)
|
||||
- ✅ Can manage multiple hosts with different auth methods
|
||||
- ✅ Can perform SFTP operations (native client)
|
||||
- ✅ Can export/import credentials across devices
|
||||
- ✅ Works on Linux, macOS, Windows, and Termux
|
||||
- ✅ Secure credential storage with proper permissions
|
||||
- ✅ User-friendly error messages and help text
|
||||
- ✅ Gruvbox Material Dark Hard palette for comfortable extended use
|
||||
|
||||
### 🚀 Ready for Next Phase
|
||||
### 🚀 Phase 3 — Future
|
||||
|
||||
After completing these tasks, the project will be ready for:
|
||||
|
||||
1. **Phase 2 Development** - Enhanced features like SFTP TUI, encryption, key management
|
||||
2. **User Testing** - Real-world usage and feedback
|
||||
3. **Documentation** - Advanced guides and tutorials
|
||||
4. **Community Building** - Open source contribution guidelines
|
||||
|
||||
**Estimated Development Time**: 3-4 weeks for experienced Go developer
|
||||
|
||||
**Next Steps**: Execute the implementation plan using the executing-plans skill!
|
||||
1. **AES-256-GCM encrypted secrets** (inspired by tamagosh)
|
||||
2. **Known_hosts verification** for SFTP
|
||||
3. **In-app SSH key generation**
|
||||
4. **Multi-session without lag** — PTY multiplexer + VT terminal emulator
|
||||
5. **Cloud sync, custom terminal emulator, web interface**
|
||||
@@ -3,11 +3,21 @@ 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/bubbles v1.0.0 // indirect
|
||||
github.com/charmbracelet/bubbletea v1.3.10 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.1 // indirect
|
||||
github.com/charmbracelet/lipgloss v1.1.0 // 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
|
||||
@@ -17,8 +27,8 @@ require (
|
||||
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/google/uuid v1.6.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
|
||||
@@ -32,13 +42,10 @@ require (
|
||||
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/cobra v1.10.2 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/spf13/viper v1.21.0 // 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/crypto v0.53.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
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=
|
||||
@@ -21,16 +23,29 @@ github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEX
|
||||
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=
|
||||
@@ -47,8 +62,14 @@ 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=
|
||||
@@ -65,18 +86,71 @@ 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=
|
||||
|
||||
@@ -4,8 +4,13 @@ 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"
|
||||
@@ -101,6 +106,83 @@ func (c *Client) Execute(_ context.Context, cmd string) (string, error) {
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"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
|
||||
}
|
||||
fallthrough
|
||||
|
||||
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{
|
||||
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(),
|
||||
}
|
||||
}
|
||||
|
||||
t.saved = true
|
||||
return t, saveHostCmd(host, t.dataDir)
|
||||
}
|
||||
|
||||
func (t *HostFormTab) View() string {
|
||||
contentW := t.width - 12
|
||||
if contentW < 50 {
|
||||
contentW = 50
|
||||
}
|
||||
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")
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
SubtitleStyle.Render("Ctrl+Tab:switch Ctrl+Q:close Tab:next Enter:next Ctrl+S:save Esc:cancel")))
|
||||
|
||||
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() {}
|
||||
@@ -1,84 +0,0 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
)
|
||||
|
||||
var (
|
||||
HostNameStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("226")).Bold(true)
|
||||
HostDetailStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
|
||||
SelectedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212")).Background(lipgloss.Color("235")).Padding(0, 1)
|
||||
TagStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("86"))
|
||||
)
|
||||
|
||||
// renderHostList renders the host list screen
|
||||
func renderHostList(m *Model) string {
|
||||
var b strings.Builder
|
||||
|
||||
b.WriteString(TitleStyle.Render("HOSTKEEPER - SSH Manager"))
|
||||
b.WriteString("\n\n")
|
||||
|
||||
if len(m.Hosts) == 0 {
|
||||
b.WriteString(SubtitleStyle.Render("No hosts found. Add your first host with: hostkeeper add"))
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString(InfoStyle.Render("Press 'q' to quit"))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
for i, host := range m.Hosts {
|
||||
if i == m.SelectedIndex {
|
||||
b.WriteString(renderSelectedHost(host))
|
||||
} else {
|
||||
b.WriteString(renderHost(host))
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
b.WriteString("\n")
|
||||
b.WriteString(SubtitleStyle.Render("\u2191\u2193: Navigate | Enter: Connect | q: Quit"))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// renderHost renders a single host
|
||||
func renderHost(host *models.Host) string {
|
||||
var b strings.Builder
|
||||
|
||||
b.WriteString(HostNameStyle.Render(host.Name))
|
||||
b.WriteString("\n")
|
||||
|
||||
details := fmt.Sprintf(" %s@%s:%d", host.Username, host.Hostname, host.Port)
|
||||
b.WriteString(HostDetailStyle.Render(details))
|
||||
|
||||
if len(host.Tags) > 0 {
|
||||
tags := formatTagsForTUI(host.Tags)
|
||||
b.WriteString(" " + TagStyle.Render(tags))
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// renderSelectedHost renders the selected host with highlight
|
||||
func renderSelectedHost(host *models.Host) string {
|
||||
hostText := renderHost(host)
|
||||
return SelectedStyle.Render(hostText)
|
||||
}
|
||||
|
||||
// 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,262 @@
|
||||
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 — exactly like tamagosh
|
||||
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()
|
||||
}
|
||||
|
||||
// Build rows (plain + styled)
|
||||
type styledRow struct {
|
||||
text string
|
||||
plain string
|
||||
}
|
||||
var rows []styledRow
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
for i := start; i < start+maxHosts; i++ {
|
||||
host := t.hosts[i]
|
||||
|
||||
// tamagosh format: " %-12s %-18s :%d"
|
||||
raw := fmt.Sprintf(" %-12s %-18s :%d", host.Name, host.Hostname, host.Port)
|
||||
|
||||
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
|
||||
var footer styledRow
|
||||
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Enter:SSH Ctrl+N:add Ctrl+F:SFTP Ctrl+K:keys Ctrl+P:snippets q:quit"
|
||||
footer = styledRow{text: SubtitleStyle.Render(footerText), plain: footerText}
|
||||
rows = append(rows, footer) // for widest measurement
|
||||
|
||||
// Title
|
||||
title := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render("Connection List")
|
||||
titlePlain := "Connection List"
|
||||
|
||||
// tamagosh: widest content line drives the box's natural width
|
||||
widestRow := 0
|
||||
for _, r := range rows {
|
||||
if w := lipgloss.Width(r.plain); w > widestRow {
|
||||
widestRow = w
|
||||
}
|
||||
}
|
||||
contentW := widestRow
|
||||
if w := lipgloss.Width(footer.plain); w > contentW {
|
||||
contentW = w
|
||||
}
|
||||
if w := lipgloss.Width(titlePlain); w > contentW {
|
||||
contentW = w
|
||||
}
|
||||
const sidePad = 6
|
||||
targetW := contentW + sidePad*2
|
||||
|
||||
var content strings.Builder
|
||||
|
||||
// Centered title
|
||||
content.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, title))
|
||||
content.WriteString("\n\n")
|
||||
|
||||
// Center each row independently within the box
|
||||
for _, r := range rows[:len(rows)-1] { // exclude footer, added below
|
||||
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, r.text)
|
||||
content.WriteString(line)
|
||||
content.WriteString("\n")
|
||||
}
|
||||
content.WriteString("\n")
|
||||
|
||||
// Centered footer
|
||||
content.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, footer.text))
|
||||
|
||||
// Wrap in a rounded border box
|
||||
box := BorderStyle.Render(content.String())
|
||||
|
||||
// Center the whole box horizontally
|
||||
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,242 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"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{
|
||||
Name: name,
|
||||
Type: t.inputs[keyFieldType].Value(),
|
||||
PrivateKey: privateKey,
|
||||
Passphrase: t.inputs[keyFieldPassphrase].Value(),
|
||||
}
|
||||
}
|
||||
|
||||
t.saved = true
|
||||
return t, saveKeyCmd(key, t.dataDir)
|
||||
}
|
||||
|
||||
func (t *KeyFormTab) View() string {
|
||||
contentW := t.width - 12
|
||||
if contentW < 50 {
|
||||
contentW = 50
|
||||
}
|
||||
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")
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
SubtitleStyle.Render("Ctrl+Tab:switch Ctrl+Q:close Tab:next Enter:next Ctrl+S:save Esc:cancel")))
|
||||
|
||||
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,236 @@
|
||||
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
|
||||
}
|
||||
var rows []styledRow
|
||||
|
||||
title := "SSH Key Pairs"
|
||||
titlePlain := title
|
||||
|
||||
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})
|
||||
}
|
||||
}
|
||||
|
||||
footerPlain := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Ctrl+N:add Ctrl+E:edit D:delete Esc:back"
|
||||
footer := styledRow{text: SubtitleStyle.Render(footerPlain), plain: footerPlain}
|
||||
|
||||
widestRow := lipgloss.Width(titlePlain)
|
||||
for _, r := range rows {
|
||||
if w := lipgloss.Width(r.plain); w > widestRow {
|
||||
widestRow = w
|
||||
}
|
||||
}
|
||||
if w := lipgloss.Width(footer.plain); w > widestRow {
|
||||
widestRow = w
|
||||
}
|
||||
|
||||
const sidePad = 6
|
||||
targetW := widestRow + sidePad*2
|
||||
|
||||
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")
|
||||
|
||||
// Render rows, excluding the footer (last element)
|
||||
for _, r := range rows[:len(rows)-1] {
|
||||
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, r.text)
|
||||
inner.WriteString(line)
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
inner.WriteString("\n")
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, footer.text))
|
||||
|
||||
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() {}
|
||||
|
||||
// keyListLoadedMsg carries the loaded key list
|
||||
type keyListLoadedMsg struct {
|
||||
keys []*models.KeyPair
|
||||
err error
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
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}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,696 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/pkg/sftp"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
sshclient "git.tukangketik.id/swanadiva/hostkeeper/pkg/ssh"
|
||||
)
|
||||
|
||||
type paneType int
|
||||
|
||||
const (
|
||||
paneLocal paneType = iota
|
||||
paneRemote
|
||||
)
|
||||
|
||||
// sftpPane holds state for one side of the dual-pane browser
|
||||
type sftpPane struct {
|
||||
cwd string
|
||||
entries []os.FileInfo
|
||||
selIdx int
|
||||
scroll int
|
||||
|
||||
filterMode bool
|
||||
filter string
|
||||
|
||||
// Remote only
|
||||
sftpClient *sftp.Client
|
||||
|
||||
// Local only
|
||||
localRoot string
|
||||
}
|
||||
|
||||
// SFTPBrowserTab provides a dual-pane (local ↔ remote) SFTP file browser
|
||||
type SFTPBrowserTab struct {
|
||||
host *models.Host
|
||||
dataDir string
|
||||
|
||||
sshClient *sshclient.Client
|
||||
sftp *sftp.Client
|
||||
|
||||
left sftpPane
|
||||
right sftpPane
|
||||
active paneType
|
||||
connected bool
|
||||
err error
|
||||
width int
|
||||
height int
|
||||
|
||||
filterInput textinput.Model
|
||||
|
||||
transferring bool
|
||||
transferMsg string
|
||||
|
||||
mu sync.Mutex
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
func NewSFTPBrowserTab(host *models.Host, dataDir string) *SFTPBrowserTab {
|
||||
fi := textinput.New()
|
||||
fi.Placeholder = "Filter..."
|
||||
|
||||
home, _ := os.UserHomeDir()
|
||||
|
||||
return &SFTPBrowserTab{
|
||||
host: host,
|
||||
dataDir: dataDir,
|
||||
active: paneRemote,
|
||||
left: sftpPane{
|
||||
cwd: home,
|
||||
localRoot: home,
|
||||
},
|
||||
right: sftpPane{
|
||||
cwd: "/",
|
||||
},
|
||||
filterInput: fi,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) Name() string { return "SFTP: " + t.host.Name }
|
||||
|
||||
func (t *SFTPBrowserTab) Init() tea.Cmd {
|
||||
go t.connect()
|
||||
go t.refreshLocal()
|
||||
return t.poll
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) poll() tea.Msg {
|
||||
t.mu.Lock()
|
||||
conn := t.connected
|
||||
err := t.err
|
||||
t.mu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
return sftpRefreshMsg{err: err}
|
||||
}
|
||||
if conn {
|
||||
return sftpRefreshMsg{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) connect() {
|
||||
timeout := 30 * time.Second
|
||||
cl := sshclient.NewClient(t.host, timeout)
|
||||
|
||||
ctx := context.Background()
|
||||
if err := cl.Connect(ctx); err != nil {
|
||||
t.mu.Lock()
|
||||
t.err = fmt.Errorf("SSH connect: %w", err)
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
sftpClient, err := sftp.NewClient(cl.GetClient())
|
||||
if err != nil {
|
||||
cl.Close()
|
||||
t.mu.Lock()
|
||||
t.err = fmt.Errorf("SFTP init: %w", err)
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
home, err := sftpClient.Getwd()
|
||||
if err != nil {
|
||||
home = "/"
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
t.sshClient = cl
|
||||
t.sftp = sftpClient
|
||||
t.right.sftpClient = sftpClient
|
||||
t.right.cwd = home
|
||||
t.connected = true
|
||||
t.mu.Unlock()
|
||||
|
||||
t.refreshRemote()
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) refreshLocal() {
|
||||
t.mu.Lock()
|
||||
p := &t.left
|
||||
p.entries = nil
|
||||
t.mu.Unlock()
|
||||
|
||||
entries, err := os.ReadDir(p.cwd)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var infos []os.FileInfo
|
||||
for _, e := range entries {
|
||||
info, err := e.Info()
|
||||
if err == nil {
|
||||
infos = append(infos, info)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(infos, func(i, j int) bool {
|
||||
if infos[i].IsDir() != infos[j].IsDir() {
|
||||
return infos[i].IsDir()
|
||||
}
|
||||
return strings.ToLower(infos[i].Name()) < strings.ToLower(infos[j].Name())
|
||||
})
|
||||
|
||||
t.mu.Lock()
|
||||
p.entries = infos
|
||||
if p.selIdx >= len(infos) {
|
||||
p.selIdx = 0
|
||||
}
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) refreshRemote() {
|
||||
t.mu.Lock()
|
||||
p := &t.right
|
||||
sftpClient := p.sftpClient
|
||||
cwd := p.cwd
|
||||
t.mu.Unlock()
|
||||
|
||||
if sftpClient == nil {
|
||||
return
|
||||
}
|
||||
|
||||
entries, err := sftpClient.ReadDir(cwd)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
if entries[i].IsDir() != entries[j].IsDir() {
|
||||
return entries[i].IsDir()
|
||||
}
|
||||
return strings.ToLower(entries[i].Name()) < strings.ToLower(entries[j].Name())
|
||||
})
|
||||
|
||||
t.mu.Lock()
|
||||
p.entries = entries
|
||||
if p.selIdx >= len(entries) {
|
||||
p.selIdx = 0
|
||||
}
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) activePane() *sftpPane {
|
||||
if t.active == paneLocal {
|
||||
return &t.left
|
||||
}
|
||||
return &t.right
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) 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()
|
||||
return t, nil
|
||||
|
||||
case sftpRefreshMsg:
|
||||
if msg.err != nil {
|
||||
t.mu.Lock()
|
||||
t.err = msg.err
|
||||
t.mu.Unlock()
|
||||
return t, nil
|
||||
}
|
||||
// Re-render only
|
||||
return t, t.poll
|
||||
|
||||
case tea.KeyMsg:
|
||||
p := t.activePane()
|
||||
|
||||
if p.filterMode {
|
||||
switch msg.String() {
|
||||
case "esc", "enter":
|
||||
p.filterMode = false
|
||||
p.filter = ""
|
||||
return t, nil
|
||||
case "backspace":
|
||||
if len(p.filter) > 0 {
|
||||
p.filter = p.filter[:len(p.filter)-1]
|
||||
}
|
||||
return t, nil
|
||||
default:
|
||||
if len(msg.Runes) == 1 {
|
||||
p.filter += string(msg.Runes[0])
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
|
||||
switch msg.String() {
|
||||
case "tab":
|
||||
t.mu.Lock()
|
||||
if t.active == paneLocal {
|
||||
t.active = paneRemote
|
||||
} else {
|
||||
t.active = paneLocal
|
||||
}
|
||||
t.mu.Unlock()
|
||||
return t, nil
|
||||
|
||||
case "up", "k":
|
||||
t.mu.Lock()
|
||||
if p.selIdx > 0 {
|
||||
p.selIdx--
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case "down", "j":
|
||||
t.mu.Lock()
|
||||
if p.selIdx < len(p.entries)-1 {
|
||||
p.selIdx++
|
||||
}
|
||||
t.mu.Unlock()
|
||||
|
||||
case "enter", "right":
|
||||
t.mu.Lock()
|
||||
entries := p.entries
|
||||
idx := p.selIdx
|
||||
t.mu.Unlock()
|
||||
|
||||
if idx >= 0 && idx < len(entries) && entries[idx].IsDir() {
|
||||
t.mu.Lock()
|
||||
p.cwd = path.Join(p.cwd, entries[idx].Name())
|
||||
p.selIdx = 0
|
||||
t.mu.Unlock()
|
||||
if t.active == paneRemote {
|
||||
go t.refreshRemote()
|
||||
} else {
|
||||
go t.refreshLocal()
|
||||
}
|
||||
}
|
||||
|
||||
case "left", "backspace":
|
||||
t.mu.Lock()
|
||||
parent := path.Dir(p.cwd)
|
||||
if parent == "." {
|
||||
parent = "/"
|
||||
}
|
||||
if (t.active == paneLocal && parent != p.cwd) || (t.active == paneRemote && parent != p.cwd) {
|
||||
p.cwd = parent
|
||||
p.selIdx = 0
|
||||
}
|
||||
t.mu.Unlock()
|
||||
if t.active == paneRemote {
|
||||
go t.refreshRemote()
|
||||
} else {
|
||||
go t.refreshLocal()
|
||||
}
|
||||
|
||||
case "/":
|
||||
p.filterMode = true
|
||||
p.filter = ""
|
||||
|
||||
case "r":
|
||||
if t.active == paneRemote {
|
||||
go t.refreshRemote()
|
||||
} else {
|
||||
go t.refreshLocal()
|
||||
}
|
||||
|
||||
case "c":
|
||||
t.mu.Lock()
|
||||
src, dst := t.left, t.right
|
||||
srcType, dstType := paneLocal, paneRemote
|
||||
if t.active == paneRemote {
|
||||
src, dst = t.right, t.left
|
||||
srcType, dstType = paneRemote, paneLocal
|
||||
}
|
||||
idx := src.selIdx
|
||||
srcEntries := src.entries
|
||||
srcCwd := src.cwd
|
||||
dstCwd := dst.cwd
|
||||
t.mu.Unlock()
|
||||
|
||||
if idx >= 0 && idx < len(srcEntries) && !srcEntries[idx].IsDir() {
|
||||
srcPath := path.Join(srcCwd, srcEntries[idx].Name())
|
||||
dstPath := path.Join(dstCwd, srcEntries[idx].Name())
|
||||
|
||||
go t.copyFile(srcType, dstType, srcPath, dstPath, srcEntries[idx].Name())
|
||||
}
|
||||
|
||||
case "d":
|
||||
t.mu.Lock()
|
||||
p := t.activePane()
|
||||
entries := p.entries
|
||||
idx := p.selIdx
|
||||
cwd := p.cwd
|
||||
isRemote := t.active == paneRemote
|
||||
t.mu.Unlock()
|
||||
|
||||
if idx >= 0 && idx < len(entries) {
|
||||
fullPath := path.Join(cwd, entries[idx].Name())
|
||||
go t.deleteItem(fullPath, entries[idx].IsDir(), isRemote)
|
||||
}
|
||||
|
||||
case "n":
|
||||
if t.active == paneRemote {
|
||||
go t.mkdirRemote()
|
||||
}
|
||||
|
||||
case "esc":
|
||||
return t, func() tea.Msg { return closeFormMsg{} }
|
||||
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
return t, t.poll
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) copyFile(srcType, dstType paneType, srcPath, dstPath, name string) {
|
||||
t.mu.Lock()
|
||||
t.transferring = true
|
||||
t.transferMsg = fmt.Sprintf("Copying %s...", name)
|
||||
t.mu.Unlock()
|
||||
|
||||
var err error
|
||||
if srcType == paneRemote && dstType == paneLocal {
|
||||
// Download
|
||||
t.mu.Lock()
|
||||
client := t.right.sftpClient
|
||||
t.mu.Unlock()
|
||||
if client != nil {
|
||||
err = downloadFile(client, srcPath, dstPath)
|
||||
}
|
||||
} else if srcType == paneLocal && dstType == paneRemote {
|
||||
// Upload
|
||||
t.mu.Lock()
|
||||
client := t.right.sftpClient
|
||||
t.mu.Unlock()
|
||||
if client != nil {
|
||||
err = uploadFile(client, srcPath, dstPath)
|
||||
}
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if err != nil {
|
||||
t.err = fmt.Errorf("copy %s: %w", name, err)
|
||||
} else {
|
||||
t.transferMsg = ""
|
||||
}
|
||||
t.transferring = false
|
||||
t.mu.Unlock()
|
||||
|
||||
if dstType == paneRemote {
|
||||
t.refreshRemote()
|
||||
} else {
|
||||
t.refreshLocal()
|
||||
}
|
||||
}
|
||||
|
||||
func downloadFile(client *sftp.Client, remotePath, localPath string) error {
|
||||
src, err := client.Open(remotePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
dst, err := os.Create(localPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
_, err = io.Copy(dst, src)
|
||||
return err
|
||||
}
|
||||
|
||||
func uploadFile(client *sftp.Client, localPath, remotePath string) error {
|
||||
src, err := os.Open(localPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
dst, err := client.Create(remotePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
_, err = io.Copy(dst, src)
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) deleteItem(fullPath string, isDir bool, isRemote bool) {
|
||||
t.mu.Lock()
|
||||
t.transferring = true
|
||||
t.transferMsg = fmt.Sprintf("Deleting %s...", filepath.Base(fullPath))
|
||||
t.mu.Unlock()
|
||||
|
||||
var err error
|
||||
if isRemote {
|
||||
t.mu.Lock()
|
||||
client := t.right.sftpClient
|
||||
t.mu.Unlock()
|
||||
if client != nil {
|
||||
if isDir {
|
||||
err = client.RemoveDirectory(fullPath)
|
||||
} else {
|
||||
err = client.Remove(fullPath)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if isDir {
|
||||
err = os.RemoveAll(fullPath)
|
||||
} else {
|
||||
err = os.Remove(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
if err != nil {
|
||||
t.err = fmt.Errorf("delete: %w", err)
|
||||
}
|
||||
t.transferring = false
|
||||
t.transferMsg = ""
|
||||
t.mu.Unlock()
|
||||
|
||||
if isRemote {
|
||||
go t.refreshRemote()
|
||||
} else {
|
||||
go t.refreshLocal()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) mkdirRemote() {
|
||||
t.mu.Lock()
|
||||
client := t.right.sftpClient
|
||||
cwd := t.right.cwd
|
||||
t.mu.Unlock()
|
||||
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
name := fmt.Sprintf("new-dir-%d", time.Now().Unix())
|
||||
if err := client.Mkdir(path.Join(cwd, name)); err != nil {
|
||||
t.mu.Lock()
|
||||
t.err = fmt.Errorf("mkdir: %w", err)
|
||||
t.mu.Unlock()
|
||||
return
|
||||
}
|
||||
t.refreshRemote()
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) View() string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if !t.connected && t.err != nil {
|
||||
var b strings.Builder
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("SFTP Error: %v", t.err))))
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Press Esc to close")))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
if !t.connected {
|
||||
return lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render(fmt.Sprintf("Connecting SFTP to %s...", t.host.Name)))
|
||||
}
|
||||
|
||||
halfW := t.width / 2
|
||||
if halfW < 20 {
|
||||
halfW = 20
|
||||
}
|
||||
|
||||
leftView := t.renderPane(&t.left, paneLocal, halfW)
|
||||
rightView := t.renderPane(&t.right, paneRemote, halfW)
|
||||
|
||||
var b strings.Builder
|
||||
|
||||
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
AppTitleStyle.Render(fmt.Sprintf("SFTP: %s@%s", t.host.Username, t.host.Hostname))))
|
||||
b.WriteString("\n")
|
||||
|
||||
b.WriteString(lipgloss.JoinHorizontal(lipgloss.Top, leftView, rightView))
|
||||
|
||||
if t.err != nil {
|
||||
b.WriteString("\n" + lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||
}
|
||||
|
||||
if t.transferring && t.transferMsg != "" {
|
||||
b.WriteString("\n" + lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
InfoStyle.Render(t.transferMsg)))
|
||||
}
|
||||
|
||||
b.WriteString("\n" + lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||
SubtitleStyle.Render("Ctrl+Tab:switch Ctrl+Q:close Tab:pane ↑↓:nav /:filter C:copy D:delete N:mkdir R:refresh Esc:close")))
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) renderPane(p *sftpPane, pt paneType, maxW int) string {
|
||||
isActive := t.active == pt
|
||||
|
||||
title := "Local"
|
||||
if pt == paneRemote {
|
||||
title = "Remote"
|
||||
}
|
||||
|
||||
paneStyle := StylePaneInactive
|
||||
if isActive {
|
||||
paneStyle = StylePaneActive
|
||||
}
|
||||
|
||||
// Title
|
||||
titleBar := fmt.Sprintf(" %s ", title)
|
||||
if isActive {
|
||||
titleBar = StatusBarStyle.Render(" " + title + " ")
|
||||
} else {
|
||||
titleBar = SubtitleStyle.Render(" " + title + " ")
|
||||
}
|
||||
|
||||
// CWD
|
||||
cwdStr := p.cwd
|
||||
if len(cwdStr) > maxW-4 {
|
||||
cwdStr = "..." + cwdStr[len(cwdStr)-maxW+7:]
|
||||
}
|
||||
|
||||
var content strings.Builder
|
||||
content.WriteString(SubtitleStyle.Render(fmt.Sprintf(" %s", cwdStr)))
|
||||
content.WriteString("\n\n")
|
||||
|
||||
// Filter
|
||||
var visible []os.FileInfo
|
||||
if p.filter != "" {
|
||||
lower := strings.ToLower(p.filter)
|
||||
for _, e := range p.entries {
|
||||
if strings.Contains(strings.ToLower(e.Name()), lower) {
|
||||
visible = append(visible, e)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
visible = p.entries
|
||||
}
|
||||
|
||||
if len(visible) == 0 {
|
||||
content.WriteString(SubtitleStyle.Render(" (empty)"))
|
||||
} else {
|
||||
maxDisplay := t.height - 6
|
||||
if maxDisplay < 5 {
|
||||
maxDisplay = 5
|
||||
}
|
||||
start := 0
|
||||
if p.selIdx >= maxDisplay {
|
||||
start = p.selIdx - maxDisplay + 1
|
||||
}
|
||||
end := start + maxDisplay
|
||||
if end > len(visible) {
|
||||
end = len(visible)
|
||||
}
|
||||
|
||||
for i := start; i < end; i++ {
|
||||
entry := visible[i]
|
||||
name := entry.Name()
|
||||
var line string
|
||||
|
||||
if entry.IsDir() {
|
||||
line = fmt.Sprintf(" %s/", name)
|
||||
} else {
|
||||
size := formatSize(entry.Size())
|
||||
line = fmt.Sprintf(" %s (%s)", name, size)
|
||||
}
|
||||
|
||||
if len(line) > maxW {
|
||||
line = line[:maxW-1] + "…"
|
||||
}
|
||||
|
||||
if i == p.selIdx {
|
||||
content.WriteString(SelectedStyle.Render(line))
|
||||
} else if entry.IsDir() {
|
||||
content.WriteString(InfoStyle.Render(line))
|
||||
} else {
|
||||
content.WriteString(HostDetailStyle.Render(line))
|
||||
}
|
||||
content.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
if p.filterMode {
|
||||
content.WriteString("\n" + SubtitleStyle.Render("Filter: "+p.filter+"_"))
|
||||
}
|
||||
|
||||
inner := titleBar + "\n" + content.String()
|
||||
return paneStyle.Width(maxW).Render(inner)
|
||||
}
|
||||
|
||||
func (t *SFTPBrowserTab) Close() {
|
||||
t.closeOnce.Do(func() {
|
||||
if t.sftp != nil {
|
||||
t.sftp.Close()
|
||||
}
|
||||
if t.sshClient != nil {
|
||||
t.sshClient.Close()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type sftpRefreshMsg struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func formatSize(size int64) string {
|
||||
switch {
|
||||
case size >= 1<<30:
|
||||
return fmt.Sprintf("%.1f GiB", float64(size)/float64(1<<30))
|
||||
case size >= 1<<20:
|
||||
return fmt.Sprintf("%.1f MiB", float64(size)/float64(1<<20))
|
||||
case size >= 1<<10:
|
||||
return fmt.Sprintf("%.1f KiB", float64(size)/float64(1<<10))
|
||||
default:
|
||||
return fmt.Sprintf("%d B", size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/textinput"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"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{
|
||||
Name: name,
|
||||
Command: command,
|
||||
Description: t.inputs[snippetFieldDescription].Value(),
|
||||
Tags: tags,
|
||||
}
|
||||
}
|
||||
|
||||
t.saved = true
|
||||
return t, saveSnippetCmd(sn, t.dataDir)
|
||||
}
|
||||
|
||||
func (t *SnippetFormTab) View() string {
|
||||
contentW := t.width - 12
|
||||
if contentW < 50 {
|
||||
contentW = 50
|
||||
}
|
||||
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")
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||
SubtitleStyle.Render("Ctrl+Tab:switch Ctrl+Q:close Tab:next Enter:next Ctrl+S:save Esc:cancel")))
|
||||
|
||||
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,236 @@
|
||||
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
|
||||
}
|
||||
var rows []styledRow
|
||||
|
||||
title := "Command Snippets"
|
||||
titlePlain := title
|
||||
|
||||
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})
|
||||
}
|
||||
}
|
||||
|
||||
footerPlain := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Ctrl+N:add Ctrl+E:edit D:delete Esc:back"
|
||||
footer := styledRow{text: SubtitleStyle.Render(footerPlain), plain: footerPlain}
|
||||
|
||||
widestRow := lipgloss.Width(titlePlain)
|
||||
for _, r := range rows {
|
||||
if w := lipgloss.Width(r.plain); w > widestRow {
|
||||
widestRow = w
|
||||
}
|
||||
}
|
||||
if w := lipgloss.Width(footer.plain); w > widestRow {
|
||||
widestRow = w
|
||||
}
|
||||
|
||||
const sidePad = 6
|
||||
targetW := widestRow + sidePad*2
|
||||
|
||||
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")
|
||||
|
||||
// Render rows, excluding the footer (last element)
|
||||
for _, r := range rows[:len(rows)-1] {
|
||||
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, r.text)
|
||||
inner.WriteString(line)
|
||||
inner.WriteString("\n")
|
||||
}
|
||||
inner.WriteString("\n")
|
||||
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, footer.text))
|
||||
|
||||
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() {}
|
||||
|
||||
// snippetListLoadedMsg carries the loaded snippet list
|
||||
type snippetListLoadedMsg struct {
|
||||
snippets []*models.Snippet
|
||||
err error
|
||||
}
|
||||
+137
@@ -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)
|
||||
)
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
// 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
|
||||
if wsMsg, ok := msg.(tea.WindowSizeMsg); ok {
|
||||
tm.SetSize(wsMsg.Width, wsMsg.Height)
|
||||
}
|
||||
|
||||
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
|
||||
func renderTabBar(tm *TabManager) string {
|
||||
if len(tm.tabs) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var cells []string
|
||||
for i, tab := range tm.tabs {
|
||||
name := tab.Name()
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
+181
-42
@@ -1,23 +1,15 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||
)
|
||||
|
||||
// Styles for TUI components
|
||||
var (
|
||||
TitleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("86")).Bold(true)
|
||||
SubtitleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
|
||||
HighlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212")).Bold(true)
|
||||
ErrorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("196")).Bold(true)
|
||||
SuccessStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("76")).Bold(true)
|
||||
InfoStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("117"))
|
||||
)
|
||||
|
||||
// Screen represents different TUI screens
|
||||
// Screen represents different TUI screens (deprecated, use tabs)
|
||||
type Screen int
|
||||
|
||||
const (
|
||||
@@ -28,16 +20,22 @@ const (
|
||||
|
||||
// Model represents the main TUI model
|
||||
type Model struct {
|
||||
CurrentScreen Screen
|
||||
Hosts []*models.Host
|
||||
SelectedIndex int
|
||||
tabs *TabManager
|
||||
CurrentScreen Screen // deprecated, kept for backward compat
|
||||
Hosts []*models.Host // deprecated
|
||||
SelectedIndex int // deprecated
|
||||
Error error
|
||||
Quit bool
|
||||
dataDir string
|
||||
}
|
||||
|
||||
// New creates a new TUI model
|
||||
func New() *Model {
|
||||
hostList := NewHostListTab()
|
||||
tm := NewTabManager(hostList)
|
||||
|
||||
return &Model{
|
||||
tabs: tm,
|
||||
CurrentScreen: ScreenHostList,
|
||||
SelectedIndex: 0,
|
||||
Quit: false,
|
||||
@@ -46,56 +44,197 @@ func New() *Model {
|
||||
|
||||
// Init initializes the TUI
|
||||
func (m *Model) Init() tea.Cmd {
|
||||
return nil
|
||||
return m.tabs.Init()
|
||||
}
|
||||
|
||||
// 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:
|
||||
switch msg.String() {
|
||||
case "ctrl+c", "q":
|
||||
// Only hard quit on ctrl+c (let tabs handle q)
|
||||
if msg.String() == "ctrl+c" {
|
||||
m.Quit = true
|
||||
return m, tea.Quit
|
||||
|
||||
case "up", "k":
|
||||
if m.SelectedIndex > 0 {
|
||||
m.SelectedIndex--
|
||||
}
|
||||
|
||||
case "down", "j":
|
||||
if m.SelectedIndex < len(m.Hosts)-1 {
|
||||
m.SelectedIndex++
|
||||
}
|
||||
|
||||
case "enter", " ":
|
||||
if len(m.Hosts) > 0 {
|
||||
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 openSFTPMsg:
|
||||
tab := NewSFTPBrowserTab(msg.host, m.dataDir)
|
||||
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 return to list (which auto-refreshes via Init)
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case deleteKeyResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case saveSnippetResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
return m, nil
|
||||
}
|
||||
if m.tabs.Len() > 1 {
|
||||
m.tabs.CloseActive()
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case deleteSnippetResultMsg:
|
||||
if msg.err != nil {
|
||||
m.Error = msg.err
|
||||
}
|
||||
return m, nil
|
||||
|
||||
}
|
||||
|
||||
return m, nil
|
||||
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"
|
||||
}
|
||||
|
||||
switch m.CurrentScreen {
|
||||
case ScreenHostList:
|
||||
return renderHostList(m)
|
||||
default:
|
||||
return "Screen not implemented yet"
|
||||
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) {
|
||||
m.Hosts = hosts
|
||||
if len(hosts) > 0 && m.SelectedIndex >= len(hosts) {
|
||||
m.SelectedIndex = len(hosts) - 1
|
||||
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
|
||||
}
|
||||
|
||||
+89
-2
@@ -10,13 +10,23 @@ func TestTUIInitialization(t *testing.T) {
|
||||
t.Fatal("Failed to initialize TUI")
|
||||
}
|
||||
|
||||
if ui.CurrentScreen != ScreenHostList {
|
||||
t.Errorf("expected CurrentScreen ScreenHostList, got %d", ui.CurrentScreen)
|
||||
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) {
|
||||
@@ -29,4 +39,81 @@ func TestTUILoadHosts(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user