chinampa/pkg/errors/handler.go

59 lines
1.3 KiB
Go
Raw Normal View History

2022-12-19 03:04:34 +00:00
// Copyright © 2022 Roberto Hidalgo <chinampa@un.rob.mx>
2022-12-31 05:53:24 +00:00
// SPDX-License-Identifier: Apache-2.0
2022-12-19 03:04:34 +00:00
package errors
import (
"os"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
_c "git.rob.mx/nidito/chinampa/internal/constants"
2022-12-31 05:53:24 +00:00
"git.rob.mx/nidito/chinampa/pkg/statuscode"
2022-12-19 03:04:34 +00:00
)
func showHelp(cmd *cobra.Command) {
if cmd.Name() != _c.HelpCommandName {
err := cmd.Help()
if err != nil {
2022-12-31 05:53:24 +00:00
os.Exit(statuscode.ProgrammerError)
2022-12-19 03:04:34 +00:00
}
}
}
func HandleCobraExit(cmd *cobra.Command, err error) error {
2022-12-19 03:04:34 +00:00
if err == nil {
ok, err := cmd.PersistentFlags().GetBool(_c.HelpCommandName)
2022-12-19 03:04:34 +00:00
if cmd.Name() == _c.HelpCommandName || err == nil && ok {
2022-12-31 05:53:24 +00:00
os.Exit(statuscode.RenderHelp)
2022-12-19 03:04:34 +00:00
}
os.Exit(statuscode.Ok)
2022-12-19 03:04:34 +00:00
}
switch err.(type) {
2022-12-19 03:04:34 +00:00
case BadArguments:
showHelp(cmd)
logrus.Error(err)
2022-12-31 05:53:24 +00:00
os.Exit(statuscode.Usage)
2022-12-19 03:04:34 +00:00
case NotFound:
showHelp(cmd)
logrus.Error(err)
2022-12-31 05:53:24 +00:00
os.Exit(statuscode.NotFound)
2022-12-19 03:04:34 +00:00
default:
if strings.HasPrefix(err.Error(), "unknown command") {
showHelp(cmd)
2022-12-31 05:53:24 +00:00
os.Exit(statuscode.NotFound)
2022-12-19 03:04:34 +00:00
} else if strings.HasPrefix(err.Error(), "unknown flag") || strings.HasPrefix(err.Error(), "unknown shorthand flag") {
showHelp(cmd)
logrus.Error(err)
2022-12-31 05:53:24 +00:00
os.Exit(statuscode.Usage)
2022-12-19 03:04:34 +00:00
}
}
logrus.Errorf("Unknown error: %s", err)
os.Exit(2)
return err
2022-12-19 03:04:34 +00:00
}