-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgsh.go
73 lines (60 loc) · 1.47 KB
/
gsh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"log"
"os/user"
"path"
"github.com/alexflint/go-arg"
"github.com/fatih/color"
"github.com/ktr0731/go-fuzzyfinder"
)
const (
defaultConfigPath = ".config/gsh.yml"
)
// args - application args
type args struct {
Config string `arg:"-c,help:path to config"`
PrintOnly bool `arg:"-p,help:only print ssh command"`
Patterns []string `arg:"positional,help:patterns to match server name hostname and user"`
}
func main() {
usr, err := user.Current()
if err != nil {
log.Fatal("Unable to get current user: ", err)
}
// default arguments
var args args
args.Config = path.Join(usr.HomeDir, defaultConfigPath)
args.PrintOnly = false
arg.MustParse(&args)
// get server list from config file
var servers []Server
if servers, err = readConfig(args.Config, usr.Username, 22); err != nil {
log.Fatalf("Failed to read config file '%s': %s\n", args.Config, err)
}
// match servers against patterns
var matched []Server
for _, s := range servers {
if s.matchAll(args.Patterns) == true {
matched = append(matched, s)
}
}
if len(matched) == 0 {
color.Red("no server matched")
return
}
if len(matched) == 1 {
connect(matched[0], args.PrintOnly)
return
}
idx, err := fuzzyfinder.Find(matched, func(i int) string {
return fmt.Sprintf("%s", matched[i].String())
})
if err != nil {
if err != fuzzyfinder.ErrAbort {
log.Fatalf("Failed to find server: %s", err)
}
return
}
connect(matched[idx], args.PrintOnly)
}