Merge pull request #4584 from cli/FlagErrorf

Add FlagErrorf; encapsulate FlagError.error
This commit is contained in:
Alan Donovan 2021-10-21 14:14:05 -04:00 committed by GitHub
commit 2f7f224c9e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
48 changed files with 103 additions and 114 deletions

View file

@ -49,7 +49,7 @@ check your internet connection or https://githubstatus.com
{ {
name: "Cobra flag error", name: "Cobra flag error",
args: args{ args: args{
err: &cmdutil.FlagError{Err: errors.New("unknown flag --foo")}, err: cmdutil.FlagErrorf("unknown flag --foo"),
cmd: cmd, cmd: cmd,
debug: false, debug: false,
}, },

View file

@ -173,12 +173,12 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command
if c.Flags().Changed("hostname") { if c.Flags().Changed("hostname") {
if err := ghinstance.HostnameValidator(opts.Hostname); err != nil { if err := ghinstance.HostnameValidator(opts.Hostname); err != nil {
return &cmdutil.FlagError{Err: fmt.Errorf("error parsing `--hostname`: %w", err)} return cmdutil.FlagErrorf("error parsing `--hostname`: %w", err)
} }
} }
if opts.Paginate && !strings.EqualFold(opts.RequestMethod, "GET") && opts.RequestPath != "graphql" { if opts.Paginate && !strings.EqualFold(opts.RequestMethod, "GET") && opts.RequestPath != "graphql" {
return &cmdutil.FlagError{Err: errors.New("the `--paginate` option is not supported for non-GET requests")} return cmdutil.FlagErrorf("the `--paginate` option is not supported for non-GET requests")
} }
if err := cmdutil.MutuallyExclusive( if err := cmdutil.MutuallyExclusive(

View file

@ -69,11 +69,11 @@ func NewCmdLogin(f *cmdutil.Factory, runF func(*LoginOptions) error) *cobra.Comm
`), `),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if !opts.IO.CanPrompt() && !(tokenStdin || opts.Web) { if !opts.IO.CanPrompt() && !(tokenStdin || opts.Web) {
return &cmdutil.FlagError{Err: errors.New("--web or --with-token required when not running interactively")} return cmdutil.FlagErrorf("--web or --with-token required when not running interactively")
} }
if tokenStdin && opts.Web { if tokenStdin && opts.Web {
return &cmdutil.FlagError{Err: errors.New("specify only one of --web or --with-token")} return cmdutil.FlagErrorf("specify only one of --web or --with-token")
} }
if tokenStdin { if tokenStdin {
@ -91,7 +91,7 @@ func NewCmdLogin(f *cmdutil.Factory, runF func(*LoginOptions) error) *cobra.Comm
if cmd.Flags().Changed("hostname") { if cmd.Flags().Changed("hostname") {
if err := ghinstance.HostnameValidator(opts.Hostname); err != nil { if err := ghinstance.HostnameValidator(opts.Hostname); err != nil {
return &cmdutil.FlagError{Err: fmt.Errorf("error parsing --hostname: %w", err)} return cmdutil.FlagErrorf("error parsing --hostname: %w", err)
} }
} }

View file

@ -48,7 +48,7 @@ func NewCmdLogout(f *cmdutil.Factory, runF func(*LogoutOptions) error) *cobra.Co
`), `),
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if opts.Hostname == "" && !opts.IO.CanPrompt() { if opts.Hostname == "" && !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("--hostname required when not running interactively")} return cmdutil.FlagErrorf("--hostname required when not running interactively")
} }
if runF != nil { if runF != nil {

View file

@ -62,7 +62,7 @@ func NewCmdRefresh(f *cmdutil.Factory, runF func(*RefreshOptions) error) *cobra.
opts.Interactive = opts.IO.CanPrompt() opts.Interactive = opts.IO.CanPrompt()
if !opts.Interactive && opts.Hostname == "" { if !opts.Interactive && opts.Hostname == "" {
return &cmdutil.FlagError{Err: errors.New("--hostname required when not running interactively")} return cmdutil.FlagErrorf("--hostname required when not running interactively")
} }
opts.MainExecutable = f.Executable() opts.MainExecutable = f.Executable()

View file

@ -21,7 +21,7 @@ func newListCmd(app *App) *cobra.Command {
Args: noArgsConstraint, Args: noArgsConstraint,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if limit < 1 { if limit < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid limit: %v", limit)} return cmdutil.FlagErrorf("invalid limit: %v", limit)
} }
return app.List(cmd.Context(), asJSON, limit) return app.List(cmd.Context(), asJSON, limit)

View file

@ -231,7 +231,7 @@ func (a *App) Copy(ctx context.Context, args []string, opts cpOptions) error {
opts.scpArgs = append(opts.scpArgs, arg) opts.scpArgs = append(opts.scpArgs, arg)
} }
if !hasRemote { if !hasRemote {
return &cmdutil.FlagError{Err: fmt.Errorf("at least one argument must have a 'remote:' prefix")} return cmdutil.FlagErrorf("at least one argument must have a 'remote:' prefix")
} }
return a.SSH(ctx, nil, opts.sshOptions) return a.SSH(ctx, nil, opts.sshOptions)
} }

View file

@ -1,7 +1,6 @@
package completion package completion
import ( import (
"errors"
"fmt" "fmt"
"github.com/MakeNowJust/heredoc" "github.com/MakeNowJust/heredoc"
@ -68,7 +67,7 @@ func NewCmdCompletion(io *iostreams.IOStreams) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if shellType == "" { if shellType == "" {
if io.IsStdoutTTY() { if io.IsStdoutTTY() {
return &cmdutil.FlagError{Err: errors.New("error: the value for `--shell` is required")} return cmdutil.FlagErrorf("error: the value for `--shell` is required")
} }
shellType = "bash" shellType = "bash"
} }

View file

@ -117,13 +117,13 @@ func NewCmdExtension(f *cmdutil.Factory) *cobra.Command {
Short: "Upgrade installed extensions", Short: "Upgrade installed extensions",
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 && !flagAll { if len(args) == 0 && !flagAll {
return &cmdutil.FlagError{Err: errors.New("must specify an extension to upgrade")} return cmdutil.FlagErrorf("must specify an extension to upgrade")
} }
if len(args) > 0 && flagAll { if len(args) > 0 && flagAll {
return &cmdutil.FlagError{Err: errors.New("cannot use `--all` with extension name")} return cmdutil.FlagErrorf("cannot use `--all` with extension name")
} }
if len(args) > 1 { if len(args) > 1 {
return &cmdutil.FlagError{Err: errors.New("too many arguments")} return cmdutil.FlagErrorf("too many arguments")
} }
return nil return nil
}, },

View file

@ -61,7 +61,7 @@ func NewCmdClone(f *cmdutil.Factory, runF func(*CloneOptions) error) *cobra.Comm
if err == pflag.ErrHelp { if err == pflag.ErrHelp {
return err return err
} }
return &cmdutil.FlagError{Err: fmt.Errorf("%w\nSeparate git clone flags with '--'.", err)} return cmdutil.FlagErrorf("%w\nSeparate git clone flags with '--'.", err)
}) })
return cmd return cmd

