package command import ( "fmt" "os" "sort" "github.com/pkg/errors" "github.com/urfave/cli/v2" "gitlab.com/wpetit/goweb/logger" ) func Main(name string, usage string, commands ...*cli.Command) { app := &cli.App{ Name: name, Usage: usage, Commands: commands, Before: func(ctx *cli.Context) error { workdir := ctx.String("workdir") // Switch to new working directory if defined if workdir != "" { if err := os.Chdir(workdir); err != nil { return errors.Wrap(err, "could not change working directory") } } logLevel := ctx.String("log-level") switch logLevel { case "debug": logger.SetLevel(logger.LevelDebug) case "info": logger.SetLevel(logger.LevelInfo) case "warn": logger.SetLevel(logger.LevelWarn) case "error": logger.SetLevel(logger.LevelError) case "critical": logger.SetLevel(logger.LevelCritical) } return nil }, Flags: []cli.Flag{ &cli.StringFlag{ Name: "workdir", Value: "", EnvVars: []string{"ARCAST_WORKDIR"}, Usage: "The working directory", }, &cli.BoolFlag{ Name: "debug", EnvVars: []string{"ARCAST_DEBUG"}, Usage: "Enable debug mode", }, &cli.StringFlag{ Name: "log-level", EnvVars: []string{"ARCAST_LOG_LEVEL"}, Usage: "Set logging level", Value: "info", }, }, } app.ExitErrHandler = func(ctx *cli.Context, err error) { if err == nil { return } debug := ctx.Bool("debug") if !debug { fmt.Printf("[ERROR] %+v\n", err) } else { fmt.Printf("%+v", err) } } sort.Sort(cli.FlagsByName(app.Flags)) sort.Sort(cli.CommandsByName(app.Commands)) if err := app.Run(os.Args); err != nil { os.Exit(1) } }