-
Notifications
You must be signed in to change notification settings - Fork 0
/
gscp.go
128 lines (117 loc) · 2.54 KB
/
gscp.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package gscp
import (
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
)
type Host struct {
Name string
Options []Option
}
type Hosts []Host
// Represents an ssh config option.
type Option struct {
Name string
Value string
}
// Defines optional arguments for LoadConfig ().
type option func(*LoadOpts)
type LoadOpts struct {
path string
}
// Used to specify the path of the config file to be loaded in LoadConfig.
// Returns the setter function of the path of LoadOpts.
func Path(p string) option {
return func(l *LoadOpts) {
l.path = p
}
}
func (h Host) FindOption(s string) Option {
for _, v := range h.Options {
if v.Name == s {
return v
}
}
return Option{}
}
func (h Hosts) FindHost(s string) Host {
for _, v := range h {
if v.Name == s {
return v
}
}
return Host{}
}
// Load ssh config.
// path is optional.
// If nothing is done, `~/.ssh.config` is read.
// To specify a path, pass the return value of Path() as an argument.
func LoadConfig(path ...option) (string, error) {
home, _ := os.UserHomeDir()
p := &LoadOpts{
path: filepath.Join(home, ".ssh", "config"),
}
for _, opt := range path {
opt(p)
}
f, err := os.Open(p.path)
if err != nil {
return "", fmt.Errorf("ERROR LoadConfig() Open: %w", err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return "", fmt.Errorf("ERROR LoadConfig() ReadAll: %w", err)
}
return string(data), nil
}
// Parses a config given as a string.
func Parse(s string) (Hosts, error) {
var hosts Hosts
reg := "\r\n|\n"
tmp := regexp.MustCompile(reg).Split(s, -1)
r := regexp.MustCompile(`^[a-zA-Z]`)
for _, v := range tmp {
if r.MatchString(v) {
arr := strings.Fields(v)
if strings.ToLower(arr[0]) == "host" {
hosts = append(hosts, Host{Name: arr[1]})
}
if strings.ToLower(arr[0]) == "include" {
home, _ := os.UserHomeDir()
files, _ := filepath.Glob(filepath.Join(home, ".ssh", arr[1]))
for _, f := range files {
s, err := LoadConfig(Path(f))
if err != nil {
return nil, fmt.Errorf("ERROR Parse(): %w", err)
}
t, err := Parse(s)
if err != nil {
return nil, fmt.Errorf("ERROR Parse(): %w", err)
}
hosts = append(hosts, t...)
}
}
} else {
i := strings.TrimSpace(v)
if len(i) == 0 {
continue
}
if strings.HasPrefix(i, "#") {
continue
}
s := strings.Fields(i)
if len(s) == 0 {
continue
}
if len(hosts) == 0 {
continue
}
hosts[len(hosts)-1].Options = append(hosts[len(hosts)-1].Options, Option{Name: s[0], Value: s[1]})
}
}
return hosts, nil
}