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

import (
	"fmt"
LinuxSuRen's avatar
LinuxSuRen 已提交
5
	"io"
6
	"log"
LinuxSuRen's avatar
LinuxSuRen 已提交
7
	"os"
LinuxSuRen's avatar
LinuxSuRen 已提交
8 9
	"os/exec"
	"strings"
LinuxSuRen's avatar
LinuxSuRen 已提交
10

11
	"github.com/jenkins-zh/jenkins-cli/app"
LinuxSuRen's avatar
LinuxSuRen 已提交
12 13 14
	"github.com/spf13/cobra"
)

LinuxSuRen's avatar
LinuxSuRen 已提交
15
// RootOptions is a global option for whole cli
16
type RootOptions struct {
17 18 19 20
	ConfigFile string
	Jenkins    string
	Version    bool
	Debug      bool
21 22
}

LinuxSuRen's avatar
LinuxSuRen 已提交
23
var rootCmd = &cobra.Command{
24 25 26 27 28
	Use:   "jcli",
	Short: "jcli is a tool which could help you with your multiple Jenkins",
	Long: `jcli is Jenkins CLI which could help with your multiple Jenkins,
				  Manage your Jenkins and your pipelines
				  More information could found at https://jenkins-zh.cn`,
29 30
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Println("Jenkins CLI (jcli) manage your Jenkins")
31
		if rootOptions.Version {
32 33
			cmd.Printf("Version: %s\n", app.GetVersion())
			cmd.Printf("Commit: %s\n", app.GetCommit())
34
		}
35 36 37 38 39 40 41 42 43
		if rootOptions.Jenkins != "" {
			current := getCurrentJenkinsFromOptionsOrDie()
			if current != nil {
				cmd.Println("Current Jenkins is:", current.Name)
			} else {
				cmd.Println("Cannot found the configuration")
			}
		}

LinuxSuRen's avatar
LinuxSuRen 已提交
44 45 46
	},
}

LinuxSuRen's avatar
LinuxSuRen 已提交
47
// Execute will exectue the command
LinuxSuRen's avatar
LinuxSuRen 已提交
48 49 50 51 52 53 54
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

55
var rootOptions RootOptions
LinuxSuRen's avatar
LinuxSuRen 已提交
56 57 58

func init() {
	cobra.OnInitialize(initConfig)
59
	rootCmd.PersistentFlags().StringVarP(&rootOptions.ConfigFile, "configFile", "", "", "An alternative config file")
LinuxSuRen's avatar
LinuxSuRen 已提交
60
	rootCmd.PersistentFlags().StringVarP(&rootOptions.Jenkins, "jenkins", "j", "", "Select a Jenkins server for this time")
61
	rootCmd.PersistentFlags().BoolVarP(&rootOptions.Version, "version", "v", false, "Print the version of Jenkins CLI")
62
	rootCmd.PersistentFlags().BoolVarP(&rootOptions.Debug, "debug", "", false, "Print the output into debug.html")
LinuxSuRen's avatar
LinuxSuRen 已提交
63 64 65
}

func initConfig() {
66 67 68
	if rootOptions.Version && rootCmd.Flags().NFlag() == 1 {
		return
	}
69 70 71
	if rootOptions.ConfigFile == "" {
		if err := loadDefaultConfig(); err != nil {
			configLoadErrorHandle(err)
72
		}
73 74 75 76 77 78
	} else {
		if err := loadConfig(rootOptions.ConfigFile); err != nil {
			configLoadErrorHandle(err)
		}
	}
}
79

80 81 82 83
func configLoadErrorHandle(err error) {
	if os.IsNotExist(err) {
		log.Printf("No config file found.")
		return
84
	}
85 86

	log.Fatalf("Config file is invalid: %v", err)
LinuxSuRen's avatar
LinuxSuRen 已提交
87
}
LinuxSuRen's avatar
LinuxSuRen 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104

func getCurrentJenkinsFromOptions() (jenkinsServer *JenkinsServer) {
	jenkinsOpt := rootOptions.Jenkins
	if jenkinsOpt == "" {
		jenkinsServer = getCurrentJenkins()
	} else {
		jenkinsServer = findJenkinsByName(jenkinsOpt)
	}
	return
}

func getCurrentJenkinsFromOptionsOrDie() (jenkinsServer *JenkinsServer) {
	if jenkinsServer = getCurrentJenkinsFromOptions(); jenkinsServer == nil {
		log.Fatal("Cannot found Jenkins by", rootOptions.Jenkins) // TODO not accurate
	}
	return
}
LinuxSuRen's avatar
LinuxSuRen 已提交
105

LinuxSuRen's avatar
LinuxSuRen 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119
func getCmdPath(cmd *cobra.Command) string {
	current := cmd.Use
	if cmd.HasParent() {
		parentName := getCmdPath(cmd.Parent())
		if parentName == "" {
			return current
		}

		return fmt.Sprintf("%s.%s", parentName, current)
	}
	// don't need the name of root cmd
	return ""
}

LinuxSuRen's avatar
LinuxSuRen 已提交
120
func executePreCmd(cmd *cobra.Command, _ []string, writer io.Writer) (err error) {
LinuxSuRen's avatar
LinuxSuRen 已提交
121 122
	config := getConfig()
	if config == nil {
LinuxSuRen's avatar
LinuxSuRen 已提交
123
		err = fmt.Errorf("Cannot find config file")
LinuxSuRen's avatar
LinuxSuRen 已提交
124 125 126 127
		return
	}

	path := getCmdPath(cmd)
LinuxSuRen's avatar
LinuxSuRen 已提交
128 129
	for _, hook := range config.PreHooks {
		if path != hook.Path {
LinuxSuRen's avatar
LinuxSuRen 已提交
130 131 132
			continue
		}

LinuxSuRen's avatar
LinuxSuRen 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
		if err = execute(hook.Command, writer); err != nil {
			return
		}
	}
	return
}

func executePostCmd(cmd *cobra.Command, _ []string, writer io.Writer) (err error) {
	config := getConfig()
	if config == nil {
		err = fmt.Errorf("Cannot find config file")
		return
	}

	path := getCmdPath(cmd)
	for _, hook := range config.PostHooks {
		if path != hook.Path {
			continue
		}

		if err = execute(hook.Command, writer); err != nil {
LinuxSuRen's avatar
LinuxSuRen 已提交
154 155
			return
		}
LinuxSuRen's avatar
LinuxSuRen 已提交
156
	}
LinuxSuRen's avatar
LinuxSuRen 已提交
157
	return
LinuxSuRen's avatar
LinuxSuRen 已提交
158 159
}

LinuxSuRen's avatar
LinuxSuRen 已提交
160
func execute(command string, writer io.Writer) (err error) {
LinuxSuRen's avatar
LinuxSuRen 已提交
161 162
	array := strings.Split(command, " ")
	cmd := exec.Command(array[0], array[1:]...)
LinuxSuRen's avatar
LinuxSuRen 已提交
163 164 165
	cmd.Stdout = writer
	err = cmd.Run()
	return
LinuxSuRen's avatar
LinuxSuRen 已提交
166
}