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

import (
	"fmt"
5
	"log"
LinuxSuRen's avatar
LinuxSuRen 已提交
6 7
	"os"

8
	"github.com/jenkins-zh/jenkins-cli/app"
LinuxSuRen's avatar
LinuxSuRen 已提交
9 10 11
	"github.com/spf13/cobra"
)

LinuxSuRen's avatar
LinuxSuRen 已提交
12
// RootOptions is a global option for whole cli
13
type RootOptions struct {
LinuxSuRen's avatar
LinuxSuRen 已提交
14
	Jenkins string
15
	Version bool
16
	Debug   bool
17 18
}

LinuxSuRen's avatar
LinuxSuRen 已提交
19
var rootCmd = &cobra.Command{
20 21 22 23 24
	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`,
yJunS's avatar
yJunS 已提交
25
	Run: func(_ *cobra.Command, _ []string) {
26 27
		fmt.Println("Jenkins CLI (jcli) manage your Jenkins")

LinuxSuRen's avatar
LinuxSuRen 已提交
28
		current := getCurrentJenkinsFromOptionsOrDie()
29 30 31 32 33 34
		if current != nil {
			fmt.Println("Current Jenkins is:", current.Name)
		} else {
			fmt.Println("Cannot found the configuration")
		}

35
		if rootOptions.Version {
LinuxSuRen's avatar
LinuxSuRen 已提交
36 37
			fmt.Printf("Version: %s\n", app.GetVersion())
			fmt.Printf("Commit: %s\n", app.GetCommit())
38
		}
LinuxSuRen's avatar
LinuxSuRen 已提交
39 40 41 42 43 44 45 46 47 48
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

49
var rootOptions RootOptions
LinuxSuRen's avatar
LinuxSuRen 已提交
50 51 52

func init() {
	cobra.OnInitialize(initConfig)
LinuxSuRen's avatar
LinuxSuRen 已提交
53
	rootCmd.PersistentFlags().StringVarP(&rootOptions.Jenkins, "jenkins", "j", "", "Select a Jenkins server for this time")
54
	rootCmd.PersistentFlags().BoolVarP(&rootOptions.Version, "version", "v", false, "Print the version of Jenkins CLI")
55
	rootCmd.PersistentFlags().BoolVarP(&rootOptions.Debug, "debug", "", false, "Print the output into debug.html")
LinuxSuRen's avatar
LinuxSuRen 已提交
56 57 58
}

func initConfig() {
59 60 61 62 63 64 65 66
	if err := loadDefaultConfig(); err != nil {
		if os.IsNotExist(err) {
			log.Printf("No config file found.")
			return
		}

		log.Fatalf("Config file is invalid: %v", err)
	}
LinuxSuRen's avatar
LinuxSuRen 已提交
67
}
LinuxSuRen's avatar
LinuxSuRen 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

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
}