plugin.go 7.1 KB
Newer Older
LinuxSuRen's avatar
LinuxSuRen 已提交
1 2 3 4
package cmd

import (
	"bytes"
LinuxSuRen's avatar
LinuxSuRen 已提交
5
	"crypto/tls"
LinuxSuRen's avatar
LinuxSuRen 已提交
6 7 8 9 10 11 12 13
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
14
	"strings"
LinuxSuRen's avatar
LinuxSuRen 已提交
15

LinuxSuRen's avatar
LinuxSuRen 已提交
16
	"github.com/gosuri/uiprogress"
17
	"github.com/linuxsuren/jenkins-cli/client"
LinuxSuRen's avatar
LinuxSuRen 已提交
18
	"github.com/linuxsuren/jenkins-cli/util"
LinuxSuRen's avatar
LinuxSuRen 已提交
19 20 21
	"github.com/spf13/cobra"
)

22
// PluginOptions contains the command line options
LinuxSuRen's avatar
LinuxSuRen 已提交
23
type PluginOptions struct {
24 25
	OutputOption

26 27 28
	Upload      bool
	CheckUpdate bool
	Open        bool
LinuxSuRen's avatar
LinuxSuRen 已提交
29 30
	List        bool

LinuxSuRen's avatar
LinuxSuRen 已提交
31
	Install   []string
LinuxSuRen's avatar
LinuxSuRen 已提交
32
	Uninstall string
LinuxSuRen's avatar
LinuxSuRen 已提交
33 34

	Filter []string
LinuxSuRen's avatar
LinuxSuRen 已提交
35 36 37 38
}

func init() {
	rootCmd.AddCommand(pluginCmd)
39 40 41 42 43 44 45 46
	pluginCmd.Flags().BoolVarP(&pluginOpt.Upload, "upload", "u", false, "Upload plugin to your Jenkins server")
	pluginCmd.Flags().BoolVarP(&pluginOpt.CheckUpdate, "check", "c", false, "Checkout update center server")
	pluginCmd.Flags().BoolVarP(&pluginOpt.Open, "open", "o", false, "Open the browse with the address of plugin manager")
	pluginCmd.Flags().BoolVarP(&pluginOpt.List, "list", "l", false, "Print all the plugins which are installed")
	pluginCmd.Flags().StringVarP(&pluginOpt.Format, "format", "", TableOutputFormat, "Format the output")
	pluginCmd.Flags().StringArrayVarP(&pluginOpt.Install, "install", "", []string{}, "Install a plugin by shortName")
	pluginCmd.Flags().StringVarP(&pluginOpt.Uninstall, "uninstall", "", "", "Uninstall a plugin by shortName")
	pluginCmd.Flags().StringArrayVarP(&pluginOpt.Filter, "filter", "", []string{}, "Filter for the list, like: active, hasUpdate, downgradable, enable, name=foo")
LinuxSuRen's avatar
LinuxSuRen 已提交
47 48
}

49
var pluginOpt PluginOptions
LinuxSuRen's avatar
LinuxSuRen 已提交
50 51 52

