gitee.com/mirrors/gauge@v1.0.6/cmd/cmd.go (about)

     1  // Copyright 2015 ThoughtWorks, Inc.
     2  
     3  // This file is part of Gauge.
     4  
     5  // Gauge is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  
    10  // Gauge is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU General Public License for more details.
    14  
    15  // You should have received a copy of the GNU General Public License
    16  // along with Gauge.  If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package cmd
    19  
    20  import (
    21  	"encoding/json"
    22  	"os"
    23  
    24  	"github.com/getgauge/gauge/config"
    25  	"github.com/getgauge/gauge/env"
    26  	"github.com/getgauge/gauge/execution"
    27  	"github.com/getgauge/gauge/filter"
    28  	"github.com/getgauge/gauge/logger"
    29  	"github.com/getgauge/gauge/order"
    30  	"github.com/getgauge/gauge/reporter"
    31  	"github.com/getgauge/gauge/skel"
    32  	"github.com/getgauge/gauge/track"
    33  	"github.com/getgauge/gauge/util"
    34  	"github.com/getgauge/gauge/validation"
    35  	"github.com/spf13/cobra"
    36  )
    37  
    38  const (
    39  	logLevelDefault        = "info"
    40  	dirDefault             = "."
    41  	machineReadableDefault = false
    42  	gaugeVersionDefault    = false
    43  
    44  	logLevelName        = "log-level"
    45  	dirName             = "dir"
    46  	machineReadableName = "machine-readable"
    47  	gaugeVersionName    = "version"
    48  )
    49  
    50  var (
    51  	GaugeCmd = &cobra.Command{
    52  		Use: "gauge <command> [flags] [args]",
    53  		Example: `  gauge run specs/
    54    gauge run --parallel specs/`,
    55  		Run: func(cmd *cobra.Command, args []string) {
    56  			if gaugeVersion {
    57  				printVersion()
    58  				return
    59  			}
    60  			if len(args) < 1 {
    61  				cmd.Help()
    62  			}
    63  		},
    64  		DisableAutoGenTag: true,
    65  		PersistentPreRun: func(cmd *cobra.Command, args []string) {
    66  			initLogger(cmd.Name())
    67  			notifyTelemetryIfNeeded(cmd, args)
    68  			skel.CreateSkelFilesIfRequired()
    69  			track.Init()
    70  			config.SetProjectRoot(args)
    71  			setGlobalFlags()
    72  			initPackageFlags()
    73  		},
    74  	}
    75  	logLevel        string
    76  	dir             string
    77  	machineReadable bool
    78  	gaugeVersion    bool
    79  )
    80  
    81  type notification struct {
    82  	Title   string `json:"title"`
    83  	Message string `json:"message"`
    84  	Type    string `json:"type"`
    85  }
    86  
    87  func (status *notification) getJSON() (string, error) {
    88  	j, err := json.Marshal(status)
    89  	if err != nil {
    90  		return "", err
    91  	}
    92  	return string(j), nil
    93  }
    94  
    95  func notifyTelemetryIfNeeded(cmd *cobra.Command, args []string) {
    96  	if !gaugeVersion && !config.TelemetryConsent() {
    97  		if machineReadable {
    98  			n := &notification{
    99  				Title:   "Gauge Telemetry",
   100  				Message: track.GaugeTelemetryMachineRedableMessage,
   101  				Type:    "info",
   102  			}
   103  			s, _ := n.getJSON()
   104  			logger.Infof(true, "{\"type\":\"notification\",\"notification\":%s}\n", s)
   105  		} else {
   106  			logger.Infof(true, "%s\n%s\n", track.GaugeTelemetryMessageHeading, track.GaugeTelemetryMessage)
   107  		}
   108  	}
   109  }
   110  
   111  func initLogger(n string) {
   112  	if lsp {
   113  
   114  		logger.Initialize(machineReadable, logLevel, logger.LSP)
   115  	} else if n == "daemon" {
   116  		logger.Initialize(machineReadable, logLevel, logger.API)
   117  	} else {
   118  		logger.Initialize(machineReadable, logLevel, logger.CLI)
   119  	}
   120  }
   121  
   122  func init() {
   123  	GaugeCmd.SetUsageTemplate(`Usage:{{if .Runnable}}
   124    {{.UseLine}}{{end}}{{if gt (len .Aliases) 0}}
   125  
   126  Aliases:
   127    {{.NameAndAliases}}{{end}}{{if .HasExample}}
   128  
   129  Examples:
   130  {{.Example}}{{end}}{{if .HasAvailableSubCommands}}
   131  
   132  Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
   133    {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
   134  
   135  Flags:
   136  {{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
   137  
   138  Global Flags:
   139  {{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
   140  
   141  Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
   142    {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
   143  
   144  Use "{{.CommandPath}} [command] --help" for more information about a command.
   145  Complete manual is available at https://manpage.gauge.org/.{{end}}
   146  `)
   147  	GaugeCmd.PersistentFlags().StringVarP(&logLevel, logLevelName, "l", logLevelDefault, "Set level of logging to debug, info, warning, error or critical")
   148  	GaugeCmd.PersistentFlags().StringVarP(&dir, dirName, "d", dirDefault, "Set the working directory for the current command, accepts a path relative to current directory")
   149  	GaugeCmd.PersistentFlags().BoolVarP(&machineReadable, machineReadableName, "m", machineReadableDefault, "Prints output in JSON format")
   150  	GaugeCmd.Flags().BoolVarP(&gaugeVersion, gaugeVersionName, "v", gaugeVersionDefault, "Print Gauge and plugin versions")
   151  }
   152  
   153  func Parse() error {
   154  	InitHelp(GaugeCmd)
   155  	return GaugeCmd.Execute()
   156  }
   157  
   158  func InitHelp(c *cobra.Command) {
   159  	c.Flags().BoolP("help", "h", false, "Help for "+c.Name())
   160  	if c.HasSubCommands() {
   161  		for _, sc := range c.Commands() {
   162  			InitHelp(sc)
   163  		}
   164  	}
   165  }
   166  
   167  func getSpecsDir(args []string) []string {
   168  	if len(args) > 0 {
   169  		return args
   170  	}
   171  	return util.GetSpecDirs()
   172  }
   173  
   174  func setGlobalFlags() {
   175  	util.SetWorkingDir(dir)
   176  }
   177  
   178  func initPackageFlags() {
   179  	if parallel {
   180  		simpleConsole = true
   181  		reporter.IsParallel = true
   182  	}
   183  	reporter.SimpleConsoleOutput = simpleConsole
   184  	reporter.Verbose = verbose
   185  	reporter.MachineReadable = machineReadable
   186  	execution.MachineReadable = machineReadable
   187  	execution.ExecuteTags = tags
   188  	execution.SetTableRows(rows)
   189  	validation.TableRows = rows
   190  	execution.NumberOfExecutionStreams = streams
   191  	execution.InParallel = parallel
   192  	execution.TagsToFilterForParallelRun = tagsToFilterForParallelRun
   193  	execution.Verbose = verbose
   194  	execution.Strategy = strategy
   195  	filter.ExecuteTags = tags
   196  	order.Sorted = sort
   197  	filter.Distribute = group
   198  	filter.NumberOfExecutionStreams = streams
   199  	reporter.NumberOfExecutionStreams = streams
   200  	validation.HideSuggestion = hideSuggestion
   201  	if group != -1 {
   202  		execution.Strategy = execution.Eager
   203  	}
   204  	filter.ScenariosName = scenarios
   205  	execution.MaxRetriesCount = maxRetriesCount
   206  	execution.RetryOnlyTags = retryOnlyTags
   207  }
   208  
   209  var exit = func(err error, additionalText string) {
   210  	if err != nil {
   211  		logger.Errorf(true, err.Error())
   212  	}
   213  	if additionalText != "" {
   214  		logger.Infof(true, additionalText)
   215  	}
   216  	os.Exit(1)
   217  }
   218  
   219  func loadEnvAndReinitLogger(cmd *cobra.Command) {
   220  	if e := env.LoadEnv(environment); e != nil {
   221  		logger.Fatalf(true, e.Error())
   222  	}
   223  	initLogger(cmd.Name())
   224  }