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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-21 06:28:25 +00:00
|
|
|
// HandleCobraExit is called when a command errors out or was not found.
|
2023-01-18 04:20:46 +00:00
|
|
|
func HandleCobraExit(cmd *cobra.Command, err error) error {
|
2022-12-19 03:04:34 +00:00
|
|
|
if err == nil {
|
2023-01-18 04:20:46 +00:00
|
|
|
os.Exit(statuscode.Ok)
|
2024-06-19 20:16:10 +00:00
|
|
|
return nil
|
2022-12-19 03:04:34 +00:00
|
|
|
}
|
|
|
|
|
2023-01-18 04:20:46 +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)
|
2023-01-18 04:20:46 +00:00
|
|
|
return err
|
2022-12-19 03:04:34 +00:00
|
|
|
}
|