Test / test (pull_request) Successful in 4m15s
- info/open/whois: NetBox details (site, nested locations, rack units, role, platform, tenant, IPs per interface), web page, reverse IP lookup - cache status, site, role, platform, tenant, location chain and rack; ask before connecting to hosts in ssh.warn_status (--force skips) - ssh rules and command restrictions match site/role/platform/tenant/status - tui.columns selects what the TUI shows; optional TCP reachability column; detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters - resolver.fallback tries other strategies' addresses when unreachable - copy-id, known-hosts reset and address-change notices - export ansible (YAML/INI) and export ssh-config - token: keyring stores NetBox tokens in the system keyring - fix stale menu number in testenv configure test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1390 lines
39 KiB
Go
1390 lines
39 KiB
Go
package tui
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"io"
|
||
"net"
|
||
"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 {
|
||
Command string
|
||
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
|
||
}
|
||
|
||
// reachMsg is the result of probing a listed host's SSH port.
|
||
type reachMsg struct {
|
||
key string
|
||
state reachState
|
||
}
|
||
|
||
// detailMsg carries the text of the detail view (ctrl+l).
|
||
type detailMsg struct {
|
||
key string
|
||
text string
|
||
err error
|
||
}
|
||
|
||
// flashMsg is a short notice in the footer, e.g. after opening NetBox.
|
||
type flashMsg struct {
|
||
text string
|
||
err error
|
||
}
|
||
|
||
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 {
|
||
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
|
||
status string
|
||
site, role string
|
||
platform, tenant string
|
||
cluster string
|
||
location string // site › locations › rack › U
|
||
}
|
||
|
||
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 ---
|
||
|
||
// reachState is the result of the reachability probe of a host.
|
||
type reachState uint8
|
||
|
||
const (
|
||
reachUnknown reachState = iota
|
||
reachPending
|
||
reachUp
|
||
reachDown
|
||
reachSkipped // behind a jump host: not probed
|
||
)
|
||
|
||
// compactDelegate shares the model's marks so marked hosts show a dot.
|
||
// With reach set, a column shows whether the SSH port answers.
|
||
type compactDelegate struct {
|
||
marked map[string]bool
|
||
reach map[string]reachState
|
||
columns []string // nil = defaultColumns
|
||
}
|
||
|
||
// defaultColumns matches config.DefaultTUIColumns.
|
||
var defaultColumns = []string{"alias", "ip", "source", "status"}
|
||
|
||
var (
|
||
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
|
||
attrStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
|
||
aliasStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("109"))
|
||
statusStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("214"))
|
||
)
|
||
|
||
// column renders one configured column of a host, or "" when it is empty.
|
||
func (h hostItem) column(name string) string {
|
||
attr := func(key, value string) string {
|
||
if value == "" {
|
||
return ""
|
||
}
|
||
return attrStyle.Render(key + ":" + value)
|
||
}
|
||
switch name {
|
||
case "alias":
|
||
if h.alias != "" {
|
||
return aliasStyle.Render("→ " + h.alias)
|
||
}
|
||
case "ip":
|
||
if h.ip != "" {
|
||
return dimStyle.Render(h.ip)
|
||
}
|
||
case "kind":
|
||
if h.kind != "" {
|
||
return "[" + h.kind + "]"
|
||
}
|
||
case "source":
|
||
if h.provenance != "" {
|
||
return "[" + h.provenance + "]"
|
||
}
|
||
case "status":
|
||
if h.status != "" && !strings.EqualFold(h.status, "active") {
|
||
return statusStyle.Render("[" + h.status + "]")
|
||
}
|
||
case "site":
|
||
return attr("site", h.site)
|
||
case "location":
|
||
if h.location != "" {
|
||
return attrStyle.Render("⌂ " + h.location)
|
||
}
|
||
case "role":
|
||
return attr("role", h.role)
|
||
case "platform":
|
||
return attr("platform", h.platform)
|
||
case "tenant":
|
||
return attr("tenant", h.tenant)
|
||
case "cluster":
|
||
return attr("cluster", h.cluster)
|
||
case "tags":
|
||
if len(h.tags) > 0 {
|
||
return attrStyle.Render("#" + strings.Join(h.tags, " #"))
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
|
||
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 = "● "
|
||
}
|
||
badge := ""
|
||
if h.pinned {
|
||
badge = "◆ "
|
||
} else if h.favorite {
|
||
badge = "★ "
|
||
}
|
||
columns := d.columns
|
||
if columns == nil {
|
||
columns = defaultColumns
|
||
}
|
||
// The reachability mark is a fixed-width prefix so names stay aligned.
|
||
reach := ""
|
||
if d.reach != nil {
|
||
switch d.reach[h.key()] {
|
||
case reachUp:
|
||
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("2")).Render("✓") + " "
|
||
case reachDown:
|
||
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("✗") + " "
|
||
case reachPending:
|
||
reach = dimStyle.Render("·") + " "
|
||
default:
|
||
reach = " "
|
||
}
|
||
}
|
||
line := " " + mark + reach + badge + h.Title()
|
||
for _, name := range columns {
|
||
if text := h.column(name); text != "" {
|
||
line += " " + text
|
||
}
|
||
}
|
||
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
|
||
status, site, role, platform, tenant string
|
||
location string
|
||
}
|
||
|
||
func (f filterOpts) empty() bool {
|
||
return len(f.tags) == 0 && f.kind == "" && f.status == "" && f.site == "" && f.role == "" && f.platform == "" && f.tenant == "" && f.location == ""
|
||
}
|
||
|
||
func parseFilter(s string) filterOpts {
|
||
var f filterOpts
|
||
for _, part := range strings.Fields(s) {
|
||
key, value, ok := strings.Cut(part, ":")
|
||
if !ok {
|
||
continue
|
||
}
|
||
switch strings.ToLower(key) {
|
||
case "tag":
|
||
f.tags = append(f.tags, value)
|
||
case "kind":
|
||
f.kind = value
|
||
case "status":
|
||
f.status = value
|
||
case "site":
|
||
f.site = value
|
||
case "role":
|
||
f.role = value
|
||
case "platform":
|
||
f.platform = value
|
||
case "tenant":
|
||
f.tenant = value
|
||
case "location", "rack":
|
||
f.location = value
|
||
}
|
||
}
|
||
return f
|
||
}
|
||
|
||
func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
|
||
if f.empty() {
|
||
return entries
|
||
}
|
||
out := make([]netbox.HostEntry, 0, len(entries))
|
||
for _, e := range entries {
|
||
if f.kind != "" && e.Kind != f.kind {
|
||
continue
|
||
}
|
||
if f.status != "" && !strings.EqualFold(e.Status, f.status) {
|
||
continue
|
||
}
|
||
if f.site != "" && !e.Site.Matches(f.site) || f.role != "" && !e.Role.Matches(f.role) ||
|
||
f.platform != "" && !e.Platform.Matches(f.platform) || f.tenant != "" && !e.Tenant.Matches(f.tenant) ||
|
||
f.location != "" && !inLocation(e, f.location) {
|
||
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 {
|
||
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
|
||
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
|
||
|
||
columns []string // nil = defaultColumns
|
||
reach map[string]reachState // probe results by hostItem.key()
|
||
reachTimeout time.Duration
|
||
reachPort func(name, kind string, tags []string) (port int, probe bool)
|
||
opener func(name, kind string, id int) error
|
||
details func(name, kind string, id int) (string, error)
|
||
detailHost *hostItem
|
||
detailText string
|
||
detailErr error
|
||
flash string
|
||
}
|
||
|
||
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 status:active site:fsn1 location:room-2 role:router platform:junos"
|
||
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{
|
||
historyLimit: 10, favorites: map[string]bool{}, pinned: map[string]bool{},
|
||
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 {
|
||
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(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] = entryFromCache(e, false)
|
||
}
|
||
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 reachMsg:
|
||
if m.reach != nil {
|
||
m.reach[msg.key] = msg.state
|
||
}
|
||
return m, nil
|
||
|
||
case detailMsg:
|
||
if m.detailHost != nil && m.detailHost.key() == msg.key {
|
||
m.detailText, m.detailErr = msg.text, msg.err
|
||
}
|
||
return m, nil
|
||
|
||
case flashMsg:
|
||
m.flash = msg.text
|
||
if msg.err != nil {
|
||
m.flash = "error: " + msg.err.Error()
|
||
}
|
||
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.flash != "" {
|
||
m.flash = ""
|
||
}
|
||
if m.detailHost != nil {
|
||
switch msg.String() {
|
||
case "esc", "ctrl+l", "q":
|
||
m.detailHost = nil
|
||
m.input.Focus()
|
||
case "enter":
|
||
h := m.detailHost
|
||
m.selected = &SelectedHost{Name: h.name, IP: h.ip, Kind: h.kind}
|
||
return m, tea.Quit
|
||
case "ctrl+g":
|
||
return m, m.openCmd(*m.detailHost)
|
||
}
|
||
return m, nil
|
||
}
|
||
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
|
||
}
|
||
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+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()
|
||
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+g":
|
||
if item, ok := m.list.SelectedItem().(hostItem); ok {
|
||
return m, m.openCmd(item)
|
||
}
|
||
return m, nil
|
||
|
||
case "ctrl+l":
|
||
if item, ok := m.list.SelectedItem().(hostItem); ok && m.details != nil {
|
||
m.detailHost = &item
|
||
m.detailText, m.detailErr = "", nil
|
||
m.input.Blur()
|
||
details, key := m.details, item.key()
|
||
return m, func() tea.Msg {
|
||
text, err := details(item.name, item.kind, item.id)
|
||
return detailMsg{key: key, text: text, err: err}
|
||
}
|
||
}
|
||
return m, nil
|
||
|
||
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, m.probeCmd()
|
||
}
|
||
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, m.probeCmd()
|
||
}
|
||
|
||
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.detailHost != nil {
|
||
var out strings.Builder
|
||
title := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("Details — " + m.detailHost.Title())
|
||
out.WriteString(title + "\n\n")
|
||
switch {
|
||
case m.detailErr != nil:
|
||
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("Error: "+m.detailErr.Error()) + "\n")
|
||
case m.detailText == "":
|
||
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("Loading…") + "\n")
|
||
default:
|
||
text := m.detailText
|
||
if m.height > 4 {
|
||
lines := strings.Split(strings.TrimRight(text, "\n"), "\n")
|
||
if len(lines) > m.height-4 {
|
||
lines = append(lines[:m.height-5], "…")
|
||
}
|
||
text = strings.Join(lines, "\n") + "\n"
|
||
}
|
||
out.WriteString(text)
|
||
}
|
||
if m.flash != "" {
|
||
out.WriteString("\n" + m.flash + "\n")
|
||
}
|
||
out.WriteString("\n" + lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("enter connect ctrl+g open in NetBox esc back") + "\n")
|
||
return out.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 {
|
||
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+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 ctrl+l details ctrl+g NetBox page"
|
||
if m.flash != "" {
|
||
hint = m.flash
|
||
}
|
||
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) {
|
||
cached = append(cached, entryFromCache(entry, true))
|
||
}
|
||
}
|
||
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}
|
||
}
|
||
|
||
// entryFromCache converts a cache entry for the list. With split, the
|
||
// instance prefix becomes Source, like in live NetBox results.
|
||
func entryFromCache(e cache.Entry, split bool) netbox.HostEntry {
|
||
h := netbox.HostEntry{Name: e.Name, ID: e.ID, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Cached: true, CachedAt: e.CachedAt, Static: e.Static,
|
||
Status: e.Status, Site: cache.RefOf(e.Site), Role: cache.RefOf(e.Role), Platform: cache.RefOf(e.Platform), Tenant: cache.RefOf(e.Tenant),
|
||
Location: e.Location, Rack: e.Rack, Position: e.Position}
|
||
if split {
|
||
h.Source, h.Name = netbox.SplitTarget(e.Name)
|
||
}
|
||
return h
|
||
}
|
||
|
||
// updateListItems applies the active filter and sets the list items.
|
||
func (m *Model) updateListItems(entries []netbox.HostEntry) {
|
||
f := parseFilter(m.filterInput.Value())
|
||
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))
|
||
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 = ""
|
||
}
|
||
}
|
||
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, status: e.Status,
|
||
site: e.Site.Key(), role: e.Role.Key(), platform: e.Platform.Key(), tenant: e.Tenant.Key(), cluster: e.Cluster, location: e.LocationPath()}
|
||
}
|
||
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
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
// SetReachability enables the reachability column: listed hosts are probed
|
||
// with a TCP connect to the port returned by portFor, unless it returns
|
||
// probe=false (for hosts behind a jump host). Configure it before the program starts.
|
||
func (m *Model) SetReachability(timeout time.Duration, portFor func(name, kind string, tags []string) (port int, probe bool)) {
|
||
if timeout <= 0 {
|
||
timeout = 300 * time.Millisecond
|
||
}
|
||
m.reach = map[string]reachState{}
|
||
m.reachTimeout = timeout
|
||
m.reachPort = portFor
|
||
m.list.SetDelegate(m.delegate())
|
||
}
|
||
|
||
// SetColumns selects what is shown next to each hostname, in order (see
|
||
// config.TUIColumns). "reachability" is ignored here: SetReachability
|
||
// enables the check. Configure it before the program starts.
|
||
func (m *Model) SetColumns(columns []string) {
|
||
m.columns = append([]string{}, columns...)
|
||
m.list.SetDelegate(m.delegate())
|
||
}
|
||
|
||
func (m *Model) delegate() compactDelegate {
|
||
return compactDelegate{marked: m.marked, reach: m.reach, columns: m.columns}
|
||
}
|
||
|
||
// probeCmd starts probes for listed hosts that have no result yet.
|
||
func (m *Model) probeCmd() tea.Cmd {
|
||
if m.reach == nil {
|
||
return nil
|
||
}
|
||
var cmds []tea.Cmd
|
||
for _, it := range m.list.Items() {
|
||
h, ok := it.(hostItem)
|
||
if !ok || m.reach[h.key()] != reachUnknown {
|
||
continue
|
||
}
|
||
key := h.key()
|
||
port, probe := 22, true
|
||
if m.reachPort != nil {
|
||
port, probe = m.reachPort(h.name, h.kind, h.tags)
|
||
}
|
||
if !probe || h.ip == "" {
|
||
m.reach[key] = reachSkipped
|
||
continue
|
||
}
|
||
m.reach[key] = reachPending
|
||
address, timeout := h.ip, m.reachTimeout
|
||
cmds = append(cmds, func() tea.Msg {
|
||
conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout)
|
||
if err != nil {
|
||
return reachMsg{key: key, state: reachDown}
|
||
}
|
||
_ = conn.Close()
|
||
return reachMsg{key: key, state: reachUp}
|
||
})
|
||
}
|
||
return tea.Batch(cmds...)
|
||
}
|
||
|
||
// SetOpener opens a host's NetBox page (ctrl+g). Configure it before the program starts.
|
||
func (m *Model) SetOpener(open func(name, kind string, id int) error) { m.opener = open }
|
||
|
||
// SetDetails provides the text of the detail view (ctrl+l). Configure it before the program starts.
|
||
func (m *Model) SetDetails(details func(name, kind string, id int) (string, error)) {
|
||
m.details = details
|
||
}
|
||
|
||
func (m *Model) openCmd(h hostItem) tea.Cmd {
|
||
if m.opener == nil {
|
||
return nil
|
||
}
|
||
open := m.opener
|
||
return func() tea.Msg {
|
||
if err := open(h.name, h.kind, h.id); err != nil {
|
||
return flashMsg{err: err}
|
||
}
|
||
return flashMsg{text: "opened " + h.name + " in NetBox"}
|
||
}
|
||
}
|
||
|
||
// inLocation reports whether a host is in the location want at any level of
|
||
// its location chain, or in the rack named want.
|
||
func inLocation(e netbox.HostEntry, want string) bool {
|
||
for _, location := range e.Location {
|
||
if location.Matches(want) {
|
||
return true
|
||
}
|
||
}
|
||
return want != "" && strings.EqualFold(e.Rack, want)
|
||
}
|