1
0
mirror of https://github.com/go-task/task.git synced 2025-04-23 12:18:57 +02:00

refactor: move flags into a package-level struct var

This commit is contained in:
Pete Davison 2023-04-27 10:44:40 +00:00 committed by Andrey Nering
parent af95e5b3e0
commit 745de72d7e

View File

@ -43,30 +43,9 @@ tasks:
Options: Options:
` `
func main() { var flags struct {
if err := run(); err != nil { version bool
if err, ok := err.(errors.TaskError); ok { help bool
log.Print(err.Error())
os.Exit(err.Code())
}
log.Print(err.Error())
os.Exit(errors.CodeUnknown)
}
os.Exit(errors.CodeOk)
}
func run() error {
log.SetFlags(0)
log.SetOutput(os.Stderr)
pflag.Usage = func() {
log.Print(usage)
pflag.PrintDefaults()
}
var (
versionFlag bool
helpFlag bool
init bool init bool
list bool list bool
listAll bool listAll bool
@ -88,47 +67,68 @@ func run() error {
color bool color bool
interval time.Duration interval time.Duration
global bool global bool
) }
pflag.BoolVar(&versionFlag, "version", false, "Show Task version.") func main() {
pflag.BoolVarP(&helpFlag, "help", "h", false, "Shows Task usage.") if err := run(); err != nil {
pflag.BoolVarP(&init, "init", "i", false, "Creates a new Taskfile.yml in the current folder.") if err, ok := err.(errors.TaskError); ok {
pflag.BoolVarP(&list, "list", "l", false, "Lists tasks with description of current Taskfile.") log.Print(err.Error())
pflag.BoolVarP(&listAll, "list-all", "a", false, "Lists tasks with or without a description.") os.Exit(err.Code())
pflag.BoolVarP(&listJson, "json", "j", false, "Formats task list as JSON.") }
pflag.StringVar(&taskSort, "sort", "", "Changes the order of the tasks when listed.") log.Print(err.Error())
pflag.BoolVar(&status, "status", false, "Exits with non-zero exit code if any of the given tasks is not up-to-date.") os.Exit(errors.CodeUnknown)
pflag.BoolVarP(&force, "force", "f", false, "Forces execution even when the task is up-to-date.") }
pflag.BoolVarP(&watch, "watch", "w", false, "Enables watch of the given task.") os.Exit(errors.CodeOk)
pflag.BoolVarP(&verbose, "verbose", "v", false, "Enables verbose mode.") }
pflag.BoolVarP(&silent, "silent", "s", false, "Disables echoing.")
pflag.BoolVarP(&parallel, "parallel", "p", false, "Executes tasks provided on command line in parallel.") func run() error {
pflag.BoolVarP(&dry, "dry", "n", false, "Compiles and prints tasks in the order that they would be run, without executing them.") log.SetFlags(0)
pflag.BoolVar(&summary, "summary", false, "Show summary about a task.") log.SetOutput(os.Stderr)
pflag.BoolVarP(&exitCode, "exit-code", "x", false, "Pass-through the exit code of the task command.")
pflag.StringVarP(&dir, "dir", "d", "", "Sets directory of execution.") pflag.Usage = func() {
pflag.StringVarP(&entrypoint, "taskfile", "t", "", `Choose which Taskfile to run. Defaults to "Taskfile.yml".`) log.Print(usage)
pflag.StringVarP(&output.Name, "output", "o", "", "Sets output style: [interleaved|group|prefixed].") pflag.PrintDefaults()
pflag.StringVar(&output.Group.Begin, "output-group-begin", "", "Message template to print before a task's grouped output.") }
pflag.StringVar(&output.Group.End, "output-group-end", "", "Message template to print after a task's grouped output.")
pflag.BoolVar(&output.Group.ErrorOnly, "output-group-error-only", false, "Swallow output from successful tasks.") pflag.BoolVar(&flags.version, "version", false, "Show Task version.")
pflag.BoolVarP(&color, "color", "c", true, "Colored output. Enabled by default. Set flag to false or use NO_COLOR=1 to disable.") pflag.BoolVarP(&flags.help, "help", "h", false, "Shows Task usage.")
pflag.IntVarP(&concurrency, "concurrency", "C", 0, "Limit number tasks to run concurrently.") pflag.BoolVarP(&flags.init, "init", "i", false, "Creates a new Taskfile.yml in the current folder.")
pflag.DurationVarP(&interval, "interval", "I", 0, "Interval to watch for changes.") pflag.BoolVarP(&flags.list, "list", "l", false, "Lists tasks with description of current Taskfile.")
pflag.BoolVarP(&global, "global", "g", false, "Runs global Taskfile, from $HOME/Taskfile.{yml,yaml}.") pflag.BoolVarP(&flags.listAll, "list-all", "a", false, "Lists tasks with or without a description.")
pflag.BoolVarP(&flags.listJson, "json", "j", false, "Formats task list as JSON.")
pflag.StringVar(&flags.taskSort, "sort", "", "Changes the order of the tasks when listed.")
pflag.BoolVar(&flags.status, "status", false, "Exits with non-zero exit code if any of the given tasks is not up-to-date.")
pflag.BoolVarP(&flags.force, "force", "f", false, "Forces execution even when the task is up-to-date.")
pflag.BoolVarP(&flags.watch, "watch", "w", false, "Enables watch of the given task.")
pflag.BoolVarP(&flags.verbose, "verbose", "v", false, "Enables verbose mode.")
pflag.BoolVarP(&flags.silent, "silent", "s", false, "Disables echoing.")
pflag.BoolVarP(&flags.parallel, "parallel", "p", false, "Executes tasks provided on command line in parallel.")
pflag.BoolVarP(&flags.dry, "dry", "n", false, "Compiles and prints tasks in the order that they would be run, without executing them.")
pflag.BoolVar(&flags.summary, "summary", false, "Show summary about a task.")
pflag.BoolVarP(&flags.exitCode, "exit-code", "x", false, "Pass-through the exit code of the task command.")
pflag.StringVarP(&flags.dir, "dir", "d", "", "Sets directory of execution.")
pflag.StringVarP(&flags.entrypoint, "taskfile", "t", "", `Choose which Taskfile to run. Defaults to "Taskfile.yml".`)
pflag.StringVarP(&flags.output.Name, "output", "o", "", "Sets output style: [interleaved|group|prefixed].")
pflag.StringVar(&flags.output.Group.Begin, "output-group-begin", "", "Message template to print before a task's grouped output.")
pflag.StringVar(&flags.output.Group.End, "output-group-end", "", "Message template to print after a task's grouped output.")
pflag.BoolVar(&flags.output.Group.ErrorOnly, "output-group-error-only", false, "Swallow output from successful tasks.")
pflag.BoolVarP(&flags.color, "color", "c", true, "Colored output. Enabled by default. Set flag to false or use NO_COLOR=1 to disable.")
pflag.IntVarP(&flags.concurrency, "concurrency", "C", 0, "Limit number tasks to run concurrently.")
pflag.DurationVarP(&flags.interval, "interval", "I", 0, "Interval to watch for changes.")
pflag.BoolVarP(&flags.global, "global", "g", false, "Runs global Taskfile, from $HOME/Taskfile.{yml,yaml}.")
pflag.Parse() pflag.Parse()
if versionFlag { if flags.version {
fmt.Printf("Task version: %s\n", ver.GetVersion()) fmt.Printf("Task version: %s\n", ver.GetVersion())
return nil return nil
} }
if helpFlag { if flags.help {
pflag.Usage() pflag.Usage()
return nil return nil
} }
if init { if flags.init {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -139,40 +139,40 @@ func run() error {
return nil return nil
} }
if global && dir != "" { if flags.global && flags.dir != "" {
log.Fatal("task: You can't set both --global and --dir") log.Fatal("task: You can't set both --global and --dir")
return nil return nil
} }
if global { if flags.global {
home, err := os.UserHomeDir() home, err := os.UserHomeDir()
if err != nil { if err != nil {
return fmt.Errorf("task: Failed to get user home directory: %w", err) return fmt.Errorf("task: Failed to get user home directory: %w", err)
} }
dir = home flags.dir = home
} }
if dir != "" && entrypoint != "" { if flags.dir != "" && flags.entrypoint != "" {
return errors.New("task: You can't set both --dir and --taskfile") return errors.New("task: You can't set both --dir and --taskfile")
} }
if entrypoint != "" { if flags.entrypoint != "" {
dir = filepath.Dir(entrypoint) flags.dir = filepath.Dir(flags.entrypoint)
entrypoint = filepath.Base(entrypoint) flags.entrypoint = filepath.Base(flags.entrypoint)
} }
if output.Name != "group" { if flags.output.Name != "group" {
if output.Group.Begin != "" { if flags.output.Group.Begin != "" {
return errors.New("task: You can't set --output-group-begin without --output=group") return errors.New("task: You can't set --output-group-begin without --output=group")
} }
if output.Group.End != "" { if flags.output.Group.End != "" {
return errors.New("task: You can't set --output-group-end without --output=group") return errors.New("task: You can't set --output-group-end without --output=group")
} }
if output.Group.ErrorOnly { if flags.output.Group.ErrorOnly {
return errors.New("task: You can't set --output-group-error-only without --output=group") return errors.New("task: You can't set --output-group-error-only without --output=group")
} }
} }
var taskSorter sort.TaskSorter var taskSorter sort.TaskSorter
switch taskSort { switch flags.taskSort {
case "none": case "none":
taskSorter = &sort.Noop{} taskSorter = &sort.Noop{}
case "alphanumeric": case "alphanumeric":
@ -180,34 +180,34 @@ func run() error {
} }
e := task.Executor{ e := task.Executor{
Force: force, Force: flags.force,
Watch: watch, Watch: flags.watch,
Verbose: verbose, Verbose: flags.verbose,
Silent: silent, Silent: flags.silent,
Dir: dir, Dir: flags.dir,
Dry: dry, Dry: flags.dry,
Entrypoint: entrypoint, Entrypoint: flags.entrypoint,
Summary: summary, Summary: flags.summary,
Parallel: parallel, Parallel: flags.parallel,
Color: color, Color: flags.color,
Concurrency: concurrency, Concurrency: flags.concurrency,
Interval: interval, Interval: flags.interval,
Stdin: os.Stdin, Stdin: os.Stdin,
Stdout: os.Stdout, Stdout: os.Stdout,
Stderr: os.Stderr, Stderr: os.Stderr,
OutputStyle: output, OutputStyle: flags.output,
TaskSorter: taskSorter, TaskSorter: taskSorter,
} }
listOptions := task.NewListOptions(list, listAll, listJson) listOptions := task.NewListOptions(flags.list, flags.listAll, flags.listJson)
if err := listOptions.Validate(); err != nil { if err := listOptions.Validate(); err != nil {
return err return err
} }
if (listOptions.ShouldListTasks()) && silent { if (listOptions.ShouldListTasks()) && flags.silent {
e.ListTaskNames(listAll) e.ListTaskNames(flags.listAll)
return nil return nil
} }
@ -245,20 +245,20 @@ func run() error {
globals.Set("CLI_ARGS", taskfile.Var{Static: cliArgs}) globals.Set("CLI_ARGS", taskfile.Var{Static: cliArgs})
e.Taskfile.Vars.Merge(globals) e.Taskfile.Vars.Merge(globals)
if !watch { if !flags.watch {
e.InterceptInterruptSignals() e.InterceptInterruptSignals()
} }
ctx := context.Background() ctx := context.Background()
if status { if flags.status {
return e.Status(ctx, calls...) return e.Status(ctx, calls...)
} }
if err := e.Run(ctx, calls...); err != nil { if err := e.Run(ctx, calls...); err != nil {
e.Logger.Errf(logger.Red, "%v\n", err) e.Logger.Errf(logger.Red, "%v\n", err)
if exitCode { if flags.exitCode {
if err, ok := err.(*errors.TaskRunError); ok { if err, ok := err.(*errors.TaskRunError); ok {
os.Exit(err.TaskExitCode()) os.Exit(err.TaskExitCode())
} }