v1
This commit is contained in:
commit
8d4915543e
132 files changed
+20628
No files matched your search
@@ -0,0 +1,195 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
func tuiSourceServer(t *testing.T, fail bool) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if fail {
|
||||
http.Error(w, "offline", 503)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/dcim/devices/" {
|
||||
fmt.Fprint(w, `{"count":1,"results":[{"id":1,"name":"web","primary_ip4":{"address":"10.0.0.1/24"}}]}`)
|
||||
} else {
|
||||
fmt.Fprint(w, `{"count":0,"results":[]}`)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
func TestCombinedSearchDoesNotStopAtFirstCachedInstance(t *testing.T) {
|
||||
office, lab := tuiSourceServer(t, false), tuiSourceServer(t, false)
|
||||
client := netbox.NewMultiClient([]netbox.Source{{Name: "office", URL: office.URL}, {Name: "lab", URL: lab.URL}})
|
||||
c := cache.New("", 3600)
|
||||
c.Upsert(cache.Entry{Name: "office/web", Kind: "device", IP: "10.0.0.9"})
|
||||
m := New(client, c, "")
|
||||
msg := m.doSearch("web", 1)().(searchResultMsg)
|
||||
if msg.err != nil || len(msg.entries) != 2 {
|
||||
t.Fatalf("cache hid another instance: %+v, %v", msg.entries, msg.err)
|
||||
}
|
||||
m.input.SetValue("web")
|
||||
m.seq = 1
|
||||
m.Update(msg)
|
||||
if len(m.list.Items()) != 2 {
|
||||
t.Fatal("combined results not displayed")
|
||||
}
|
||||
for _, item := range m.list.Items() {
|
||||
if !strings.Contains(item.(hostItem).name, "/") {
|
||||
t.Fatal("instance not visible in results")
|
||||
}
|
||||
}
|
||||
m.list.Select(0)
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || m.selected.Name != "lab/web" {
|
||||
t.Fatalf("selection lost source: %+v", m.selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) {
|
||||
office, lab := tuiSourceServer(t, false), tuiSourceServer(t, true)
|
||||
client := netbox.NewMultiClient([]netbox.Source{{Name: "office", URL: office.URL}, {Name: "lab", URL: lab.URL}})
|
||||
c := cache.New("", 3600)
|
||||
c.Upsert(cache.Entry{Name: "lab/web", Kind: "device", IP: "10.0.0.2"})
|
||||
m := New(client, c, "")
|
||||
m.input.SetValue("web")
|
||||
m.seq = 1
|
||||
m.Update(tea.WindowSizeMsg{Width: 100, Height: 24})
|
||||
msg := m.doSearch("web", 1)().(searchResultMsg)
|
||||
if len(msg.entries) != 2 || msg.err == nil {
|
||||
t.Fatalf("partial outage lost cache or warning: %+v, %v", msg.entries, msg.err)
|
||||
}
|
||||
m.Update(msg)
|
||||
view := m.View().Content
|
||||
if !strings.Contains(view, "warning:") || !strings.Contains(view, "lab/web") || !strings.Contains(view, "office/web") {
|
||||
t.Fatalf("partial results hidden: %s", view)
|
||||
}
|
||||
if rows := strings.Count(view, "\n"); rows > 24 {
|
||||
t.Fatalf("outage warning overflowed view: %d", rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenPrefixKeepsCanonicalTargets(t *testing.T) {
|
||||
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "OFFICE", DisablePrefix: true}, {Name: "lab"},
|
||||
}}
|
||||
for _, cached := range []bool{false, true} {
|
||||
for _, action := range []string{"ssh", "sftp", "multi", "autocomplete", "edit", "tunnel"} {
|
||||
t.Run(fmt.Sprintf("cached=%v/%s", cached, action), func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.SetHostLabel(cfg.HostLabel)
|
||||
m.Update(tea.WindowSizeMsg{Width: 100, Height: 24})
|
||||
entries := []netbox.HostEntry{
|
||||
{Source: "office", Name: "web01", PrimaryIP4: "10.0.0.1"},
|
||||
{Source: "lab", Name: "web01", PrimaryIP4: "10.0.0.2"},
|
||||
}
|
||||
if cached {
|
||||
for i := range entries {
|
||||
entries[i].Name = entries[i].Target()
|
||||
entries[i].Source = ""
|
||||
}
|
||||
}
|
||||
m.updateListItems(entries)
|
||||
item := m.list.Items()[0].(hostItem)
|
||||
if item.Title() != "web01" || item.name != "office/web01" {
|
||||
t.Fatalf("display changed identity: %+v", item)
|
||||
}
|
||||
view := m.View().Content
|
||||
if strings.Contains(view, "office/web01") || !strings.Contains(view, "lab/web01") {
|
||||
t.Fatalf("wrong rendered prefixes: %s", view)
|
||||
}
|
||||
switch action {
|
||||
case "ssh", "sftp":
|
||||
key := tea.KeyPressMsg{Code: tea.KeyEnter}
|
||||
if action == "sftp" {
|
||||
key = tea.KeyPressMsg{Code: 'o', Mod: tea.ModCtrl}
|
||||
}
|
||||
m.Update(key)
|
||||
if m.selected == nil || m.selected.Name != "office/web01" {
|
||||
t.Fatalf("lost instance: %+v", m.selected)
|
||||
}
|
||||
case "multi":
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || len(m.selected.Targets) != 1 || m.selected.Targets[0] != "office/web01" {
|
||||
t.Fatalf("multi lost instance: %+v", m.selected)
|
||||
}
|
||||
case "autocomplete":
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyTab})
|
||||
if m.input.Value() != "office/web01" {
|
||||
t.Fatal("autocomplete lost instance")
|
||||
}
|
||||
case "edit":
|
||||
m.Update(tea.KeyPressMsg{Code: 'e', Mod: tea.ModCtrl})
|
||||
if m.editHost == nil || m.editHost.name != "office/web01" {
|
||||
t.Fatal("editor lost instance")
|
||||
}
|
||||
case "tunnel":
|
||||
m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl})
|
||||
if m.forwardHost == nil || m.forwardHost.name != "office/web01" {
|
||||
t.Fatal("tunnel lost instance")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenPrefixDuplicateLabels(t *testing.T) {
|
||||
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
|
||||
{Name: "office", DisablePrefix: true}, {Name: "lab", DisablePrefix: true},
|
||||
}}
|
||||
for _, other := range []netbox.HostEntry{
|
||||
{Source: "lab", Name: "WEB"},
|
||||
{Name: "web", Kind: "static"},
|
||||
} {
|
||||
m := New(nil, nil, "")
|
||||
m.SetHostLabel(cfg.HostLabel)
|
||||
m.updateListItems([]netbox.HostEntry{{Source: "office", Name: "web"}, other})
|
||||
for _, entry := range m.list.Items() {
|
||||
item := entry.(hostItem)
|
||||
if item.Title() != item.name {
|
||||
t.Fatalf("ambiguous label: %+v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasesShownNextToHostName(t *testing.T) {
|
||||
m := New(nil, cache.New("", 3600), "")
|
||||
m.SetAliases(func(target string) string {
|
||||
return map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "web01": "web01"}[target]
|
||||
})
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "fsn1-bx1.hoster.de", PrimaryIP4: "10.0.0.1"}, {Name: "web01", PrimaryIP4: "10.0.0.2"}})
|
||||
items := m.list.Items()
|
||||
if got := items[0].(hostItem).alias; got != "fsnbx1" {
|
||||
t.Fatalf("alias = %q", got)
|
||||
}
|
||||
// An alias equal to the shown name is not repeated.
|
||||
if got := items[1].(hostItem).alias; got != "" {
|
||||
t.Fatalf("redundant alias %q", got)
|
||||
}
|
||||
var b strings.Builder
|
||||
compactDelegate{marked: map[string]bool{}}.Render(&b, m.list, 1, items[0])
|
||||
if !strings.Contains(b.String(), "fsn1-bx1.hoster.de") || !strings.Contains(b.String(), "→ fsnbx1") {
|
||||
t.Fatalf("row %q", b.String())
|
||||
}
|
||||
// Without SetAliases nothing changes.
|
||||
plain := New(nil, cache.New("", 3600), "")
|
||||
plain.updateListItems([]netbox.HostEntry{{Name: "fsn1-bx1.hoster.de"}})
|
||||
if got := plain.list.Items()[0].(hostItem).alias; got != "" {
|
||||
t.Fatalf("alias without SetAliases: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,868 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"charm.land/bubbles/v2/list"
|
||||
"charm.land/bubbles/v2/textarea"
|
||||
"charm.land/bubbles/v2/textinput"
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"charm.land/lipgloss/v2"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/notes"
|
||||
)
|
||||
|
||||
// SelectedHost is returned when the user confirms a host in the TUI.
|
||||
type SelectedHost struct {
|
||||
Kind string
|
||||
Name string
|
||||
IP string
|
||||
User string // empty = use config default
|
||||
Port string // empty = use default port
|
||||
Action string // ActionSSH, ActionSFTP, ActionTunnel, or ActionMulti
|
||||
Forwards []string // forward names or specs for ActionTunnel
|
||||
Targets []string // marked hosts for ActionMulti
|
||||
}
|
||||
|
||||
// Actions the user can start on a host.
|
||||
const (
|
||||
ActionSSH = ""
|
||||
ActionSFTP = "sftp"
|
||||
ActionTunnel = "tunnel"
|
||||
ActionMulti = "multi"
|
||||
)
|
||||
|
||||
// --- bubbletea messages ---
|
||||
|
||||
type debounceMsg struct {
|
||||
query string
|
||||
seq int
|
||||
}
|
||||
type noteResultMsg struct {
|
||||
note notes.Note
|
||||
err error
|
||||
saved bool
|
||||
}
|
||||
|
||||
type searchResultMsg struct {
|
||||
query string
|
||||
seq int
|
||||
entries []netbox.HostEntry
|
||||
err error
|
||||
recent bool // true when this is a recently-used list, not a search result
|
||||
}
|
||||
|
||||
// --- 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
|
||||
}
|
||||
|
||||
func (h hostItem) Title() string {
|
||||
if h.label != "" {
|
||||
return h.label
|
||||
}
|
||||
return h.name
|
||||
}
|
||||
func (h hostItem) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) }
|
||||
func (h hostItem) FilterValue() string { return h.name }
|
||||
|
||||
// --- compact list delegate ---
|
||||
|
||||
// compactDelegate shares the model's marks so marked hosts show a dot.
|
||||
type compactDelegate struct{ marked map[string]bool }
|
||||
|
||||
func (d compactDelegate) Height() int { return 1 }
|
||||
func (d compactDelegate) Spacing() int { return 0 }
|
||||
func (d compactDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }
|
||||
func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.Item) {
|
||||
h, ok := item.(hostItem)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
mark := " "
|
||||
if d.marked[h.key()] {
|
||||
mark = "● "
|
||||
}
|
||||
title := h.Title()
|
||||
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))
|
||||
if index == m.Index() {
|
||||
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
|
||||
}
|
||||
fmt.Fprint(w, line)
|
||||
}
|
||||
|
||||
// --- filter ---
|
||||
|
||||
type filterOpts struct {
|
||||
tags []string
|
||||
kind string
|
||||
}
|
||||
|
||||
func parseFilter(s string) filterOpts {
|
||||
var f filterOpts
|
||||
for _, part := range strings.Fields(s) {
|
||||
if after, ok := strings.CutPrefix(part, "tag:"); ok {
|
||||
f.tags = append(f.tags, after)
|
||||
} else if after, ok := strings.CutPrefix(part, "kind:"); ok {
|
||||
f.kind = after
|
||||
}
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
|
||||
if len(f.tags) == 0 && f.kind == "" {
|
||||
return entries
|
||||
}
|
||||
out := make([]netbox.HostEntry, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if f.kind != "" && e.Kind != f.kind {
|
||||
continue
|
||||
}
|
||||
if len(f.tags) > 0 {
|
||||
tagSet := make(map[string]bool, len(e.Tags))
|
||||
for _, t := range e.Tags {
|
||||
tagSet[strings.ToLower(t)] = true
|
||||
}
|
||||
allMatch := true
|
||||
for _, want := range f.tags {
|
||||
if !tagSet[strings.ToLower(want)] {
|
||||
allMatch = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if !allMatch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// --- Model ---
|
||||
|
||||
type Model struct {
|
||||
noteErr error
|
||||
editHost *hostItem
|
||||
noteInput textarea.Model
|
||||
noteService *notes.Service
|
||||
note notes.Note
|
||||
noteMode, noteRemote, noteBusy bool
|
||||
noteLoaded bool
|
||||
defaultPort int
|
||||
input textinput.Model
|
||||
filterInput textinput.Model // tag:X kind:Y filter, toggled with ctrl+f
|
||||
editInput textinput.Model // user@host:port inline editor
|
||||
forwardInput textinput.Model // forward names/specs, ctrl+t
|
||||
forwardHost *hostItem
|
||||
forwardsFor func(name, kind string, tags []string) []string
|
||||
list list.Model
|
||||
client *netbox.Client
|
||||
cache *cache.Cache
|
||||
defaultUser string
|
||||
lastSent string // last query sent to NetBox (or served from cache)
|
||||
lastResults []netbox.HostEntry // raw results before filter applied
|
||||
seq int // sequence number to discard stale results
|
||||
loading bool
|
||||
err error
|
||||
selected *SelectedHost
|
||||
width int
|
||||
height int
|
||||
recentMode bool // true when showing recent hosts (empty search, initial state)
|
||||
filterOpen bool // Ctrl+F toggles
|
||||
editMode bool // Ctrl+E on the selected item
|
||||
forwardMode bool // Ctrl+T on the selected item
|
||||
marked map[string]bool // hostItem.key() of hosts marked with space
|
||||
hostLabel func(string) string
|
||||
aliasFor func(string) string // shortcut alias per target, "" for none
|
||||
markOrder []string // targets in the order they were marked
|
||||
}
|
||||
|
||||
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
|
||||
ti := textinput.New()
|
||||
ti.Placeholder = "Search hostname…"
|
||||
ti.Focus()
|
||||
|
||||
fi := textinput.New()
|
||||
fi.Placeholder = "tag:prod kind:vm"
|
||||
fi.Prompt = "Filter: "
|
||||
|
||||
ei := textinput.New()
|
||||
ei.Prompt = ""
|
||||
|
||||
fwd := textinput.New()
|
||||
fwd.Prompt = ""
|
||||
fwd.Placeholder = "web, 8080:localhost:80"
|
||||
|
||||
marked := make(map[string]bool)
|
||||
l := list.New(nil, compactDelegate{marked: marked}, 0, 0)
|
||||
l.SetShowHelp(false)
|
||||
l.SetShowTitle(false)
|
||||
l.SetShowStatusBar(false)
|
||||
l.SetFilteringEnabled(false)
|
||||
l.DisableQuitKeybindings()
|
||||
port := 22
|
||||
if len(defaultPorts) > 0 && defaultPorts[0] > 0 {
|
||||
port = defaultPorts[0]
|
||||
}
|
||||
|
||||
ni := textarea.New()
|
||||
ni.CharLimit = 0
|
||||
ni.SetHeight(10)
|
||||
return &Model{
|
||||
noteInput: ni,
|
||||
defaultPort: port,
|
||||
input: ti,
|
||||
filterInput: fi,
|
||||
editInput: ei,
|
||||
forwardInput: fwd,
|
||||
marked: marked,
|
||||
list: l,
|
||||
client: client,
|
||||
cache: c,
|
||||
defaultUser: defaultUser,
|
||||
recentMode: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) Init() tea.Cmd {
|
||||
return tea.Batch(textinput.Blink, m.loadRecent())
|
||||
}
|
||||
|
||||
// loadRecent returns a Cmd that immediately resolves to the recently-used host list.
|
||||
func (m *Model) loadRecent() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
if m.cache == nil {
|
||||
return searchResultMsg{query: "", entries: nil, recent: true}
|
||||
}
|
||||
recent := m.cache.RecentlyUsed(10)
|
||||
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}
|
||||
}
|
||||
return searchResultMsg{query: "", entries: entries, recent: true}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
defer m.resizeList()
|
||||
switch msg := msg.(type) {
|
||||
case noteResultMsg:
|
||||
m.noteBusy = false
|
||||
m.noteErr = msg.err
|
||||
if msg.err == nil {
|
||||
m.noteLoaded = true
|
||||
m.note = msg.note
|
||||
m.noteInput.SetValue(msg.note.Text)
|
||||
if msg.saved {
|
||||
m.noteMode = false
|
||||
m.noteInput.Blur()
|
||||
m.input.Focus()
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case tea.WindowSizeMsg:
|
||||
m.width = msg.Width
|
||||
m.height = msg.Height
|
||||
m.input.SetWidth(max(1, msg.Width-lipgloss.Width(m.input.Prompt)))
|
||||
m.filterInput.SetWidth(max(1, msg.Width-lipgloss.Width(m.filterInput.Prompt)))
|
||||
m.editInput.SetWidth(max(1, msg.Width-lipgloss.Width("Connect as: ")))
|
||||
m.noteInput.SetWidth(max(10, msg.Width-4))
|
||||
return m, nil
|
||||
|
||||
case tea.KeyPressMsg:
|
||||
if msg.String() == "ctrl+c" {
|
||||
return m, tea.Quit
|
||||
}
|
||||
if m.noteMode {
|
||||
if m.noteBusy {
|
||||
return m, nil
|
||||
}
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
m.noteMode = false
|
||||
m.noteInput.Blur()
|
||||
m.input.Focus()
|
||||
m.noteErr = nil
|
||||
return m, nil
|
||||
case "ctrl+s":
|
||||
if !m.noteLoaded {
|
||||
return m, nil
|
||||
}
|
||||
note := m.note
|
||||
note.Text = m.noteInput.Value()
|
||||
remote, service := m.noteRemote, m.noteService
|
||||
m.noteBusy = true
|
||||
return m, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
return noteResultMsg{note: note, saved: true, err: service.Write(ctx, note, remote)}
|
||||
}
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.noteInput, cmd = m.noteInput.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
// --- Forward mode ---
|
||||
if m.forwardMode {
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
m.forwardMode = false
|
||||
m.forwardInput.Blur()
|
||||
m.input.Focus()
|
||||
m.err = nil
|
||||
return m, nil
|
||||
case "enter":
|
||||
item := *m.forwardHost
|
||||
forwards, err := parseForwards(m.forwardInput.Value(), m.availableForwards(item))
|
||||
if err != nil {
|
||||
m.err = err
|
||||
return m, nil
|
||||
}
|
||||
m.selected = &SelectedHost{Name: item.name, IP: item.ip, Kind: item.kind, Action: ActionTunnel, Forwards: forwards}
|
||||
return m, tea.Quit
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.forwardInput, cmd = m.forwardInput.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// --- Edit mode ---
|
||||
if m.editMode {
|
||||
switch msg.String() {
|
||||
case "esc":
|
||||
m.editMode = false
|
||||
m.editInput.Blur()
|
||||
m.input.Focus()
|
||||
return m, nil
|
||||
case "enter":
|
||||
if m.editHost != nil {
|
||||
item := *m.editHost
|
||||
value := m.editInput.Value()
|
||||
if idx := strings.LastIndex(value, ":"); idx >= 0 {
|
||||
port, err := strconv.Atoi(strings.TrimSpace(value[idx+1:]))
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
m.err = fmt.Errorf("port must be between 1 and 65535")
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
m.selected = m.buildSelected(item)
|
||||
}
|
||||
return m, tea.Quit
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.editInput, cmd = m.editInput.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// --- Filter focused ---
|
||||
if m.filterOpen {
|
||||
switch msg.String() {
|
||||
case "ctrl+f", "esc":
|
||||
m.filterOpen = false
|
||||
m.filterInput.Blur()
|
||||
m.filterInput.SetValue("")
|
||||
m.input.Focus()
|
||||
m.updateListItems(m.lastResults)
|
||||
return m, nil
|
||||
case "enter":
|
||||
m.filterOpen = false
|
||||
m.filterInput.Blur()
|
||||
m.input.Focus()
|
||||
m.updateListItems(m.lastResults)
|
||||
return m, nil
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.filterInput, cmd = m.filterInput.Update(msg)
|
||||
m.updateListItems(m.lastResults)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// --- Normal mode ---
|
||||
switch msg.String() {
|
||||
case "ctrl+c", "esc":
|
||||
return m, tea.Quit
|
||||
|
||||
case "ctrl+f":
|
||||
m.filterOpen = true
|
||||
m.input.Blur()
|
||||
m.filterInput.Focus()
|
||||
return m, nil
|
||||
|
||||
case "enter":
|
||||
if len(m.markOrder) > 0 {
|
||||
m.selected = &SelectedHost{Action: ActionMulti, Targets: append([]string(nil), m.markOrder...)}
|
||||
return m, tea.Quit
|
||||
}
|
||||
if item, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
m.selected = &SelectedHost{Name: item.name, IP: item.ip, Kind: item.kind}
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
case "space":
|
||||
if item, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
m.toggleMark(item)
|
||||
m.list.CursorDown()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
case "ctrl+a":
|
||||
m.toggleAllVisible()
|
||||
return m, nil
|
||||
|
||||
case "ctrl+e":
|
||||
if item, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
m.openEdit(item)
|
||||
return m, nil
|
||||
}
|
||||
|
||||
case "ctrl+o":
|
||||
if item, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
m.selected = &SelectedHost{Name: item.name, IP: item.ip, Kind: item.kind, Action: ActionSFTP}
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
case "ctrl+t":
|
||||
if item, ok := m.list.SelectedItem().(hostItem); ok {
|
||||
m.forwardMode = true
|
||||
m.forwardHost = &item
|
||||
m.err = nil
|
||||
m.input.Blur()
|
||||
m.forwardInput.SetValue("")
|
||||
m.forwardInput.Focus()
|
||||
return m, nil
|
||||
}
|
||||
|
||||
case "ctrl+n", "ctrl+b":
|
||||
if item, ok := m.list.SelectedItem().(hostItem); ok && m.noteService != nil {
|
||||
m.noteMode = true
|
||||
m.noteLoaded = false
|
||||
m.noteBusy = true
|
||||
m.noteRemote = msg.String() == "ctrl+b"
|
||||
m.input.Blur()
|
||||
m.noteInput.Focus()
|
||||
m.noteInput.SetValue("")
|
||||
m.noteErr = nil
|
||||
host := netbox.HostEntry{ID: item.id, Name: item.name, Kind: item.kind}
|
||||
m.note = notes.Note{Host: host}
|
||||
remote, service := m.noteRemote, m.noteService
|
||||
return m, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
note, err := service.Read(ctx, host, remote)
|
||||
return noteResultMsg{note: note, err: err}
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
case "tab":
|
||||
if m.list.Items() != nil && len(m.list.Items()) > 0 {
|
||||
if item, ok := m.list.Items()[0].(hostItem); ok {
|
||||
m.input.SetValue(item.name)
|
||||
m.input.CursorEnd()
|
||||
m.seq++
|
||||
return m, m.startDebounce()
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
case debounceMsg:
|
||||
q := m.input.Value()
|
||||
if msg.seq != m.seq || msg.query != q {
|
||||
return m, nil
|
||||
}
|
||||
m.lastSent = q
|
||||
m.recentMode = false
|
||||
m.loading = true
|
||||
seq := m.seq
|
||||
return m, m.doSearch(q, seq)
|
||||
|
||||
case searchResultMsg:
|
||||
if msg.recent {
|
||||
if m.input.Value() != "" || m.seq > 0 {
|
||||
return m, nil
|
||||
}
|
||||
m.recentMode = true
|
||||
m.lastResults = msg.entries
|
||||
m.updateListItems(msg.entries)
|
||||
return m, nil
|
||||
}
|
||||
if msg.seq != m.seq || msg.query != m.input.Value() {
|
||||
return m, nil // discard stale result
|
||||
}
|
||||
m.loading = false
|
||||
m.err = msg.err
|
||||
m.lastResults = msg.entries
|
||||
m.updateListItems(msg.entries)
|
||||
return m, nil
|
||||
}
|
||||
|
||||
if m.noteMode {
|
||||
if m.noteBusy {
|
||||
return m, nil
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.noteInput, cmd = m.noteInput.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
// Paste and cursor events are separate from key presses in Bubble Tea v2.
|
||||
// Route them to the focused editor as well.
|
||||
if m.editMode {
|
||||
var cmd tea.Cmd
|
||||
m.editInput, cmd = m.editInput.Update(msg)
|
||||
return m, cmd
|
||||
}
|
||||
if m.filterOpen {
|
||||
var cmd tea.Cmd
|
||||
m.filterInput, cmd = m.filterInput.Update(msg)
|
||||
m.updateListItems(m.lastResults)
|
||||
return m, cmd
|
||||
}
|
||||
// Forward to search input and restart debounce timer.
|
||||
var cmds []tea.Cmd
|
||||
var inputCmd tea.Cmd
|
||||
oldQuery := m.input.Value()
|
||||
m.input, inputCmd = m.input.Update(msg)
|
||||
cmds = append(cmds, inputCmd)
|
||||
if m.input.Value() != oldQuery {
|
||||
m.seq++
|
||||
cmds = append(cmds, m.startDebounce())
|
||||
}
|
||||
|
||||
var listCmd tea.Cmd
|
||||
m.list, listCmd = m.list.Update(msg)
|
||||
cmds = append(cmds, listCmd)
|
||||
|
||||
return m, tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
func (m *Model) View() tea.View {
|
||||
view := tea.NewView(m.viewContent())
|
||||
view.AltScreen = true
|
||||
return view
|
||||
}
|
||||
|
||||
func (m *Model) viewContent() string {
|
||||
if m.noteMode {
|
||||
target := "local"
|
||||
if m.noteRemote {
|
||||
target = "NetBox comments"
|
||||
}
|
||||
status := "ctrl+s save esc cancel"
|
||||
if m.noteBusy {
|
||||
status = "Loading / saving…"
|
||||
}
|
||||
errText := ""
|
||||
if m.noteErr != nil {
|
||||
errText = "\nError: " + m.noteErr.Error()
|
||||
}
|
||||
return fmt.Sprintf("Notes [%s] — %s\n\n%s\n%s%s\n", target, m.note.Host.Name, m.noteInput.View(), status, errText)
|
||||
}
|
||||
var sb strings.Builder
|
||||
|
||||
title := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("netssh")
|
||||
sb.WriteString(title + "\n\n")
|
||||
sb.WriteString(m.input.View() + "\n")
|
||||
|
||||
if m.filterOpen {
|
||||
sb.WriteString(m.filterInput.View() + "\n")
|
||||
}
|
||||
|
||||
if m.loading {
|
||||
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" searching…") + "\n")
|
||||
} else {
|
||||
if m.err != nil {
|
||||
warning := " warning: " + strings.ReplaceAll(m.err.Error(), "\n", "; ")
|
||||
style := lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
|
||||
if m.width > 0 {
|
||||
style = style.MaxWidth(m.width)
|
||||
}
|
||||
sb.WriteString(style.Render(warning) + "\n")
|
||||
}
|
||||
if m.recentMode && m.input.Value() == "" {
|
||||
if len(m.list.Items()) > 0 {
|
||||
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" Recent connections") + "\n")
|
||||
}
|
||||
}
|
||||
sb.WriteString(m.list.View())
|
||||
}
|
||||
|
||||
if m.forwardMode {
|
||||
dim := lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
|
||||
sb.WriteString("\n" + dim.Render("Forward via "+m.forwardHost.name+": "))
|
||||
sb.WriteString(m.forwardInput.View() + "\n")
|
||||
available := "none configured — enter specs such as 8080:localhost:80"
|
||||
if names := m.availableForwards(*m.forwardHost); len(names) > 0 {
|
||||
available = strings.Join(names, ", ")
|
||||
}
|
||||
sb.WriteString(dim.Render(" forwards: "+available) + "\n")
|
||||
sb.WriteString(dim.Render(" enter start tunnel esc cancel") + "\n")
|
||||
} else if m.editMode {
|
||||
sb.WriteString("\n")
|
||||
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("Connect as: "))
|
||||
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"
|
||||
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)
|
||||
}
|
||||
sb.WriteString("\n" + lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(hint) + "\n")
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// Selected returns the host chosen by the user, or nil if none was selected.
|
||||
func (m *Model) Selected() *SelectedHost {
|
||||
return m.selected
|
||||
}
|
||||
|
||||
func (m *Model) startDebounce() tea.Cmd {
|
||||
query, seq := m.input.Value(), m.seq
|
||||
return tea.Tick(300*time.Millisecond, func(_ time.Time) tea.Msg {
|
||||
return debounceMsg{query: query, seq: seq}
|
||||
})
|
||||
}
|
||||
|
||||
func (m *Model) doSearch(query string, seq int) tea.Cmd {
|
||||
opts := m.netboxSearchOpts()
|
||||
return func() tea.Msg {
|
||||
var cached []netbox.HostEntry
|
||||
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})
|
||||
}
|
||||
}
|
||||
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
|
||||
return searchResultMsg{query: query, seq: seq, entries: cached}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
entries, err := m.client.Search(ctx, query, opts)
|
||||
// A cached hit in one instance must not hide live hosts in other instances.
|
||||
seen := make(map[string]bool)
|
||||
for _, e := range entries {
|
||||
seen[e.Target()+"\x00"+e.Kind] = true
|
||||
}
|
||||
for _, e := range cached {
|
||||
if !seen[e.Target()+"\x00"+e.Kind] {
|
||||
entries = append(entries, e)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(entries, func(i, j int) bool { return entries[i].Target() < entries[j].Target() })
|
||||
return searchResultMsg{query: query, seq: seq, entries: entries, err: err}
|
||||
}
|
||||
}
|
||||
|
||||
// netboxSearchOpts derives SearchOptions from the current filter input.
|
||||
func (m *Model) netboxSearchOpts() netbox.SearchOptions {
|
||||
f := parseFilter(m.filterInput.Value())
|
||||
var tag string
|
||||
if len(f.tags) > 0 {
|
||||
tag = f.tags[0]
|
||||
}
|
||||
return netbox.SearchOptions{Tag: tag, Kind: f.kind}
|
||||
}
|
||||
|
||||
// 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)
|
||||
items := make([]list.Item, len(filtered))
|
||||
labels := make([]string, len(filtered))
|
||||
counts := make(map[string]int, len(filtered))
|
||||
canonical := make(map[string]bool, len(filtered))
|
||||
for i, e := range filtered {
|
||||
labels[i] = e.Target()
|
||||
canonical[strings.ToLower(e.Target())] = true
|
||||
if m.hostLabel != nil {
|
||||
labels[i] = m.hostLabel(e.Target())
|
||||
}
|
||||
counts[strings.ToLower(labels[i])]++
|
||||
}
|
||||
for i, e := range filtered {
|
||||
ip := e.PrimaryIP4
|
||||
if ip == "" {
|
||||
ip = e.PrimaryIP6
|
||||
}
|
||||
label := labels[i]
|
||||
if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) {
|
||||
label = e.Target()
|
||||
}
|
||||
alias := ""
|
||||
if m.aliasFor != nil {
|
||||
alias = m.aliasFor(e.Target())
|
||||
if strings.EqualFold(alias, label) {
|
||||
alias = ""
|
||||
}
|
||||
}
|
||||
items[i] = hostItem{label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
|
||||
}
|
||||
m.list.SetItems(items)
|
||||
m.resizeList()
|
||||
}
|
||||
|
||||
// resizeList keeps the footer visible when the recent heading or editors change.
|
||||
func (m *Model) resizeList() {
|
||||
if m.width <= 0 || m.height <= 0 {
|
||||
return
|
||||
}
|
||||
extraRows := 5 // title, blank line, search, footer separator, footer
|
||||
if m.err != nil {
|
||||
extraRows++
|
||||
}
|
||||
if m.recentMode && m.input.Value() == "" && len(m.list.Items()) > 0 {
|
||||
extraRows++
|
||||
}
|
||||
if m.filterOpen {
|
||||
extraRows++
|
||||
}
|
||||
if m.editMode {
|
||||
extraRows++
|
||||
}
|
||||
height := max(1, m.height-extraRows)
|
||||
if m.list.Width() != m.width || m.list.Height() != height {
|
||||
m.list.SetSize(m.width, height)
|
||||
}
|
||||
}
|
||||
|
||||
// openEdit switches to edit mode for the given list item.
|
||||
func (m *Model) openEdit(item hostItem) {
|
||||
m.editMode = true
|
||||
m.editHost = &item
|
||||
m.input.Blur()
|
||||
|
||||
user := m.defaultUser
|
||||
prefix := ""
|
||||
if user != "" {
|
||||
prefix = user + "@"
|
||||
}
|
||||
m.editInput.SetValue(fmt.Sprintf("%s%s:%d", prefix, item.name, m.defaultPort))
|
||||
m.editInput.CursorEnd()
|
||||
m.editInput.Focus()
|
||||
}
|
||||
|
||||
// buildSelected parses the editInput to extract user/port overrides.
|
||||
func (m *Model) buildSelected(item hostItem) *SelectedHost {
|
||||
s := strings.TrimSpace(m.editInput.Value())
|
||||
sel := &SelectedHost{Name: item.name, IP: item.ip, Kind: item.kind}
|
||||
|
||||
// Extract user: everything before @
|
||||
if idx := strings.Index(s, "@"); idx != -1 {
|
||||
sel.User = strings.TrimSpace(s[:idx])
|
||||
s = s[idx+1:]
|
||||
}
|
||||
|
||||
// Extract port: after the last colon, if it's a number
|
||||
if idx := strings.LastIndex(s, ":"); idx != -1 {
|
||||
portStr := strings.TrimSpace(s[idx+1:])
|
||||
if port, err := strconv.Atoi(portStr); err == nil && port > 0 && port <= 65535 {
|
||||
sel.Port = portStr
|
||||
}
|
||||
}
|
||||
|
||||
return sel
|
||||
}
|
||||
|
||||
func (m *Model) SetNotes(service *notes.Service) { m.noteService = service }
|
||||
|
||||
func (h hostItem) key() string { return h.name + "\x00" + h.kind }
|
||||
|
||||
// toggleMark marks or unmarks a host for opening several side by side.
|
||||
func (m *Model) toggleMark(item hostItem) {
|
||||
key := item.key()
|
||||
if m.marked[key] {
|
||||
delete(m.marked, key)
|
||||
for i, target := range m.markOrder {
|
||||
if target == item.name {
|
||||
m.markOrder = append(m.markOrder[:i], m.markOrder[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
m.marked[key] = true
|
||||
m.markOrder = append(m.markOrder, item.name)
|
||||
}
|
||||
|
||||
// toggleAllVisible marks every listed host, or unmarks them if all are marked.
|
||||
func (m *Model) toggleAllVisible() {
|
||||
var items []hostItem
|
||||
allMarked := true
|
||||
for _, it := range m.list.Items() {
|
||||
if item, ok := it.(hostItem); ok {
|
||||
items = append(items, item)
|
||||
allMarked = allMarked && m.marked[item.key()]
|
||||
}
|
||||
}
|
||||
for _, item := range items {
|
||||
if m.marked[item.key()] == allMarked {
|
||||
m.toggleMark(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetForwards provides the forward names configured for a host (ctrl+t).
|
||||
func (m *Model) SetForwards(forwardsFor func(name, kind string, tags []string) []string) {
|
||||
m.forwardsFor = forwardsFor
|
||||
}
|
||||
|
||||
func (m *Model) availableForwards(item hostItem) []string {
|
||||
if m.forwardsFor == nil {
|
||||
return nil
|
||||
}
|
||||
return m.forwardsFor(item.name, item.kind, item.tags)
|
||||
}
|
||||
|
||||
// parseForwards accepts configured names and specs containing a colon,
|
||||
// separated by commas or spaces.
|
||||
func parseForwards(input string, available []string) ([]string, error) {
|
||||
known := make(map[string]bool, len(available))
|
||||
for _, name := range available {
|
||||
known[strings.ToLower(name)] = true
|
||||
}
|
||||
fields := strings.FieldsFunc(input, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' })
|
||||
if len(fields) == 0 {
|
||||
return nil, fmt.Errorf("enter a forward name or a spec such as 8080:localhost:80")
|
||||
}
|
||||
for _, field := range fields {
|
||||
if !known[strings.ToLower(field)] && !strings.Contains(field, ":") {
|
||||
return nil, fmt.Errorf("unknown forward %q", field)
|
||||
}
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// SetHostLabel sets the display name formatter without changing host identity.
|
||||
// Configure it before the program starts, just like SetNotes and SetForwards.
|
||||
func (m *Model) SetHostLabel(format func(string) string) {
|
||||
m.hostLabel = format
|
||||
}
|
||||
|
||||
// SetAliases shows the shortcut alias returned for each target next to its
|
||||
// name; return "" for hosts without one. Configure it before the program starts.
|
||||
func (m *Model) SetAliases(aliasFor func(target string) string) {
|
||||
m.aliasFor = aliasFor
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/notes"
|
||||
)
|
||||
|
||||
func TestTypingEDoesNotOpenConnectionEditor(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "server"}})
|
||||
m.Update(tea.KeyPressMsg{Code: 'e', Text: "e"})
|
||||
if m.editMode || m.input.Value() != "e" {
|
||||
t.Fatal("e intercepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleResultsAndDebounceAreIgnored(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.input.SetValue("web")
|
||||
m.seq = 3
|
||||
m.Update(searchResultMsg{query: "web", seq: 1, entries: []netbox.HostEntry{{Name: "old"}}})
|
||||
if len(m.list.Items()) != 0 {
|
||||
t.Fatal("stale result accepted")
|
||||
}
|
||||
_, cmd := m.Update(debounceMsg{query: "w", seq: 1})
|
||||
if cmd != nil {
|
||||
t.Fatal("stale debounce accepted")
|
||||
}
|
||||
m.Update(searchResultMsg{query: "web", seq: 3, entries: []netbox.HostEntry{{Name: "web01"}}})
|
||||
if len(m.list.Items()) != 1 {
|
||||
t.Fatal("current result ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditPreservesDefaultAndExplicitPort22(t *testing.T) {
|
||||
m := New(nil, nil, "", 2222)
|
||||
item := hostItem{name: "web01", ip: "10.0.0.1"}
|
||||
m.openEdit(item)
|
||||
if m.editInput.Value() != "web01:2222" {
|
||||
t.Fatal(m.editInput.Value())
|
||||
}
|
||||
m.editInput.SetValue("ops@web01:22")
|
||||
selected := m.buildSelected(item)
|
||||
if selected.Port != "22" || selected.User != "ops" {
|
||||
t.Fatalf("bad override: %+v", selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedNoteLoadCannotBeSaved(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.SetNotes(¬es.Service{Dir: t.TempDir()})
|
||||
m.noteMode = true
|
||||
_, cmd := m.Update(tea.KeyPressMsg{Code: 's', Mod: tea.ModCtrl})
|
||||
if cmd != nil {
|
||||
t.Fatal("save allowed before successful load")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionEditorKeepsOriginalHost(t *testing.T) {
|
||||
m := New(nil, nil, "admin")
|
||||
first := hostItem{name: "first", ip: "10.0.0.1"}
|
||||
m.openEdit(first)
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "second", PrimaryIP4: "10.0.0.2"}})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || m.selected.Name != "first" {
|
||||
t.Fatalf("edited host changed: %+v", m.selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCtrlOSelectsSFTP(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "web01", PrimaryIP4: "10.0.0.1"}})
|
||||
m.Update(tea.KeyPressMsg{Code: 'o', Mod: tea.ModCtrl})
|
||||
if m.selected == nil || m.selected.Action != ActionSFTP || m.selected.Name != "web01" {
|
||||
t.Fatalf("got %+v", m.selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCtrlTStartsTunnelWithForwards(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.SetForwards(func(name, kind string, tags []string) []string {
|
||||
if name != "web01" || len(tags) != 1 {
|
||||
t.Errorf("forwards asked for %s %v", name, tags)
|
||||
}
|
||||
return []string{"web"}
|
||||
})
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "web01", PrimaryIP4: "10.0.0.1", Tags: []string{"dmz"}}})
|
||||
m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl})
|
||||
if !m.forwardMode || m.selected != nil {
|
||||
t.Fatal("forward input not opened")
|
||||
}
|
||||
if !strings.Contains(m.viewContent(), "forwards: web") {
|
||||
t.Fatalf("configured forwards not shown:\n%s", m.viewContent())
|
||||
}
|
||||
|
||||
m.forwardInput.SetValue("nope")
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected != nil || m.err == nil {
|
||||
t.Fatal("unknown forward accepted")
|
||||
}
|
||||
|
||||
m.forwardInput.SetValue("WEB, 9000:localhost:9000")
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
want := []string{"WEB", "9000:localhost:9000"}
|
||||
if m.selected == nil || m.selected.Action != ActionTunnel || !reflect.DeepEqual(m.selected.Forwards, want) {
|
||||
t.Fatalf("got %+v", m.selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardInputEscCancels(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "web01"}})
|
||||
m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEscape})
|
||||
if m.forwardMode || m.selected != nil {
|
||||
t.Fatal("esc did not cancel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpaceMarksHostsAndEnterOpensThem(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "a", Kind: "device"}, {Name: "b", Kind: "device"}, {Name: "c", Kind: "vm"}})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
|
||||
if len(m.markOrder) != 1 || m.markOrder[0] != "a" || m.list.Index() != 1 {
|
||||
t.Fatalf("space: marks %v, cursor %d", m.markOrder, m.list.Index())
|
||||
}
|
||||
if m.input.Value() != "" {
|
||||
t.Fatal("space went into the search field")
|
||||
}
|
||||
m.list.Select(2)
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
|
||||
if !strings.Contains(m.viewContent(), "2 marked") {
|
||||
t.Fatalf("no marked count:\n%s", m.viewContent())
|
||||
}
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || m.selected.Action != ActionMulti || !reflect.DeepEqual(m.selected.Targets, []string{"a", "c"}) {
|
||||
t.Fatalf("got %+v", m.selected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCtrlATogglesAllVisible(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.updateListItems([]netbox.HostEntry{{Name: "a"}, {Name: "b"}})
|
||||
m.toggleMark(hostItem{name: "a"})
|
||||
m.Update(tea.KeyPressMsg{Code: 'a', Mod: tea.ModCtrl})
|
||||
if !reflect.DeepEqual(m.markOrder, []string{"a", "b"}) {
|
||||
t.Fatalf("mark all: %v", m.markOrder)
|
||||
}
|
||||
m.Update(tea.KeyPressMsg{Code: 'a', Mod: tea.ModCtrl})
|
||||
if len(m.markOrder) != 0 {
|
||||
t.Fatalf("unmark all: %v", m.markOrder)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
|
||||
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
||||
)
|
||||
|
||||
func TestV2PasteFollowsFocusedEditor(t *testing.T) {
|
||||
t.Run("search", func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
_, cmd := m.Update(tea.PasteMsg{Content: "web-ä"})
|
||||
if m.input.Value() != "web-ä" || m.seq != 1 || cmd == nil {
|
||||
t.Fatalf("paste did not start search: %q, seq %d", m.input.Value(), m.seq)
|
||||
}
|
||||
})
|
||||
t.Run("connection editor", func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.openEdit(hostItem{name: "web", ip: "10.0.0.1"})
|
||||
m.editInput.SetValue("")
|
||||
m.Update(tea.PasteMsg{Content: "ops@web:2222"})
|
||||
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if m.selected == nil || m.selected.User != "ops" || m.selected.Port != "2222" {
|
||||
t.Fatalf("paste lost in editor: %+v", m.selected)
|
||||
}
|
||||
if m.input.Value() != "" {
|
||||
t.Fatal("editor paste changed search")
|
||||
}
|
||||
})
|
||||
t.Run("filter", func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.lastResults = []netbox.HostEntry{{Name: "vm", Kind: "vm"}, {Name: "device", Kind: "device"}}
|
||||
m.updateListItems(m.lastResults)
|
||||
m.Update(tea.KeyPressMsg{Code: 'f', Mod: tea.ModCtrl})
|
||||
m.Update(tea.PasteMsg{Content: "kind:vm"})
|
||||
if m.filterInput.Value() != "kind:vm" || len(m.list.Items()) != 1 {
|
||||
t.Fatalf("paste did not filter: %q, %d results", m.filterInput.Value(), len(m.list.Items()))
|
||||
}
|
||||
if m.input.Value() != "" {
|
||||
t.Fatal("filter paste changed search")
|
||||
}
|
||||
})
|
||||
t.Run("notes", func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.noteMode = true
|
||||
m.input.Blur()
|
||||
m.noteInput.Focus()
|
||||
m.Update(tea.PasteMsg{Content: "First line\nSecond line"})
|
||||
if m.noteInput.Value() != "First line\nSecond line" {
|
||||
t.Fatalf("multiline paste lost: %q", m.noteInput.Value())
|
||||
}
|
||||
m.noteBusy = true
|
||||
m.Update(tea.PasteMsg{Content: "must not change busy note"})
|
||||
if m.noteInput.Value() != "First line\nSecond line" {
|
||||
t.Fatal("paste edited note while loading/saving")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestV2ViewKeepsAlternateScreenInEachMode(t *testing.T) {
|
||||
for _, mode := range []string{"search", "edit", "notes"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.Update(tea.WindowSizeMsg{Width: 80, Height: 24})
|
||||
if mode == "edit" {
|
||||
m.openEdit(hostItem{name: "web"})
|
||||
}
|
||||
if mode == "notes" {
|
||||
m.noteMode = true
|
||||
}
|
||||
view := m.View()
|
||||
if !view.AltScreen || strings.TrimSpace(view.Content) == "" {
|
||||
t.Fatalf("invalid %s view: %+v", mode, view)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestV2KeyReleaseDoesNotTypeTwice(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.Update(tea.KeyPressMsg{Code: 'e', Text: "e"})
|
||||
m.Update(tea.KeyReleaseMsg{Code: 'e', Text: "e"})
|
||||
if m.input.Value() != "e" {
|
||||
t.Fatalf("key release changed input: %q", m.input.Value())
|
||||
}
|
||||
m.Update(tea.KeyPressMsg{Code: ' ', Text: " "})
|
||||
if m.input.Value() != "e " {
|
||||
t.Fatalf("space not inserted: %q", m.input.Value())
|
||||
}
|
||||
}
|
||||
|
||||
func TestV2ResizeShowsFullSearchPromptAndFooter(t *testing.T) {
|
||||
m := New(nil, nil, "")
|
||||
m.Update(tea.WindowSizeMsg{Width: 100, Height: 24})
|
||||
var entries []netbox.HostEntry
|
||||
for range 30 {
|
||||
entries = append(entries, netbox.HostEntry{Name: "web", Kind: "device"})
|
||||
}
|
||||
m.updateListItems(entries)
|
||||
view := m.View()
|
||||
if m.input.Width() != 98 || m.filterInput.Width() != 92 || m.editInput.Width() != 88 {
|
||||
t.Fatalf("editors were not sized for terminal: search=%d filter=%d edit=%d", m.input.Width(), m.filterInput.Width(), m.editInput.Width())
|
||||
}
|
||||
if !strings.Contains(view.Content, "earch hostname") || !strings.Contains(view.Content, "ctrl+c quit") {
|
||||
t.Fatalf("search prompt or footer missing: %s", view.Content)
|
||||
}
|
||||
assertFits := func() {
|
||||
t.Helper()
|
||||
if rows := strings.Count(m.View().Content, "\n"); rows > 24 {
|
||||
t.Fatalf("view overflows terminal: %d rows", rows)
|
||||
}
|
||||
}
|
||||
assertFits()
|
||||
m.lastResults = entries
|
||||
m.Update(tea.KeyPressMsg{Code: 'f', Mod: tea.ModCtrl})
|
||||
assertFits()
|
||||
m.Update(tea.KeyPressMsg{Code: 'f', Mod: tea.ModCtrl})
|
||||
m.Update(tea.KeyPressMsg{Code: 'e', Mod: tea.ModCtrl})
|
||||
assertFits()
|
||||
}
|
||||
Reference in new issue
Block a user