var pluginCmd = &cobra.Command{
	Use:   "plugin",
53 54
	Short: "Manage the plugins of Jenkins",
	Long:  `Manage the plugins of Jenkins`,
LinuxSuRen's avatar
LinuxSuRen 已提交
55
	Run: func(cmd *cobra.Command, args []string) {
56
		if pluginOpt.Upload {
LinuxSuRen's avatar
LinuxSuRen 已提交
57 58
			crumb, config := getCrumb()

59
			api := fmt.Sprintf("%s/pluginManager/uploadPlugin", config.URL)
LinuxSuRen's avatar
LinuxSuRen 已提交
60 61

			path, _ := os.Getwd()
62
			dirName := filepath.Base(path)
63
			dirName = strings.Replace(dirName, "-plugin", "", -1)
64
			path += fmt.Sprintf("/target/%s.hpi", dirName)
LinuxSuRen's avatar
LinuxSuRen 已提交
65 66 67 68 69
			extraParams := map[string]string{}
			request, err := newfileUploadRequest(api, extraParams, "@name", path)
			if err != nil {
				log.Fatal(err)
			}
70
			request.SetBasicAuth(config.UserName, config.Token)
LinuxSuRen's avatar
LinuxSuRen 已提交
71 72 73
			request.Header.Add("Accept", "*/*")
			request.Header.Add(crumb.CrumbRequestField, crumb.Crumb)
			if err == nil {
LinuxSuRen's avatar
LinuxSuRen 已提交
74 75 76 77
				tr := &http.Transport{
					TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
				}
				client := &http.Client{Transport: tr}
LinuxSuRen's avatar
LinuxSuRen 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
				var response *http.Response
				response, err = client.Do(request)
				if err != nil {
					fmt.Println(err)
				} else if response.StatusCode != 200 {
					var data []byte
					if data, err = ioutil.ReadAll(response.Body); err == nil {
						fmt.Println(string(data))
					} else {
						log.Fatal(err)
					}
				}
			} else {
				log.Fatal(err)
			}
		}
94

LinuxSuRen's avatar
LinuxSuRen 已提交
95 96 97 98 99 100
		config := getCurrentJenkins()
		jenkins := getCurrentJenkins()
		jclient := &client.PluginManager{}
		jclient.URL = jenkins.URL
		jclient.UserName = config.UserName
		jclient.Token = config.Token
101 102 103 104 105 106 107
		if pluginOpt.CheckUpdate {
			jclient.CheckUpdate(func(response *http.Response) {
				code := response.StatusCode
				if code == 200 {
					fmt.Println("update site updated.")
				} else {
					contentData, _ := ioutil.ReadAll(response.Body)
LinuxSuRen's avatar
LinuxSuRen 已提交
108
					log.Fatal(fmt.Sprintf("response code is %d, content: %s",
109 110 111 112 113 114 115 116 117 118 119 120
						code, string(contentData)))
				}
			})
		}

		if pluginOpt.Open {
			if jenkins.URL != "" {
				open(fmt.Sprintf("%s/pluginManager", jenkins.URL))
			} else {
				log.Fatal(fmt.Sprintf("No URL fond from %s", jenkins.Name))
			}
		}
LinuxSuRen's avatar
LinuxSuRen 已提交
121 122

		if pluginOpt.List {
LinuxSuRen's avatar
LinuxSuRen 已提交
123 124 125 126
			var (
				filter       bool
				hasUpdate    bool
				downgradable bool
LinuxSuRen's avatar
LinuxSuRen 已提交
127 128 129
				enable       bool
				active       bool
				pluginName   string
LinuxSuRen's avatar
LinuxSuRen 已提交
130 131 132 133 134 135 136 137 138
			)
			if pluginOpt.Filter != nil {
				filter = true
				for _, f := range pluginOpt.Filter {
					switch f {
					case "hasUpdate":
						hasUpdate = true
					case "downgradable":
						downgradable = true
LinuxSuRen's avatar
LinuxSuRen 已提交
139 140 141 142 143 144 145 146 147 148
					case "enable":
						enable = true
					case "active":
						active = true
					case "name":
						downgradable = true
					}

					if strings.HasPrefix(f, "name=") {
						pluginName = strings.TrimPrefix(f, "name=")
LinuxSuRen's avatar
LinuxSuRen 已提交
149 150 151 152
					}
				}
			}

LinuxSuRen's avatar
LinuxSuRen 已提交
153
			if plugins, err := jclient.GetPlugins(); err == nil {
154 155
				filteredPlugins := make([]client.Plugin, 0)
				for _, plugin := range plugins.Plugins {
LinuxSuRen's avatar
LinuxSuRen 已提交
156 157 158 159 160 161 162 163
					if filter {
						if hasUpdate && !plugin.HasUpdate {
							continue
						}

						if downgradable && !plugin.Downgradable {
							continue
						}
LinuxSuRen's avatar
LinuxSuRen 已提交
164 165 166 167 168 169 170 171 172 173 174 175

						if enable && !plugin.Enable {
							continue
						}

						if active && !plugin.Active {
							continue
						}

						if pluginName != "" && !strings.Contains(plugin.ShortName, pluginName) {
							continue
						}
176 177

						filteredPlugins = append(filteredPlugins, plugin)
LinuxSuRen's avatar
LinuxSuRen 已提交
178
					}
LinuxSuRen's avatar
LinuxSuRen 已提交
179
				}
180 181 182 183 184 185 186 187

				if data, err := pluginOpt.Output(filteredPlugins); err == nil {
					if len(data) > 0 {
						fmt.Println(string(data))
					}
				} else {
					log.Fatal(err)
				}
LinuxSuRen's avatar
LinuxSuRen 已提交
188 189 190 191 192
			} else {
				log.Fatal(err)
			}
		}

LinuxSuRen's avatar
LinuxSuRen 已提交
193 194 195 196 197 198
		if pluginOpt.Install != nil && len(pluginOpt.Install) > 0 {
			if err := jclient.InstallPlugin(pluginOpt.Install); err != nil {
				log.Fatal(err)
			}
		}

LinuxSuRen's avatar
LinuxSuRen 已提交
199 200 201 202 203
		if pluginOpt.Uninstall != "" {
			if err := jclient.UninstallPlugin(pluginOpt.Uninstall); err != nil {
				log.Fatal(err)
			}
		}
LinuxSuRen's avatar
LinuxSuRen 已提交
204 205 206
	},
}

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
func (o *PluginOptions) Output(obj interface{}) (data []byte, err error) {
	if data, err = o.OutputOption.Output(obj); err != nil {
		pluginList := obj.([]client.Plugin)
		table := util.CreateTable(os.Stdout)
		table.AddRow("number", "name", "version", "update")
		for i, plugin := range pluginList {
			table.AddRow(fmt.Sprintf("%d", i), plugin.ShortName, plugin.Version, fmt.Sprintf("%v", plugin.HasUpdate))
		}
		table.Render()
		err = nil
		data = []byte{}
	}
	return
}

