arcast/internal/command/main.go

86 lines
1.7 KiB
Go
Raw Permalink Normal View History

2023-12-13 20:07:22 +01:00
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, version string, commands ...*cli.Command) {
2023-12-13 20:07:22 +01:00
app := &cli.App{
Name: name,
Usage: usage,
Commands: commands,
Version: version,
2023-12-13 20:07:22 +01:00
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)
}
}