Skip to content

Commit

Permalink
Merge pull request #296 from redhatrises/fix_global_commands
Browse files Browse the repository at this point in the history
Have Global Options run before command and sub-command processing
  • Loading branch information
shawndwells committed Jun 13, 2018
2 parents fc5426d + 80e14a5 commit 17724c0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
1 change: 0 additions & 1 deletion cmd/masonry/masonry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (

var usage = `
Usage:
masonry [flags]
masonry [command]
Available Commands:
Expand Down
29 changes: 14 additions & 15 deletions pkg/cmd/masonry/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ var Verbose bool
// Version for cli variable holding program version
var Version bool

func init() {
log.SetOutput(ioutil.Discard)
}

// NewMasonryCommand Main Masonry command cli
// Add new commands/subcommands for new verbs in this function
func NewMasonryCommand(in io.Reader, out, err io.Writer) *cobra.Command {
Expand All @@ -31,44 +35,39 @@ func NewMasonryCommand(in io.Reader, out, err io.Writer) *cobra.Command {
Long: `Compliance Masonry is a command-line interface (CLI) that
allows users to construct certification documentation using
the OpenControl Schema`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
PersistentPreRun: func(cmd *cobra.Command, args []string) {
err := RunGlobalFlags(out, cmd)
clierrors.CheckError(err)
},
}

cmds.ResetFlags()
// Global Options
cmds.PersistentFlags().BoolVarP(&Verbose, "verbose", "", false, "Run with verbosity")
cmds.PersistentFlags().BoolVarP(&Version, "version", "v", false, "Print the version")

// Add new main commands here
cmds.AddCommand(diff.NewCmdDiff(out))
cmds.AddCommand(docs.NewCmdDocs(out))
cmds.AddCommand(export.NewCmdExport(out))
cmds.AddCommand(get.NewCmdGet(out))

// Global Options
cmds.PersistentFlags().BoolVarP(&Verbose, "verbose", "", false, "Run with verbosity")
cmds.PersistentFlags().BoolVarP(&Version, "version", "v", false, "Print the version")

return cmds
}

// RunGlobalFlags runs global options when specified in cli
func RunGlobalFlags(out io.Writer, cmd *cobra.Command) error {
flagVersion := Version
flagVerbose := Verbose

var flagVersion = cmd.Flag("version").Value.String()
var flagVerbose = cmd.Flag("verbose").Value.String()

log.SetOutput(ioutil.Discard)
if flagVerbose == "true" {
if flagVerbose {
log.SetOutput(os.Stderr)
log.Println("Running with verbosity")
}

if flagVersion == "true" {
if flagVersion {
fmt.Printf("compliance-masonry: version %s\n", version.Version)
os.Exit(0)
}

return nil
Expand Down

0 comments on commit 17724c0

Please sign in to comment.