Compare commits

..

No commits in common. "ed6ea2939a9d2aaea5bb1f64cb52650d9c023933" and "9bb5d18f8e4d05762c80bba09a604cc987984301" have entirely different histories.

30 changed files with 161 additions and 2544 deletions

View File

@ -68,12 +68,10 @@ jobs:
run: |
mkdir -p dist
VERSION=${GITHUB_REF#refs/tags/}
# Remove 'v' prefix if present for version injection
VERSION_CLEAN=${VERSION#v}
if [ "${{ matrix.goos }}" = "windows" ]; then
go build -ldflags="-s -w -X github.com/Gu1llaum-3/sshm/cmd.AppVersion=${VERSION_CLEAN}" -o dist/sshm-${{ matrix.suffix }}.exe .
go build -ldflags="-s -w -X github.com/Gu1llaum-3/sshm/cmd.version=${VERSION}" -o dist/sshm-${{ matrix.suffix }}.exe .
else
go build -ldflags="-s -w -X github.com/Gu1llaum-3/sshm/cmd.AppVersion=${VERSION_CLEAN}" -o dist/sshm-${{ matrix.suffix }} .
go build -ldflags="-s -w -X github.com/Gu1llaum-3/sshm/cmd.version=${VERSION}" -o dist/sshm-${{ matrix.suffix }} .
fi
- name: Create archive
@ -118,7 +116,7 @@ jobs:
- name: Check if pre-release
id: check_prerelease
run: |
if [[ "${GITHUB_REF#refs/tags/}" == *"-beta"* ]] || [[ "${GITHUB_REF#refs/tags/}" == *"-alpha"* ]] || [[ "${GITHUB_REF#refs/tags/}" == *"-rc"* ]] || [[ "${GITHUB_REF#refs/tags/}" == *"-dev"* ]]; then
if [[ "${GITHUB_REF#refs/tags/}" == *"-beta"* ]] || [[ "${GITHUB_REF#refs/tags/}" == *"-alpha"* ]] || [[ "${GITHUB_REF#refs/tags/}" == *"-rc"* ]]; then
echo "is_prerelease=true" >> $GITHUB_OUTPUT
else
echo "is_prerelease=false" >> $GITHUB_OUTPUT

187
README.md
View File

@ -25,29 +25,35 @@ SSHM is a beautiful command-line tool that transforms how you manage and connect
## ✨ Features
### 🚀 **Core Capabilities**
### 🎯 **Core Features**
- **🎨 Beautiful TUI Interface** - Navigate your SSH hosts with an elegant, interactive terminal UI
- **⚡ Quick Connect** - Connect to any host instantly through the TUI or the CLI with `sshm <host>`
- **🔄 Port Forwarding** - Easy setup for Local, Remote, and Dynamic (SOCKS) forwarding with history persistence
- **📝 Easy Management** - Add, edit, move, and manage SSH configurations seamlessly
- **⚡ Quick Connect** - Connect to any host instantly
- **🔄 Port Forwarding** - Easy setup for Local, Remote, and Dynamic (SOCKS) forwarding
- **📝Easy Management** - Add, edit, and manage SSH configurations seamlessly
- **🏷️ Tag Support** - Organize your hosts with custom tags for better categorization
- **🔍 Smart Search** - Find hosts quickly with built-in filtering and search
- **📝 Real-time Status** - Live SSH connectivity indicators with asynchronous ping checks and color-coded status
- **🔔 Smart Updates** - Automatic version checking with update notifications
- **📈 Connection History** - Track your SSH connections with last login timestamps
### 🛠️ **Technical Features**
- **🔒 Secure** - Works directly with your existing `~/.ssh/config` file
- **📁 Custom Config Support** - Use any SSH configuration file with the `-c` flag
- **📂 SSH Include Support** - Full support for SSH Include directives to organize configurations across multiple files
- **⚙️ SSH Options Support** - Add any SSH configuration option through intuitive forms
- **🔄 Automatic Conversion** - Seamlessly converts between command-line and config formats
- **🔄 Automatic Backups** - Backup configurations automatically before changes
- **✅ Validation** - Prevent configuration errors with built-in validation
- **🔗 ProxyJump Support** - Secure connection tunneling through bastion hosts
- **⌨️ Keyboard Shortcuts** - Power user navigation with vim-like shortcuts
- **🌐 Cross-platform** - Supports Linux, macOS (Intel & Apple Silicon), and Windows
- **⚡ Lightweight** - Single binary with no dependencies, zero configuration required
### 🛠️ **Management Operations**
- **Add new SSH hosts** with interactive forms
- **Edit existing configurations** in-place
- **Delete hosts** with confirmation prompts
- **Port forwarding setup** with intuitive interface for Local (-L), Remote (-R), and Dynamic (-D) forwarding
- **Backup configurations** automatically before changes
- **Validate settings** to prevent configuration errors
- **ProxyJump support** for secure connection tunneling through bastion hosts
- **SSH Options management** - Add any SSH option with automatic format conversion
- **Full SSH compatibility** - Maintains compatibility with standard SSH tools
### 🎮 **User Experience**
- **Zero configuration** - Works out of the box with your existing SSH setup
- **Keyboard shortcuts** for power users
- **Cross-platform** - Supports Linux, macOS (Intel & Apple Silicon), and Windows
- **Lightweight** - Single binary with no dependencies
## 🚀 Quick Start
@ -99,17 +105,10 @@ sshm
- `a` - Add new host
- `e` - Edit selected host
- `d` - Delete selected host
- `m` - Move host to another config file (requires SSH Include directives)
- `f` - Port forwarding setup
- `q` - Quit
- `/` - Search/filter hosts
**Real-time Status Indicators:**
- 🟢 **Online** - Host is reachable via SSH
- 🟡 **Connecting** - Currently checking host connectivity
- 🔴 **Offline** - Host is unreachable or SSH connection failed
- ⚫ **Unknown** - Connectivity status not yet determined
**Sorting & Filtering:**
- `s` - Switch between sorting modes (name ↔ last login)
- `n` - Sort by **name** (alphabetical)
@ -159,7 +158,6 @@ SSHM provides an intuitive interface for setting up SSH port forwarding. Press `
- Configure ports and addresses with guided forms
- Optional bind address configuration (defaults to 127.0.0.1)
- Real-time validation of port numbers and addresses
- **Port forwarding history** - Save frequently used configurations for quick reuse
- Connect automatically with configured forwarding options
**Troubleshooting Port Forwarding:**
@ -220,15 +218,9 @@ SSHM provides both command-line operations and an interactive TUI interface:
# Launch interactive TUI mode for browsing and connecting to hosts
sshm
# Connect directly to a specific host (with history tracking)
sshm my-server
# Launch TUI with custom SSH config file
sshm -c /path/to/custom/ssh_config
# Connect directly with custom SSH config file
sshm my-server -c /path/to/custom/ssh_config
# Add a new host using interactive form
sshm add
@ -244,42 +236,13 @@ sshm edit my-server
# Edit host with custom SSH config file
sshm edit my-server -c /path/to/custom/ssh_config
# Move a host to another SSH config file (requires Include directives)
sshm move my-server
# Move host with custom SSH config file (requires Include directives)
sshm move my-server -c /path/to/custom/ssh_config
# Search for hosts (interactive filter)
sshm search
# Show version information (includes update check)
# Show version information
sshm --version
# Show help and available commands
sshm --help
```
### Direct Host Connection
SSHM supports direct connection to hosts via the command line, making it easy to integrate into your existing workflow:
```bash
# Connect directly to any configured host
sshm production-server
sshm db-staging
sshm web-01
# All direct connections are tracked in your history
# Use the TUI to see your most recently connected hosts
```
**Features of Direct Connection:**
- **Instant connection** - No TUI navigation required
- **History tracking** - All connections are recorded with timestamps
- **Error handling** - Clear messages if host doesn't exist or configuration issues
- **Config file support** - Works with custom config files using `-c` flag
### Backup Configuration
SSHM automatically creates backups of your SSH configuration files before making any changes to ensure your configurations are safe.
@ -294,10 +257,6 @@ SSHM automatically creates backups of your SSH configuration files before making
- Stored separately to avoid SSH Include conflicts
- Easy manual recovery if needed
**Additional Storage:**
- **Connection History**: Stored in the same config directory for persistent tracking
- **Port Forwarding History**: Saved configurations for quick reuse of common forwarding setups
**Quick Recovery:**
```bash
# Unix/Linux/macOS
@ -318,96 +277,8 @@ sshm -c /path/to/custom/ssh_config
# Use custom config file with commands
sshm add hostname -c /path/to/custom/ssh_config
sshm edit hostname -c /path/to/custom/ssh_config
sshm move hostname -c /path/to/custom/ssh_config
```
### Advanced Features
#### Host Movement Between Config Files
SSHM provides a powerful `move` command to relocate SSH hosts between different configuration files. **This feature requires SSH Include directives to be present in your SSH configuration.**
```bash
# Move a host to another config file (requires Include directives)
sshm move my-server
# Move with custom config file (requires Include directives)
sshm move my-server -c /path/to/custom/ssh_config
```
**⚠️ Important Requirements:**
- **SSH Include directives must be present** in your SSH config file (either `~/.ssh/config` or the file specified with `-c`)
- The config file must contain `Include` statements referencing other SSH configuration files
- Without Include directives, the move command will display an error message
**Features:**
- **Interactive file selector** - Choose destination config file from Include directives
- **Include support** - Works seamlessly with SSH Include directives structure
- **Atomic operations** - Safe host movement with automatic backups
- **Validation** - Prevents conflicts and ensures configuration integrity
- **Error handling** - Clear messages when Include files are needed but not found
**Use Cases:**
- Reorganize hosts from main config to specialized include files
- Move development hosts to separate environment-specific configs
- Consolidate configurations for better organization
**Example Setup Required:**
Your main SSH config file must contain Include directives like:
```ssh
# ~/.ssh/config
Include ~/.ssh/config.d/*
Include work-servers.conf
Include projects/*.conf
Host personal-server
HostName personal.example.com
User myuser
```
#### Real-time Connectivity Status
SSHM features asynchronous SSH connectivity checking that provides visual indicators of host availability:
**Status Indicators:**
- 🟢 **Online** - SSH connection successful (shows response time)
- 🟡 **Connecting** - Currently testing connectivity
- 🔴 **Offline** - SSH connection failed or host unreachable
- ⚫ **Unknown** - Status not yet determined
**Features:**
- **Non-blocking checks** - Status updates happen in the background
- **Response time tracking** - See connection latency for online hosts
- **Automatic refresh** - Status indicators update continuously
- **Error details** - Detailed error information for failed connections
#### Automatic Update Checking
SSHM includes built-in version checking that notifies you of available updates:
**Features:**
- **Background checking** - Version check happens asynchronously
- **Release notifications** - Clear indicators when updates are available
- **Pre-release detection** - Identifies beta and development versions
- **GitHub integration** - Direct links to release pages
- **Non-intrusive** - Updates don't interrupt your workflow
**Update notifications appear:**
- In the main TUI interface as a subtle notification
- In the `sshm --version` command output
- Only when a newer stable version is available
#### Port Forwarding History
SSHM remembers your port forwarding configurations for easy reuse:
**Features:**
- **Automatic saving** - Successful forwarding setups are saved automatically
- **Quick reuse** - Previously used configurations appear as suggestions
- **Per-host history** - Forwarding history is tracked per SSH host
- **All forward types** - Supports Local (-L), Remote (-R), and Dynamic (-D) forwarding history
- **Persistent storage** - History survives application restarts
### Platform-Specific Notes
**Windows:**
@ -578,29 +449,20 @@ sshm/
│ ├── root.go # Root command and interactive mode
│ ├── add.go # Add host command
│ ├── edit.go # Edit host command
│ ├── move.go # Move host command
│ └── search.go # Search command
├── internal/
│ ├── config/ # SSH configuration management
│ │ └── ssh.go # Config parsing and manipulation
│ ├── connectivity/ # SSH connectivity checking
│ │ └── ping.go # Asynchronous SSH ping functionality
│ ├── history/ # Connection history tracking
│ │ ├── history.go # History management and last login tracking
│ │ └── port_forward_test.go # Port forwarding history tests
│ ├── version/ # Version checking and updates
│ │ ├── version.go # GitHub release checking and version comparison
│ │ └── version_test.go # Version parsing and comparison tests
│ │ └── history.go # History management and last login tracking
│ ├── ui/ # Terminal UI components (Bubble Tea)
│ │ ├── tui.go # Main TUI interface and program setup
│ │ ├── model.go # Core TUI model and state
│ │ ├── update.go # Message handling and state updates
│ │ ├── view.go # UI rendering and layout
│ │ ├── table.go # Host list table component with status indicators
│ │ ├── table.go # Host list table component
│ │ ├── add_form.go # Add host form interface
│ │ ├── edit_form.go# Edit host form interface
│ │ ├── move_form.go# Move host form interface
│ │ ├── port_forward_form.go # Port forwarding setup with history
│ │ ├── styles.go # Lip Gloss styling definitions
│ │ ├── sort.go # Sorting and filtering logic
│ │ └── utils.go # UI utility functions
@ -628,7 +490,6 @@ sshm/
- [Bubble Tea](https://github.com/charmbracelet/bubbletea) - TUI framework
- [Bubbles](https://github.com/charmbracelet/bubbles) - TUI components
- [Lipgloss](https://github.com/charmbracelet/lipgloss) - Styling
- [Go Crypto SSH](https://golang.org/x/crypto/ssh) - SSH connectivity checking
## 📦 Releases

View File

@ -2,7 +2,6 @@ package cmd
import (
"fmt"
"github.com/Gu1llaum-3/sshm/internal/ui"
"github.com/spf13/cobra"
@ -27,5 +26,5 @@ var addCmd = &cobra.Command{
}
func init() {
RootCmd.AddCommand(addCmd)
rootCmd.AddCommand(addCmd)
}

View File

@ -1,88 +0,0 @@
package cmd
import (
"bytes"
"testing"
"github.com/spf13/cobra"
)
func TestAddCommand(t *testing.T) {
// Test that the add command is properly configured
if addCmd.Use != "add [hostname]" {
t.Errorf("Expected Use 'add [hostname]', got '%s'", addCmd.Use)
}
if addCmd.Short != "Add a new SSH host configuration" {
t.Errorf("Expected Short description, got '%s'", addCmd.Short)
}
// Test that it accepts maximum 1 argument
err := addCmd.Args(addCmd, []string{"host1", "host2"})
if err == nil {
t.Error("Expected error for too many arguments")
}
// Test that it accepts 0 or 1 argument
err = addCmd.Args(addCmd, []string{})
if err != nil {
t.Errorf("Expected no error for 0 arguments, got %v", err)
}
err = addCmd.Args(addCmd, []string{"hostname"})
if err != nil {
t.Errorf("Expected no error for 1 argument, got %v", err)
}
}
func TestAddCommandRegistration(t *testing.T) {
// Check that add command is registered with root command
found := false
for _, cmd := range RootCmd.Commands() {
if cmd.Name() == "add" {
found = true
break
}
}
if !found {
t.Error("Add command not found in root command")
}
}
func TestAddCommandHelp(t *testing.T) {
// Test help output
cmd := &cobra.Command{}
cmd.AddCommand(addCmd)
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetArgs([]string{"add", "--help"})
// This should not return an error for help
err := cmd.Execute()
if err != nil {
t.Errorf("Expected no error for help command, got %v", err)
}
output := buf.String()
if !contains(output, "Add a new SSH host configuration") {
t.Error("Help output should contain command description")
}
}
// Helper function to check if string contains substring
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
(len(s) > len(substr) && (s[:len(substr)] == substr ||
s[len(s)-len(substr):] == substr ||
containsSubstring(s, substr))))
}
func containsSubstring(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}

View File

@ -2,7 +2,6 @@ package cmd
import (
"fmt"
"github.com/Gu1llaum-3/sshm/internal/ui"
"github.com/spf13/cobra"
@ -24,5 +23,5 @@ var editCmd = &cobra.Command{
}
func init() {
RootCmd.AddCommand(editCmd)
rootCmd.AddCommand(editCmd)
}

View File

@ -1,70 +0,0 @@
package cmd
import (
"bytes"
"testing"
"github.com/spf13/cobra"
)
func TestEditCommand(t *testing.T) {
// Test that the edit command is properly configured
if editCmd.Use != "edit <hostname>" {
t.Errorf("Expected Use 'edit <hostname>', got '%s'", editCmd.Use)
}
if editCmd.Short != "Edit an existing SSH host configuration" {
t.Errorf("Expected Short description, got '%s'", editCmd.Short)
}
// Test that it requires exactly 1 argument
err := editCmd.Args(editCmd, []string{})
if err == nil {
t.Error("Expected error for no arguments")
}
err = editCmd.Args(editCmd, []string{"host1", "host2"})
if err == nil {
t.Error("Expected error for too many arguments")
}
err = editCmd.Args(editCmd, []string{"hostname"})
if err != nil {
t.Errorf("Expected no error for 1 argument, got %v", err)
}
}
func TestEditCommandRegistration(t *testing.T) {
// Check that edit command is registered with root command
found := false
for _, cmd := range RootCmd.Commands() {
if cmd.Name() == "edit" {
found = true
break
}
}
if !found {
t.Error("Edit command not found in root command")
}
}
func TestEditCommandHelp(t *testing.T) {
// Test help output
cmd := &cobra.Command{}
cmd.AddCommand(editCmd)
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetArgs([]string{"edit", "--help"})
// This should not return an error for help
err := cmd.Execute()
if err != nil {
t.Errorf("Expected no error for help command, got %v", err)
}
output := buf.String()
if !contains(output, "Edit an existing SSH host configuration") {
t.Error("Help output should contain command description")
}
}

View File

@ -1,28 +0,0 @@
package cmd
import (
"fmt"
"github.com/Gu1llaum-3/sshm/internal/ui"
"github.com/spf13/cobra"
)
var moveCmd = &cobra.Command{
Use: "move <hostname>",
Short: "Move an existing SSH host configuration to another config file",
Long: `Move an existing SSH host configuration to another config file with an interactive file selector.`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
hostname := args[0]
err := ui.RunMoveForm(hostname, configFile)
if err != nil {
fmt.Printf("Error moving host: %v\n", err)
}
},
}
func init() {
RootCmd.AddCommand(moveCmd)
}

View File

@ -1,57 +1,45 @@
package cmd
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"strings"
"syscall"
"time"
"github.com/Gu1llaum-3/sshm/internal/config"
"github.com/Gu1llaum-3/sshm/internal/history"
"github.com/Gu1llaum-3/sshm/internal/ui"
"github.com/Gu1llaum-3/sshm/internal/version"
"github.com/spf13/cobra"
)
// AppVersion will be set at build time via -ldflags
var AppVersion = "dev"
// version will be set at build time via -ldflags
var version = "dev"
// configFile holds the path to the SSH config file
var configFile string
// RootCmd is the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "sshm [host]",
var rootCmd = &cobra.Command{
Use: "sshm",
Short: "SSH Manager - A modern SSH connection manager",
Long: `SSHM is a modern SSH manager for your terminal.
Main usage:
Running 'sshm' (without arguments) opens the interactive TUI window to browse, search, and connect to your SSH hosts graphically.
Running 'sshm <host>' connects directly to the specified host and records the connection in your history.
You can also use sshm in CLI mode for other operations like adding, editing, or searching hosts.
You can also use sshm in CLI mode for direct operations.
Hosts are read from your ~/.ssh/config file by default.`,
Version: AppVersion,
Args: cobra.ArbitraryArgs,
SilenceUsage: true,
SilenceErrors: true, // We'll handle errors ourselves
RunE: func(cmd *cobra.Command, args []string) error {
Version: version,
Run: func(cmd *cobra.Command, args []string) {
// If no arguments provided, run interactive mode
if len(args) == 0 {
runInteractiveMode()
return nil
return
}
// If a host name is provided, connect directly
hostName := args[0]
connectToHost(hostName)
return nil
},
}
@ -97,7 +85,7 @@ func runInteractiveMode() {
}
// Run the interactive TUI
if err := ui.RunInteractiveMode(hosts, configFile, AppVersion); err != nil {
if err := ui.RunInteractiveMode(hosts, configFile); err != nil {
log.Fatalf("Error running interactive mode: %v", err)
}
}
@ -132,88 +120,25 @@ func connectToHost(hostName string) {
os.Exit(1)
}
// Record the connection in history
historyManager, err := history.NewHistoryManager()
if err != nil {
// Log the error but don't prevent the connection
fmt.Printf("Warning: Could not initialize connection history: %v\n", err)
} else {
err = historyManager.RecordConnection(hostName)
if err != nil {
// Log the error but don't prevent the connection
fmt.Printf("Warning: Could not record connection history: %v\n", err)
}
}
// Build and execute the SSH command
// Connect to the host
fmt.Printf("Connecting to %s...\n", hostName)
var sshCmd *exec.Cmd
// Build the SSH command with the appropriate config file
var sshCmd []string
if configFile != "" {
sshCmd = exec.Command("ssh", "-F", configFile, hostName)
sshCmd = []string{"ssh", "-F", configFile, hostName}
} else {
sshCmd = exec.Command("ssh", hostName)
sshCmd = []string{"ssh", hostName}
}
// Set up the command to use the same stdin, stdout, and stderr as the parent process
sshCmd.Stdin = os.Stdin
sshCmd.Stdout = os.Stdout
sshCmd.Stderr = os.Stderr
// Execute the SSH command
err = sshCmd.Run()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
// SSH command failed, exit with the same code
if status, ok := exitError.Sys().(syscall.WaitStatus); ok {
os.Exit(status.ExitStatus())
}
}
fmt.Printf("Error executing SSH command: %v\n", err)
os.Exit(1)
}
}
// getVersionWithUpdateCheck returns a custom version string with update check
func getVersionWithUpdateCheck() string {
versionText := fmt.Sprintf("sshm version %s", AppVersion)
// Check for updates
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
updateInfo, err := version.CheckForUpdates(ctx, AppVersion)
if err != nil {
// Return just version if check fails
return versionText + "\n"
}
if updateInfo != nil && updateInfo.Available {
versionText += fmt.Sprintf("\n🚀 Update available: %s → %s (%s)",
updateInfo.CurrentVer,
updateInfo.LatestVer,
updateInfo.ReleaseURL)
}
return versionText + "\n"
// Note: In a real implementation, you'd use exec.Command here
// For now, just print the command that would be executed
fmt.Printf("%s\n", strings.Join(sshCmd, " "))
}
// Execute adds all child commands to the root command and sets flags appropriately.
func Execute() {
// Custom error handling for unknown commands that might be host names
if err := RootCmd.Execute(); err != nil {
// Check if this is an "unknown command" error and the argument might be a host name
errStr := err.Error()
if strings.Contains(errStr, "unknown command") {
// Extract the command name from the error
parts := strings.Split(errStr, "\"")
if len(parts) >= 2 {
potentialHost := parts[1]
// Try to connect to this as a host
connectToHost(potentialHost)
return
}
}
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
@ -221,8 +146,5 @@ func Execute() {
func init() {
// Add the config file flag
RootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "SSH config file to use (default: ~/.ssh/config)")
// Set custom version template with update check
RootCmd.SetVersionTemplate(getVersionWithUpdateCheck())
rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "SSH config file to use (default: ~/.ssh/config)")
}

View File

@ -1,145 +0,0 @@
package cmd
import (
"bytes"
"strings"
"testing"
)
func TestRootCommand(t *testing.T) {
// Test that the root command is properly configured
if RootCmd.Use != "sshm [host]" {
t.Errorf("Expected Use 'sshm [host]', got '%s'", RootCmd.Use)
}
if RootCmd.Short != "SSH Manager - A modern SSH connection manager" {
t.Errorf("Expected Short description, got '%s'", RootCmd.Short)
}
if RootCmd.Version != AppVersion {
t.Errorf("Expected Version '%s', got '%s'", AppVersion, RootCmd.Version)
}
}
func TestRootCommandFlags(t *testing.T) {
// Test that persistent flags are properly configured
flags := RootCmd.PersistentFlags()
// Check config flag
configFlag := flags.Lookup("config")
if configFlag == nil {
t.Error("Expected --config flag to be defined")
return
}
if configFlag.Shorthand != "c" {
t.Errorf("Expected config flag shorthand 'c', got '%s'", configFlag.Shorthand)
}
}
func TestRootCommandSubcommands(t *testing.T) {
// Test that all expected subcommands are registered
// Note: completion and help are automatically added by Cobra and may not always appear in Commands()
expectedCommands := []string{"add", "edit", "search"}
commands := RootCmd.Commands()
commandNames := make(map[string]bool)
for _, cmd := range commands {
commandNames[cmd.Name()] = true
}
for _, expected := range expectedCommands {
if !commandNames[expected] {
t.Errorf("Expected command '%s' not found", expected)
}
}
// Check that we have at least the core commands
if len(commandNames) < 3 {
t.Errorf("Expected at least 3 commands, got %d", len(commandNames))
}
}
func TestRootCommandHelp(t *testing.T) {
// Test help output
buf := new(bytes.Buffer)
RootCmd.SetOut(buf)
RootCmd.SetArgs([]string{"--help"})
// This should not return an error for help
err := RootCmd.Execute()
if err != nil {
t.Errorf("Expected no error for help command, got %v", err)
}
output := buf.String()
if !strings.Contains(output, "modern SSH manager") {
t.Error("Help output should contain command description")
}
if !strings.Contains(output, "Usage:") {
t.Error("Help output should contain usage section")
}
}
func TestRootCommandVersion(t *testing.T) {
// Test that version command executes without error
// Note: Cobra handles version output internally, so we just check for no error
RootCmd.SetArgs([]string{"--version"})
// This should not return an error for version
err := RootCmd.Execute()
if err != nil {
t.Errorf("Expected no error for version command, got %v", err)
}
// Reset args for other tests
RootCmd.SetArgs([]string{})
}
func TestExecuteFunction(t *testing.T) {
// Test that Execute function exists and can be called
// We can't easily test the actual execution without mocking,
// but we can test that the function exists
t.Log("Execute function exists and is accessible")
}
func TestConnectToHostFunction(t *testing.T) {
// Test that connectToHost function exists and can be called
// Note: We can't easily test the actual connection without a valid SSH config
// and without actually connecting to a host, but we can verify the function exists
t.Log("connectToHost function exists and is accessible")
// The function will handle errors internally (like host not found)
// We don't want to actually test the SSH connection in unit tests
}
func TestRunInteractiveModeFunction(t *testing.T) {
// Test that runInteractiveMode function exists
// We can't easily test the actual execution without mocking the UI,
// but we can verify the function signature
t.Log("runInteractiveMode function exists and is accessible")
}
func TestConfigFileVariable(t *testing.T) {
// Test that configFile variable is properly initialized
originalConfigFile := configFile
defer func() { configFile = originalConfigFile }()
// Set config file through flag
RootCmd.SetArgs([]string{"--config", "/tmp/test-config"})
RootCmd.ParseFlags([]string{"--config", "/tmp/test-config"})
// The configFile variable should be updated by the flag parsing
// Note: This test verifies the flag binding works
}
func TestVersionVariable(t *testing.T) {
// Test that version variable has a default value
if AppVersion == "" {
t.Error("AppVersion variable should have a default value")
}
// Test that version is set to "dev" by default
if AppVersion != "dev" {
t.Logf("AppVersion is set to '%s' (expected 'dev' for development)", AppVersion)
}
}

View File

@ -235,7 +235,7 @@ func escapeJSON(s string) string {
func init() {
// Add search command to root
RootCmd.AddCommand(searchCmd)
rootCmd.AddCommand(searchCmd)
// Add flags
searchCmd.Flags().StringVarP(&outputFormat, "format", "f", "table", "Output format (table, json, simple)")

View File

@ -1,120 +0,0 @@
package cmd
import (
"strings"
"testing"
)
func TestSearchCommand(t *testing.T) {
// Test that the search command is properly configured
if searchCmd.Use != "search [query]" {
t.Errorf("Expected Use 'search [query]', got '%s'", searchCmd.Use)
}
if searchCmd.Short != "Search SSH hosts by name, hostname, or tags" {
t.Errorf("Expected Short description, got '%s'", searchCmd.Short)
}
// Test that it accepts maximum 1 argument
err := searchCmd.Args(searchCmd, []string{"query1", "query2"})
if err == nil {
t.Error("Expected error for too many arguments")
}
// Test that it accepts 0 or 1 argument
err = searchCmd.Args(searchCmd, []string{})
if err != nil {
t.Errorf("Expected no error for 0 arguments, got %v", err)
}
err = searchCmd.Args(searchCmd, []string{"query"})
if err != nil {
t.Errorf("Expected no error for 1 argument, got %v", err)
}
}
func TestSearchCommandRegistration(t *testing.T) {
// Check that search command is registered with root command
found := false
for _, cmd := range RootCmd.Commands() {
if cmd.Name() == "search" {
found = true
break
}
}
if !found {
t.Error("Search command not found in root command")
}
}
func TestSearchCommandFlags(t *testing.T) {
// Test that flags are properly configured
flags := searchCmd.Flags()
// Check format flag
formatFlag := flags.Lookup("format")
if formatFlag == nil {
t.Error("Expected --format flag to be defined")
}
// Check tags flag
tagsFlag := flags.Lookup("tags")
if tagsFlag == nil {
t.Error("Expected --tags flag to be defined")
}
// Check names flag
namesFlag := flags.Lookup("names")
if namesFlag == nil {
t.Error("Expected --names flag to be defined")
}
}
func TestSearchCommandHelp(t *testing.T) {
// Test that the command has the right help properties
// Instead of executing --help, just check the Long description
if searchCmd.Long == "" {
t.Error("Search command should have a Long description")
}
if !strings.Contains(searchCmd.Long, "Search") {
t.Error("Long description should contain information about searching")
}
}
func TestFormatOutput(t *testing.T) {
tests := []struct {
name string
format string
valid bool
}{
{"table format", "table", true},
{"json format", "json", true},
{"simple format", "simple", true},
{"invalid format", "invalid", false},
{"empty format", "", true}, // Should default to table
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
valid := isValidFormat(tt.format)
if valid != tt.valid {
t.Errorf("isValidFormat(%q) = %v, want %v", tt.format, valid, tt.valid)
}
})
}
}
// Helper function to validate format (this would be in the actual search.go)
func isValidFormat(format string) bool {
if format == "" {
return true // Default to table
}
validFormats := []string{"table", "json", "simple"}
for _, valid := range validFormats {
if format == valid {
return true
}
}
return false
}

View File

@ -40,8 +40,8 @@ func GetDefaultSSHConfigPath() (string, error) {
}
}
// GetSSHMConfigDir returns the SSHM config directory
func GetSSHMConfigDir() (string, error) {
// GetSSHMBackupDir returns the SSHM backup directory
func GetSSHMBackupDir() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
@ -67,15 +67,6 @@ func GetSSHMConfigDir() (string, error) {
}
}
return configDir, nil
}
// GetSSHMBackupDir returns the SSHM backup directory
func GetSSHMBackupDir() (string, error) {
configDir, err := GetSSHMConfigDir()
if err != nil {
return "", err
}
return filepath.Join(configDir, "backups"), nil
}
@ -553,40 +544,17 @@ func HostExists(hostName string) (bool, error) {
// HostExistsInFile checks if a host exists in a specific config file
func HostExistsInFile(hostName string, configPath string) (bool, error) {
// Parse only the specific file, not its includes
return HostExistsInSpecificFile(hostName, configPath)
}
// HostExistsInSpecificFile checks if a host exists in a specific file only (no includes)
func HostExistsInSpecificFile(hostName string, configPath string) (bool, error) {
file, err := os.Open(configPath)
hosts, err := ParseSSHConfigFile(configPath)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
// Check for Host declaration
if strings.HasPrefix(strings.ToLower(line), "host ") {
// Extract host names (can be multiple hosts on one line)
hostPart := strings.TrimSpace(line[5:]) // Remove "host "
hostNames := strings.Fields(hostPart)
for _, name := range hostNames {
if name == hostName {
for _, host := range hosts {
if host.Name == hostName {
return true, nil
}
}
}
}
return false, scanner.Err()
return false, nil
}
// GetSSHHost retrieves a specific host configuration by name
@ -972,67 +940,3 @@ func GetIncludedConfigFiles() ([]string, error) {
return writableFiles, nil
}
// MoveHostToFile moves an SSH host from its current config file to a target config file
func MoveHostToFile(hostName string, targetConfigFile string) error {
// Find the host in all configs to get its current location and data
host, err := FindHostInAllConfigs(hostName)
if err != nil {
return err
}
// Check if the target file is different from the current source file
if host.SourceFile == targetConfigFile {
return fmt.Errorf("host '%s' is already in the target config file '%s'", hostName, targetConfigFile)
}
// First, add the host to the target config file
err = AddSSHHostToFile(*host, targetConfigFile)
if err != nil {
return fmt.Errorf("failed to add host to target file: %v", err)
}
// Then, remove the host from its current source file
err = DeleteSSHHostFromFile(hostName, host.SourceFile)
if err != nil {
// If removal fails, we should try to rollback the addition, but for simplicity
// we'll just return the error. In a production environment, you might want
// to implement a proper rollback mechanism.
return fmt.Errorf("failed to remove host from source file: %v", err)
}
return nil
}
// GetConfigFilesExcludingCurrent returns all config files except the one containing the specified host
func GetConfigFilesExcludingCurrent(hostName string, baseConfigFile string) ([]string, error) {
// Get all config files
var allFiles []string
var err error
if baseConfigFile != "" {
allFiles, err = GetAllConfigFilesFromBase(baseConfigFile)
} else {
allFiles, err = GetAllConfigFiles()
}
if err != nil {
return nil, err
}
// Find the host to get its current source file
host, err := FindHostInAllConfigs(hostName)
if err != nil {
return nil, err
}
// Filter out the current source file
var filteredFiles []string
for _, file := range allFiles {
if file != host.SourceFile {
filteredFiles = append(filteredFiles, file)
}
}
return filteredFiles, nil
}

View File

@ -813,177 +813,3 @@ Include subdir/*.conf
t.Errorf("GetAllConfigFilesFromBase('') should behave like GetAllConfigFiles(). Got %d vs %d files", len(defaultFiles), len(allFiles))
}
}
func TestHostExistsInSpecificFile(t *testing.T) {
// Create temporary directory for test files
tempDir := t.TempDir()
// Create main config file
mainConfig := filepath.Join(tempDir, "config")
mainConfigContent := `Host main-host
HostName example.com
User mainuser
Include included.conf
Host another-host
HostName another.example.com
User anotheruser
`
err := os.WriteFile(mainConfig, []byte(mainConfigContent), 0600)
if err != nil {
t.Fatalf("Failed to create main config: %v", err)
}
// Create included config file
includedConfig := filepath.Join(tempDir, "included.conf")
includedConfigContent := `Host included-host
HostName included.example.com
User includeduser
`
err = os.WriteFile(includedConfig, []byte(includedConfigContent), 0600)
if err != nil {
t.Fatalf("Failed to create included config: %v", err)
}
// Test that host exists in main config file (should ignore includes)
exists, err := HostExistsInSpecificFile("main-host", mainConfig)
if err != nil {
t.Fatalf("HostExistsInSpecificFile() error = %v", err)
}
if !exists {
t.Error("main-host should exist in main config file")
}
// Test that host from included file does NOT exist in main config file
exists, err = HostExistsInSpecificFile("included-host", mainConfig)
if err != nil {
t.Fatalf("HostExistsInSpecificFile() error = %v", err)
}
if exists {
t.Error("included-host should NOT exist in main config file (should ignore includes)")
}
// Test that host exists in included config file
exists, err = HostExistsInSpecificFile("included-host", includedConfig)
if err != nil {
t.Fatalf("HostExistsInSpecificFile() error = %v", err)
}
if !exists {
t.Error("included-host should exist in included config file")
}
// Test non-existent host
exists, err = HostExistsInSpecificFile("non-existent", mainConfig)
if err != nil {
t.Fatalf("HostExistsInSpecificFile() error = %v", err)
}
if exists {
t.Error("non-existent host should not exist")
}
// Test with non-existent file
exists, err = HostExistsInSpecificFile("any-host", "/non/existent/file")
if err != nil {
t.Fatalf("HostExistsInSpecificFile() should not return error for non-existent file: %v", err)
}
if exists {
t.Error("non-existent file should not contain any hosts")
}
}
func TestGetConfigFilesExcludingCurrent(t *testing.T) {
// This test verifies the function works when SSH config is properly set up
// Since GetConfigFilesExcludingCurrent depends on FindHostInAllConfigs which uses the default SSH config,
// we'll test the function more directly by creating a temporary SSH config setup
// Skip this test if we can't access SSH config directory
_, err := GetSSHDirectory()
if err != nil {
t.Skipf("Skipping test: cannot get SSH directory: %v", err)
}
// Check if SSH config exists
defaultConfigPath, err := GetDefaultSSHConfigPath()
if err != nil {
t.Skipf("Skipping test: cannot get default SSH config path: %v", err)
}
if _, err := os.Stat(defaultConfigPath); os.IsNotExist(err) {
t.Skipf("Skipping test: SSH config file does not exist at %s", defaultConfigPath)
}
// Test that the function returns something for a hypothetical host
// We can't guarantee specific hosts exist, so we test the function doesn't crash
_, err = GetConfigFilesExcludingCurrent("test-host-that-probably-does-not-exist", defaultConfigPath)
if err == nil {
t.Log("GetConfigFilesExcludingCurrent() succeeded for non-existent host (expected)")
} else if strings.Contains(err.Error(), "not found") {
t.Log("GetConfigFilesExcludingCurrent() correctly reported host not found")
} else {
t.Fatalf("GetConfigFilesExcludingCurrent() unexpected error = %v", err)
}
// Test with valid SSH config directory
if err == nil {
t.Log("GetConfigFilesExcludingCurrent() function is working correctly")
}
}
func TestMoveHostToFile(t *testing.T) {
// This test verifies the MoveHostToFile function works when SSH config is properly set up
// Since MoveHostToFile depends on FindHostInAllConfigs which uses the default SSH config,
// we'll test the error handling and basic function behavior
// Check if SSH config exists
defaultConfigPath, err := GetDefaultSSHConfigPath()
if err != nil {
t.Skipf("Skipping test: cannot get default SSH config path: %v", err)
}
if _, err := os.Stat(defaultConfigPath); os.IsNotExist(err) {
t.Skipf("Skipping test: SSH config file does not exist at %s", defaultConfigPath)
}
// Create a temporary destination config file
tempDir := t.TempDir()
destConfig := filepath.Join(tempDir, "dest.conf")
destConfigContent := `Host dest-host
HostName dest.example.com
User destuser
`
err = os.WriteFile(destConfig, []byte(destConfigContent), 0600)
if err != nil {
t.Fatalf("Failed to create dest config: %v", err)
}
// Test moving non-existent host (should return error)
err = MoveHostToFile("non-existent-host-12345", destConfig)
if err == nil {
t.Error("MoveHostToFile() should return error for non-existent host")
} else if !strings.Contains(err.Error(), "not found") {
t.Errorf("Expected 'not found' error, got: %v", err)
}
// Test moving to non-existent file (should return error)
err = MoveHostToFile("any-host", "/non/existent/file")
if err == nil {
t.Error("MoveHostToFile() should return error for non-existent destination file")
}
// Verify that the HostExistsInSpecificFile function works correctly
// This is a component that MoveHostToFile uses
exists, err := HostExistsInSpecificFile("dest-host", destConfig)
if err != nil {
t.Fatalf("HostExistsInSpecificFile() error = %v", err)
}
if !exists {
t.Error("dest-host should exist in destination config file")
}
// Test that the component functions work for the move operation
t.Log("MoveHostToFile() error handling works correctly")
}

View File

@ -1,144 +0,0 @@
package connectivity
import (
"context"
"testing"
"time"
"github.com/Gu1llaum-3/sshm/internal/config"
)
func TestNewPingManager(t *testing.T) {
pm := NewPingManager(5 * time.Second)
if pm == nil {
t.Error("NewPingManager() returned nil")
}
if pm.results == nil {
t.Error("PingManager.results map not initialized")
}
}
func TestPingManager_PingHost(t *testing.T) {
pm := NewPingManager(1 * time.Second)
ctx := context.Background()
// Test ping method exists and doesn't panic
host := config.SSHHost{Name: "test", Hostname: "127.0.0.1", Port: "22"}
result := pm.PingHost(ctx, host)
if result == nil {
t.Error("Expected ping result to be returned")
}
// Test with invalid host
invalidHost := config.SSHHost{Name: "invalid", Hostname: "invalid.host.12345", Port: "22"}
result = pm.PingHost(ctx, invalidHost)
if result == nil {
t.Error("Expected ping result to be returned even for invalid host")
}
}
func TestPingManager_GetStatus(t *testing.T) {
pm := NewPingManager(1 * time.Second)
// Test unknown host
status := pm.GetStatus("unknown.host")
if status != StatusUnknown {
t.Errorf("Expected StatusUnknown for unknown host, got %v", status)
}
// Test after ping
ctx := context.Background()
host := config.SSHHost{Name: "test", Hostname: "127.0.0.1", Port: "22"}
pm.PingHost(ctx, host)
status = pm.GetStatus("test")
if status == StatusUnknown {
t.Error("Expected status to be set after ping")
}
}
func TestPingManager_PingMultipleHosts(t *testing.T) {
pm := NewPingManager(1 * time.Second)
hosts := []config.SSHHost{
{Name: "localhost", Hostname: "127.0.0.1", Port: "22"},
{Name: "invalid", Hostname: "invalid.host.12345", Port: "22"},
}
ctx := context.Background()
// Ping each host individually
for _, host := range hosts {
result := pm.PingHost(ctx, host)
if result == nil {
t.Errorf("Expected ping result for host %s", host.Name)
}
// Check that status was set
status := pm.GetStatus(host.Name)
if status == StatusUnknown {
t.Errorf("Expected status to be set for host %s after ping", host.Name)
}
}
}
func TestPingManager_GetResult(t *testing.T) {
pm := NewPingManager(1 * time.Second)
ctx := context.Background()
// Test getting result for unknown host
result, exists := pm.GetResult("unknown")
if exists || result != nil {
t.Error("Expected no result for unknown host")
}
// Test after ping
host := config.SSHHost{Name: "test", Hostname: "127.0.0.1", Port: "22"}
pm.PingHost(ctx, host)
result, exists = pm.GetResult("test")
if !exists || result == nil {
t.Error("Expected result to exist after ping")
}
if result.HostName != "test" {
t.Errorf("Expected hostname 'test', got '%s'", result.HostName)
}
}
func TestPingStatus_String(t *testing.T) {
tests := []struct {
status PingStatus
expected string
}{
{StatusUnknown, "unknown"},
{StatusConnecting, "connecting"},
{StatusOnline, "online"},
{StatusOffline, "offline"},
{PingStatus(999), "unknown"}, // Invalid status
}
for _, tt := range tests {
t.Run(tt.expected, func(t *testing.T) {
if got := tt.status.String(); got != tt.expected {
t.Errorf("PingStatus.String() = %v, want %v", got, tt.expected)
}
})
}
}
func TestPingHost_Basic(t *testing.T) {
// Test that the ping functionality exists
pm := NewPingManager(1 * time.Second)
ctx := context.Background()
host := config.SSHHost{Name: "test", Hostname: "127.0.0.1", Port: "22"}
// Just ensure the function doesn't panic
result := pm.PingHost(ctx, host)
if result == nil {
t.Error("Expected ping result to be returned")
}
// Test that status is set
status := pm.GetStatus("test")
if status == StatusUnknown {
t.Error("Expected status to be set after ping attempt")
}
}

View File

@ -15,21 +15,11 @@ type ConnectionHistory struct {
Connections map[string]ConnectionInfo `json:"connections"`
}
// PortForwardConfig stores port forwarding configuration
type PortForwardConfig struct {
Type string `json:"type"` // "local", "remote", "dynamic"
LocalPort string `json:"local_port"`
RemoteHost string `json:"remote_host"`
RemotePort string `json:"remote_port"`
BindAddress string `json:"bind_address"`
}
// ConnectionInfo stores information about a specific connection
type ConnectionInfo struct {
HostName string `json:"host_name"`
LastConnect time.Time `json:"last_connect"`
ConnectCount int `json:"connect_count"`
PortForwarding *PortForwardConfig `json:"port_forwarding,omitempty"`
}
// HistoryManager manages the connection history
@ -40,23 +30,12 @@ type HistoryManager struct {
// NewHistoryManager creates a new history manager
func NewHistoryManager() (*HistoryManager, error) {
configDir, err := config.GetSSHMConfigDir()
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, err
}
// Ensure config dir exists
if err := os.MkdirAll(configDir, 0755); err != nil {
return nil, err
}
historyPath := filepath.Join(configDir, "sshm_history.json")
// Migration: check if old history file exists and migrate it
if err := migrateOldHistoryFile(historyPath); err != nil {
// Don't fail if migration fails, just log it
// In a production environment, you might want to log this properly
}
historyPath := filepath.Join(homeDir, ".ssh", "sshm_history.json")
hm := &HistoryManager{
historyPath: historyPath,
@ -75,46 +54,6 @@ func NewHistoryManager() (*HistoryManager, error) {
return hm, nil
}
// migrateOldHistoryFile migrates the old history file from ~/.ssh to ~/.config/sshm
// TODO: Remove this migration logic in v2.0.0 (introduced in v1.6.0)
func migrateOldHistoryFile(newHistoryPath string) error {
// Check if new file already exists, skip migration
if _, err := os.Stat(newHistoryPath); err == nil {
return nil // New file exists, no migration needed
}
// Get old history file path - use same logic as SSH config location
sshDir, err := config.GetSSHDirectory()
if err != nil {
return err
}
oldHistoryPath := filepath.Join(sshDir, "sshm_history.json")
// Check if old file exists
if _, err := os.Stat(oldHistoryPath); os.IsNotExist(err) {
return nil // Old file doesn't exist, nothing to migrate
}
// Read old file
data, err := os.ReadFile(oldHistoryPath)
if err != nil {
return err
}
// Write to new location
if err := os.WriteFile(newHistoryPath, data, 0644); err != nil {
return err
}
// Remove old file only if write was successful
if err := os.Remove(oldHistoryPath); err != nil {
// Don't fail if we can't remove the old file
// The migration was successful even if cleanup failed
}
return nil
}
// loadHistory loads the connection history from the JSON file
func (hm *HistoryManager) loadHistory() error {
data, err := os.ReadFile(hm.historyPath)
@ -267,42 +206,3 @@ func (hm *HistoryManager) GetAllConnectionsInfo() []ConnectionInfo {
return connections
}
// RecordPortForwarding saves port forwarding configuration for a host
func (hm *HistoryManager) RecordPortForwarding(hostName, forwardType, localPort, remoteHost, remotePort, bindAddress string) error {
now := time.Now()
portForwardConfig := &PortForwardConfig{
Type: forwardType,
LocalPort: localPort,
RemoteHost: remoteHost,
RemotePort: remotePort,
BindAddress: bindAddress,
}
if conn, exists := hm.history.Connections[hostName]; exists {
// Update existing connection
conn.LastConnect = now
conn.ConnectCount++
conn.PortForwarding = portForwardConfig
hm.history.Connections[hostName] = conn
} else {
// Create new connection record
hm.history.Connections[hostName] = ConnectionInfo{
HostName: hostName,
LastConnect: now,
ConnectCount: 1,
PortForwarding: portForwardConfig,
}
}
return hm.saveHistory()
}
// GetPortForwardingConfig retrieves the last used port forwarding configuration for a host
func (hm *HistoryManager) GetPortForwardingConfig(hostName string) *PortForwardConfig {
if conn, exists := hm.history.Connections[hostName]; exists {
return conn.PortForwarding
}
return nil
}

View File

@ -1,164 +0,0 @@
package history
import (
"os"
"path/filepath"
"testing"
"time"
)
// createTestHistoryManager creates a history manager with a temporary file for testing
func createTestHistoryManager(t *testing.T) *HistoryManager {
// Create temporary directory
tempDir := t.TempDir()
historyPath := filepath.Join(tempDir, "test_sshm_history.json")
hm := &HistoryManager{
historyPath: historyPath,
history: &ConnectionHistory{Connections: make(map[string]ConnectionInfo)},
}
return hm
}
func TestNewHistoryManager(t *testing.T) {
hm, err := NewHistoryManager()
if err != nil {
t.Fatalf("NewHistoryManager() error = %v", err)
}
if hm == nil {
t.Fatal("NewHistoryManager() returned nil")
}
if hm.historyPath == "" {
t.Error("Expected historyPath to be set")
}
}
func TestHistoryManager_RecordConnection(t *testing.T) {
hm := createTestHistoryManager(t)
// Add a connection
err := hm.RecordConnection("testhost")
if err != nil {
t.Errorf("RecordConnection() error = %v", err)
}
// Check that the connection was added
lastUsed, exists := hm.GetLastConnectionTime("testhost")
if !exists || lastUsed.IsZero() {
t.Error("Expected connection to be recorded")
}
}
func TestHistoryManager_GetLastConnectionTime(t *testing.T) {
hm := createTestHistoryManager(t)
// Test with no connections
lastUsed, exists := hm.GetLastConnectionTime("nonexistent-testhost")
if exists || !lastUsed.IsZero() {
t.Error("Expected no connection for non-existent host")
}
// Add a connection
err := hm.RecordConnection("testhost")
if err != nil {
t.Errorf("RecordConnection() error = %v", err)
}
// Test with existing connection
lastUsed, exists = hm.GetLastConnectionTime("testhost")
if !exists || lastUsed.IsZero() {
t.Error("Expected non-zero time for existing host")
}
// Check that the time is recent (within last minute)
if time.Since(lastUsed) > time.Minute {
t.Error("Last used time seems too old")
}
}
func TestHistoryManager_GetConnectionCount(t *testing.T) {
hm := createTestHistoryManager(t)
// Add same host multiple times
for i := 0; i < 3; i++ {
err := hm.RecordConnection("testhost-count")
if err != nil {
t.Errorf("RecordConnection() error = %v", err)
}
time.Sleep(1 * time.Millisecond)
}
// Should have correct count
count := hm.GetConnectionCount("testhost-count")
if count != 3 {
t.Errorf("Expected connection count 3, got %d", count)
}
}
func TestMigrateOldHistoryFile(t *testing.T) {
// This test verifies that migration doesn't fail when called
// The actual migration logic will be tested in integration tests
tempDir := t.TempDir()
newHistoryPath := filepath.Join(tempDir, "sshm_history.json")
// Test that migration works when no old file exists (common case)
if err := migrateOldHistoryFile(newHistoryPath); err != nil {
t.Errorf("migrateOldHistoryFile() with no old file error = %v", err)
}
// Test that migration skips when new file already exists
if err := os.WriteFile(newHistoryPath, []byte(`{"connections":{}}`), 0644); err != nil {
t.Fatalf("Failed to write new history file: %v", err)
}
if err := migrateOldHistoryFile(newHistoryPath); err != nil {
t.Errorf("migrateOldHistoryFile() with existing new file error = %v", err)
}
// File should be unchanged
data, err := os.ReadFile(newHistoryPath)
if err != nil {
t.Errorf("Failed to read new file: %v", err)
}
if string(data) != `{"connections":{}}` {
t.Error("New file was modified when it shouldn't have been")
}
}
func TestMigrateOldHistoryFile_NoOldFile(t *testing.T) {
// Test migration when no old file exists
tempDir := t.TempDir()
newHistoryPath := filepath.Join(tempDir, "sshm_history.json")
// Should not return error when old file doesn't exist
if err := migrateOldHistoryFile(newHistoryPath); err != nil {
t.Errorf("migrateOldHistoryFile() with no old file error = %v", err)
}
}
func TestMigrateOldHistoryFile_NewFileExists(t *testing.T) {
// Test migration when new file already exists (should skip migration)
tempDir := t.TempDir()
newHistoryPath := filepath.Join(tempDir, "sshm_history.json")
// Create new file first
if err := os.WriteFile(newHistoryPath, []byte(`{"connections":{}}`), 0644); err != nil {
t.Fatalf("Failed to write new history file: %v", err)
}
// Migration should skip when new file exists
if err := migrateOldHistoryFile(newHistoryPath); err != nil {
t.Errorf("migrateOldHistoryFile() with existing new file error = %v", err)
}
// New file should be unchanged
data, err := os.ReadFile(newHistoryPath)
if err != nil {
t.Errorf("Failed to read new file: %v", err)
}
if string(data) != `{"connections":{}}` {
t.Error("New file was modified when it shouldn't have been")
}
}

View File

@ -1,183 +0,0 @@
package history
import (
"os"
"path/filepath"
"testing"
)
func TestPortForwardingHistory(t *testing.T) {
// Create temporary directory for testing
tempDir, err := os.MkdirTemp("", "sshm_test_*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
// Create history manager with temp directory
historyPath := filepath.Join(tempDir, "test_history.json")
hm := &HistoryManager{
historyPath: historyPath,
history: &ConnectionHistory{Connections: make(map[string]ConnectionInfo)},
}
hostName := "test-server"
// Test recording port forwarding configuration
err = hm.RecordPortForwarding(hostName, "local", "8080", "localhost", "80", "127.0.0.1")
if err != nil {
t.Fatalf("Failed to record port forwarding: %v", err)
}
// Test retrieving port forwarding configuration
config := hm.GetPortForwardingConfig(hostName)
if config == nil {
t.Fatalf("Expected port forwarding config to exist")
}
// Verify the saved configuration
if config.Type != "local" {
t.Errorf("Expected Type 'local', got %s", config.Type)
}
if config.LocalPort != "8080" {
t.Errorf("Expected LocalPort '8080', got %s", config.LocalPort)
}
if config.RemoteHost != "localhost" {
t.Errorf("Expected RemoteHost 'localhost', got %s", config.RemoteHost)
}
if config.RemotePort != "80" {
t.Errorf("Expected RemotePort '80', got %s", config.RemotePort)
}
if config.BindAddress != "127.0.0.1" {
t.Errorf("Expected BindAddress '127.0.0.1', got %s", config.BindAddress)
}
// Test updating configuration with different values
err = hm.RecordPortForwarding(hostName, "remote", "3000", "app-server", "8000", "")
if err != nil {
t.Fatalf("Failed to record updated port forwarding: %v", err)
}
// Verify the updated configuration
config = hm.GetPortForwardingConfig(hostName)
if config == nil {
t.Fatalf("Expected port forwarding config to exist after update")
}
if config.Type != "remote" {
t.Errorf("Expected updated Type 'remote', got %s", config.Type)
}
if config.LocalPort != "3000" {
t.Errorf("Expected updated LocalPort '3000', got %s", config.LocalPort)
}
if config.RemoteHost != "app-server" {
t.Errorf("Expected updated RemoteHost 'app-server', got %s", config.RemoteHost)
}
if config.RemotePort != "8000" {
t.Errorf("Expected updated RemotePort '8000', got %s", config.RemotePort)
}
if config.BindAddress != "" {
t.Errorf("Expected updated BindAddress to be empty, got %s", config.BindAddress)
}
// Test dynamic forwarding
err = hm.RecordPortForwarding(hostName, "dynamic", "1080", "", "", "0.0.0.0")
if err != nil {
t.Fatalf("Failed to record dynamic port forwarding: %v", err)
}
config = hm.GetPortForwardingConfig(hostName)
if config == nil {
t.Fatalf("Expected port forwarding config to exist for dynamic forwarding")
}
if config.Type != "dynamic" {
t.Errorf("Expected Type 'dynamic', got %s", config.Type)
}
if config.LocalPort != "1080" {
t.Errorf("Expected LocalPort '1080', got %s", config.LocalPort)
}
if config.RemoteHost != "" {
t.Errorf("Expected RemoteHost to be empty for dynamic forwarding, got %s", config.RemoteHost)
}
if config.RemotePort != "" {
t.Errorf("Expected RemotePort to be empty for dynamic forwarding, got %s", config.RemotePort)
}
if config.BindAddress != "0.0.0.0" {
t.Errorf("Expected BindAddress '0.0.0.0', got %s", config.BindAddress)
}
}
func TestPortForwardingHistoryPersistence(t *testing.T) {
// Create temporary directory for testing
tempDir, err := os.MkdirTemp("", "sshm_test_*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
historyPath := filepath.Join(tempDir, "test_history.json")
// Create first history manager and record data
hm1 := &HistoryManager{
historyPath: historyPath,
history: &ConnectionHistory{Connections: make(map[string]ConnectionInfo)},
}
hostName := "persistent-server"
err = hm1.RecordPortForwarding(hostName, "local", "9090", "db-server", "5432", "")
if err != nil {
t.Fatalf("Failed to record port forwarding: %v", err)
}
// Create second history manager and load data
hm2 := &HistoryManager{
historyPath: historyPath,
history: &ConnectionHistory{Connections: make(map[string]ConnectionInfo)},
}
err = hm2.loadHistory()
if err != nil {
t.Fatalf("Failed to load history: %v", err)
}
// Verify the loaded configuration
config := hm2.GetPortForwardingConfig(hostName)
if config == nil {
t.Fatalf("Expected port forwarding config to be loaded from file")
}
if config.Type != "local" {
t.Errorf("Expected loaded Type 'local', got %s", config.Type)
}
if config.LocalPort != "9090" {
t.Errorf("Expected loaded LocalPort '9090', got %s", config.LocalPort)
}
if config.RemoteHost != "db-server" {
t.Errorf("Expected loaded RemoteHost 'db-server', got %s", config.RemoteHost)
}
if config.RemotePort != "5432" {
t.Errorf("Expected loaded RemotePort '5432', got %s", config.RemotePort)
}
}
func TestGetPortForwardingConfigNonExistent(t *testing.T) {
// Create temporary directory for testing
tempDir, err := os.MkdirTemp("", "sshm_test_*")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tempDir)
historyPath := filepath.Join(tempDir, "test_history.json")
hm := &HistoryManager{
historyPath: historyPath,
history: &ConnectionHistory{Connections: make(map[string]ConnectionInfo)},
}
// Test getting configuration for non-existent host
config := hm.GetPortForwardingConfig("non-existent-host")
if config != nil {
t.Errorf("Expected nil config for non-existent host, got %+v", config)
}
}

View File

@ -4,10 +4,9 @@ import (
"os"
"os/user"
"path/filepath"
"strings"
"github.com/Gu1llaum-3/sshm/internal/config"
"github.com/Gu1llaum-3/sshm/internal/validation"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
@ -149,8 +148,8 @@ func (m *addFormModel) Update(msg tea.Msg) (*addFormModel, tea.Cmd) {
case "ctrl+c", "esc":
return m, func() tea.Msg { return addFormCancelMsg{} }
case "ctrl+s":
// Allow submission from any field with Ctrl+S (Save)
case "ctrl+enter":
// Allow submission from any field with Ctrl+Enter
return m, m.submitForm()
case "tab", "shift+tab", "enter", "up", "down":
@ -239,7 +238,7 @@ func (m *addFormModel) View() string {
b.WriteString("\n\n")
}
b.WriteString(m.styles.FormHelp.Render("Tab/Shift+Tab: navigate • Enter on last field: submit • Ctrl+S: save • Ctrl+C/Esc: cancel"))
b.WriteString(m.styles.FormHelp.Render("Tab/Shift+Tab: navigate • Enter on last field: submit • Ctrl+Enter: submit • Ctrl+C/Esc: cancel"))
b.WriteString("\n")
b.WriteString(m.styles.FormHelp.Render("* Required fields"))

View File

@ -1,10 +1,9 @@
package ui
import (
"strings"
"github.com/Gu1llaum-3/sshm/internal/config"
"github.com/Gu1llaum-3/sshm/internal/validation"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
@ -140,8 +139,8 @@ func (m *editFormModel) Update(msg tea.Msg) (*editFormModel, tea.Cmd) {
case "ctrl+c", "esc":
return m, func() tea.Msg { return editFormCancelMsg{} }
case "ctrl+s":
// Allow submission from any field with Ctrl+S (Save)
case "ctrl+enter":
// Allow submission from any field with Ctrl+Enter
return m, m.submitEditForm()
case "tab", "shift+tab", "enter", "up", "down":
@ -248,7 +247,7 @@ func (m *editFormModel) View() string {
b.WriteString("\n\n")
}
b.WriteString(m.styles.FormHelp.Render("Tab/Shift+Tab: navigate • Enter on last field: submit • Ctrl+S: save • Ctrl+C/Esc: cancel"))
b.WriteString(m.styles.FormHelp.Render("Tab/Shift+Tab: navigate • Enter on last field: submit • Ctrl+Enter: submit • Ctrl+C/Esc: cancel"))
b.WriteString("\n")
b.WriteString(m.styles.FormHelp.Render("* Required fields"))

View File

@ -40,85 +40,64 @@ func (m *helpModel) Update(msg tea.Msg) (*helpModel, tea.Cmd) {
func (m *helpModel) View() string {
// Title
title := m.styles.Header.Render("📖 SSHM - Commands")
title := m.styles.Header.Render("📖 SSHM - Help & Commands")
// Create two columns of commands for better visual organization
leftColumn := lipgloss.JoinVertical(lipgloss.Left,
m.styles.FocusedLabel.Render("Navigation & Connection"),
// Create horizontal sections with compact layout
line1 := lipgloss.JoinHorizontal(lipgloss.Center,
m.styles.FocusedLabel.Render("🧭 ↑/↓/j/k"),
" ",
m.styles.HelpText.Render("navigate"),
" ",
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("⏎"),
m.styles.HelpText.Render("connect to selected host")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("i "),
m.styles.HelpText.Render("show host information")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("/ "),
m.styles.HelpText.Render("search hosts")),
lipgloss.JoinHorizontal(lipgloss.Left,
" ",
m.styles.HelpText.Render("connect"),
" ",
m.styles.FocusedLabel.Render("a/e/d"),
" ",
m.styles.HelpText.Render("add/edit/delete"),
)
line2 := lipgloss.JoinHorizontal(lipgloss.Center,
m.styles.FocusedLabel.Render("Tab"),
m.styles.HelpText.Render("switch focus")),
" ",
m.styles.FocusedLabel.Render("Host Management"),
m.styles.HelpText.Render("switch focus"),
" ",
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("a "),
m.styles.HelpText.Render("add new host")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("e "),
m.styles.HelpText.Render("edit selected host")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("m "),
m.styles.HelpText.Render("move host to another config")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("d "),
m.styles.HelpText.Render("delete selected host")),
)
rightColumn := lipgloss.JoinVertical(lipgloss.Left,
m.styles.FocusedLabel.Render("Advanced Features"),
"",
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("p"),
m.styles.HelpText.Render("ping all hosts")),
lipgloss.JoinHorizontal(lipgloss.Left,
" ",
m.styles.HelpText.Render("ping all"),
" ",
m.styles.FocusedLabel.Render("f"),
m.styles.HelpText.Render("setup port forwarding")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("s "),
m.styles.HelpText.Render("cycle sort modes")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("n "),
m.styles.HelpText.Render("sort by name")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("r "),
m.styles.HelpText.Render("sort by recent connection")),
" ",
m.styles.FocusedLabel.Render("System"),
m.styles.HelpText.Render("port forward"),
" ",
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("h "),
m.styles.HelpText.Render("show this help")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("q "),
m.styles.HelpText.Render("quit application")),
lipgloss.JoinHorizontal(lipgloss.Left,
m.styles.FocusedLabel.Render("ESC "),
m.styles.HelpText.Render("exit current view")),
m.styles.FocusedLabel.Render("s/r/n"),
" ",
m.styles.HelpText.Render("sort modes"),
)
// Join the two columns side by side
columns := lipgloss.JoinHorizontal(lipgloss.Top,
leftColumn,
" ", // spacing between columns
rightColumn,
line3 := lipgloss.JoinHorizontal(lipgloss.Center,
m.styles.FocusedLabel.Render("/"),
" ",
m.styles.HelpText.Render("search"),
" ",
m.styles.FocusedLabel.Render("h"),
" ",
m.styles.HelpText.Render("help"),
" ",
m.styles.FocusedLabel.Render("q/ESC"),
" ",
m.styles.HelpText.Render("quit"),
)
// Create the main content
content := lipgloss.JoinVertical(lipgloss.Center,
title,
"",
columns,
line1,
"",
line2,
"",
line3,
"",
m.styles.HelpText.Render("Press ESC, h, q or Enter to close"),
)

View File

@ -4,7 +4,6 @@ import (
"github.com/Gu1llaum-3/sshm/internal/config"
"github.com/Gu1llaum-3/sshm/internal/connectivity"
"github.com/Gu1llaum-3/sshm/internal/history"
"github.com/Gu1llaum-3/sshm/internal/version"
"github.com/charmbracelet/bubbles/table"
"github.com/charmbracelet/bubbles/textinput"
@ -37,7 +36,6 @@ const (
ViewList ViewMode = iota
ViewAdd
ViewEdit
ViewMove
ViewInfo
ViewPortForward
ViewHelp
@ -80,15 +78,10 @@ type Model struct {
sortMode SortMode
configFile string // Path to the SSH config file
// Version update information
updateInfo *version.UpdateInfo
currentVersion string
// View management
viewMode ViewMode
addForm *addFormModel
editForm *editFormModel
moveForm *moveFormModel
infoForm *infoFormModel
portForwardForm *portForwardModel
helpForm *helpModel
@ -99,10 +92,6 @@ type Model struct {
height int
styles Styles
ready bool
// Error handling
errorMessage string
showingError bool
}
// updateTableStyles updates the table header border color based on focus state

View File

@ -1,188 +0,0 @@
package ui
import (
"fmt"
"github.com/Gu1llaum-3/sshm/internal/config"
tea "github.com/charmbracelet/bubbletea"
)
type moveFormModel struct {
fileSelector *fileSelectorModel
hostName string
configFile string
width int
height int
styles Styles
state moveFormState
}
type moveFormState int
const (
moveFormSelectingFile moveFormState = iota
moveFormProcessing
)
type moveFormSubmitMsg struct {
hostName string
targetFile string
err error
}
type moveFormCancelMsg struct{}
// NewMoveForm creates a new move form for moving a host to another config file
func NewMoveForm(hostName string, styles Styles, width, height int, configFile string) (*moveFormModel, error) {
// Get all config files except the one containing the current host
files, err := config.GetConfigFilesExcludingCurrent(hostName, configFile)
if err != nil {
return nil, fmt.Errorf("failed to get config files: %v", err)
}
if len(files) == 0 {
return nil, fmt.Errorf("no includes found in SSH config file - move operation requires multiple config files")
}
// Create a custom file selector for move operation
fileSelector, err := newFileSelectorFromFiles(
fmt.Sprintf("Select destination config file for host '%s':", hostName),
styles,
width,
height,
files,
)
if err != nil {
return nil, fmt.Errorf("failed to create file selector: %v", err)
}
return &moveFormModel{
fileSelector: fileSelector,
hostName: hostName,
configFile: configFile,
width: width,
height: height,
styles: styles,
state: moveFormSelectingFile,
}, nil
}
func (m *moveFormModel) Init() tea.Cmd {
return m.fileSelector.Init()
}
func (m *moveFormModel) Update(msg tea.Msg) (*moveFormModel, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m.styles = NewStyles(m.width)
if m.fileSelector != nil {
m.fileSelector.width = m.width
m.fileSelector.height = m.height
m.fileSelector.styles = m.styles
}
return m, nil
case tea.KeyMsg:
switch m.state {
case moveFormSelectingFile:
switch msg.String() {
case "enter":
if m.fileSelector != nil && len(m.fileSelector.files) > 0 {
selectedFile := m.fileSelector.files[m.fileSelector.selected]
m.state = moveFormProcessing
return m, m.submitMove(selectedFile)
}
case "esc", "q":
return m, func() tea.Msg { return moveFormCancelMsg{} }
default:
// Forward other keys to file selector
if m.fileSelector != nil {
newFileSelector, cmd := m.fileSelector.Update(msg)
m.fileSelector = newFileSelector
return m, cmd
}
}
case moveFormProcessing:
// Dans cet état, on attend le résultat de l'opération
// Le résultat sera géré par le modèle principal
switch msg.String() {
case "esc", "q":
return m, func() tea.Msg { return moveFormCancelMsg{} }
}
}
}
return m, nil
}
func (m *moveFormModel) View() string {
switch m.state {
case moveFormSelectingFile:
if m.fileSelector != nil {
return m.fileSelector.View()
}
return "Loading..."
case moveFormProcessing:
return m.styles.FormTitle.Render("Moving host...") + "\n\n" +
m.styles.HelpText.Render(fmt.Sprintf("Moving host '%s' to selected config file...", m.hostName))
default:
return "Unknown state"
}
}
func (m *moveFormModel) submitMove(targetFile string) tea.Cmd {
return func() tea.Msg {
err := config.MoveHostToFile(m.hostName, targetFile)
return moveFormSubmitMsg{
hostName: m.hostName,
targetFile: targetFile,
err: err,
}
}
}
// Standalone move form for CLI usage
type standaloneMoveForm struct {
moveFormModel *moveFormModel
}
func (m standaloneMoveForm) Init() tea.Cmd {
return m.moveFormModel.Init()
}
func (m standaloneMoveForm) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg.(type) {
case moveFormCancelMsg:
return m, tea.Quit
case moveFormSubmitMsg:
// En mode standalone, on quitte après le déplacement (succès ou erreur)
return m, tea.Quit
}
newForm, cmd := m.moveFormModel.Update(msg)
m.moveFormModel = newForm
return m, cmd
}
func (m standaloneMoveForm) View() string {
return m.moveFormModel.View()
}
// RunMoveForm provides backward compatibility for standalone move form
func RunMoveForm(hostName string, configFile string) error {
styles := NewStyles(80)
moveForm, err := NewMoveForm(hostName, styles, 80, 24, configFile)
if err != nil {
return err
}
m := standaloneMoveForm{moveForm}
p := tea.NewProgram(m, tea.WithAltScreen())
_, err = p.Run()
return err
}

View File

@ -5,7 +5,6 @@ import (
"strconv"
"strings"
"github.com/Gu1llaum-3/sshm/internal/history"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
@ -30,7 +29,6 @@ type portForwardModel struct {
width int
height int
configFile string
historyManager *history.HistoryManager
}
// portForwardSubmitMsg is sent when the port forward form is submitted
@ -43,7 +41,7 @@ type portForwardSubmitMsg struct {
type portForwardCancelMsg struct{}
// NewPortForwardForm creates a new port forward form model
func NewPortForwardForm(hostName string, styles Styles, width, height int, configFile string, historyManager *history.HistoryManager) *portForwardModel {
func NewPortForwardForm(hostName string, styles Styles, width, height int, configFile string) *portForwardModel {
inputs := make([]textinput.Model, 5)
// Forward type input (display only, controlled by arrow keys)
@ -51,6 +49,7 @@ func NewPortForwardForm(hostName string, styles Styles, width, height int, confi
inputs[pfTypeInput].Placeholder = "Use ←/→ to change forward type"
inputs[pfTypeInput].Focus()
inputs[pfTypeInput].Width = 40
inputs[pfTypeInput].SetValue("Local (-L)")
// Local port input
inputs[pfLocalPortInput] = textinput.New()
@ -86,12 +85,8 @@ func NewPortForwardForm(hostName string, styles Styles, width, height int, confi
width: width,
height: height,
configFile: configFile,
historyManager: historyManager,
}
// Load previous port forwarding configuration if available
pf.loadPreviousConfig()
// Initialize input visibility
pf.updateInputVisibility()
@ -375,11 +370,6 @@ func (m *portForwardModel) submitForm() tea.Cmd {
return portForwardSubmitMsg{err: fmt.Errorf("invalid port number"), sshArgs: nil}
}
// Get form values for saving to history
remoteHost := strings.TrimSpace(m.inputs[pfRemoteHostInput].Value())
remotePort := strings.TrimSpace(m.inputs[pfRemotePortInput].Value())
bindAddress := strings.TrimSpace(m.inputs[pfBindAddressInput].Value())
// Build SSH command with port forwarding
var sshArgs []string
@ -389,10 +379,13 @@ func (m *portForwardModel) submitForm() tea.Cmd {
}
// Add forwarding arguments
var forwardTypeStr string
bindAddress := strings.TrimSpace(m.inputs[pfBindAddressInput].Value())
switch m.forwardType {
case LocalForward:
forwardTypeStr = "local"
remoteHost := strings.TrimSpace(m.inputs[pfRemoteHostInput].Value())
remotePort := strings.TrimSpace(m.inputs[pfRemotePortInput].Value())
if remoteHost == "" {
remoteHost = "localhost"
}
@ -415,30 +408,31 @@ func (m *portForwardModel) submitForm() tea.Cmd {
sshArgs = append(sshArgs, "-L", forwardArg)
case RemoteForward:
forwardTypeStr = "remote"
if remoteHost == "" {
remoteHost = "localhost"
localHost := strings.TrimSpace(m.inputs[pfRemoteHostInput].Value())
localPortStr := strings.TrimSpace(m.inputs[pfRemotePortInput].Value())
if localHost == "" {
localHost = "localhost"
}
if remotePort == "" {
if localPortStr == "" {
return portForwardSubmitMsg{err: fmt.Errorf("local port is required for remote forwarding"), sshArgs: nil}
}
// Validate local port
if _, err := strconv.Atoi(remotePort); err != nil {
if _, err := strconv.Atoi(localPortStr); err != nil {
return portForwardSubmitMsg{err: fmt.Errorf("invalid local port number"), sshArgs: nil}
}
// Build -R argument (note: localPort is actually the remote port in this context)
var forwardArg string
if bindAddress != "" {
forwardArg = fmt.Sprintf("%s:%s:%s:%s", bindAddress, localPort, remoteHost, remotePort)
forwardArg = fmt.Sprintf("%s:%s:%s:%s", bindAddress, localPort, localHost, localPortStr)
} else {
forwardArg = fmt.Sprintf("%s:%s:%s", localPort, remoteHost, remotePort)
forwardArg = fmt.Sprintf("%s:%s:%s", localPort, localHost, localPortStr)
}
sshArgs = append(sshArgs, "-R", forwardArg)
case DynamicForward:
forwardTypeStr = "dynamic"
// Build -D argument
var forwardArg string
if bindAddress != "" {
@ -449,21 +443,6 @@ func (m *portForwardModel) submitForm() tea.Cmd {
sshArgs = append(sshArgs, "-D", forwardArg)
}
// Save port forwarding configuration to history
if m.historyManager != nil {
if err := m.historyManager.RecordPortForwarding(
m.hostName,
forwardTypeStr,
localPort,
remoteHost,
remotePort,
bindAddress,
); err != nil {
// Log the error but don't fail the connection
// In a production environment, you might want to handle this differently
}
}
// Add hostname
sshArgs = append(sshArgs, m.hostName)
@ -509,47 +488,3 @@ func (m *portForwardModel) getPrevValidField(currentField int) int {
}
return -1
}
// loadPreviousConfig loads the previous port forwarding configuration for this host
func (m *portForwardModel) loadPreviousConfig() {
if m.historyManager == nil {
m.inputs[pfTypeInput].SetValue("Local (-L)")
return
}
config := m.historyManager.GetPortForwardingConfig(m.hostName)
if config == nil {
m.inputs[pfTypeInput].SetValue("Local (-L)")
return
}
// Set forward type based on saved configuration
switch config.Type {
case "local":
m.forwardType = LocalForward
case "remote":
m.forwardType = RemoteForward
case "dynamic":
m.forwardType = DynamicForward
default:
m.forwardType = LocalForward
}
m.inputs[pfTypeInput].SetValue(m.forwardType.String())
// Set values from saved configuration
if config.LocalPort != "" {
m.inputs[pfLocalPortInput].SetValue(config.LocalPort)
}
if config.RemoteHost != "" {
m.inputs[pfRemoteHostInput].SetValue(config.RemoteHost)
} else if m.forwardType != DynamicForward {
// Default to localhost for local and remote forwarding if not set
m.inputs[pfRemoteHostInput].SetValue("localhost")
}
if config.RemotePort != "" {
m.inputs[pfRemotePortInput].SetValue(config.RemotePort)
}
if config.BindAddress != "" {
m.inputs[pfBindAddressInput].SetValue(config.BindAddress)
}
}

View File

@ -178,13 +178,12 @@ func (m *Model) updateTableHeight() {
// Calculate dynamic table height based on terminal size
// Layout breakdown:
// - ASCII title: 5 lines (1 empty + 4 text lines)
// - Update banner : 1 line (if present)
// - Search bar: 1 line
// - Help text: 1 line
// - App margins/spacing: 3 lines
// - Safety margin: 3 lines (to ensure UI elements are always visible)
// Total reserved: 14 lines minimum to preserve essential UI elements
reservedHeight := 14
// Total reserved: 13 lines minimum to preserve essential UI elements
reservedHeight := 13
availableHeight := m.height - reservedHeight
hostCount := len(m.table.Rows())

View File

@ -16,7 +16,7 @@ import (
)
// NewModel creates a new TUI model with the given SSH hosts
func NewModel(hosts []config.SSHHost, configFile, currentVersion string) Model {
func NewModel(hosts []config.SSHHost, configFile string) Model {
// Initialize the history manager
historyManager, err := history.NewHistoryManager()
if err != nil {
@ -38,7 +38,6 @@ func NewModel(hosts []config.SSHHost, configFile, currentVersion string) Model {
pingManager: pingManager,
sortMode: SortByName,
configFile: configFile,
currentVersion: currentVersion,
styles: styles,
width: 80,
height: 24,
@ -137,8 +136,8 @@ func NewModel(hosts []config.SSHHost, configFile, currentVersion string) Model {
}
// RunInteractiveMode starts the interactive TUI interface
func RunInteractiveMode(hosts []config.SSHHost, configFile, currentVersion string) error {
m := NewModel(hosts, configFile, currentVersion)
func RunInteractiveMode(hosts []config.SSHHost, configFile string) error {
m := NewModel(hosts, configFile)
// Start the application in alt screen mode for clean output
p := tea.NewProgram(m, tea.WithAltScreen())

View File

@ -8,18 +8,14 @@ import (
"github.com/Gu1llaum-3/sshm/internal/config"
"github.com/Gu1llaum-3/sshm/internal/connectivity"
"github.com/Gu1llaum-3/sshm/internal/version"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
)
// Messages for SSH ping functionality and version checking
// Messages for SSH ping functionality
type (
pingResultMsg *connectivity.HostPingResult
versionCheckMsg *version.UpdateInfo
versionErrorMsg error
errorMsg string
)
// startPingAllCmd creates a command to ping all hosts concurrently
@ -53,33 +49,12 @@ func pingSingleHostCmd(pingManager *connectivity.PingManager, host config.SSHHos
}
}
// checkVersionCmd creates a command to check for version updates
func checkVersionCmd(currentVersion string) tea.Cmd {
return func() tea.Msg {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
updateInfo, err := version.CheckForUpdates(ctx, currentVersion)
if err != nil {
return versionErrorMsg(err)
}
return versionCheckMsg(updateInfo)
}
}
// Init initializes the model
func (m Model) Init() tea.Cmd {
var cmds []tea.Cmd
// Basic initialization commands
cmds = append(cmds, textinput.Blink)
// Check for version updates if we have a current version
if m.currentVersion != "" {
cmds = append(cmds, checkVersionCmd(m.currentVersion))
}
return tea.Batch(cmds...)
return tea.Batch(
textinput.Blink,
// Ping is now optional - use 'p' key to start ping
)
}
// Update handles model updates
@ -110,11 +85,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.editForm.height = m.height
m.editForm.styles = m.styles
}
if m.moveForm != nil {
m.moveForm.width = m.width
m.moveForm.height = m.height
m.moveForm.styles = m.styles
}
if m.infoForm != nil {
m.infoForm.width = m.width
m.infoForm.height = m.height
@ -145,27 +115,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, nil
case versionCheckMsg:
// Handle version check result
if msg != nil {
m.updateInfo = msg
}
return m, nil
case versionErrorMsg:
// Handle version check error (silently - not critical)
// We don't want to show error messages for version checks
// as it might disrupt the user experience
return m, nil
case errorMsg:
// Handle general error messages
if string(msg) == "clear" {
m.showingError = false
m.errorMessage = ""
}
return m, nil
case addFormSubmitMsg:
if msg.err != nil {
// Show error in form
@ -254,51 +203,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.table.Focus()
return m, nil
case moveFormSubmitMsg:
if msg.err != nil {
// En cas d'erreur, on pourrait afficher une notification ou retourner à la liste
// Pour l'instant, on retourne simplement à la liste
m.viewMode = ViewList
m.moveForm = nil
m.table.Focus()
return m, nil
} else {
// Success: refresh hosts and return to list view
var hosts []config.SSHHost
var err error
if m.configFile != "" {
hosts, err = config.ParseSSHConfigFile(m.configFile)
} else {
hosts, err = config.ParseSSHConfig()
}
if err != nil {
return m, tea.Quit
}
m.hosts = m.sortHosts(hosts)
// Reapply search filter if there is one active
if m.searchInput.Value() != "" {
m.filteredHosts = m.filterHosts(m.searchInput.Value())
} else {
m.filteredHosts = m.hosts
}
m.updateTableRows()
m.viewMode = ViewList
m.moveForm = nil
m.table.Focus()
return m, nil
}
case moveFormCancelMsg:
// Cancel: return to list view
m.viewMode = ViewList
m.moveForm = nil
m.table.Focus()
return m, nil
case infoFormCancelMsg:
// Cancel: return to list view
m.viewMode = ViewList
@ -399,13 +303,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.editForm = newForm
return m, cmd
}
case ViewMove:
if m.moveForm != nil {
var newForm *moveFormModel
newForm, cmd = m.moveForm.Update(msg)
m.moveForm = newForm
return m, cmd
}
case ViewInfo:
if m.infoForm != nil {
var newForm *infoFormModel
@ -588,27 +485,6 @@ func (m Model) handleListViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, textinput.Blink
}
}
case "m":
if !m.searchMode && !m.deleteMode {
// Move the selected host to another config file
selected := m.table.SelectedRow()
if len(selected) > 0 {
hostName := extractHostNameFromTableRow(selected[0]) // Extract hostname from first column
moveForm, err := NewMoveForm(hostName, m.styles, m.width, m.height, m.configFile)
if err != nil {
// Show error message to user
m.errorMessage = err.Error()
m.showingError = true
return m, func() tea.Msg {
time.Sleep(3 * time.Second) // Show error for 3 seconds
return errorMsg("clear")
}
}
m.moveForm = moveForm
m.viewMode = ViewMove
return m, textinput.Blink
}
}
case "i":
if !m.searchMode && !m.deleteMode {
// Show info for the selected host
@ -686,7 +562,7 @@ func (m Model) handleListViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
selected := m.table.SelectedRow()
if len(selected) > 0 {
hostName := extractHostNameFromTableRow(selected[0]) // Extract hostname from first column
m.portForwardForm = NewPortForwardForm(hostName, m.styles, m.width, m.height, m.configFile, m.historyManager)
m.portForwardForm = NewPortForwardForm(hostName, m.styles, m.width, m.height, m.configFile)
m.viewMode = ViewPortForward
return m, textinput.Blink
}

View File

@ -23,10 +23,6 @@ func (m Model) View() string {
if m.editForm != nil {
return m.editForm.View()
}
case ViewMove:
if m.moveForm != nil {
return m.moveForm.View()
}
case ViewInfo:
if m.infoForm != nil {
return m.infoForm.View()
@ -58,34 +54,6 @@ func (m Model) renderListView() string {
// Add the ASCII title
components = append(components, m.styles.Header.Render(asciiTitle))
// Add update notification if available (between title and search)
if m.updateInfo != nil && m.updateInfo.Available {
updateText := fmt.Sprintf("🚀 Update available: %s → %s",
m.updateInfo.CurrentVer,
m.updateInfo.LatestVer)
updateStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("10")). // Green color
Bold(true).
Align(lipgloss.Center) // Center the notification
components = append(components, updateStyle.Render(updateText))
}
// Add error message if there's one to show
if m.showingError && m.errorMessage != "" {
errorStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("9")). // Red color
Background(lipgloss.Color("1")). // Dark red background
Bold(true).
Padding(0, 1).
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("9")).
Align(lipgloss.Center)
components = append(components, errorStyle.Render("❌ "+m.errorMessage))
}
// Add the search bar with the appropriate style based on focus
searchPrompt := "Search (/ to focus): "
if m.searchMode {
@ -189,30 +157,3 @@ func (m Model) renderDeleteConfirmation() string {
return box.Render(raw)
}
// renderUpdateNotification renders the update notification banner
func (m Model) renderUpdateNotification() string {
if m.updateInfo == nil || !m.updateInfo.Available {
return ""
}
// Create the notification message
message := fmt.Sprintf("🚀 Update available: %s → %s",
m.updateInfo.CurrentVer,
m.updateInfo.LatestVer)
// Add release URL if available
if m.updateInfo.ReleaseURL != "" {
message += fmt.Sprintf(" • View release: %s", m.updateInfo.ReleaseURL)
}
// Style the notification with a bright color to make it stand out
notificationStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("#00FF00")). // Bright green
Bold(true).
Padding(0, 1).
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("#00AA00")) // Darker green border
return notificationStyle.Render(message)
}

View File

@ -1,177 +0,0 @@
package validation
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidateHostname(t *testing.T) {
tests := []struct {
name string
hostname string
want bool
}{
{"valid hostname", "example.com", true},
{"valid IP", "192.168.1.1", true}, // IPs are valid hostnames too
{"valid subdomain", "sub.example.com", true},
{"valid single word", "localhost", true},
{"empty hostname", "", false},
{"hostname too long", strings.Repeat("a", 254), false},
{"hostname with space", "example .com", false},
{"hostname starting with dot", ".example.com", false},
{"hostname ending with dot", "example.com.", false},
{"hostname with hyphen", "my-server.com", true},
{"hostname starting with number", "1example.com", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ValidateHostname(tt.hostname); got != tt.want {
t.Errorf("ValidateHostname(%q) = %v, want %v", tt.hostname, got, tt.want)
}
})
}
}
func TestValidateIP(t *testing.T) {
tests := []struct {
name string
ip string
want bool
}{
{"valid IPv4", "192.168.1.1", true},
{"valid IPv6", "2001:db8::1", true},
{"invalid IP", "256.256.256.256", false},
{"empty IP", "", false},
{"hostname not IP", "example.com", false},
{"localhost", "127.0.0.1", true},
{"zero IP", "0.0.0.0", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ValidateIP(tt.ip); got != tt.want {
t.Errorf("ValidateIP(%q) = %v, want %v", tt.ip, got, tt.want)
}
})
}
}
func TestValidatePort(t *testing.T) {
tests := []struct {
name string
port string
want bool
}{
{"valid port 22", "22", true},
{"valid port 80", "80", true},
{"valid port 65535", "65535", true},
{"valid port 1", "1", true},
{"empty port", "", true}, // Empty defaults to 22
{"invalid port 0", "0", false},
{"invalid port 65536", "65536", false},
{"invalid port negative", "-1", false},
{"invalid port string", "abc", false},
{"invalid port with space", "22 ", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ValidatePort(tt.port); got != tt.want {
t.Errorf("ValidatePort(%q) = %v, want %v", tt.port, got, tt.want)
}
})
}
}
func TestValidateHostName(t *testing.T) {
tests := []struct {
name string
hostName string
want bool
}{
{"valid host name", "myserver", true},
{"valid host name with hyphen", "my-server", true},
{"valid host name with number", "server1", true},
{"empty host name", "", false},
{"host name too long", strings.Repeat("a", 51), false},
{"host name with space", "my server", false},
{"host name with tab", "my\tserver", false},
{"host name with newline", "my\nserver", false},
{"host name with hash", "my#server", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ValidateHostName(tt.hostName); got != tt.want {
t.Errorf("ValidateHostName(%q) = %v, want %v", tt.hostName, got, tt.want)
}
})
}
}
func TestValidateIdentityFile(t *testing.T) {
// Create a temporary file for testing
tmpDir := t.TempDir()
validFile := filepath.Join(tmpDir, "test_key")
if err := os.WriteFile(validFile, []byte("test"), 0600); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
path string
want bool
}{
{"empty path", "", true}, // Optional field
{"valid file", validFile, true},
{"non-existent file", "/path/to/nonexistent", false},
{"tilde path", "~/.ssh/id_rsa", true}, // Will pass if file exists
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ValidateIdentityFile(tt.path); got != tt.want {
t.Errorf("ValidateIdentityFile(%q) = %v, want %v", tt.path, got, tt.want)
}
})
}
}
func TestValidateHost(t *testing.T) {
// Create a temporary file for identity testing
tmpDir := t.TempDir()
validIdentity := filepath.Join(tmpDir, "test_key")
if err := os.WriteFile(validIdentity, []byte("test"), 0600); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
hostName string
hostname string
port string
identity string
wantErr bool
}{
{"valid host", "myserver", "example.com", "22", "", false},
{"valid host with identity", "myserver", "192.168.1.1", "2222", validIdentity, false},
{"empty host name", "", "example.com", "22", "", true},
{"invalid host name", "my server", "example.com", "22", "", true},
{"empty hostname", "myserver", "", "22", "", true},
{"invalid hostname", "myserver", "invalid..hostname", "22", "", true},
{"invalid port", "myserver", "example.com", "99999", "", true},
{"invalid identity", "myserver", "example.com", "22", "/nonexistent", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateHost(tt.hostName, tt.hostname, tt.port, tt.identity)
if (err != nil) != tt.wantErr {
t.Errorf("ValidateHost() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

View File

@ -1,145 +0,0 @@
package version
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
// GitHubRelease represents a GitHub release response
type GitHubRelease struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
HTMLURL string `json:"html_url"`
Prerelease bool `json:"prerelease"`
Draft bool `json:"draft"`
}
// UpdateInfo contains information about available updates
type UpdateInfo struct {
Available bool
CurrentVer string
LatestVer string
ReleaseURL string
ReleaseName string
}
// parseVersion extracts version numbers from a version string (e.g., "v1.2.3" -> [1, 2, 3])
func parseVersion(version string) []int {
// Remove 'v' prefix if present
version = strings.TrimPrefix(version, "v")
parts := strings.Split(version, ".")
nums := make([]int, len(parts))
for i, part := range parts {
// Remove any non-numeric suffixes (e.g., "1-beta", "2-rc1")
numPart := strings.FieldsFunc(part, func(r rune) bool {
return r == '-' || r == '+' || r == '_'
})[0]
if num, err := strconv.Atoi(numPart); err == nil {
nums[i] = num
}
}
return nums
}
// compareVersions compares two version strings
// Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2
func compareVersions(v1, v2 string) int {
nums1 := parseVersion(v1)
nums2 := parseVersion(v2)
// Pad with zeros to make lengths equal
maxLen := len(nums1)
if len(nums2) > maxLen {
maxLen = len(nums2)
}
for len(nums1) < maxLen {
nums1 = append(nums1, 0)
}
for len(nums2) < maxLen {
nums2 = append(nums2, 0)
}
// Compare each part
for i := 0; i < maxLen; i++ {
if nums1[i] < nums2[i] {
return -1
}
if nums1[i] > nums2[i] {
return 1
}
}
return 0
}
// CheckForUpdates checks GitHub for the latest release of sshm
func CheckForUpdates(ctx context.Context, currentVersion string) (*UpdateInfo, error) {
// Skip version check if current version is "dev"
if currentVersion == "dev" {
return &UpdateInfo{
Available: false,
CurrentVer: currentVersion,
}, nil
}
// Create HTTP client with timeout
client := &http.Client{
Timeout: 10 * time.Second,
}
// Create request with context
req, err := http.NewRequestWithContext(ctx, "GET",
"https://api.github.com/repos/Gu1llaum-3/sshm/releases/latest", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Set user agent
req.Header.Set("User-Agent", "sshm/"+currentVersion)
// Make the request
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch latest release: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GitHub API returned status %d", resp.StatusCode)
}
// Parse the response
var release GitHubRelease
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
// Skip pre-releases and drafts
if release.Prerelease || release.Draft {
return &UpdateInfo{
Available: false,
CurrentVer: currentVersion,
}, nil
}
// Compare versions
updateAvailable := compareVersions(currentVersion, release.TagName) < 0
return &UpdateInfo{
Available: updateAvailable,
CurrentVer: currentVersion,
LatestVer: release.TagName,
ReleaseURL: release.HTMLURL,
ReleaseName: release.Name,
}, nil
}

View File

@ -1,56 +0,0 @@
package version
import (
"testing"
)
func TestParseVersion(t *testing.T) {
tests := []struct {
version string
expected []int
}{
{"v1.2.3", []int{1, 2, 3}},
{"1.2.3", []int{1, 2, 3}},
{"v2.0.0", []int{2, 0, 0}},
{"1.2.3-beta", []int{1, 2, 3}},
{"1.2.3-rc1", []int{1, 2, 3}},
{"dev", []int{0}},
}
for _, test := range tests {
result := parseVersion(test.version)
if len(result) != len(test.expected) {
t.Errorf("parseVersion(%q) length = %d, want %d", test.version, len(result), len(test.expected))
continue
}
for i, v := range result {
if v != test.expected[i] {
t.Errorf("parseVersion(%q)[%d] = %d, want %d", test.version, i, v, test.expected[i])
break
}
}
}
}
func TestCompareVersions(t *testing.T) {
tests := []struct {
v1 string
v2 string
expected int
}{
{"v1.0.0", "v1.0.1", -1},
{"v1.0.1", "v1.0.0", 1},
{"v1.0.0", "v1.0.0", 0},
{"1.2.3", "1.2.4", -1},
{"2.0.0", "1.9.9", 1},
{"1.2.3-beta", "1.2.3", 0}, // Should ignore suffixes
{"1.2.3", "1.2.3-rc1", 0},
}
for _, test := range tests {
result := compareVersions(test.v1, test.v2)
if result != test.expected {
t.Errorf("compareVersions(%q, %q) = %d, want %d", test.v1, test.v2, result, test.expected)
}
}
}