@@ -5,6 +5,14 @@ Licensed under the MIT license, see LICENSE in the project root for details.
55package completion
66
77import (
8+ "bufio"
9+ "errors"
10+ "fmt"
11+ "maps"
12+ "os"
13+ "os/user"
14+ "slices"
15+
816 "github.com/spf13/cobra"
917 "github.com/tschaefer/finchctl/internal/config"
1018)
@@ -39,3 +47,43 @@ func CompleteDashboardRole(cmd *cobra.Command, args []string, toComplete string)
3947
4048 return []string {"viewer" , "operator" , "admin" }, cobra .ShellCompDirectiveNoFileComp
4149}
50+
51+ func CompleteHostName (cmd * cobra.Command , args []string , toComplete string ) ([]cobra.Completion , cobra.ShellCompDirective ) {
52+ if len (args ) != 0 {
53+ return nil , cobra .ShellCompDirectiveNoFileComp
54+ }
55+
56+ curUser , err := user .Current ()
57+ if err != nil {
58+ panic (err )
59+ }
60+
61+ knownHosts := curUser .HomeDir + "/.ssh/known_hosts"
62+ if _ , err = os .Stat (knownHosts ); errors .Is (err , os .ErrNotExist ) {
63+ return nil , cobra .ShellCompDirectiveNoFileComp
64+ }
65+
66+ readFile , err := os .Open (knownHosts )
67+ if err != nil {
68+ return nil , cobra .ShellCompDirectiveNoFileComp
69+ }
70+ defer func () {
71+ _ = readFile .Close ()
72+ }()
73+
74+ fileScanner := bufio .NewScanner (readFile )
75+ fileScanner .Split (bufio .ScanLines )
76+
77+ hosts := map [string ]int {}
78+ for fileScanner .Scan () {
79+ var host string
80+ if _ , err := fmt .Sscan (fileScanner .Text (), & host ); err != nil {
81+ continue
82+ }
83+
84+ hosts [host ] = 1
85+ }
86+ list := slices .Sorted (maps .Keys (hosts ))
87+
88+ return list , cobra .ShellCompDirectiveNoFileComp
89+ }
0 commit comments