View file

@ -82,7 +82,7 @@ func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Co
return nil return nil
} }
if opts.IO.IsStdinTTY() { if opts.IO.IsStdinTTY() {
return &cmdutil.FlagError{Err: errors.New("no filenames passed and nothing on STDIN")} return cmdutil.FlagErrorf("no filenames passed and nothing on STDIN")
} }
return nil return nil
}, },

View file

@ -1,7 +1,6 @@
package list package list
import ( import (
"fmt"
"net/http" "net/http"
"strings" "strings"
"time" "time"
@ -40,7 +39,7 @@ func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Comman
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if opts.Limit < 1 { if opts.Limit < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid limit: %v", opts.Limit)} return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
} }
opts.Visibility = "all" opts.Visibility = "all"

View file

@ -35,7 +35,7 @@ func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 { if len(args) == 0 {
if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() { if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() {
return &cmdutil.FlagError{Err: errors.New("GPG key file missing")} return cmdutil.FlagErrorf("GPG key file missing")
} }
opts.KeyFile = "-" opts.KeyFile = "-"
} else { } else {

View file

@ -1,7 +1,6 @@
package create package create
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -83,13 +82,13 @@ func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Co
} }
if !opts.IO.CanPrompt() && opts.RecoverFile != "" { if !opts.IO.CanPrompt() && opts.RecoverFile != "" {
return &cmdutil.FlagError{Err: errors.New("`--recover` only supported when running interactively")} return cmdutil.FlagErrorf("`--recover` only supported when running interactively")
} }
opts.Interactive = !(titleProvided && bodyProvided) opts.Interactive = !(titleProvided && bodyProvided)
if opts.Interactive && !opts.IO.CanPrompt() { if opts.Interactive && !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("must provide title and body when not running interactively")} return cmdutil.FlagErrorf("must provide title and body when not running interactively")
} }
if runF != nil { if runF != nil {

View file

@ -1,7 +1,6 @@
package edit package edit
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -106,7 +105,7 @@ func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Comman
} }
if opts.Interactive && !opts.IO.CanPrompt() { if opts.Interactive && !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("field to edit flag required when not running interactively")} return cmdutil.FlagErrorf("field to edit flag required when not running interactively")
} }
if runF != nil { if runF != nil {

View file

@ -68,7 +68,7 @@ func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Comman
opts.BaseRepo = f.BaseRepo opts.BaseRepo = f.BaseRepo
if opts.LimitResults < 1 { if opts.LimitResults < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid limit: %v", opts.LimitResults)} return cmdutil.FlagErrorf("invalid limit: %v", opts.LimitResults)
} }
if runF != nil { if runF != nil {

View file

@ -1,7 +1,6 @@
package checks package checks
import ( import (
"errors"
"fmt" "fmt"
"sort" "sort"
"time" "time"
@ -49,7 +48,7 @@ func NewCmdChecks(f *cmdutil.Factory, runF func(*ChecksOptions) error) *cobra.Co
opts.Finder = shared.NewFinder(f) opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
if len(args) > 0 { if len(args) > 0 {

View file

@ -1,8 +1,6 @@
package comment package comment
import ( import (
"errors"
"github.com/MakeNowJust/heredoc" "github.com/MakeNowJust/heredoc"
"github.com/cli/cli/v2/internal/ghrepo" "github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/pkg/cmd/pr/shared" "github.com/cli/cli/v2/pkg/cmd/pr/shared"
@ -39,7 +37,7 @@ func NewCmdComment(f *cmdutil.Factory, runF func(*shared.CommentableOptions) err
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error { PreRunE: func(cmd *cobra.Command, args []string) error {
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
var selector string var selector string
if len(args) > 0 { if len(args) > 0 {

View file

@ -126,11 +126,11 @@ func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Co
opts.MaintainerCanModify = !noMaintainerEdit opts.MaintainerCanModify = !noMaintainerEdit
if !opts.IO.CanPrompt() && opts.RecoverFile != "" { if !opts.IO.CanPrompt() && opts.RecoverFile != "" {
return &cmdutil.FlagError{Err: errors.New("`--recover` only supported when running interactively")} return cmdutil.FlagErrorf("`--recover` only supported when running interactively")
} }
if !opts.IO.CanPrompt() && !opts.WebMode && !opts.TitleProvided && !opts.Autofill { if !opts.IO.CanPrompt() && !opts.WebMode && !opts.TitleProvided && !opts.Autofill {
return &cmdutil.FlagError{Err: errors.New("`--title` or `--fill` required when not running interactively")} return cmdutil.FlagErrorf("`--title` or `--fill` required when not running interactively")
} }
if opts.IsDraft && opts.WebMode { if opts.IsDraft && opts.WebMode {

View file

@ -50,7 +50,7 @@ func NewCmdDiff(f *cmdutil.Factory, runF func(*DiffOptions) error) *cobra.Comman
opts.Finder = shared.NewFinder(f) opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
if len(args) > 0 { if len(args) > 0 {
@ -58,7 +58,7 @@ func NewCmdDiff(f *cmdutil.Factory, runF func(*DiffOptions) error) *cobra.Comman
} }
if !validColorFlag(opts.UseColor) { if !validColorFlag(opts.UseColor) {
return &cmdutil.FlagError{Err: fmt.Errorf("did not understand color: %q. Expected one of always, never, or auto", opts.UseColor)} return cmdutil.FlagErrorf("did not understand color: %q. Expected one of always, never, or auto", opts.UseColor)
} }
if opts.UseColor == "auto" && !opts.IO.IsStdoutTTY() { if opts.UseColor == "auto" && !opts.IO.IsStdoutTTY() {

View file

@ -1,7 +1,6 @@
package edit package edit
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -120,7 +119,7 @@ func NewCmdEdit(f *cmdutil.Factory, runF func(*EditOptions) error) *cobra.Comman
} }
if opts.Interactive && !opts.IO.CanPrompt() { if opts.Interactive && !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("--tile, --body, --reviewer, --assignee, --label, --project, or --milestone required when not running interactively")} return cmdutil.FlagErrorf("--tile, --body, --reviewer, --assignee, --label, --project, or --milestone required when not running interactively")
} }
if runF != nil { if runF != nil {

View file

@ -75,7 +75,7 @@ func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Comman
opts.BaseRepo = f.BaseRepo opts.BaseRepo = f.BaseRepo
if opts.LimitResults < 1 { if opts.LimitResults < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid value for --limit: %v", opts.LimitResults)} return cmdutil.FlagErrorf("invalid value for --limit: %v", opts.LimitResults)
} }
if cmd.Flags().Changed("draft") { if cmd.Flags().Changed("draft") {

View file

@ -75,7 +75,7 @@ func NewCmdMerge(f *cmdutil.Factory, runF func(*MergeOptions) error) *cobra.Comm
opts.Finder = shared.NewFinder(f) opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
if len(args) > 0 { if len(args) > 0 {
@ -97,11 +97,11 @@ func NewCmdMerge(f *cmdutil.Factory, runF func(*MergeOptions) error) *cobra.Comm
} }
if methodFlags == 0 { if methodFlags == 0 {
if !opts.IO.CanPrompt() { if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("--merge, --rebase, or --squash required when not running interactively")} return cmdutil.FlagErrorf("--merge, --rebase, or --squash required when not running interactively")
} }
opts.InteractiveMode = true opts.InteractiveMode = true
} else if methodFlags > 1 { } else if methodFlags > 1 {
return &cmdutil.FlagError{Err: errors.New("only one of --merge, --rebase, or --squash can be enabled")} return cmdutil.FlagErrorf("only one of --merge, --rebase, or --squash can be enabled")
} }
opts.IsDeleteBranchIndicated = cmd.Flags().Changed("delete-branch") opts.IsDeleteBranchIndicated = cmd.Flags().Changed("delete-branch")

View file

@ -1,7 +1,6 @@
package ready package ready
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
@ -42,7 +41,7 @@ func NewCmdReady(f *cmdutil.Factory, runF func(*ReadyOptions) error) *cobra.Comm
opts.Finder = shared.NewFinder(f) opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
if len(args) > 0 { if len(args) > 0 {

View file

@ -72,7 +72,7 @@ func NewCmdReview(f *cmdutil.Factory, runF func(*ReviewOptions) error) *cobra.Co
opts.Finder = shared.NewFinder(f) opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
if len(args) > 0 { if len(args) > 0 {
@ -106,26 +106,26 @@ func NewCmdReview(f *cmdutil.Factory, runF func(*ReviewOptions) error) *cobra.Co
found++ found++
opts.ReviewType = api.ReviewRequestChanges opts.ReviewType = api.ReviewRequestChanges
if opts.Body == "" { if opts.Body == "" {
return &cmdutil.FlagError{Err: errors.New("body cannot be blank for request-changes review")} return cmdutil.FlagErrorf("body cannot be blank for request-changes review")
} }
} }
if flagComment { if flagComment {
found++ found++
opts.ReviewType = api.ReviewComment opts.ReviewType = api.ReviewComment
if opts.Body == "" { if opts.Body == "" {
return &cmdutil.FlagError{Err: errors.New("body cannot be blank for comment review")} return cmdutil.FlagErrorf("body cannot be blank for comment review")
} }
} }
if found == 0 && opts.Body == "" { if found == 0 && opts.Body == "" {
if !opts.IO.CanPrompt() { if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("--approve, --request-changes, or --comment required when not running interactively")} return cmdutil.FlagErrorf("--approve, --request-changes, or --comment required when not running interactively")
} }
opts.InteractiveMode = true opts.InteractiveMode = true
} else if found == 0 && opts.Body != "" { } else if found == 0 && opts.Body != "" {
return &cmdutil.FlagError{Err: errors.New("--body unsupported without --approve, --request-changes, or --comment")} return cmdutil.FlagErrorf("--body unsupported without --approve, --request-changes, or --comment")
} else if found > 1 { } else if found > 1 {
return &cmdutil.FlagError{Err: errors.New("need exactly one of --approve, --request-changes, or --comment")} return cmdutil.FlagErrorf("need exactly one of --approve, --request-changes, or --comment")
} }
if runF != nil { if runF != nil {

View file

@ -65,15 +65,15 @@ func CommentablePreRun(cmd *cobra.Command, opts *CommentableOptions) error {
if inputFlags == 0 { if inputFlags == 0 {
if !opts.IO.CanPrompt() { if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("`--body`, `--body-file` or `--web` required when not running interactively")} return cmdutil.FlagErrorf("`--body`, `--body-file` or `--web` required when not running interactively")
} }
opts.Interactive = true opts.Interactive = true
} else if inputFlags == 1 { } else if inputFlags == 1 {
if !opts.IO.CanPrompt() && opts.InputType == InputTypeEditor { if !opts.IO.CanPrompt() && opts.InputType == InputTypeEditor {
return &cmdutil.FlagError{Err: errors.New("`--body`, `--body-file` or `--web` required when not running interactively")} return cmdutil.FlagErrorf("`--body`, `--body-file` or `--web` required when not running interactively")
} }
} else if inputFlags > 1 { } else if inputFlags > 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("specify only one of `--body`, `--body-file`, `--editor`, or `--web`")} return cmdutil.FlagErrorf("specify only one of `--body`, `--body-file`, `--editor`, or `--web`")
} }
return nil return nil

View file

@ -1,7 +1,6 @@
package view package view
import ( import (
"errors"
"fmt" "fmt"
"sort" "sort"
"strconv" "strconv"
@ -55,7 +54,7 @@ func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Comman
opts.Finder = shared.NewFinder(f) opts.Finder = shared.NewFinder(f)
if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 { if repoOverride, _ := cmd.Flags().GetString("repo"); repoOverride != "" && len(args) == 0 {
return &cmdutil.FlagError{Err: errors.New("argument required when using the --repo flag")} return cmdutil.FlagErrorf("argument required when using the --repo flag")
} }
if len(args) > 0 { if len(args) > 0 {

View file

@ -61,7 +61,7 @@ func NewCmdDownload(f *cmdutil.Factory, runF func(*DownloadOptions) error) *cobr
if len(args) == 0 { if len(args) == 0 {
if len(opts.FilePatterns) == 0 { if len(opts.FilePatterns) == 0 {
return &cmdutil.FlagError{Err: errors.New("the '--pattern' flag is required when downloading the latest release")} return cmdutil.FlagErrorf("the '--pattern' flag is required when downloading the latest release")
} }
} else { } else {
opts.TagName = args[0] opts.TagName = args[0]

View file

@ -62,7 +62,7 @@ func NewCmdClone(f *cmdutil.Factory, runF func(*CloneOptions) error) *cobra.Comm
if err == pflag.ErrHelp { if err == pflag.ErrHelp {
return err return err
} }
return &cmdutil.FlagError{Err: fmt.Errorf("%w\nSeparate git clone flags with '--'.", err)} return cmdutil.FlagErrorf("%w\nSeparate git clone flags with '--'.", err)
}) })
return cmd return cmd

View file

@ -1,7 +1,6 @@
package create package create
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"path" "path"
@ -94,25 +93,25 @@ func NewCmdCreate(f *cmdutil.Factory, runF func(*CreateOptions) error) *cobra.Co
} }
if len(args) == 0 && (opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "") { if len(args) == 0 && (opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "") {
return &cmdutil.FlagError{Err: errors.New(".gitignore and license templates are added only when a specific repository name is passed")} return cmdutil.FlagErrorf(".gitignore and license templates are added only when a specific repository name is passed")
} }
if opts.Template != "" && (opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "") { if opts.Template != "" && (opts.GitIgnoreTemplate != "" || opts.LicenseTemplate != "") {
return &cmdutil.FlagError{Err: errors.New(".gitignore and license templates are not added when template is provided")} return cmdutil.FlagErrorf(".gitignore and license templates are not added when template is provided")
} }
if !opts.IO.CanPrompt() { if !opts.IO.CanPrompt() {
if opts.Name == "" { if opts.Name == "" {
return &cmdutil.FlagError{Err: errors.New("name argument required when not running interactively")} return cmdutil.FlagErrorf("name argument required when not running interactively")
} }
if !opts.Internal && !opts.Private && !opts.Public { if !opts.Internal && !opts.Private && !opts.Public {
return &cmdutil.FlagError{Err: errors.New("`--public`, `--private`, or `--internal` required when not running interactively")} return cmdutil.FlagErrorf("`--public`, `--private`, or `--internal` required when not running interactively")
} }
} }
if opts.Template != "" && (opts.Homepage != "" || opts.Team != "" || cmd.Flags().Changed("enable-issues") || cmd.Flags().Changed("enable-wiki")) { if opts.Template != "" && (opts.Homepage != "" || opts.Team != "" || cmd.Flags().Changed("enable-issues") || cmd.Flags().Changed("enable-wiki")) {
return &cmdutil.FlagError{Err: errors.New("The `--template` option is not supported with `--homepage`, `--team`, `--enable-issues`, or `--enable-wiki`")} return cmdutil.FlagErrorf("The `--template` option is not supported with `--homepage`, `--team`, `--enable-issues`, or `--enable-wiki`")
} }
if runF != nil { if runF != nil {

View file

@ -1,7 +1,6 @@
package delete package delete
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
@ -41,8 +40,7 @@ To authorize, run "gh auth refresh -s delete_repo"`,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
opts.RepoArg = args[0] opts.RepoArg = args[0]
if !opts.IO.CanPrompt() && !opts.Confirmed { if !opts.IO.CanPrompt() && !opts.Confirmed {
return &cmdutil.FlagError{ return cmdutil.FlagErrorf("could not prompt: confirmation with prompt or --confirm flag required")
Err: errors.New("could not prompt: confirmation with prompt or --confirm flag required")}
} }
if runF != nil { if runF != nil {
return runF(opts) return runF(opts)

View file

@ -1,7 +1,6 @@
package fork package fork
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
@ -61,7 +60,7 @@ func NewCmdFork(f *cmdutil.Factory, runF func(*ForkOptions) error) *cobra.Comman
Use: "fork [<repository>] [-- <gitflags>...]", Use: "fork [<repository>] [-- <gitflags>...]",
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
if cmd.ArgsLenAtDash() == 0 && len(args[1:]) > 0 { if cmd.ArgsLenAtDash() == 0 && len(args[1:]) > 0 {
return &cmdutil.FlagError{Err: fmt.Errorf("repository argument required when passing 'git clone' flags")} return cmdutil.FlagErrorf("repository argument required when passing 'git clone' flags")
} }
return nil return nil
}, },
@ -84,11 +83,11 @@ Additional 'git clone' flags can be passed in by listing them after '--'.`,
} }
if cmd.Flags().Changed("org") && opts.Organization == "" { if cmd.Flags().Changed("org") && opts.Organization == "" {
return &cmdutil.FlagError{Err: errors.New("--org cannot be blank")} return cmdutil.FlagErrorf("--org cannot be blank")
} }
if opts.RemoteName == "" { if opts.RemoteName == "" {
return &cmdutil.FlagError{Err: errors.New("--remote-name cannot be blank")} return cmdutil.FlagErrorf("--remote-name cannot be blank")
} else if !cmd.Flags().Changed("remote-name") { } else if !cmd.Flags().Changed("remote-name") {
opts.Rename = true // Any existing 'origin' will be renamed to upstream opts.Rename = true // Any existing 'origin' will be renamed to upstream
} }
@ -109,7 +108,7 @@ Additional 'git clone' flags can be passed in by listing them after '--'.`,
if err == pflag.ErrHelp { if err == pflag.ErrHelp {
return err return err
} }
return &cmdutil.FlagError{Err: fmt.Errorf("%w\nSeparate git clone flags with '--'.", err)} return cmdutil.FlagErrorf("%w\nSeparate git clone flags with '--'.", err)
}) })
cmd.Flags().BoolVar(&opts.Clone, "clone", false, "Clone the fork {true|false}") cmd.Flags().BoolVar(&opts.Clone, "clone", false, "Clone the fork {true|false}")

View file

@ -54,17 +54,17 @@ func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Comman
Short: "List repositories owned by user or organization", Short: "List repositories owned by user or organization",
RunE: func(c *cobra.Command, args []string) error { RunE: func(c *cobra.Command, args []string) error {
if opts.Limit < 1 { if opts.Limit < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid limit: %v", opts.Limit)} return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
} }
if flagPrivate && flagPublic { if flagPrivate && flagPublic {
return &cmdutil.FlagError{Err: fmt.Errorf("specify only one of `--public` or `--private`")} return cmdutil.FlagErrorf("specify only one of `--public` or `--private`")
} }
if opts.Source && opts.Fork { if opts.Source && opts.Fork {
return &cmdutil.FlagError{Err: fmt.Errorf("specify only one of `--source` or `--fork`")} return cmdutil.FlagErrorf("specify only one of `--source` or `--fork`")
} }
if opts.Archived && opts.NonArchived { if opts.Archived && opts.NonArchived {
return &cmdutil.FlagError{Err: fmt.Errorf("specify only one of `--archived` or `--no-archived`")} return cmdutil.FlagErrorf("specify only one of `--archived` or `--no-archived`")
} }
if flagPrivate { if flagPrivate {

View file

@ -38,7 +38,7 @@ func rootFlagErrorFunc(cmd *cobra.Command, err error) error {
if err == pflag.ErrHelp { if err == pflag.ErrHelp {
return err return err
} }
return &cmdutil.FlagError{Err: err} return cmdutil.FlagErrorWrap(err)
} }
var hasFailed bool var hasFailed bool

View file

@ -40,7 +40,7 @@ func NewCmdCancel(f *cmdutil.Factory, runF func(*CancelOptions) error) *cobra.Co
if len(args) > 0 { if len(args) > 0 {
opts.RunID = args[0] opts.RunID = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("run ID required when not running interactively")} return cmdutil.FlagErrorf("run ID required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }

View file

@ -48,7 +48,7 @@ func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Comman
opts.PlainOutput = !terminal opts.PlainOutput = !terminal
if opts.Limit < 1 { if opts.Limit < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid limit: %v", opts.Limit)} return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
} }
if runF != nil { if runF != nil {

View file

@ -40,7 +40,7 @@ func NewCmdRerun(f *cmdutil.Factory, runF func(*RerunOptions) error) *cobra.Comm
if len(args) > 0 { if len(args) > 0 {
opts.RunID = args[0] opts.RunID = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("run ID required when not running interactively")} return cmdutil.FlagErrorf("run ID required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }

View file

@ -118,7 +118,7 @@ func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Comman
if len(args) == 0 && opts.JobID == "" { if len(args) == 0 && opts.JobID == "" {
if !opts.IO.CanPrompt() { if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("run or job ID required when not running interactively")} return cmdutil.FlagErrorf("run or job ID required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }
@ -135,11 +135,11 @@ func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Comman
} }
if opts.Web && opts.Log { if opts.Web && opts.Log {
return &cmdutil.FlagError{Err: errors.New("specify only one of --web or --log")} return cmdutil.FlagErrorf("specify only one of --web or --log")
} }
if opts.Log && opts.LogFailed { if opts.Log && opts.LogFailed {
return &cmdutil.FlagError{Err: errors.New("specify only one of --log or --log-failed")} return cmdutil.FlagErrorf("specify only one of --log or --log-failed")
} }
if runF != nil { if runF != nil {

View file

@ -1,7 +1,6 @@
package watch package watch
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"runtime" "runtime"
@ -57,7 +56,7 @@ func NewCmdWatch(f *cmdutil.Factory, runF func(*WatchOptions) error) *cobra.Comm
if len(args) > 0 { if len(args) > 0 {
opts.RunID = args[0] opts.RunID = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("run ID required when not running interactively")} return cmdutil.FlagErrorf("run ID required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }

View file

@ -71,7 +71,7 @@ func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command
`), `),
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 { if len(args) != 1 {
return &cmdutil.FlagError{Err: errors.New("must pass single secret name")} return cmdutil.FlagErrorf("must pass single secret name")
} }
return nil return nil
}, },
@ -92,23 +92,19 @@ func NewCmdSet(f *cmdutil.Factory, runF func(*SetOptions) error) *cobra.Command
if cmd.Flags().Changed("visibility") { if cmd.Flags().Changed("visibility") {
if opts.OrgName == "" { if opts.OrgName == "" {
return &cmdutil.FlagError{Err: errors.New( return cmdutil.FlagErrorf("--visibility not supported for repository secrets; did you mean to pass --org?")
"--visibility not supported for repository secrets; did you mean to pass --org?")}
} }
if opts.Visibility != shared.All && opts.Visibility != shared.Private && opts.Visibility != shared.Selected { if opts.Visibility != shared.All && opts.Visibility != shared.Private && opts.Visibility != shared.Selected {
return &cmdutil.FlagError{Err: errors.New( return cmdutil.FlagErrorf("--visibility must be one of `all`, `private`, or `selected`")
"--visibility must be one of `all`, `private`, or `selected`")}
} }
if opts.Visibility != shared.Selected && cmd.Flags().Changed("repos") { if opts.Visibility != shared.Selected && cmd.Flags().Changed("repos") {
return &cmdutil.FlagError{Err: errors.New( return cmdutil.FlagErrorf("--repos only supported when --visibility='selected'")
"--repos only supported when --visibility='selected'")}
} }
if opts.Visibility == shared.Selected && !cmd.Flags().Changed("repos") { if opts.Visibility == shared.Selected && !cmd.Flags().Changed("repos") {
return &cmdutil.FlagError{Err: errors.New( return cmdutil.FlagErrorf("--repos flag required when --visibility='selected'")
"--repos flag required when --visibility='selected'")}
} }
} else { } else {
if cmd.Flags().Changed("repos") { if cmd.Flags().Changed("repos") {

View file

@ -1,7 +1,6 @@
package add package add
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -36,7 +35,7 @@ func NewCmdAdd(f *cmdutil.Factory, runF func(*AddOptions) error) *cobra.Command
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 { if len(args) == 0 {
if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() { if opts.IO.IsStdoutTTY() && opts.IO.IsStdinTTY() {
return &cmdutil.FlagError{Err: errors.New("public key file missing")} return cmdutil.FlagErrorf("public key file missing")
} }
opts.KeyFile = "-" opts.KeyFile = "-"
} else { } else {

View file

@ -40,7 +40,7 @@ func NewCmdDisable(f *cmdutil.Factory, runF func(*DisableOptions) error) *cobra.
if len(args) > 0 { if len(args) > 0 {
opts.Selector = args[0] opts.Selector = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("workflow ID or name required when not running interactively")} return cmdutil.FlagErrorf("workflow ID or name required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }

View file

@ -40,7 +40,7 @@ func NewCmdEnable(f *cmdutil.Factory, runF func(*EnableOptions) error) *cobra.Co
if len(args) > 0 { if len(args) > 0 {
opts.Selector = args[0] opts.Selector = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("workflow ID or name required when not running interactively")} return cmdutil.FlagErrorf("workflow ID or name required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }

View file

@ -45,7 +45,7 @@ func NewCmdList(f *cmdutil.Factory, runF func(*ListOptions) error) *cobra.Comman
opts.PlainOutput = !terminal opts.PlainOutput = !terminal
if opts.Limit < 1 { if opts.Limit < 1 {
return &cmdutil.FlagError{Err: fmt.Errorf("invalid limit: %v", opts.Limit)} return cmdutil.FlagErrorf("invalid limit: %v", opts.Limit)
} }
if runF != nil { if runF != nil {

View file

@ -78,7 +78,7 @@ func NewCmdRun(f *cmdutil.Factory, runF func(*RunOptions) error) *cobra.Command
`), `),
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
if len(opts.MagicFields)+len(opts.RawFields) > 0 && len(args) == 0 { if len(opts.MagicFields)+len(opts.RawFields) > 0 && len(args) == 0 {
return &cmdutil.FlagError{Err: fmt.Errorf("workflow argument required when passing -f or -F")} return cmdutil.FlagErrorf("workflow argument required when passing -f or -F")
} }
return nil return nil
}, },
@ -91,7 +91,7 @@ func NewCmdRun(f *cmdutil.Factory, runF func(*RunOptions) error) *cobra.Command
if len(args) > 0 { if len(args) > 0 {
opts.Selector = args[0] opts.Selector = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("workflow ID, name, or filename required when not running interactively")} return cmdutil.FlagErrorf("workflow ID, name, or filename required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }
@ -103,16 +103,16 @@ func NewCmdRun(f *cmdutil.Factory, runF func(*RunOptions) error) *cobra.Command
} }
opts.JSONInput = string(jsonIn) opts.JSONInput = string(jsonIn)
} else if opts.JSON { } else if opts.JSON {
return &cmdutil.FlagError{Err: errors.New("--json specified but nothing on STDIN")} return cmdutil.FlagErrorf("--json specified but nothing on STDIN")
} }
if opts.Selector == "" { if opts.Selector == "" {
if opts.JSONInput != "" { if opts.JSONInput != "" {
return &cmdutil.FlagError{Err: errors.New("workflow argument required when passing JSON")} return cmdutil.FlagErrorf("workflow argument required when passing JSON")
} }
} else { } else {
if opts.JSON && inputFieldsPassed { if opts.JSON && inputFieldsPassed {
return &cmdutil.FlagError{Err: errors.New("only one of STDIN or -f/-F can be passed")} return cmdutil.FlagErrorf("only one of STDIN or -f/-F can be passed")
} }
} }

View file

@ -1,7 +1,6 @@
package view package view
import ( import (
"errors"
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
@ -59,13 +58,13 @@ func NewCmdView(f *cmdutil.Factory, runF func(*ViewOptions) error) *cobra.Comman
if len(args) > 0 { if len(args) > 0 {
opts.Selector = args[0] opts.Selector = args[0]
} else if !opts.IO.CanPrompt() { } else if !opts.IO.CanPrompt() {
return &cmdutil.FlagError{Err: errors.New("workflow argument required when not running interactively")} return cmdutil.FlagErrorf("workflow argument required when not running interactively")
} else { } else {
opts.Prompt = true opts.Prompt = true
} }
if !opts.YAML && opts.Ref != "" { if !opts.YAML && opts.Ref != "" {
return &cmdutil.FlagError{Err: errors.New("`--yaml` required when specifying `--ref`")} return cmdutil.FlagErrorf("`--yaml` required when specifying `--ref`")
} }
if runF != nil { if runF != nil {

View file

@ -1,7 +1,6 @@
package cmdutil package cmdutil
import ( import (
"errors"
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -15,7 +14,7 @@ func MinimumArgs(n int, msg string) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error {
if len(args) < n { if len(args) < n {
return &FlagError{Err: errors.New(msg)} return FlagErrorf("%s", msg)
} }
return nil return nil
} }
@ -25,11 +24,11 @@ func ExactArgs(n int, msg string) cobra.PositionalArgs {
return func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error {
if len(args) > n { if len(args) > n {
return &FlagError{Err: errors.New("too many arguments")} return FlagErrorf("too many arguments")
} }
if len(args) < n { if len(args) < n {
return &FlagError{Err: errors.New(msg)} return FlagErrorf("%s", msg)
} }
return nil return nil
@ -57,5 +56,5 @@ func NoArgsQuoteReminder(cmd *cobra.Command, args []string) error {
errMsg += "; please quote all values that have spaces" errMsg += "; please quote all values that have spaces"
} }
return &FlagError{Err: errors.New(errMsg)} return FlagErrorf("%s", errMsg)
} }

View file

@ -2,22 +2,33 @@ package cmdutil
import ( import (
"errors" "errors"
"fmt"
"github.com/AlecAivazis/survey/v2/terminal" "github.com/AlecAivazis/survey/v2/terminal"
) )
// FlagErrorf returns a new FlagError that wraps an error produced by
// fmt.Errorf(format, args...).
func FlagErrorf(format string, args ...interface{}) error {
return FlagErrorWrap(fmt.Errorf(format, args...))
}
// FlagError returns a new FlagError that wraps the specified error.
func FlagErrorWrap(err error) error { return &FlagError{err} }
// A *FlagError indicates an error processing command-line flags or other arguments. // A *FlagError indicates an error processing command-line flags or other arguments.
// Such errors cause the application to display the usage message. // Such errors cause the application to display the usage message.
type FlagError struct { type FlagError struct {
Err error // Note: not struct{error}: only *FlagError should satisfy error.
err error
} }
func (fe *FlagError) Error() string { func (fe *FlagError) Error() string {
return fe.Err.Error() return fe.err.Error()
} }
func (fe *FlagError) Unwrap() error { func (fe *FlagError) Unwrap() error {
return fe.Err return fe.err
} }
// SilentError is an error that triggers exit code 1 without any error messaging // SilentError is an error that triggers exit code 1 without any error messaging
@ -38,7 +49,7 @@ func MutuallyExclusive(message string, conditions ...bool) error {
} }
} }
if numTrue > 1 { if numTrue > 1 {
return &FlagError{Err: errors.New(message)} return FlagErrorf("%s", message)
} }
return nil return nil
} }