2020-05-18 18:24:17 +00:00
|
|
|
package cliutil
|
|
|
|
|
2020-05-21 20:36:49 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
2020-06-12 16:20:36 +00:00
|
|
|
"log"
|
2020-05-21 20:36:49 +00:00
|
|
|
|
2020-06-08 22:01:48 +00:00
|
|
|
"github.com/cloudflare/cloudflared/logger"
|
2020-06-12 16:20:36 +00:00
|
|
|
"github.com/pkg/errors"
|
2020-08-05 10:49:53 +00:00
|
|
|
"github.com/urfave/cli/v2"
|
2020-05-21 20:36:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type usageError string
|
|
|
|
|
|
|
|
func (ue usageError) Error() string {
|
|
|
|
return string(ue)
|
|
|
|
}
|
|
|
|
|
|
|
|
func UsageError(format string, args ...interface{}) error {
|
|
|
|
if len(args) == 0 {
|
|
|
|
return usageError(format)
|
|
|
|
} else {
|
|
|
|
msg := fmt.Sprintf(format, args...)
|
|
|
|
return usageError(msg)
|
|
|
|
}
|
|
|
|
}
|
2020-05-18 18:24:17 +00:00
|
|
|
|
|
|
|
// Ensures exit with error code if actionFunc returns an error
|
|
|
|
func ErrorHandler(actionFunc cli.ActionFunc) cli.ActionFunc {
|
|
|
|
return func(ctx *cli.Context) error {
|
2020-11-09 22:53:51 +00:00
|
|
|
defer logger.SharedWriteManager.Shutdown()
|
|
|
|
|
2020-05-18 18:24:17 +00:00
|
|
|
err := actionFunc(ctx)
|
|
|
|
if err != nil {
|
2020-05-21 20:36:49 +00:00
|
|
|
if _, ok := err.(usageError); ok {
|
|
|
|
msg := fmt.Sprintf("%s\nSee 'cloudflared %s --help'.", err.Error(), ctx.Command.FullName())
|
2020-11-09 22:53:51 +00:00
|
|
|
err = cli.Exit(msg, -1)
|
|
|
|
} else if _, ok := err.(cli.ExitCoder); !ok {
|
|
|
|
err = cli.Exit(err.Error(), 1)
|
2020-05-21 20:36:49 +00:00
|
|
|
}
|
2020-05-18 18:24:17 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-06-12 16:20:36 +00:00
|
|
|
|
|
|
|
// PrintLoggerSetupError returns an error to stdout to notify when a logger can't start
|
|
|
|
func PrintLoggerSetupError(msg string, err error) error {
|
|
|
|
l, le := logger.New()
|
|
|
|
if le != nil {
|
|
|
|
log.Printf("%s: %s", msg, err)
|
|
|
|
} else {
|
|
|
|
l.Errorf("%s: %s", msg, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return errors.Wrap(err, msg)
|
|
|
|
}
|