-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
122 lines (108 loc) · 2.45 KB
/
util.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
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/finkf/pcwgo/api"
"github.com/spf13/cobra"
)
func chk(err error) {
if err == nil {
return
}
log.Fatalf("error: %v", err)
}
func exactArgs(allowed ...int) func(_ *cobra.Command, args []string) error {
return func(_ *cobra.Command, args []string) error {
n := len(args)
for _, allowed := range allowed {
if n == allowed {
return nil
}
}
return fmt.Errorf("invalid number of args: %d (allowed: %v)", n, args)
}
}
func parseIDs(id string, ids ...*int) int {
split := strings.Split(id, ":")
var i int
for i = 0; i < len(ids) && i < len(split); i++ {
id, err := strconv.Atoi(split[i])
if err != nil {
return 0
}
*ids[i] = id
}
return i
}
func unescape(args ...string) []string {
res := make([]string, len(args))
for i := range args {
u, err := strconv.Unquote(`"` + args[i] + `"`)
if err != nil {
res[i] = args[i]
} else {
res[i] = u
}
}
return res
}
func getURL() string {
if opts.pocowebURL != "" {
return opts.pocowebURL
}
return os.Getenv("POCOWEB_URL")
}
func getAuth() string {
if opts.authToken != "" {
return opts.authToken
}
return os.Getenv("POCOWEB_AUTH")
}
func debugf(format string, args ...interface{}) {
if opts.debug {
log.Printf(format, args...)
}
}
func authenticate() *api.Client {
url := getURL()
auth := getAuth()
debugf("authenticating [url=%s,auth=%s]", url, auth)
return api.Authenticate(url, auth, opts.skipVerify)
}
func get(c *api.Client, url string, out interface{}) error {
debugf("GET %s [auth=%s]", url, c.Session.Auth)
return c.Get(url, out)
}
func post(c *api.Client, url string, payload, out interface{}) error {
debugf("POST %s [auth=%s]", url, c.Session.Auth)
return c.Post(url, payload, out)
}
func delete(c *api.Client, url string, out interface{}) error {
debugf("DELETE %s [auth=%s]", url, c.Session.Auth)
return c.Delete(url, nil)
}
func downloadZIP(c *api.Client, url string, out io.Writer) error {
debugf("download zip %s [auth=%s]", url, c.Session.Auth)
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
if err != nil {
return err
}
res, err := c.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("bad status code: %s", res.Status)
}
if ct := res.Header.Get("Content-Type"); ct != "application/zip" {
return fmt.Errorf("bad content type: %s", ct)
}
_, err = io.Copy(out, res.Body)
return err
}