upgrade.go 4.9 KB
Newer Older
JenkinsInChina's avatar
JenkinsInChina 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package version

import (
	"archive/tar"
	"compress/gzip"
	"fmt"
	"github.com/google/go-github/v29/github"
	"github.com/jenkins-zh/jenkins-cli/app"
	"github.com/jenkins-zh/jenkins-cli/app/cmd/common"
	"github.com/jenkins-zh/jenkins-cli/app/i18n"
	"github.com/jenkins-zh/jenkins-cli/client"
	"github.com/jenkins-zh/jenkins-cli/util"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"io"
16
	"io/ioutil"
JenkinsInChina's avatar
JenkinsInChina 已提交
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
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

// NewSelfUpgradeCmd create a command for self upgrade
func NewSelfUpgradeCmd(client common.JenkinsClient, jenkinsConfigMgr common.JenkinsConfigMgr) (cmd *cobra.Command) {
	opt := &SelfUpgradeOption{}

	cmd = &cobra.Command{
		Use:   "upgrade",
		Short: "Upgrade jcli itself",
		Long: `Upgrade jcli itself
You can use any exists version to upgrade jcli itself. If there's no argument given, it will upgrade to the latest release.
You can upgrade to the latest developing version, please use it like: jcli version upgrade dev'`,
		RunE: opt.RunE,
		Annotations: map[string]string{
			common.Since: "v0.0.26",
		},
	}
	opt.addFlags(cmd.Flags())
	return
}

func (o *SelfUpgradeOption) addFlags(flags *pflag.FlagSet) {
	flags.BoolVarP(&o.ShowProgress, "show-progress", "", true,
		i18n.T("If you want to show the progress of download Jenkins CLI"))
}

// RunE is the main point of current command
func (o *SelfUpgradeOption) RunE(cmd *cobra.Command, args []string) (err error) {
	var version string
	if len(args) > 0 {
		version = args[0]
	}

54 55 56 57 58 59 60 61 62 63 64
	// copy binary file into system path
	var targetPath string
	if targetPath, err = exec.LookPath("jcli"); err != nil {
		err = fmt.Errorf("cannot find Jenkins CLI from system path, error: %v", err)
		return
	}
	var targetF *os.File
	if targetF, err = os.OpenFile(targetPath, os.O_CREATE|os.O_RDWR, 0644); err != nil {
		return
	}

JenkinsInChina's avatar
JenkinsInChina 已提交
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
	// try to understand the version from user input
	switch version {
	case "dev":
		version = "master"
	case "":
		o.GitHubClient = github.NewClient(nil)
		ghClient := &client.GitHubReleaseClient{
			Client: o.GitHubClient,
		}
		if asset, assetErr := ghClient.GetLatestJCLIAsset(); assetErr == nil && asset != nil {
			version = asset.TagName
		} else {
			err = fmt.Errorf("cannot get the latest version, error: %s", assetErr)
			return
		}
	}

	// version review
	currentVersion := app.GetVersion()
	if currentVersion == version {
		cmd.Println("no need to upgrade Jenkins CLI")
		return
	}
	cmd.Println(fmt.Sprintf("prepare to upgrade to %s", version))

	// download the tar file of Jenkins CLI
	tmpDir := os.TempDir()
	output := fmt.Sprintf("%s/jcli.tar.gz", tmpDir)
	fileURL := fmt.Sprintf("https://cdn.jsdelivr.net/gh/jenkins-zh/jcli-repo@%s/jcli-%s-amd64.tar.gz",
		version, runtime.GOOS)
	defer func() {
		_ = os.RemoveAll(output)
	}()

99 100 101 102 103
	// make sure we count the download action
	go func() {
		o.downloadCount(version, runtime.GOOS)
	}()

JenkinsInChina's avatar
JenkinsInChina 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	downloader := util.HTTPDownloader{
		RoundTripper:   o.RoundTripper,
		TargetFilePath: output,
		URL:            fileURL,
		ShowProgress:   o.ShowProgress,
	}
	if err = downloader.DownloadFile(); err != nil {
		err = fmt.Errorf("cannot download Jenkins CLI from %s, error: %v", fileURL, err)
		return
	}

	if err = o.extractFiles(output); err == nil {
		sourceFile := fmt.Sprintf("%s/jcli", filepath.Dir(output))
		sourceF, _ := os.Open(sourceFile)
		if _, err = io.Copy(targetF, sourceF); err != nil {
			err = fmt.Errorf("cannot copy Jenkins CLI from %s to %s, error: %v", sourceFile, targetPath, err)
		}
	} else {
		err = fmt.Errorf("cannot extract Jenkins CLI from tar file, error: %v", err)
	}
	return
}

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
func (o *SelfUpgradeOption) downloadCount(version string, arch string) {
	countURL := fmt.Sprintf("https: //github.com/jenkins-zh/jenkins-cli/releases/download/v%s/jcli-%s-amd64.tar.gz",
		version, arch)

	if tempDir, err := ioutil.TempDir(".", "download-count"); err == nil {
		tempFile := tempDir + "/jcli.tar.gz"
		defer func() {
			_ = os.RemoveAll(tempDir)
		}()

		downloader := util.HTTPDownloader{
			RoundTripper:   o.RoundTripper,
			TargetFilePath: tempFile,
			URL:            countURL,
		}
		// we don't care about the result, just for counting
		_ = downloader.DownloadFile()
	}
}

JenkinsInChina's avatar
JenkinsInChina 已提交
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
func (o *SelfUpgradeOption) extractFiles(tarFile string) (err error) {
	var f *os.File
	var gzf *gzip.Reader
	if f, err = os.Open(tarFile); err != nil {
		return
	}
	defer func() {
		_ = f.Close()
	}()

	if gzf, err = gzip.NewReader(f); err != nil {
		return
	}

	tarReader := tar.NewReader(gzf)
	var header *tar.Header
	for {
		if header, err = tarReader.Next(); err == io.EOF {
			err = nil
			break
		} else if err != nil {
			break
		}
		name := header.Name

		switch header.Typeflag {
		case tar.TypeReg:
			if name != "jcli" {
				continue
			}
			var targetFile *os.File
			if targetFile, err = os.OpenFile(fmt.Sprintf("%s/%s", filepath.Dir(tarFile), name),
				os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)); err != nil {
				break
			}
			if _, err = io.Copy(targetFile, tarReader); err != nil {
				break
			}
			_ = targetFile.Close()
		}
	}
	return
}