LinuxSuRen's avatar
LinuxSuRen 已提交
222 223 224 225 226
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
LinuxSuRen's avatar
LinuxSuRen 已提交
227 228 229 230 231 232 233

	var total float64
	if stat, err := file.Stat(); err != nil {
		panic(err)
	} else {
		total = float64(stat.Size())
	}
LinuxSuRen's avatar
LinuxSuRen 已提交
234 235
	defer file.Close()

LinuxSuRen's avatar
LinuxSuRen 已提交
236 237 238 239 240
	// body := &bytes.Buffer{}
	body := &ProgressIndicator{
		Total: total,
	}
	body.Init()
LinuxSuRen's avatar
LinuxSuRen 已提交
241 242 243 244 245
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return nil, err
	}
LinuxSuRen's avatar
LinuxSuRen 已提交
246

LinuxSuRen's avatar
LinuxSuRen 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260
	_, err = io.Copy(part, file)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", uri, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	return req, err
}
LinuxSuRen's avatar
LinuxSuRen 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

type ProgressIndicator struct {
	bytes.Buffer
	Total float64
	count float64
	bar   *uiprogress.Bar
}

func (i *ProgressIndicator) Init() {
	uiprogress.Start()             // start rendering
	i.bar = uiprogress.AddBar(100) // Add a new bar

	// optionally, append and prepend completion and elapsed time
	i.bar.AppendCompleted()
	// i.bar.PrependElapsed()
}

func (i *ProgressIndicator) Write(p []byte) (n int, err error) {
	n, err = i.Buffer.Write(p)
	return
}

func (i *ProgressIndicator) Read(p []byte) (n int, err error) {
	n, err = i.Buffer.Read(p)
	i.count += float64(n)
	i.bar.Set((int)(i.count * 100 / i.Total))
	return
}