/
root.go
203 lines (176 loc) · 6 KB
/
root.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
// Copyright © 2017 Michael Lihs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cmd
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"reflect"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-rootcerts"
"github.com/michaellihs/golab/cmd/mapper"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/xanzy/go-gitlab"
)
var cfgFile, caFile, caPath string
var gitlabClient *gitlab.Client
type golabCommand struct {
Parent *cobra.Command
Flags interface{}
Opts interface{}
Paged bool
Run func(cmd golabCommand) error
Mapper mapper.FlagMapper
Cmd *cobra.Command
}
func (c golabCommand) Execute() error {
_, _, err := c.Mapper.AutoMap()
if err != nil {
return err
}
c.Flags = c.Mapper.MappedFlags()
c.Opts = c.Mapper.MappedOpts()
if err = applyPagination(c); err != nil {
return err
}
return c.Run(c)
}
func applyPagination(c golabCommand) error {
if c.Paged {
optsReflected := reflect.ValueOf(c.Opts).Elem()
page, err := c.Cmd.Flags().GetInt("page")
if err != nil {
return err
}
optsReflected.FieldByName("ListOptions").FieldByName("Page").Set(reflect.ValueOf(page))
perPage, err := c.Cmd.Flags().GetInt("per_page")
if err != nil {
return err
}
optsReflected.FieldByName("ListOptions").FieldByName("PerPage").Set(reflect.ValueOf(perPage))
}
return nil
}
func (c golabCommand) Init() error {
c.Cmd.RunE = func(cmd *cobra.Command, args []string) error {
return c.Execute()
}
c.Mapper = mapper.InitializedMapper(c.Cmd, c.Flags, c.Opts)
setPaginationFlags(c)
c.Parent.AddCommand(c.Cmd)
return nil // TODO do something useful with the error return
}
func setPaginationFlags(c golabCommand) {
if c.Paged {
c.Cmd.PersistentFlags().Int("page", 0, "(optional) Page of results to retrieve")
c.Cmd.PersistentFlags().Int("per_page", 0, "(optional) The number of results to include per page (max 100)")
}
}
var RootCmd = &cobra.Command{
Use: "golab",
Short: "Gitlab CLI written in Go",
Long: `This application provides a Command Line Interface for Gitlab.`,
DisableAutoGenTag: true, // disables footer in markdown files generated by cobra.gendoc
}
func Execute() {
initRootCommand()
if err := RootCmd.Execute(); err != nil {
os.Exit(-1)
}
}
func OutputJson(object interface{}) error {
result, err := json.MarshalIndent(object, "", " ")
if err != nil {
return err
}
fmt.Println(string(result))
return nil
}
func initRootCommand() {
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "(optional) golab config file (default is ./.golab.yml and $HOME/.golab.yml)")
RootCmd.PersistentFlags().StringVar(&caFile, "ca-file", "", "(optional) provides a .pem file to be used in certificates pool for SSL connection")
RootCmd.PersistentFlags().StringVar(&caPath, "ca-path", "", "(optional) provides a directory with .pem certificates to be used for SSL connection")
// TODO this is an ugly hack to prevent re-initialization when mocked in testing
if gitlabClient == nil {
cobra.OnInitialize(initConfig)
cobra.OnInitialize(initGitlabClient)
}
}
func initConfig() {
if cfgFile != "" { // enable ability to specify config file via flag
viper.SetConfigFile(cfgFile)
}
if config, err := RootCmd.PersistentFlags().GetString("config"); err == nil && config != "" {
viper.SetConfigFile(config)
} else {
viper.SetConfigName(".golab") // name of config file (without extension)
viper.AddConfigPath(".") // adding current directory as first search path
viper.AddConfigPath("$HOME") // adding home directory as second search path
}
viper.AutomaticEnv() // read in environment variables that match
if err := viper.ReadInConfig(); err != nil {
fmt.Println(err)
}
}
func initGitlabClient() {
baseUrl, err := url.Parse(viper.GetString("url"))
if err != nil {
fmt.Printf("Could not parse given URL '%s': %s", baseUrl, err)
}
httpClient, err := initHttpClient()
if err != nil {
panic("Error in initializing http client " + err.Error())
}
gitlabClient = gitlab.NewClient(httpClient, viper.GetString("token"))
gitlabClient.SetBaseURL(baseUrl.String() + "/api/v4")
}
func initHttpClient() (*http.Client, error) {
// see https://github.com/hashicorp/go-rootcerts
tlsConfig := &tls.Config{}
err := rootcerts.ConfigureTLS(tlsConfig, &rootcerts.Config{
//CAFile: os.Getenv("GOLAB_CAFILE"),
//CAPath: os.Getenv("GOLAB_CAPATH"),
CAFile: caFile,
CAPath: caPath,
})
if err != nil {
return nil, err
}
c := cleanhttp.DefaultClient()
t := cleanhttp.DefaultTransport()
// use this line for debugging certificates
//fmt.Println(tlsConfig.RootCAs)
t.TLSClientConfig = tlsConfig
c.Transport = t
return c, nil
// TODO this is an ugly hack to prevent SSL verification... see https://github.com/andygrunwald/go-jira/issues/52
//tr := &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify : true},
//}
//return &http.Client{Transport: tr}, nil
}
func isoTime2String(time *gitlab.ISOTime) (string, error) {
bytes, err := time.MarshalJSON()
return string(bytes), err
}