github.com/TNTworks/flogo-cli@v0.9.1-0.20220522183836-60b8a963ae00/commands/root.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/TNTworks/flogo-cli/api"
     6  	"github.com/TNTworks/flogo-cli/common"
     7  	"github.com/TNTworks/flogo-cli/util"
     8  	"github.com/spf13/cobra"
     9  	"os"
    10  )
    11  
    12  const (
    13  	VersionTpl = `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "cli version %s" .Version}}
    14  `
    15  )
    16  
    17  var verbose bool
    18  
    19  //Root command
    20  var rootCmd = &cobra.Command{
    21  	Use:   "flogo [flags] [command]",
    22  	Short: "flogo cli",
    23  	Long:  `flogo command line interface for flogo applications`,
    24  
    25  	PersistentPreRun: func(cmd *cobra.Command, args []string) {
    26  		preRun(cmd, args, verbose)
    27  	},
    28  }
    29  
    30  func Initialize(version string) {
    31  	rootCmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "verbose output")
    32  
    33  	if len(version) > 0 {
    34  		rootCmd.Version = version // use version hardcoded by a "go generate" command
    35  	} else {
    36  		_, rootCmd.Version, _ = util.GetCLIInfo() // guess version from sources in $GOPATH/src
    37  	}
    38  
    39  	rootCmd.SetVersionTemplate(VersionTpl)
    40  
    41  	//Get the list of commands from the registry of commands and add.
    42  	commandList := common.GetPlugins()
    43  
    44  	for _, command := range commandList {
    45  
    46  		rootCmd.AddCommand(command)
    47  	}
    48  }
    49  
    50  func Execute() {
    51  
    52  	if err := rootCmd.Execute(); err != nil {
    53  		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
    54  		os.Exit(1)
    55  	}
    56  }
    57  
    58  func preRun(cmd *cobra.Command, args []string, verbose bool) {
    59  	api.SetVerbose(verbose)
    60  	common.SetVerbose(verbose)
    61  
    62  	builtIn := cmd.Name() == "help" || cmd.Name() == "version"
    63  
    64  	if len(os.Args) > 1 && !builtIn {
    65  		currentDir, err := os.Getwd()
    66  		if err != nil {
    67  			fmt.Fprintf(os.Stderr, "Error determining working directory: %v\n", err)
    68  			os.Exit(1)
    69  		}
    70  		appProject := api.NewAppProject(currentDir)
    71  
    72  		err = appProject.Validate()
    73  		if err != nil {
    74  			fmt.Fprintf(os.Stderr, "Error validating project: %v\n", err)
    75  			os.Exit(1)
    76  		}
    77  
    78  		common.SetCurrentProject(appProject)
    79  	}
    80  }