Skip to content

Commit

Permalink
A different approach to parsing the flags.
Browse files Browse the repository at this point in the history
  • Loading branch information
renan-campos committed Jul 1, 2022
1 parent ca547e1 commit 2f9ac70
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 28 deletions.
27 changes: 6 additions & 21 deletions cmd/edit/service/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,20 +56,12 @@ func run(cmd *cobra.Command, argv []string) {
r := rosa.NewRuntime().WithOCM()
defer r.Cleanup()

// Adding known flags to flag checker before parsing the unknown flags
flagChecker := arguments.NewFlagCheck(cmd.Flags())

err := arguments.ParseUnknownFlags(cmd, argv)
err := arguments.ParseKnownFlags(cmd, argv, false)
if err != nil {
r.Reporter.Errorf("Failed to parse flags: %v", err)
os.Exit(1)
}

if len(cmd.Flags().Args()) > 0 {
r.Reporter.Errorf("Unrecognized command line parameter")
os.Exit(1)
}

if args.ID == "" {
r.Reporter.Errorf("Service id not specified.")
cmd.Help()
Expand All @@ -91,26 +83,19 @@ func run(cmd *cobra.Command, argv []string) {
}

addonParameters := addOn.Parameters()
addonParameters.Each(func(param *cmv1.AddOnParameter) bool {
flagChecker.AddValidFlag(param.ID())
return true
})
arguments.AddParameterFlags(cmd, addonParameters)

// Now that rosa knows the expected fields to validate,
// Validate that all of the user-specified flags are valid.
err = flagChecker.ValidateFlags(cmd.Flags())
err = arguments.ParseKnownFlags(cmd, argv, true)
if err != nil {
r.Reporter.Errorf(err.Error())
r.Reporter.Errorf("Failed to parse flags: %v", err)
os.Exit(1)
}

args.Parameters = map[string]string{}
addonParameters.Each(func(param *cmv1.AddOnParameter) bool {
flag := cmd.Flags().Lookup(param.ID())
if flag != nil {
if !param.Editable() {
r.Reporter.Errorf("Cannot edit the parameter %q", param.ID())
}
// Checking if the flag changed to ensure that the user set the value.
if flag != nil && flag.Changed {
args.Parameters[param.ID()] = flag.Value.String()
}
return true
Expand Down
94 changes: 94 additions & 0 deletions pkg/arguments/arguments.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ limitations under the License.
package arguments

import (
"fmt"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/pflag"

cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
"github.com/openshift/rosa/pkg/aws/profile"
"github.com/openshift/rosa/pkg/aws/region"
"github.com/openshift/rosa/pkg/debug"
Expand Down Expand Up @@ -101,6 +103,98 @@ func ParseUnknownFlags(cmd *cobra.Command, argv []string) error {
return nil
}

// Parse known flags will take the command line arguments and map the ones that fit with known flags.
func ParseKnownFlags(cmd *cobra.Command, argv []string, failOnUnknown bool) error {
flags := cmd.Flags()

var validArgs []string = []string{}
var upcomingValue bool
unknownFlags := ""

for _, arg := range argv {
switch {
// A long flag with a space separated value
case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="):
flagName := arg[2:]
// Skip EOF and known flags
if flag := flags.Lookup(flagName); flag != nil {
validArgs = append(validArgs, arg)
if flag.Value.Type() != "bool" {
upcomingValue = true
}
} else if failOnUnknown {
unknownFlags += fmt.Sprintf("%q, ", flagName)
}
// A long flag with a value after an equal sign
case strings.HasPrefix(arg, "--") && strings.Contains(arg, "="):
flagName := strings.SplitN(arg[2:], "=", 2)[0]
if flags.Lookup(flagName) != nil {
validArgs = append(validArgs, arg)
} else if failOnUnknown {
unknownFlags += fmt.Sprintf("%q, ", flagName)
}
upcomingValue = false
// A short flag with a space separated value
case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "="):
flagName := arg[1:]
if flag := flags.Lookup(flagName); flag != nil {
validArgs = append(validArgs, arg)
if flag.Value.Type() != "bool" {
upcomingValue = true
}
} else if failOnUnknown {
unknownFlags += fmt.Sprintf("%q, ", flagName)
}
// A short flag with with a value after an equal sign
case strings.HasPrefix(arg, "-") && strings.Contains(arg, "="):
flagName := strings.SplitN(arg[1:], "=", 2)[0]
if flags.Lookup(flagName) != nil {
validArgs = append(validArgs, arg)
} else if failOnUnknown {
unknownFlags += fmt.Sprintf("%q, ", flagName)
}
upcomingValue = false
case upcomingValue:
validArgs = append(validArgs, arg)
upcomingValue = false
}
}

if failOnUnknown && unknownFlags != "" {
return fmt.Errorf("Unknown flags passed: %s", unknownFlags[:len(unknownFlags)-2])
}

err := flags.Parse(validArgs)
if err != nil {
return err
}

// If help is called, regardless of other flags, return we want help.
// Also say we need help if the command isn't runnable.
helpVal, err := cmd.Flags().GetBool("help")
if err != nil {
// should be impossible to get here as we always declare a help
// flag in InitDefaultHelpFlag()
cmd.Println("\"help\" flag declared as non-bool. Please correct your code")
return err
}
if helpVal {
return pflag.ErrHelp
}

return nil
}

// Adds the flags that are addon parameters to the command flagset.
func AddParameterFlags(cmd *cobra.Command, params *cmv1.AddOnParameterList) {
flags := cmd.Flags()
params.Each(func(param *cmv1.AddOnParameter) bool {
var pStrVal *string = new(string)
flags.StringVar(pStrVal, param.ID(), "", param.Description())
return true
})
}

// HasUnknownFlags returns whether the flag parser detected any unknown flags
func HasUnknownFlags() bool {
return hasUnknownFlags
Expand Down
12 changes: 5 additions & 7 deletions pkg/rosa/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rosa
import (
"os"

"github.com/openshift/rosa/pkg/arguments"
"github.com/openshift/rosa/pkg/aws"
"github.com/openshift/rosa/pkg/logging"
"github.com/openshift/rosa/pkg/ocm"
Expand All @@ -12,12 +11,11 @@ import (
)

type Runtime struct {
Reporter *reporter.Object
Logger *logrus.Logger
OCMClient *ocm.Client
AWSClient aws.Client
Creator *aws.Creator
FlagChecker *arguments.FlagCheck
Reporter *reporter.Object
Logger *logrus.Logger
OCMClient *ocm.Client
AWSClient aws.Client
Creator *aws.Creator
}

func NewRuntime() *Runtime {
Expand Down

0 comments on commit 2f9ac70

Please sign in to comment.