feat: add netssh link and shell aliases for links
netssh link add|list|remove manages links; netssh NAME follows them, links complete with Tab and get a shell alias. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
793f095e80
commit
e905a39068
5 files changed
+247
-1
No files matched your search
@@ -0,0 +1,140 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func linkCmd() *cobra.Command {
|
||||||
|
cmd := &cobra.Command{
|
||||||
|
Use: "link",
|
||||||
|
Short: "Short names for hosts: netssh NAME and shell alias NAME",
|
||||||
|
Long: `Links give a host a name of your own, for example mx123 for the server that
|
||||||
|
mx123.webseite.de points to. netssh NAME then connects to the host, and new
|
||||||
|
shells get the alias NAME. netssh offers to create a link after a DNS
|
||||||
|
suggestion; links are stored under links: in the config.`,
|
||||||
|
}
|
||||||
|
cmd.AddCommand(linkListCmd(), linkAddCmd(), linkRemoveCmd())
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
func linkListCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "list",
|
||||||
|
Short: "List links",
|
||||||
|
Args: cobra.NoArgs,
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(cfg.Links) == 0 {
|
||||||
|
fmt.Fprintln(cmd.OutOrStdout(), "No links. Add one with: netssh link add NAME HOST")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(cfg.Links))
|
||||||
|
for name := range cfg.Links {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
|
||||||
|
fmt.Fprintln(w, "NAME\tHOST")
|
||||||
|
for _, name := range names {
|
||||||
|
fmt.Fprintf(w, "%s\t%s\n", name, cfg.Links[name])
|
||||||
|
}
|
||||||
|
return w.Flush()
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func linkAddCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "add NAME HOST",
|
||||||
|
Short: "Create or replace a link",
|
||||||
|
Example: " netssh link add mx123 prod/web07\n netssh link add mx123 mx123.webseite.de # asks which host owns the address",
|
||||||
|
Args: cobra.ExactArgs(2),
|
||||||
|
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||||
|
if len(args) == 1 {
|
||||||
|
return hostCompletion(cmd, args, toComplete)
|
||||||
|
}
|
||||||
|
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||||
|
},
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
name := strings.ToLower(args[0])
|
||||||
|
if _, isLink := cfg.Link(args[1]); isLink {
|
||||||
|
return fmt.Errorf("%q is a link itself; link to a host", args[1])
|
||||||
|
}
|
||||||
|
// Resolve now, so a typo fails here and the link stores the canonical target.
|
||||||
|
h, err := resolveOrSuggestQuiet(cfg, args[1])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if h.Kind == "dns" {
|
||||||
|
return fmt.Errorf("%s is not a NetBox or static host; links point to hosts netssh knows", args[1])
|
||||||
|
}
|
||||||
|
if err := saveLink(name, h.Name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Fprintf(cmd.OutOrStdout(), "netssh %s → %s (open a new shell for the alias %s)\n", name, h.Name, name)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveOrSuggestQuiet resolves for link add without offering another link.
|
||||||
|
func resolveOrSuggestQuiet(cfg *config.Config, host string) (resolvedHost, error) {
|
||||||
|
old := offerLinkFunc
|
||||||
|
offerLinkFunc = func(string, string, string) {}
|
||||||
|
defer func() { offerLinkFunc = old }()
|
||||||
|
return resolveOrSuggest(cfg, host, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func linkRemoveCmd() *cobra.Command {
|
||||||
|
return &cobra.Command{
|
||||||
|
Use: "remove NAME",
|
||||||
|
Short: "Remove a link",
|
||||||
|
Args: cobra.ExactArgs(1),
|
||||||
|
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return nil, cobra.ShellCompDirectiveError
|
||||||
|
}
|
||||||
|
var names []string
|
||||||
|
for name := range cfg.Links {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
return filterPrefix(names, toComplete, nil), cobra.ShellCompDirectiveNoFileComp
|
||||||
|
},
|
||||||
|
RunE: func(cmd *cobra.Command, args []string) error {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
removed := false
|
||||||
|
for key := range cfg.Links {
|
||||||
|
if strings.EqualFold(key, args[0]) {
|
||||||
|
delete(cfg.Links, key)
|
||||||
|
removed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !removed {
|
||||||
|
return fmt.Errorf("no link %q", args[0])
|
||||||
|
}
|
||||||
|
if err := saveHosts(cfg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Fprintf(cmd.OutOrStdout(), "Link %s removed.\n", args[0])
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
||||||
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLinksResolveAndBecomeAliases(t *testing.T) {
|
||||||
|
dnsEnv(t, "links:\n mx123: prod/web07\n")
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h, err := resolveTargetE(cfg, "MX123", false)
|
||||||
|
if err != nil || h.Name != "prod/web07" {
|
||||||
|
t.Fatalf("link not followed: %+v %v", h, err)
|
||||||
|
}
|
||||||
|
var found bool
|
||||||
|
for _, a := range hook.BuildAliasEntries(nil, *cfg) {
|
||||||
|
if a.Name == "mx123" && a.Host == "mx123" {
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("link has no shell alias")
|
||||||
|
}
|
||||||
|
if got := completeHosts("mx"); len(got) == 0 || got[0] != "mx123" {
|
||||||
|
t.Fatalf("completion: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLinkAddListRemove(t *testing.T) {
|
||||||
|
dnsEnv(t, "")
|
||||||
|
stubTerminal(t, false)
|
||||||
|
run := func(args ...string) (string, error) {
|
||||||
|
var out strings.Builder
|
||||||
|
cmd := rootCmd()
|
||||||
|
cmd.SetOut(&out)
|
||||||
|
cmd.SetArgs(args)
|
||||||
|
err := cmd.Execute()
|
||||||
|
return out.String(), err
|
||||||
|
}
|
||||||
|
if _, err := run("link", "add", "mx123", "prod/web07"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"))
|
||||||
|
if !strings.Contains(string(data), "links:\n mx123: \"prod/web07\"") {
|
||||||
|
t.Fatalf("link not written:\n%s", data)
|
||||||
|
}
|
||||||
|
if out, _ := run("link", "list"); !strings.Contains(out, "mx123 prod/web07") {
|
||||||
|
t.Fatalf("list: %q", out)
|
||||||
|
}
|
||||||
|
if _, err := run("link", "add", "x", "missing-host"); err == nil {
|
||||||
|
t.Fatal("link to unknown host accepted")
|
||||||
|
}
|
||||||
|
if _, err := run("link", "remove", "mx123"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg, _ := config.Load()
|
||||||
|
if len(cfg.Links) != 0 {
|
||||||
|
t.Fatalf("not removed: %v", cfg.Links)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateLinks(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
cfg config.Config
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{config.Config{Links: map[string]string{"mx123": "prod/web07"}}, true},
|
||||||
|
{config.Config{Links: map[string]string{"bad name": "web"}}, false},
|
||||||
|
{config.Config{Links: map[string]string{"a": "-oProxyCommand=x"}}, false},
|
||||||
|
{config.Config{Links: map[string]string{"a": "b", "b": "web"}}, false},
|
||||||
|
{config.Config{Links: map[string]string{"router": "web"}, Hosts: []config.StaticHost{{Name: "router", Address: "1.2.3.4"}}}, false},
|
||||||
|
} {
|
||||||
|
if err := tc.cfg.ValidateLinks(); (err == nil) != tc.ok {
|
||||||
|
t.Errorf("%v: %v", tc.cfg.Links, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -58,6 +58,7 @@ var managedSubcommands = map[string]bool{
|
|||||||
"export": true,
|
"export": true,
|
||||||
"token": true,
|
"token": true,
|
||||||
"known-hosts": true,
|
"known-hosts": true,
|
||||||
|
"link": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -709,7 +710,7 @@ func rootCmd() *cobra.Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd(),
|
root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd(),
|
||||||
openCmd(), infoCmd(), whoisCmd(), copyIDCmd(), exportCmd(), tokenCmd(), knownHostsCmd())
|
openCmd(), infoCmd(), whoisCmd(), copyIDCmd(), exportCmd(), tokenCmd(), knownHostsCmd(), linkCmd())
|
||||||
|
|
||||||
// cobra builds the "completion" command lazily; force init so we can extend it.
|
// cobra builds the "completion" command lazily; force init so we can extend it.
|
||||||
root.InitDefaultCompletionCmd()
|
root.InitDefaultCompletionCmd()
|
||||||
|
|||||||
@@ -136,6 +136,12 @@ func completeHosts(toComplete string) []string {
|
|||||||
c := newCache(cfg)
|
c := newCache(cfg)
|
||||||
_ = c.Load()
|
_ = c.Load()
|
||||||
hosts := hostCompletions(c.All(), toComplete, cfg.Shortcuts)
|
hosts := hostCompletions(c.All(), toComplete, cfg.Shortcuts)
|
||||||
|
for name := range cfg.Links {
|
||||||
|
if strings.HasPrefix(strings.ToLower(name), strings.ToLower(toComplete)) {
|
||||||
|
hosts = append(hosts, strings.ToLower(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(hosts)
|
||||||
if limit := cfg.Completion.MaxResults; limit > 0 && len(hosts) > limit {
|
if limit := cfg.Completion.MaxResults; limit > 0 && len(hosts) > limit {
|
||||||
hosts = hosts[:limit]
|
hosts = hosts[:limit]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -129,6 +129,20 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
|
|||||||
out = append(out, AliasEntry{Name: cfg.Shell.Alias})
|
out = append(out, AliasEntry{Name: cfg.Shell.Alias})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Links are names the user chose explicitly: they come before host aliases.
|
||||||
|
validLink := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
|
||||||
|
links := make([]string, 0, len(cfg.Links))
|
||||||
|
for name := range cfg.Links {
|
||||||
|
links = append(links, strings.ToLower(name))
|
||||||
|
}
|
||||||
|
sort.Strings(links)
|
||||||
|
for _, name := range links {
|
||||||
|
if !seen[name] && validLink.MatchString(name) {
|
||||||
|
seen[name] = true
|
||||||
|
out = append(out, AliasEntry{Name: name, Host: name})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
withoutPrefix := make(map[string]bool, len(cfg.NetBoxes))
|
withoutPrefix := make(map[string]bool, len(cfg.NetBoxes))
|
||||||
for _, source := range cfg.NetBoxes {
|
for _, source := range cfg.NetBoxes {
|
||||||
withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix
|
withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix
|
||||||
|
|||||||
Reference in new issue
Block a user