-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathconn.go
97 lines (84 loc) · 1.6 KB
/
conn.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
package p4
import (
"time"
)
const defaultExpTimeout = 15 * time.Second
var defaultTimeout = &Timeout{
Login: defaultExpTimeout,
Read: defaultExpTimeout,
Write: defaultExpTimeout,
}
type opType int
const (
opTypeInvalid opType = iota
opTypeLogin
opTypeRead
opTypeWrite
opTypeMax
)
// ConnOptions Conn is an interface to the Conn command line client.
type ConnOptions struct {
address string
binary string
username string
password string
client string
}
type ConnOptionFunc func(*Conn)
type Conn struct {
ConnOptions
env []string
timeout *Timeout
}
type Timeout struct {
Login time.Duration `json:"login"`
Read time.Duration `json:"read"`
Write time.Duration `json:"write"`
}
func (t *Timeout) OpTimeout(opt opType) time.Duration {
if t == nil {
return defaultExpTimeout
}
switch opt {
case opTypeLogin:
return t.Login
case opTypeRead:
return t.Read
case opTypeWrite:
return t.Write
default:
return defaultExpTimeout
}
}
func NewConn(address, username, password string, options ...ConnOptionFunc) (conn *Conn, err error) {
conn = &Conn{
ConnOptions: ConnOptions{
binary: "p4",
address: address,
username: username,
password: password,
},
timeout: defaultTimeout,
}
for _, opt := range options {
opt(conn)
}
if err = conn.Login(); err != nil {
return
}
return
}
func WithClient(client string) ConnOptionFunc {
return func(conn *Conn) {
conn.SetClient(client)
}
}
func WithTimeout(timeout *Timeout) ConnOptionFunc {
return func(conn *Conn) {
if timeout != nil {
conn.timeout = timeout
} else {
conn.timeout = defaultTimeout
}
}
}