forked from ghetzel/pivot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
298 lines (249 loc) · 6.68 KB
/
connection.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package dal
import (
"fmt"
"net/url"
"strings"
"time"
"github.com/ghetzel/go-stockutil/fileutil"
"github.com/ghetzel/go-stockutil/log"
"github.com/ghetzel/go-stockutil/sliceutil"
"github.com/ghetzel/go-stockutil/stringutil"
"github.com/ghetzel/go-stockutil/typeutil"
"github.com/jdxcode/netrc"
)
var schemeAliasMap = make(map[string]string)
func AddConnectionSchemeAlias(from string, to string) {
schemeAliasMap[from] = to
}
type ConnectionString struct {
URI *url.URL
Options map[string]interface{}
}
func (self *ConnectionString) String() string {
if self.URI != nil {
backend, protocol := self.Scheme()
scheme := backend
if protocol != `` {
scheme += `+` + protocol
}
str := fmt.Sprintf(
"%s://%s",
scheme,
strings.Join(sliceutil.CompactString([]string{
self.Host(),
self.Dataset(),
}), `/`),
)
if qs := self.URI.RawQuery; qs != `` {
str += `?` + qs
}
return str
} else {
return ``
}
}
// Returns the backend and protocol components of the string.
func (self *ConnectionString) Scheme() (string, string) {
backend, protocol := stringutil.SplitPair(self.URI.Scheme, `+`)
if actual, ok := schemeAliasMap[backend]; ok && actual != `` {
backend = actual
}
return backend, strings.Trim(protocol, `/`)
}
// Returns the backend component of the string.
func (self *ConnectionString) Backend() string {
backend, _ := self.Scheme()
return backend
}
// Returns the protocol component of the string.
func (self *ConnectionString) Protocol(defaults ...string) string {
if _, protocol := self.Scheme(); protocol != `` {
return protocol
} else if len(defaults) > 0 {
return defaults[0]
} else {
return ``
}
}
// Returns the host component of the string.
func (self *ConnectionString) Host(defaults ...string) string {
if host := self.URI.Host; host != `` {
return host
} else if len(defaults) > 0 {
return defaults[0]
} else {
return ``
}
}
// Returns the dataset component of the string.
func (self *ConnectionString) Dataset() string {
dataset := self.URI.Path
dataset = strings.TrimPrefix(dataset, `/`)
dataset = strings.TrimSuffix(dataset, `/`)
return dataset
}
// Explicitly set username and password on this connection string
func (self *ConnectionString) SetCredentials(username string, password string) {
self.URI.User = url.UserPassword(username, password)
}
// Reads a .netrc-style file and loads the appropriate credentials. The host component of
// this connection string is matched with the netrc "machine" field.
func (self *ConnectionString) LoadCredentialsFromNetrc(filename string) error {
if u := self.URI.User; u == nil && filename != `` {
filename = fileutil.MustExpandUser(filename)
if fileutil.IsNonemptyFile(filename) {
if netrcFile, err := netrc.Parse(filename); err == nil {
if machine := netrcFile.Machine(self.URI.Hostname()); machine != nil {
log.Debugf("Reading credentials from %v for host %v", filename, machine.Name)
login := machine.Get(`login`)
password := machine.Get(`password`)
if login != `` || password != `` {
self.URI.User = url.UserPassword(login, password)
}
}
} else {
return fmt.Errorf("netrc error: %v", err)
}
}
}
return nil
}
// Return the credentials (if any) associated with this string, and whether they
// were present or not.
func (self *ConnectionString) Credentials() (string, string, bool) {
if userinfo := self.URI.User; userinfo != nil {
pw, _ := userinfo.Password()
return userinfo.Username(), pw, true
} else {
return ``, ``, false
}
}
func (self *ConnectionString) HasOpt(key string) bool {
_, ok := self.Options[key]
return ok
}
func (self *ConnectionString) ClearOpt(key string) {
delete(self.Options, key)
}
func (self *ConnectionString) Opt(key string) typeutil.Variant {
return typeutil.V(self.Options[key])
}
func (self *ConnectionString) OptString(key string, fallback string) string {
if v := typeutil.V(self.Options[key]).String(); v != `` {
return v
} else {
return fallback
}
}
func (self *ConnectionString) OptBool(key string, fallback bool) bool {
if self.HasOpt(key) {
return typeutil.V(self.Options[key]).Bool()
}
return fallback
}
func (self *ConnectionString) OptInt(key string, fallback int64) int64 {
if v := typeutil.V(self.Options[key]).Int(); v != 0 {
return v
} else {
return fallback
}
}
func (self *ConnectionString) OptFloat(key string, fallback float64) float64 {
if v := typeutil.V(self.Options[key]).Float(); v != 0 {
return v
} else {
return fallback
}
}
func (self *ConnectionString) OptTime(key string, fallback time.Time) time.Time {
if v := typeutil.V(self.Options[key]).Time(); !v.IsZero() {
return v
} else {
return fallback
}
}
func (self *ConnectionString) OptDuration(key string, fallback time.Duration) time.Duration {
if v := typeutil.V(self.Options[key]).Duration(); v != 0 {
return v
} else {
return fallback
}
}
func ParseConnectionString(conn string) (ConnectionString, error) {
if uri, err := url.Parse(conn); err == nil {
if err := prepareURI(uri); err == nil {
return ConnectionString{
URI: uri,
Options: optionsFromURI(uri),
}, nil
} else {
return ConnectionString{}, err
}
} else {
return ConnectionString{}, err
}
}
func MustParseConnectionString(conn string) ConnectionString {
if cs, err := ParseConnectionString(conn); err == nil {
return cs
} else {
panic(err.Error())
}
}
func MakeConnectionString(scheme string, host string, dataset string, options map[string]interface{}) (ConnectionString, error) {
qs := url.Values{}
for k, v := range options {
if strvalue, err := stringutil.ToString(v); err == nil {
values := strings.Split(strvalue, `,`)
for _, vv := range values {
qs.Add(k, vv)
}
} else {
return ConnectionString{}, err
}
}
uri := &url.URL{
Scheme: scheme,
Host: host,
Path: dataset,
RawQuery: qs.Encode(),
}
if err := prepareURI(uri); err == nil {
return ConnectionString{
URI: uri,
Options: optionsFromURI(uri),
}, nil
} else {
return ConnectionString{}, err
}
}
func prepareURI(uri *url.URL) error {
if v, err := fileutil.ExpandUser(uri.Host); err == nil {
uri.Host = v
} else {
return fmt.Errorf("host: %v", err)
}
if v, err := fileutil.ExpandUser(uri.Path); err == nil {
uri.Path = v
} else {
return fmt.Errorf("path: %v", err)
}
return nil
}
func optionsFromURI(uri *url.URL) map[string]interface{} {
rv := make(map[string]interface{})
for key, values := range uri.Query() {
if len(values) > 0 {
if len(values) == 1 {
rv[key] = stringutil.Autotype(values[0])
} else {
vI := make([]interface{}, len(values))
for i, vv := range values {
vI[i] = stringutil.Autotype(vv)
}
rv[key] = vI
}
}
}
return rv
}