forked from jenkins-zh/jenkins-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
251 lines (216 loc) · 5.66 KB
/
config.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
package cmd
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"runtime"
"github.com/linuxsuren/jenkins-cli/util"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
)
type ConfigOptions struct {
Current string
Show bool
Generate bool
List bool
ConfigFileLocation string
}
var configOptions ConfigOptions
func init() {
rootCmd.AddCommand(configCmd)
configCmd.Flags().StringVarP(&configOptions.Current, "current", "c", "", "Set the current Jenkins")
configCmd.Flags().BoolVarP(&configOptions.Show, "show", "s", false, "Show the current Jenkins")
configCmd.Flags().BoolVarP(&configOptions.Generate, "generate", "g", false, "Generate a sample config file for you")
configCmd.Flags().BoolVarP(&configOptions.List, "list", "l", false, "Display all your Jenkins configs")
}
var configCmd = &cobra.Command{
Use: "config",
Short: "Manage the config of jcli",
Long: `Manage the config of jcli`,
Args: func(cmd *cobra.Command, args []string) (err error) {
if !configOptions.Show && !configOptions.Generate &&
!configOptions.List && configOptions.Current == "" {
err = errors.New("need arguments")
}
return
},
Run: func(cmd *cobra.Command, args []string) {
current := getCurrentJenkins()
if configOptions.Show {
fmt.Printf("Current Jenkins's name is %s, url is %s\n", current.Name, current.URL)
}
if configOptions.List {
table := util.CreateTable(os.Stdout)
table.AddRow("number", "name", "url")
for i, jenkins := range getConfig().JenkinsServers {
name := jenkins.Name
if name == current.Name {
name = fmt.Sprintf("*%s", name)
}
table.AddRow(fmt.Sprintf("%d", i), name, jenkins.URL)
}
table.Render()
}
if configOptions.Generate {
if data, err := generateSampleConfig(); err == nil {
fmt.Print(string(data))
fmt.Println("# Goto 'http://localhost:8080/jenkins/me/configure', then you can generate your token.")
} else {
log.Fatal(err)
}
}
if configOptions.Current != "" {
setCurrentJenkins(configOptions.Current)
}
},
Example: "jcli config -l",
}
// JenkinsServer holds the configuration of your Jenkins
type JenkinsServer struct {
Name string `yaml:"name"`
URL string `yaml:"url"`
UserName string `yaml:"username"`
Token string `yaml:"token"`
Proxy string `yaml:"proxy"`
ProxyAuth string `yaml:"proxyAuth"`
}
type Config struct {
Current string `yaml:"current"`
JenkinsServers []JenkinsServer `yaml:"jenkins_servers"`
}
func setCurrentJenkins(name string) {
found := false
for _, jenkins := range getConfig().JenkinsServers {
if jenkins.Name == name {
found = true
break
}
}
if found {
config.Current = name
if err := saveConfig(); err != nil {
log.Fatal(err)
}
} else {
log.Fatalf("Cannot found Jenkins by name %s", name)
}
}
func generateSampleConfig() ([]byte, error) {
sampleConfig := Config{
Current: "yourServer",
JenkinsServers: []JenkinsServer{
{
Name: "yourServer",
URL: "http://localhost:8080/jenkins",
UserName: "admin",
Token: "111e3a2f0231198855dceaff96f20540a9",
},
},
}
return yaml.Marshal(&sampleConfig)
}
var config Config
func getConfig() Config {
return config
}
func getJenkinsNames() []string {
config := getConfig()
names := make([]string, 0)
for _, j := range config.JenkinsServers {
names = append(names, j.Name)
}
return names
}
func getCurrentJenkins() (jenkinsServer *JenkinsServer) {
config := getConfig()
current := config.Current
jenkinsServer = findJenkinsByName(current)
return
}
func findJenkinsByName(name string) (jenkinsServer *JenkinsServer) {
for _, cfg := range config.JenkinsServers {
if cfg.Name == name {
jenkinsServer = &cfg
break
}
}
return
}
func addJenkins(jenkinsServer JenkinsServer) (err error) {
jenkinsName := jenkinsServer.Name
if jenkinsName == "" {
err = fmt.Errorf("Name cannot be empty")
return
}
if findJenkinsByName(jenkinsName) != nil {
err = fmt.Errorf("Jenkins %s is existed", jenkinsName)
return
}
config.JenkinsServers = append(config.JenkinsServers, jenkinsServer)
err = saveConfig()
return
}
func removeJenkins(name string) (err error) {
current := getCurrentJenkins()
if name == current.Name {
err = fmt.Errorf("You cannot remove current Jenkins")
}
index := -1
config := getConfig()
for i, jenkins := range config.JenkinsServers {
if name == jenkins.Name {
index = i
break
}
}
if index == -1 {
err = fmt.Errorf("Cannot found by name %s", name)
} else {
config.JenkinsServers[index] = config.JenkinsServers[len(config.JenkinsServers)-1]
config.JenkinsServers[len(config.JenkinsServers)-1] = JenkinsServer{}
config.JenkinsServers = config.JenkinsServers[:len(config.JenkinsServers)-1]
err = saveConfig()
}
return
}
func loadDefaultConfig() (err error) {
userHome := userHomeDir()
configPath := fmt.Sprintf("%s/.jenkins-cli.yaml", userHome)
if _, err = os.Stat(configPath); err == nil {
err = loadConfig(configPath)
}
return
}
func loadConfig(path string) (err error) {
configOptions.ConfigFileLocation = path
var content []byte
if content, err = ioutil.ReadFile(path); err == nil {
err = yaml.Unmarshal([]byte(content), &config)
}
return
}
func saveConfig() (err error) {
var data []byte
config := getConfig()
if data, err = yaml.Marshal(&config); err == nil {
err = ioutil.WriteFile(configOptions.ConfigFileLocation, data, 0644)
}
return
}
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
} else if runtime.GOOS == "linux" {
home := os.Getenv("XDG_CONFIG_HOME")
if home != "" {
return home
}
}
return os.Getenv("HOME")
}