/
bz.go
118 lines (85 loc) · 2.13 KB
/
bz.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
package main
import (
"bugzilla"
"encoding/gob"
"fmt"
"net/http"
"os"
"path"
"github.com/jessevdk/xmlrpc"
)
var bz *bugzilla.Conn
func SaveCookies() {
if bz == nil || bz.Client == nil {
return
}
cookies := bz.Client.Cookies()
host := bz.Client.CookieHost()
os.MkdirAll(".cookies", 0700)
f, err := os.OpenFile(path.Join(".cookies", host), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create cookies: %s\n", err)
return
}
defer f.Close()
enc := gob.NewEncoder(f)
if err := enc.Encode(cookies); err != nil {
fmt.Fprintf(os.Stderr, "Failed to encode cookies: %s\n", err)
}
authFile := path.Join(".cookies", host+".auth")
if bugzilla.AuthUser != nil {
f, err = os.OpenFile(authFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create auth: %s\n", err)
return
}
defer f.Close()
enc = gob.NewEncoder(f)
if err := enc.Encode(*bugzilla.AuthUser); err != nil {
fmt.Fprintf(os.Stderr, "Failed to encode auth: %s\n", err)
}
} else {
os.Remove(authFile)
}
}
func loadSavedCookies(client *xmlrpc.Client) {
host := client.CookieHost()
f, err := os.Open(path.Join(".cookies", host))
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to open cookie file: %s\n", err)
return
}
defer f.Close()
dec := gob.NewDecoder(f)
cookies := make([]*http.Cookie, 0, 10)
if err := dec.Decode(&cookies); err != nil {
fmt.Fprintf(os.Stderr, "Failed to decode cookies: %s\n", err)
return
}
client.SetCookies(cookies)
authFile := path.Join(".cookies", host+".auth")
f, err = os.Open(authFile)
if err != nil {
bugzilla.AuthUser = nil
} else {
dec := gob.NewDecoder(f)
var userAuth bugzilla.UserAuth
if err := dec.Decode(&userAuth); err != nil {
fmt.Fprintf(os.Stderr, "Failed to decode auth: %s\n", err)
} else {
bugzilla.AuthUser = &userAuth
}
}
}
func Bz() (*bugzilla.Conn, error) {
if bz != nil {
return bz, nil
}
var err error
bz, err = bugzilla.Dial(bugzilla.Address{
Host: options.Bugzilla.Host,
Secure: options.Bugzilla.Secure,
})
loadSavedCookies(bz.Client)
return bz, err
}