Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve error message when detecting conflicting flags #1345

Merged
merged 3 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions cmd/oras/internal/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/errcode"
)
Expand Down Expand Up @@ -156,3 +157,27 @@ func NewErrEmptyTagOrDigest(ref string, cmd *cobra.Command, needsTag bool) error
Recommendation: fmt.Sprintf(`Please specify a reference in the form of %s. Run "%s -h" for more options and examples`, form, cmd.CommandPath()),
}
}

// CheckMutuallyExclusiveFlags checks if any mutually exclusive flags are used
// at the same time, returns an error when detecting used exclusive flags. It
// detects the first set of conflict and returns the error without checking
// the rest of the flag sets.
func CheckMutuallyExclusiveFlags(fs *pflag.FlagSet, exclusiveFlagSets ...[]string) error {
var checkConflict = func(exclusiveFlagSet []string) []string {
changedFlags := []string{}
for _, flagName := range exclusiveFlagSet {
if fs.Changed(flagName) {
changedFlags = append(changedFlags, fmt.Sprintf("--%s", flagName))
}
}
return changedFlags
}
for _, set := range exclusiveFlagSets {
changedFlags := checkConflict(set)
if len(changedFlags) >= 2 {
flags := strings.Join(changedFlags, ", ")
return fmt.Errorf("%s cannot be used at the same time", flags)
}
}
return nil
}
5 changes: 3 additions & 2 deletions cmd/oras/internal/option/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,9 @@ func (opts *Remote) Parse(cmd *cobra.Command) error {
if cmd.Flags().Lookup(passwordFromStdinFlag) != nil {
passwordAndIdTokenFlags = append(passwordAndIdTokenFlags, passwordFromStdinFlag)
}
cmd.MarkFlagsMutuallyExclusive(usernameAndIdTokenFlags...)
cmd.MarkFlagsMutuallyExclusive(passwordAndIdTokenFlags...)
if err := oerrors.CheckMutuallyExclusiveFlags(cmd.Flags(), usernameAndIdTokenFlags, passwordAndIdTokenFlags); err != nil {
return err
}
if err := opts.parseCustomHeaders(); err != nil {
return err
}
Expand Down
Loading