github.com/getgauge/gauge@v1.6.9/cmd/cmd.go (about) 1 /*---------------------------------------------------------------- 2 * Copyright (c) ThoughtWorks, Inc. 3 * Licensed under the Apache License, Version 2.0 4 * See LICENSE in the project root for license information. 5 *----------------------------------------------------------------*/ 6 7 package cmd 8 9 import ( 10 "os" 11 "path/filepath" 12 13 "github.com/getgauge/gauge/env" 14 "github.com/getgauge/gauge/execution" 15 "github.com/getgauge/gauge/filter" 16 "github.com/getgauge/gauge/logger" 17 "github.com/getgauge/gauge/order" 18 "github.com/getgauge/gauge/reporter" 19 "github.com/getgauge/gauge/skel" 20 "github.com/getgauge/gauge/util" 21 "github.com/getgauge/gauge/validation" 22 "github.com/spf13/cobra" 23 ) 24 25 const ( 26 logLevelDefault = "info" 27 dirDefault = "." 28 machineReadableDefault = false 29 gaugeVersionDefault = false 30 31 logLevelName = "log-level" 32 dirName = "dir" 33 machineReadableName = "machine-readable" 34 gaugeVersionName = "version" 35 ) 36 37 var ( 38 GaugeCmd = &cobra.Command{ 39 Use: "gauge <command> [flags] [args]", 40 Example: ` gauge run specs/ 41 gauge run --parallel specs/`, 42 Run: func(cmd *cobra.Command, args []string) { 43 if gaugeVersion { 44 printVersion() 45 return 46 } 47 if len(args) < 1 { 48 err := cmd.Help() 49 if err != nil { 50 logger.Errorf(true, "Unable to print help: %s", err.Error()) 51 } 52 } 53 }, 54 DisableAutoGenTag: true, 55 PersistentPreRun: func(cmd *cobra.Command, args []string) { 56 initLogger(cmd.Name()) 57 skel.CreateSkelFilesIfRequired() 58 setGlobalFlags() 59 initPackageFlags() 60 }, 61 } 62 logLevel string 63 dir string 64 machineReadable bool 65 gaugeVersion bool 66 ) 67 68 func initLogger(n string) { 69 if lsp { 70 logger.Initialize(machineReadable, logLevel, logger.LSP) 71 } else if n == "daemon" { 72 logger.Initialize(machineReadable, logLevel, logger.API) 73 } else { 74 logger.Initialize(machineReadable, logLevel, logger.CLI) 75 } 76 } 77 78 func init() { 79 GaugeCmd.SetUsageTemplate(`Usage:{{if .Runnable}} 80 {{.UseLine}}{{end}}{{if gt (len .Aliases) 0}} 81 82 Aliases: 83 {{.NameAndAliases}}{{end}}{{if .HasExample}} 84 85 Examples: 86 {{.Example}}{{end}}{{if .HasAvailableSubCommands}} 87 88 Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} 89 {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} 90 91 Flags: 92 {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} 93 94 Global Flags: 95 {{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} 96 97 Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} 98 {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} 99 100 Use "{{.CommandPath}} [command] --help" for more information about a command. 101 Complete manual is available at https://manpage.gauge.org/.{{end}} 102 `) 103 GaugeCmd.PersistentFlags().StringVarP(&logLevel, logLevelName, "l", logLevelDefault, "Set level of logging to debug, info, warning, error or critical") 104 GaugeCmd.PersistentFlags().StringVarP(&dir, dirName, "d", dirDefault, "Set the working directory for the current command, accepts a path relative to current directory") 105 GaugeCmd.PersistentFlags().BoolVarP(&machineReadable, machineReadableName, "m", machineReadableDefault, "Prints output in JSON format") 106 GaugeCmd.Flags().BoolVarP(&gaugeVersion, gaugeVersionName, "v", gaugeVersionDefault, "Print Gauge and plugin versions") 107 } 108 109 func Parse() error { 110 InitHelp(GaugeCmd) 111 return GaugeCmd.Execute() 112 } 113 114 func InitHelp(c *cobra.Command) { 115 c.Flags().BoolP("help", "h", false, "Help for "+c.Name()) 116 if c.HasSubCommands() { 117 for _, sc := range c.Commands() { 118 InitHelp(sc) 119 } 120 } 121 } 122 123 func getSpecsDir(args []string) []string { 124 if len(args) > 0 { 125 return args 126 } 127 return util.GetSpecDirs() 128 } 129 130 func setGlobalFlags() { 131 util.SetWorkingDir(dir) 132 } 133 134 func initPackageFlags() { 135 if parallel { 136 simpleConsole = true 137 reporter.IsParallel = true 138 } 139 reporter.SimpleConsoleOutput = simpleConsole 140 reporter.Verbose = verbose 141 reporter.MachineReadable = machineReadable 142 execution.MachineReadable = machineReadable 143 execution.ExecuteTags = tags 144 execution.SetTableRows(rows) 145 validation.TableRows = rows 146 execution.NumberOfExecutionStreams = streams 147 execution.InParallel = parallel 148 execution.TagsToFilterForParallelRun = tagsToFilterForParallelRun 149 execution.Verbose = verbose 150 execution.Strategy = strategy 151 filter.ExecuteTags = tags 152 order.Sorted = sort 153 filter.Distribute = group 154 filter.NumberOfExecutionStreams = streams 155 reporter.NumberOfExecutionStreams = streams 156 validation.HideSuggestion = hideSuggestion 157 if group != -1 { 158 execution.Strategy = execution.Eager 159 } 160 filter.ScenariosName = scenarios 161 execution.MaxRetriesCount = maxRetriesCount 162 execution.RetryOnlyTags = retryOnlyTags 163 } 164 165 var exit = func(err error, additionalText string) { 166 if err != nil { 167 logger.Error(true, err.Error()) 168 } 169 if additionalText != "" { 170 logger.Info(true, additionalText) 171 } 172 os.Exit(1) 173 } 174 175 func loadEnvAndReinitLogger(cmd *cobra.Command) { 176 var handler = func(err error) { 177 logger.Fatalf(true, "Failed to load env. %s", err.Error()) 178 } 179 if e := env.LoadEnv(environment, handler); e != nil { 180 logger.Fatal(true, e.Error()) 181 } 182 initLogger(cmd.Name()) 183 } 184 185 func ensureScreenshotsDir() { 186 screenshotDirPath, err := filepath.Abs(os.Getenv(env.GaugeScreenshotsDir)) 187 if err != nil { 188 logger.Warningf(true, "Could not create %s. %s", env.GaugeScreenshotsDir, err.Error()) 189 return 190 } 191 err = os.MkdirAll(screenshotDirPath, 0750) 192 if err != nil { 193 logger.Warningf(true, "Could not create %s %s", env.GaugeScreenshotsDir, err.Error()) 194 } else { 195 logger.Debugf(true, "Created %s at %s", env.GaugeScreenshotsDir, screenshotDirPath) 196 } 197 }