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) {
|
|
|
|
if err == nil {
|
|
|
|
ok, err := cmd.Flags().GetBool(_c.HelpCommandName)
|
|
|
|
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(42)
|
|
|
|
}
|
|
|
|
|
|
|
|
switch tErr := err.(type) {
|
|
|
|
case SubCommandExit:
|
|
|
|
logrus.Debugf("Sub-command failed with: %s", err.Error())
|
|
|
|
os.Exit(tErr.ExitCode)
|
|
|
|
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
|
|
|
case ConfigError:
|
|
|
|
showHelp(cmd)
|
|
|
|
logrus.Error(err)
|
2022-12-31 05:53:24 +00:00
|
|
|
os.Exit(statuscode.ConfigError)
|
2022-12-19 03:04:34 +00:00
|
|
|
case EnvironmentError:
|
|
|
|
logrus.Error(err)
|
2022-12-31 05:53:24 +00:00
|
|
|
os.Exit(statuscode.ConfigError)
|
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)
|
|
|
|
}
|