feat: add host actions, lifecycle hooks and operational tools
This commit is contained in:
1 parent
8d4915543e
commit
e5bde9c61f
32 files changed
+2083
-64
No files matched your search
@@ -0,0 +1,94 @@
|
||||
// Package activity stores local preferences and optional execution metadata.
|
||||
// No command arguments, environment variables, tokens or command output are logged.
|
||||
package activity
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
type Record struct {
|
||||
Time time.Time `json:"time"`
|
||||
Host string `json:"host"`
|
||||
Command string `json:"command"`
|
||||
Code int `json:"exit_code"`
|
||||
Duration time.Duration `json:"duration_ns"`
|
||||
}
|
||||
type State struct {
|
||||
Favorites map[string]bool `json:"favorites,omitempty"`
|
||||
Pinned map[string]bool `json:"pinned,omitempty"`
|
||||
Records []Record `json:"records,omitempty"`
|
||||
}
|
||||
|
||||
func Path() string { return filepath.Join(filepath.Dir(config.Path()), "netssh", "activity.json") }
|
||||
func Read() (State, error) {
|
||||
var s State
|
||||
data, err := os.ReadFile(Path())
|
||||
if os.IsNotExist(err) {
|
||||
err = nil
|
||||
} else if err == nil {
|
||||
err = json.Unmarshal(data, &s)
|
||||
}
|
||||
if s.Favorites == nil {
|
||||
s.Favorites = map[string]bool{}
|
||||
}
|
||||
if s.Pinned == nil {
|
||||
s.Pinned = map[string]bool{}
|
||||
}
|
||||
return s, err
|
||||
}
|
||||
func Update(change func(*State)) error {
|
||||
p := Path()
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
if err = unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
|
||||
return err
|
||||
}
|
||||
defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
|
||||
s, err := Read()
|
||||
if err != nil {
|
||||
return fmt.Errorf("local state: %w", err)
|
||||
}
|
||||
change(&s)
|
||||
data, err := json.MarshalIndent(s, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return storage.WriteFile(p, data, 0600)
|
||||
}
|
||||
func Prune(s *State, c config.ActivityConfig) {
|
||||
if c.RetentionDays > 0 {
|
||||
cutoff := time.Now().Add(-time.Duration(c.RetentionDays) * 24 * time.Hour)
|
||||
keep := s.Records[:0]
|
||||
for _, r := range s.Records {
|
||||
if !r.Time.Before(cutoff) {
|
||||
keep = append(keep, r)
|
||||
}
|
||||
}
|
||||
s.Records = keep
|
||||
}
|
||||
sort.SliceStable(s.Records, func(i, j int) bool { return s.Records[i].Time.Before(s.Records[j].Time) })
|
||||
if c.MaxEntries > 0 && len(s.Records) > c.MaxEntries {
|
||||
s.Records = s.Records[len(s.Records)-c.MaxEntries:]
|
||||
}
|
||||
}
|
||||
func Append(c config.ActivityConfig, r Record) error {
|
||||
if !c.Enabled {
|
||||
return nil
|
||||
}
|
||||
return Update(func(s *State) { s.Records = append(s.Records, r); Prune(s, c) })
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package activity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
)
|
||||
|
||||
func TestConcurrentActivityAndRetention(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
cfg := config.ActivityConfig{Enabled: true, RetentionDays: 1, MaxEntries: 10}
|
||||
if err := Update(func(s *State) {
|
||||
s.Favorites["prod/web"] = true
|
||||
s.Pinned["prod/web"] = true
|
||||
s.Records = []Record{{Time: time.Now().Add(-48 * time.Hour), Host: "old"}}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if err := Append(cfg, Record{Time: time.Now(), Host: fmt.Sprint(i), Command: "test"}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
s, err := Read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Records) != 10 || !s.Favorites["prod/web"] || !s.Pinned["prod/web"] {
|
||||
t.Fatalf("%+v", s)
|
||||
}
|
||||
for _, r := range s.Records {
|
||||
if r.Host == "old" {
|
||||
t.Fatal("expired record retained")
|
||||
}
|
||||
}
|
||||
info, _ := os.Stat(Path())
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Fatal(info.Mode())
|
||||
}
|
||||
}
|
||||
func TestDisabledHistoryDoesNotWrite(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
if err := Append(config.ActivityConfig{}, Record{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(Path()); !os.IsNotExist(err) {
|
||||
t.Fatal("disabled history wrote data")
|
||||
}
|
||||
}
|
||||
Vendored
+1
@@ -17,6 +17,7 @@ import (
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
Resolver string `json:"resolver,omitempty"`
|
||||
Name string `json:"name"`
|
||||
IP string `json:"ip"`
|
||||
Kind string `json:"kind"`
|
||||
|
||||
@@ -4,10 +4,15 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HostCommand defines a local command and the prefix of its generated host aliases.
|
||||
type HostCommand struct {
|
||||
PostRun string `mapstructure:"post_run"`
|
||||
Match SSHMatch `mapstructure:"match"`
|
||||
Confirm bool `mapstructure:"confirm"`
|
||||
Timeout string `mapstructure:"timeout"`
|
||||
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
|
||||
Args []string `mapstructure:"args" yaml:"args"`
|
||||
}
|
||||
@@ -15,6 +20,20 @@ type HostCommand struct {
|
||||
func (c *Config) ValidateCommands() error {
|
||||
prefixes := make(map[string]bool)
|
||||
for name, command := range c.Commands {
|
||||
if strings.ContainsRune(command.PostRun, 0) {
|
||||
return fmt.Errorf("commands.%s.post_run contains NUL", name)
|
||||
}
|
||||
if command.Match != (SSHMatch{}) {
|
||||
if err := command.Match.Validate("commands." + name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if command.Timeout != "" {
|
||||
d, err := time.ParseDuration(command.Timeout)
|
||||
if err != nil || d <= 0 {
|
||||
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
|
||||
}
|
||||
}
|
||||
if name == "" || ValidateCommandAlias(name) != nil {
|
||||
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
TUI TUIConfig `mapstructure:"tui"`
|
||||
Activity ActivityConfig `mapstructure:"activity"`
|
||||
Commands map[string]HostCommand `mapstructure:"commands"`
|
||||
Shell ShellConfig `mapstructure:"shell"`
|
||||
NetBox NetBoxConfig `mapstructure:"netbox"`
|
||||
@@ -113,6 +115,9 @@ func Load() (*Config, error) {
|
||||
v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"})
|
||||
v.SetDefault("resolver.management_subnets", []string{})
|
||||
v.SetDefault("cache.ttl", 3600)
|
||||
v.SetDefault("tui.history_limit", 10)
|
||||
v.SetDefault("activity.retention_days", 30)
|
||||
v.SetDefault("activity.max_entries", 1000)
|
||||
|
||||
configDir, err := os.UserConfigDir()
|
||||
if err == nil {
|
||||
@@ -126,7 +131,7 @@ func Load() (*Config, error) {
|
||||
v.SetEnvPrefix("NETSSH")
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AutomaticEnv()
|
||||
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
|
||||
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
|
||||
if err := v.BindEnv(key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -172,6 +177,9 @@ func Load() (*Config, error) {
|
||||
if err := cfg.ValidateHosts(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.ValidateOperations(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := cfg.ValidateCommands(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type TUIConfig struct {
|
||||
HistoryLimit int `mapstructure:"history_limit"`
|
||||
}
|
||||
type ActivityConfig struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
RetentionDays int `mapstructure:"retention_days"`
|
||||
MaxEntries int `mapstructure:"max_entries"`
|
||||
}
|
||||
|
||||
func (c *Config) ValidateOperations() error {
|
||||
if c.TUI.HistoryLimit < 0 {
|
||||
return fmt.Errorf("tui.history_limit must be >= 0 (0 = all)")
|
||||
}
|
||||
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
|
||||
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
|
||||
func (c HostCommand) Allowed(host SSHHost) bool { return c.Match.Matches(host) }
|
||||
func HookCommand(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if strings.EqualFold(s, "none") {
|
||||
return ""
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOperationsDefaultsEnvironmentAndValidation(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte("hosts:\n - name: router\n address: 192.0.2.1\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.TUI.HistoryLimit != 10 || cfg.Activity.Enabled || cfg.Activity.RetentionDays != 30 || cfg.Activity.MaxEntries != 1000 {
|
||||
t.Fatalf("%+v %+v", cfg.TUI, cfg.Activity)
|
||||
}
|
||||
t.Setenv("NETSSH_TUI_HISTORY_LIMIT", "25")
|
||||
t.Setenv("NETSSH_SSH_POST_DISCONNECT", "echo done")
|
||||
cfg, err = Load()
|
||||
if err != nil || cfg.TUI.HistoryLimit != 25 || cfg.SSH.PostDisconnect != "echo done" {
|
||||
t.Fatalf("%+v %v", cfg, err)
|
||||
}
|
||||
cfg.TUI.HistoryLimit = -1
|
||||
if cfg.ValidateOperations() == nil {
|
||||
t.Fatal("negative history accepted")
|
||||
}
|
||||
for _, timeout := range []string{"-1s", "0s", "invalid"} {
|
||||
cfg.Commands = map[string]HostCommand{"check": {Args: []string{"echo", "{host}"}, Timeout: timeout}}
|
||||
if cfg.ValidateCommands() == nil {
|
||||
t.Fatalf("accepted %q", timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestPostDisconnectLayering(t *testing.T) {
|
||||
cfg := Config{
|
||||
SSH: SSHConfig{SSHOptions: SSHOptions{PostDisconnect: "global"}, Rules: []SSHRule{{Match: SSHMatch{Tag: "lab"}, SSHOptions: SSHOptions{PostDisconnect: "none"}}}},
|
||||
NetBoxes: []NetBoxConfig{{Name: "prod", SSH: SSHOptions{PostDisconnect: "instance"}}},
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
host SSHHost
|
||||
want string
|
||||
}{
|
||||
{SSHHost{Name: "web"}, "global"},
|
||||
{SSHHost{Name: "web", Instance: "prod"}, "instance"},
|
||||
{SSHHost{Name: "web", Instance: "prod", Tags: []string{"lab"}}, ""},
|
||||
} {
|
||||
if got := HookCommand(cfg.SSHOptionsFor(tc.host).PostDisconnect); got != tc.want {
|
||||
t.Fatalf("%q want %q", got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,8 @@ type SSHOptions struct {
|
||||
Forwards map[string]Forward `mapstructure:"forwards"`
|
||||
// PreConnect is a shell command run locally before connecting; a non-zero
|
||||
// exit aborts the connection. "none" disables a hook set by a broader layer.
|
||||
PreConnect string `mapstructure:"pre_connect"`
|
||||
PreConnect string `mapstructure:"pre_connect"`
|
||||
PostDisconnect string `mapstructure:"post_disconnect"`
|
||||
}
|
||||
|
||||
// PreConnectNone disables an inherited pre_connect hook.
|
||||
@@ -170,6 +171,9 @@ func (o SSHOptions) Validate(scope string) error {
|
||||
return fmt.Errorf("%s.options: invalid option %q", scope, key)
|
||||
}
|
||||
}
|
||||
if strings.ContainsRune(o.PostDisconnect, 0) {
|
||||
return fmt.Errorf("%s.post_disconnect must not contain NUL bytes", scope)
|
||||
}
|
||||
if strings.ContainsRune(o.PreConnect, 0) {
|
||||
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
|
||||
}
|
||||
@@ -239,6 +243,9 @@ func (o SSHOptions) merge(override SSHOptions) SSHOptions {
|
||||
if override.AddressFamily != "" {
|
||||
out.AddressFamily = override.AddressFamily
|
||||
}
|
||||
if strings.TrimSpace(override.PostDisconnect) != "" {
|
||||
out.PostDisconnect = override.PostDisconnect
|
||||
}
|
||||
if strings.TrimSpace(override.PreConnect) != "" {
|
||||
out.PreConnect = override.PreConnect
|
||||
}
|
||||
|
||||
@@ -165,6 +165,15 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
|
||||
// Build from the final SSH aliases, preserving per-instance prefix and
|
||||
// collision handling. Never replace an existing SSH or command alias.
|
||||
hostAliases := append([]AliasEntry(nil), out...)
|
||||
hostMetadata := map[string]config.SSHHost{}
|
||||
for _, e := range entries {
|
||||
instance, hostname, ok := strings.Cut(e.Name, "/")
|
||||
if !ok {
|
||||
hostname = instance
|
||||
instance = ""
|
||||
}
|
||||
hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags}
|
||||
}
|
||||
var commands []string
|
||||
for name := range cfg.Commands {
|
||||
commands = append(commands, name)
|
||||
@@ -181,6 +190,9 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
|
||||
if host.Host == "" {
|
||||
continue
|
||||
}
|
||||
if !cfg.Commands[name].Allowed(hostMetadata[host.Host]) {
|
||||
continue
|
||||
}
|
||||
alias := prefix + host.Name
|
||||
commandCounts[alias]++
|
||||
candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name})
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package netbox
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SearchOptions filters a Search or SearchAll query.
|
||||
// Zero value means no filtering (return all kinds, no tag filter).
|
||||
@@ -13,6 +16,9 @@ type SearchOptions struct {
|
||||
|
||||
// HostEntry is a unified model for both devices and virtual machines from NetBox.
|
||||
type HostEntry struct {
|
||||
Cached bool
|
||||
CachedAt time.Time
|
||||
Static bool
|
||||
Source string // named NetBox instance; empty for the legacy single-instance config
|
||||
ID int
|
||||
Name string
|
||||
|
||||
@@ -28,19 +28,24 @@ func New(cfg config.ResolverConfig) (*Chain, error) {
|
||||
}
|
||||
|
||||
func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) {
|
||||
address, _, err := c.ResolveWithStrategy(ctx, entry, client)
|
||||
return address, err
|
||||
}
|
||||
|
||||
func (c *Chain) ResolveWithStrategy(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, string, error) {
|
||||
for _, s := range c.strategies {
|
||||
ip, err := s.Resolve(ctx, entry, client)
|
||||
if err == nil {
|
||||
return ip, nil
|
||||
return ip, s.Name(), nil
|
||||
}
|
||||
// Only "this strategy has no address" moves on. After an API failure
|
||||
// the next strategy would connect to (and cache) a different address
|
||||
// than the configured order asks for.
|
||||
if !errors.Is(err, ErrNoIP) {
|
||||
return "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err)
|
||||
return "", "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err)
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
|
||||
return "", "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
|
||||
}
|
||||
|
||||
func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Package runner supervises local commands while retaining terminal I/O.
|
||||
package runner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/x/term"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
Stdin io.Reader
|
||||
Stdout, Stderr io.Writer
|
||||
Env []string
|
||||
Timeout time.Duration
|
||||
Status bool
|
||||
Label string
|
||||
}
|
||||
type Result struct {
|
||||
Code int
|
||||
Started bool
|
||||
Duration time.Duration
|
||||
}
|
||||
|
||||
func Run(ctx context.Context, argv []string, o Options) Result {
|
||||
if o.Stderr == nil {
|
||||
o.Stderr = io.Discard
|
||||
}
|
||||
if o.Stdout == nil {
|
||||
o.Stdout = io.Discard
|
||||
}
|
||||
start := time.Now()
|
||||
result := Result{Code: 1}
|
||||
if ctx.Err() != nil {
|
||||
result.Code = 130
|
||||
return result
|
||||
}
|
||||
if len(argv) == 0 {
|
||||
return result
|
||||
}
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr
|
||||
cmd.Env = append(os.Environ(), o.Env...)
|
||||
interactive := false
|
||||
if f, ok := o.Stdin.(*os.File); ok {
|
||||
interactive = term.IsTerminal(f.Fd())
|
||||
}
|
||||
// Interactive SSH must share the foreground terminal process group.
|
||||
// Background jobs get an isolated group so cancellation reaches descendants.
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: !interactive}
|
||||
if err := cmd.Start(); err != nil {
|
||||
fmt.Fprintf(o.Stderr, "%s: %v\n", argv[0], err)
|
||||
return result
|
||||
}
|
||||
result.Started = true
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
sigs := make(chan os.Signal, 4)
|
||||
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
|
||||
defer signal.Stop(sigs)
|
||||
var timeout <-chan time.Time
|
||||
if o.Timeout > 0 {
|
||||
timer := time.NewTimer(o.Timeout)
|
||||
defer timer.Stop()
|
||||
timeout = timer.C
|
||||
}
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
var killTimer *time.Timer
|
||||
var kill <-chan time.Time
|
||||
defer func() {
|
||||
if killTimer != nil {
|
||||
killTimer.Stop()
|
||||
}
|
||||
}()
|
||||
send := func(sig syscall.Signal) {
|
||||
if interactive {
|
||||
_ = cmd.Process.Signal(sig)
|
||||
} else {
|
||||
_ = syscall.Kill(-cmd.Process.Pid, sig)
|
||||
}
|
||||
}
|
||||
forced := 0
|
||||
cancelCh := ctx.Done()
|
||||
stop := func(code int, sig syscall.Signal) {
|
||||
if forced != 0 {
|
||||
return
|
||||
}
|
||||
forced = code
|
||||
send(sig)
|
||||
killTimer = time.NewTimer(2 * time.Second)
|
||||
kill = killTimer.C
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case err := <-done:
|
||||
result.Duration = time.Since(start)
|
||||
result.Code = 0
|
||||
if err != nil {
|
||||
result.Code = 1
|
||||
if e, ok := err.(*exec.ExitError); ok {
|
||||
result.Code = e.ExitCode()
|
||||
if s, ok := e.Sys().(syscall.WaitStatus); ok && s.Signaled() {
|
||||
result.Code = 128 + int(s.Signal())
|
||||
}
|
||||
}
|
||||
}
|
||||
if forced != 0 {
|
||||
result.Code = forced
|
||||
}
|
||||
// Kill descendants left behind after cancellation even if the parent exited.
|
||||
if forced != 0 && !interactive {
|
||||
send(syscall.SIGKILL)
|
||||
}
|
||||
if o.Status {
|
||||
fmt.Fprintf(o.Stderr, "[%s] finished in %s (exit %d)\n", o.Label, result.Duration.Round(time.Millisecond), result.Code)
|
||||
}
|
||||
return result
|
||||
case sig := <-sigs:
|
||||
s := sig.(syscall.Signal)
|
||||
if interactive && (s == syscall.SIGINT || s == syscall.SIGQUIT) {
|
||||
continue
|
||||
} // terminal delivered it to child too
|
||||
stop(128+int(s), s)
|
||||
case <-cancelCh:
|
||||
cancelCh = nil
|
||||
stop(130, syscall.SIGTERM)
|
||||
case <-timeout:
|
||||
timeout = nil
|
||||
stop(124, syscall.SIGTERM)
|
||||
case <-kill:
|
||||
kill = nil
|
||||
send(syscall.SIGKILL)
|
||||
case <-ticker.C:
|
||||
if o.Status {
|
||||
fmt.Fprintf(o.Stderr, "[%s] running %s (Ctrl+C cancels)\n", o.Label, time.Since(start).Round(time.Second))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package runner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExitAndTimeout(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
r := Run(context.Background(), []string{"sh", "-c", "printf result; exit 7"}, Options{Stdout: &out, Stderr: io.Discard})
|
||||
if !r.Started || r.Code != 7 || out.String() != "result" {
|
||||
t.Fatalf("%+v %q", r, out.String())
|
||||
}
|
||||
start := time.Now()
|
||||
r = Run(context.Background(), []string{"sh", "-c", "trap '' TERM; sleep 30 & wait"}, Options{Stdout: io.Discard, Stderr: io.Discard, Timeout: 50 * time.Millisecond})
|
||||
if r.Code != 124 || time.Since(start) > 4*time.Second {
|
||||
t.Fatalf("timeout: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestCancellationAndNoStart(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
r := Run(ctx, []string{"sh", "-c", "exit 0"}, Options{Stderr: io.Discard})
|
||||
if r.Started || r.Code != 130 {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
var errOut bytes.Buffer
|
||||
r = Run(context.Background(), []string{"/no/such/netssh-test-executable"}, Options{Stderr: &errOut})
|
||||
if r.Started || r.Code == 0 || !strings.Contains(errOut.String(), "no such") {
|
||||
t.Fatalf("%+v %s", r, errOut.String())
|
||||
}
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
time.AfterFunc(50*time.Millisecond, cancel)
|
||||
r = Run(ctx, []string{"sh", "-c", "sleep 30"}, Options{Stdout: io.Discard, Stderr: io.Discard})
|
||||
if r.Code != 130 {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,13 @@ func editCommands(cfg *config.Config) error {
|
||||
huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix),
|
||||
huh.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary),
|
||||
huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments),
|
||||
huh.NewConfirm().Title("Confirm before running?").Value(&command.Confirm),
|
||||
huh.NewInput().Title("Timeout").Description("Optional positive duration, e.g. 30s or 5m.").Value(&command.Timeout),
|
||||
huh.NewInput().Title("Post-run script").Description("Local command after completion; receives NETSSH_EXIT_CODE.").Value(&command.PostRun),
|
||||
huh.NewInput().Title("Only for tag").Value(&command.Match.Tag),
|
||||
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
|
||||
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
|
||||
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
|
||||
).Title("Local command")).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package setup
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"charm.land/huh/v2"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
)
|
||||
|
||||
func editOperations(cfg *config.Config) error {
|
||||
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
|
||||
enabled := cfg.Activity.Enabled
|
||||
valid := func(s string) error {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 0 {
|
||||
return fmt.Errorf("enter a non-negative number")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err := huh.NewForm(huh.NewGroup(
|
||||
huh.NewInput().Title("Recent hosts shown").Description("10 by default; 0 shows all. Favorites are additional.").Value(&history).Validate(valid),
|
||||
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
|
||||
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
|
||||
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
|
||||
).Title("History & activity")).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
|
||||
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
|
||||
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
|
||||
cfg.Activity.Enabled = enabled
|
||||
return nil
|
||||
}
|
||||
@@ -24,6 +24,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
|
||||
options := formatOptions(o.Options)
|
||||
forwards := formatForwards(o.Forwards)
|
||||
preConnect := o.PreConnect
|
||||
postDisconnect := o.PostDisconnect
|
||||
|
||||
err := huh.NewForm(huh.NewGroup(
|
||||
huh.NewInput().
|
||||
@@ -70,6 +71,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
|
||||
_, err := parseForwards(s)
|
||||
return err
|
||||
}),
|
||||
huh.NewInput().Title("Post-disconnect script").Description("Local command after the client exits; none disables inheritance.").Value(&postDisconnect),
|
||||
huh.NewInput().
|
||||
Title("Pre-connect hook").
|
||||
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
|
||||
@@ -94,6 +96,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
|
||||
ExtraArgs: parseLines(extraArgs),
|
||||
Options: parsed,
|
||||
PreConnect: strings.TrimSpace(preConnect),
|
||||
PostDisconnect: strings.TrimSpace(postDisconnect),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -95,6 +95,7 @@ func runMenu(cfg *config.Config) error {
|
||||
huh.NewOption("Resolver & cache", "resolver"),
|
||||
huh.NewOption("Shortcuts & command alias", "shortcuts"),
|
||||
huh.NewOption("Custom commands — mtr, ping, scripts", "commands"),
|
||||
huh.NewOption("History & activity logging", "operations"),
|
||||
huh.NewOption("Completion", "completion"),
|
||||
huh.NewOption("Save and exit", "save"),
|
||||
).
|
||||
@@ -125,6 +126,8 @@ func runMenu(cfg *config.Config) error {
|
||||
err = editShortcuts(cfg)
|
||||
case "commands":
|
||||
err = editCommands(cfg)
|
||||
case "operations":
|
||||
err = editOperations(cfg)
|
||||
case "completion":
|
||||
err = editCompletion(cfg)
|
||||
case "save":
|
||||
@@ -382,6 +385,9 @@ func save(cfg config.Config) error {
|
||||
if err := cfg.ValidateHosts(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cfg.ValidateOperations(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cfg.ValidateCommands(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -552,9 +558,19 @@ func save(cfg config.Config) error {
|
||||
for _, arg := range command.Args {
|
||||
fmt.Fprintf(&b, " - %q\n", arg)
|
||||
}
|
||||
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
|
||||
if command.Match != (config.SSHMatch{}) {
|
||||
b.WriteString(" match:\n")
|
||||
for _, pair := range [][2]string{{"tag", command.Match.Tag}, {"instance", command.Match.Instance}, {"kind", command.Match.Kind}, {"name", command.Match.Name}} {
|
||||
if pair[1] != "" {
|
||||
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\nactivity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.TUI.HistoryLimit, cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
|
||||
if cfg.Shell.Alias != "" {
|
||||
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
|
||||
}
|
||||
@@ -568,12 +584,12 @@ func save(cfg config.Config) error {
|
||||
}
|
||||
|
||||
func sshOptionsEmpty(o config.SSHOptions) bool {
|
||||
return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 && o.PreConnect == ""
|
||||
return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 && o.PreConnect == "" && o.PostDisconnect == ""
|
||||
}
|
||||
|
||||
// writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config.
|
||||
func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
|
||||
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}} {
|
||||
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}, {"post_disconnect", o.PostDisconnect}} {
|
||||
if field[1] != "" {
|
||||
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
|
||||
}
|
||||
|
||||
@@ -698,3 +698,24 @@ func TestSaveCommandsRoundTrip(t *testing.T) {
|
||||
t.Fatalf("commands lost: %+v", got.Commands)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsRoundTrip(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
cfg := config.Config{
|
||||
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "token"},
|
||||
TUI: config.TUIConfig{HistoryLimit: 25},
|
||||
Activity: config.ActivityConfig{Enabled: true, RetentionDays: 7, MaxEntries: 50},
|
||||
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PostDisconnect: "echo done"}, Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "lab"}, SSHOptions: config.SSHOptions{PostDisconnect: "none"}}}},
|
||||
Commands: map[string]config.HostCommand{"mtr": {Args: []string{"mtr", "{address}"}, AliasPrefix: "m", Timeout: "10s", Confirm: true, PostRun: "echo done", Match: config.SSHMatch{Tag: "router", Instance: "prod"}}},
|
||||
}
|
||||
if err := save(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TUI != cfg.TUI || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
|
||||
t.Fatalf("round trip lost operations: %+v", got)
|
||||
}
|
||||
}
|
||||
+188
-14
@@ -22,6 +22,7 @@ import (
|
||||
|
||||
// SelectedHost is returned when the user confirms a host in the TUI.
|
||||
type SelectedHost struct {
|
||||
Command string
|
||||
Kind string
|
||||
Name string
|
||||
IP string
|
||||
@@ -63,13 +64,15 @@ type searchResultMsg struct {
|
||||
// --- list item ---
|
||||
|
||||
type hostItem struct {
|
||||
label string // display only; name remains the canonical target
|
||||
alias string // shortcut alias shown next to the name (shortcuts.show)
|
||||
name string
|
||||
id int
|
||||
ip string
|
||||
kind string
|
||||
tags []string
|
||||
provenance string
|
||||
favorite, pinned bool
|
||||
label string // display only; name remains the canonical target
|
||||
alias string // shortcut alias shown next to the name (shortcuts.show)
|
||||
name string
|
||||
id int
|
||||
ip string
|
||||
kind string
|
||||
tags []string
|
||||
}
|
||||
|
||||
func (h hostItem) Title() string {
|
||||
@@ -102,7 +105,16 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
|
||||
if h.alias != "" {
|
||||
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+h.alias)
|
||||
}
|
||||
line := fmt.Sprintf(" %s%s %s", mark, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
|
||||
badge := ""
|
||||
if h.pinned {
|
||||
badge = "◆ "
|
||||
} else if h.favorite {
|
||||
badge = "★ "
|
||||
}
|
||||
line := fmt.Sprintf(" %s%s %s", mark+badge, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
|
||||
if h.provenance != "" {
|
||||
line += " [" + h.provenance + "]"
|
||||
}
|
||||
if index == m.Index() {
|
||||
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
|
||||
}
|
||||
@@ -161,6 +173,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
|
||||
// --- Model ---
|
||||
|
||||
type Model struct {
|
||||
historyLimit int
|
||||
favorites, pinned map[string]bool
|
||||
savePreferences func(map[string]bool, map[string]bool) error
|
||||
commandsFor func(string, string, []string) []string
|
||||
actionHost *hostItem
|
||||
actionNames []string
|
||||
actionIndex int
|
||||
|
||||
noteErr error
|
||||
editHost *hostItem
|
||||
noteInput textarea.Model
|
||||
@@ -229,6 +249,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
|
||||
ni.CharLimit = 0
|
||||
ni.SetHeight(10)
|
||||
return &Model{
|
||||
historyLimit: 10, favorites: map[string]bool{}, pinned: map[string]bool{},
|
||||
noteInput: ni,
|
||||
defaultPort: port,
|
||||
input: ti,
|
||||
@@ -250,14 +271,40 @@ func (m *Model) Init() tea.Cmd {
|
||||
|
||||
// loadRecent returns a Cmd that immediately resolves to the recently-used host list.
|
||||
func (m *Model) loadRecent() tea.Cmd {
|
||||
favoriteNames, pinned, limit := copyBools(m.favorites), copyBools(m.pinned), m.historyLimit
|
||||
return func() tea.Msg {
|
||||
if m.cache == nil {
|
||||
return searchResultMsg{query: "", entries: nil, recent: true}
|
||||
}
|
||||
recent := m.cache.RecentlyUsed(10)
|
||||
recent := m.cache.RecentlyUsed(limit)
|
||||
seen := map[string]bool{}
|
||||
var favorites []cache.Entry
|
||||
for name, enabled := range favoriteNames {
|
||||
if !enabled {
|
||||
continue
|
||||
}
|
||||
e, _ := m.cache.Get(name)
|
||||
if e.Name == "" {
|
||||
e.Name = name
|
||||
}
|
||||
favorites = append(favorites, e)
|
||||
seen[name] = true
|
||||
}
|
||||
sort.Slice(favorites, func(i, j int) bool {
|
||||
if pinned[favorites[i].Name] != pinned[favorites[j].Name] {
|
||||
return pinned[favorites[i].Name]
|
||||
}
|
||||
return favorites[i].Name < favorites[j].Name
|
||||
})
|
||||
for _, e := range recent {
|
||||
if !seen[e.Name] {
|
||||
favorites = append(favorites, e)
|
||||
}
|
||||
}
|
||||
recent = favorites
|
||||
entries := make([]netbox.HostEntry, len(recent))
|
||||
for i, e := range recent {
|
||||
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags}
|
||||
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cached: true, CachedAt: e.CachedAt, Static: e.Static}
|
||||
}
|
||||
return searchResultMsg{query: "", entries: entries, recent: true}
|
||||
}
|
||||
@@ -294,6 +341,34 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if msg.String() == "ctrl+c" {
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
if m.actionHost != nil {
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
m.actionHost = nil
|
||||
case "up":
|
||||
if m.actionIndex > 0 {
|
||||
m.actionIndex--
|
||||
}
|
||||
case "down":
|
||||
if m.actionIndex+1 < len(m.actionNames) {
|
||||
m.actionIndex++
|
||||
}
|
||||
case "enter":
|
||||
h := m.actionHost
|
||||
if m.actionIndex == 0 {
|
||||
if len(m.markOrder) > 0 {
|
||||
m.selected = &SelectedHost{Action: ActionMulti, Targets: append([]string(nil), m.markOrder...)}
|
||||
} else {
|
||||
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip}
|
||||
}
|
||||
} else {
|
||||
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip, Command: m.actionNames[m.actionIndex], Targets: append([]string(nil), m.markOrder...)}
|
||||
}
|
||||
return m, tea.Quit
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
if m.noteMode {
|
||||
if m.noteBusy {
|
||||
return m, nil
|
||||
@@ -403,6 +478,43 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
case "ctrl+c", "esc":
|
||||
return m, tea.Quit
|
||||
|
||||
case "ctrl+r":
|
||||
if h, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
m.actionHost = &h
|
||||
m.actionIndex = 0
|
||||
m.actionNames = []string{"SSH"}
|
||||
if m.commandsFor != nil {
|
||||
m.actionNames = append(m.actionNames, m.commandsFor(h.name, h.kind, h.tags)...)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
case "ctrl+d", "ctrl+p":
|
||||
if h, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
favorites, pinned := copyBools(m.favorites), copyBools(m.pinned)
|
||||
if msg.String() == "ctrl+p" {
|
||||
pinned[h.name] = !pinned[h.name]
|
||||
if pinned[h.name] {
|
||||
favorites[h.name] = true
|
||||
}
|
||||
} else {
|
||||
favorites[h.name] = !favorites[h.name]
|
||||
if !favorites[h.name] {
|
||||
delete(pinned, h.name)
|
||||
}
|
||||
}
|
||||
if m.savePreferences != nil {
|
||||
if err := m.savePreferences(favorites, pinned); err != nil {
|
||||
m.err = err
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
m.favorites, m.pinned = favorites, pinned
|
||||
m.updateListItems(m.lastResults)
|
||||
if m.recentMode && m.input.Value() == "" {
|
||||
return m, m.loadRecent()
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
case "ctrl+f":
|
||||
m.filterOpen = true
|
||||
m.input.Blur()
|
||||
@@ -563,6 +675,24 @@ func (m *Model) View() tea.View {
|
||||
}
|
||||
|
||||
func (m *Model) viewContent() string {
|
||||
if m.actionHost != nil {
|
||||
var out strings.Builder
|
||||
fmt.Fprintf(&out, "Action for %s", m.actionHost.Title())
|
||||
if len(m.markOrder) > 0 {
|
||||
fmt.Fprintf(&out, " (%d marked hosts)", len(m.markOrder))
|
||||
}
|
||||
out.WriteString("\n\n")
|
||||
for i, n := range m.actionNames {
|
||||
marker := " "
|
||||
if i == m.actionIndex {
|
||||
marker = "> "
|
||||
}
|
||||
fmt.Fprintf(&out, "%s%s\n", marker, n)
|
||||
}
|
||||
out.WriteString("\n↑/↓ select enter run esc cancel\n")
|
||||
return out.String()
|
||||
}
|
||||
|
||||
if m.noteMode {
|
||||
target := "local"
|
||||
if m.noteRemote {
|
||||
@@ -623,7 +753,7 @@ func (m *Model) viewContent() string {
|
||||
sb.WriteString(m.editInput.View() + "\n")
|
||||
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n")
|
||||
} else {
|
||||
hint := "ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox"
|
||||
hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox"
|
||||
if n := len(m.markOrder); n > 0 {
|
||||
hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n)
|
||||
}
|
||||
@@ -652,7 +782,7 @@ func (m *Model) doSearch(query string, seq int) tea.Cmd {
|
||||
if m.cache != nil {
|
||||
for _, entry := range m.cache.Search(query) {
|
||||
source, name := netbox.SplitTarget(entry.Name)
|
||||
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags})
|
||||
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags, Cached: true, CachedAt: entry.CachedAt, Static: entry.Static})
|
||||
}
|
||||
}
|
||||
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
|
||||
@@ -689,7 +819,19 @@ func (m *Model) netboxSearchOpts() netbox.SearchOptions {
|
||||
// updateListItems applies the active filter and sets the list items.
|
||||
func (m *Model) updateListItems(entries []netbox.HostEntry) {
|
||||
f := parseFilter(m.filterInput.Value())
|
||||
filtered := applyFilter(entries, f)
|
||||
filtered := append([]netbox.HostEntry(nil), applyFilter(entries, f)...)
|
||||
sort.SliceStable(filtered, func(i, j int) bool {
|
||||
rank := func(e netbox.HostEntry) int {
|
||||
if m.pinned[e.Target()] {
|
||||
return 2
|
||||
}
|
||||
if m.favorites[e.Target()] {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
return rank(filtered[i]) > rank(filtered[j])
|
||||
})
|
||||
items := make([]list.Item, len(filtered))
|
||||
labels := make([]string, len(filtered))
|
||||
counts := make(map[string]int, len(filtered))
|
||||
@@ -718,7 +860,23 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
|
||||
alias = ""
|
||||
}
|
||||
}
|
||||
items[i] = hostItem{label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
|
||||
provenance := "live"
|
||||
if e.Static {
|
||||
provenance = "static"
|
||||
} else if e.Cached {
|
||||
if e.CachedAt.IsZero() {
|
||||
provenance = "saved host; resolve on connect"
|
||||
} else {
|
||||
age := max(time.Duration(0), time.Since(e.CachedAt)).Round(time.Second)
|
||||
provenance = "cache " + age.String()
|
||||
if m.cache != nil {
|
||||
if _, fresh := m.cache.Get(e.Target()); !fresh {
|
||||
provenance += ", stale"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
|
||||
}
|
||||
m.list.SetItems(items)
|
||||
m.resizeList()
|
||||
@@ -866,3 +1024,19 @@ func (m *Model) SetHostLabel(format func(string) string) {
|
||||
func (m *Model) SetAliases(aliasFor func(target string) string) {
|
||||
m.aliasFor = aliasFor
|
||||
}
|
||||
|
||||
func copyBools(in map[string]bool) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for k, v := range in {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (m *Model) SetHistoryLimit(limit int) { m.historyLimit = limit }
|
||||
func (m *Model) SetPreferences(favorites, pinned map[string]bool, save func(map[string]bool, map[string]bool) error) {
|
||||
m.favorites, m.pinned = copyBools(favorites), copyBools(pinned)
|
||||
m.savePreferences = save
|
||||
}
|
||||
func (m *Model) SetCommands(commands func(string, string, []string) []string) {
|
||||
m.commandsFor = commands
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
func TestFavoritesHistoryAndActions(t *testing.T) {
|
||||
c := cache.New("", 3600)
|
||||
for _, name := range []string{"a", "b", "pinned"} {
|
||||
c.Upsert(cache.Entry{Name: name, IP: "10.0.0.1", Kind: "device"})
|
||||
c.MarkUsed(name)
|
||||
}
|
||||
m := New(nil, c, "")
|
||||
m.SetHistoryLimit(1)
|
||||
m.SetPreferences(map[string]bool{"pinned": true, "offline/missing": true}, map[string]bool{"pinned": true}, nil)
|
||||
msg := m.loadRecent()().(searchResultMsg)
|
||||
if len(msg.entries) < 2 || msg.entries[0].Target() != "pinned" {
|
||||
t.Fatalf("%+v", msg.entries)
|
||||
}
|
||||
m.Update(msg)
|
||||
m.Update(tea.WindowSizeMsg{Width: 160, Height: 30})
|
||||
if !strings.Contains(m.View().Content, "◆") || !strings.Contains(m.View().Content, "cache") {
|
||||
t.Fatal(m.View().Content)
|
||||
}
|
||||
m.SetCommands(func(name, kind string, tags []string) []string { return []string{"mtr"} })
|
||||
m.Update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyDown})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.Selected() == nil || m.Selected().Command != "mtr" || m.Selected().Name != "pinned" {
|
||||
t.Fatalf("%+v", m.Selected())
|
||||
}
|
||||
}
|
||||
func TestHistoryLimitAndPreferencePersistence(t *testing.T) {
|
||||
c := cache.New("", 3600)
|
||||
for _, n := range []string{"a", "b", "c"} {
|
||||
c.Upsert(cache.Entry{Name: n})
|
||||
c.MarkUsed(n)
|
||||
}
|
||||
m := New(nil, c, "")
|
||||
m.SetHistoryLimit(2)
|
||||
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 2 {
|
||||
t.Fatal(got)
|
||||
}
|
||||
m.SetHistoryLimit(0)
|
||||
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 3 {
|
||||
t.Fatal(got)
|
||||
}
|
||||
saved := false
|
||||
m.SetPreferences(nil, nil, func(f, p map[string]bool) error { saved = f["prod/web"] && p["prod/web"]; return nil })
|
||||
entries := []netbox.HostEntry{{Name: "web", Source: "prod", Cached: true, CachedAt: time.Now().Add(-2 * time.Hour)}}
|
||||
m.lastResults = entries
|
||||
m.updateListItems(entries)
|
||||
m.Update(tea.KeyPressMsg{Code: 'p', Mod: tea.ModCtrl})
|
||||
if !saved {
|
||||
t.Fatal("pin not persisted")
|
||||
}
|
||||
item := m.list.Items()[0].(hostItem)
|
||||
if !strings.Contains(item.provenance, "stale") {
|
||||
t.Fatal(item.provenance)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user