feat: enhanced error messages for cloud and oss specific commands (#347)

* feat: enhanced error messages for cloud and oss specific commands

* chore: rename test
This commit is contained in:
William Baker
2021-12-28 10:03:29 -05:00
committed by GitHub
parent 13d0827815
commit 7af0b2ae73
36 changed files with 1503 additions and 1985 deletions

View File

@ -0,0 +1,26 @@
package context
import "github.com/urfave/cli"
const (
contextKeyCloudOnly = "cloudOnly"
contextKeyOssOnly = "ossOnly"
)
func SetCloudOnly(ctx *cli.Context) {
ctx.App.Metadata[contextKeyCloudOnly] = true
}
func SetOssOnly(ctx *cli.Context) {
ctx.App.Metadata[contextKeyOssOnly] = true
}
func GetCloudOnly(ctx *cli.Context) bool {
_, ok := ctx.App.Metadata[contextKeyCloudOnly].(bool)
return ok
}
func GetOssOnly(ctx *cli.Context) bool {
_, ok := ctx.App.Metadata[contextKeyOssOnly].(bool)
return ok
}

View File

@ -0,0 +1,51 @@
package middleware
import (
"errors"
"fmt"
"github.com/influxdata/influx-cli/v2/api"
icontext "github.com/influxdata/influx-cli/v2/pkg/cli/context"
"github.com/urfave/cli"
)
const (
OSSBuildHeader = "OSS"
CloudBuildHeader = "Cloud"
)
func WrongHostErrString(commandHost, actualHost string) string {
return fmt.Sprintf("Error: InfluxDB %s-only command used with InfluxDB %s host", commandHost, actualHost)
}
var HandleExit cli.ExitErrHandlerFunc = func(ctx *cli.Context, err error) {
if err == nil {
return
}
var header string
var genericErr api.GenericOpenAPIError
if errors.As(err, &genericErr) {
header = genericErr.BuildHeader()
}
// Replace the error message with the relevant information if a platform-specific command was used on the wrong host.
// Otherwise, pass the error message along as-is to the CLI exit handler.
var setErr bool
if header == OSSBuildHeader {
if icontext.GetCloudOnly(ctx) {
err = cli.NewExitError(WrongHostErrString(CloudBuildHeader, OSSBuildHeader), 1)
setErr = true
}
} else if header == CloudBuildHeader {
if icontext.GetOssOnly(ctx) {
err = cli.NewExitError(WrongHostErrString(OSSBuildHeader, CloudBuildHeader), 1)
setErr = true
}
}
if !setErr {
err = cli.NewExitError(fmt.Sprintf("Error: %v", err.Error()), 1)
}
cli.HandleExitCoder(err)
}

View File

@ -1,6 +1,7 @@
package middleware
import (
icontext "github.com/influxdata/influx-cli/v2/pkg/cli/context"
"github.com/urfave/cli"
)
@ -18,3 +19,25 @@ func WithBeforeFns(fns ...cli.BeforeFunc) cli.BeforeFunc {
return nil
}
}
// AddMWToCmds is used to append a middleware to a list of existing commands.
func AddMWToCmds(cmds []cli.Command, mw cli.BeforeFunc) []cli.Command {
newCmds := make([]cli.Command, 0, len(cmds))
for _, cmd := range cmds {
cmd.Before = WithBeforeFns(cmd.Before, mw)
newCmds = append(newCmds, cmd)
}
return newCmds
}
var CloudOnly cli.BeforeFunc = func(ctx *cli.Context) error {
icontext.SetCloudOnly(ctx)
return nil
}
var OSSOnly cli.BeforeFunc = func(ctx *cli.Context) error {
icontext.SetOssOnly(ctx)
return nil
}