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

functional flag builder pattern #24

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

acheong08
Copy link

I've noticed that some flags aren't exposed by the cli/root command and that every time a new flag type is added, you have to wrap it.

clir/command.go

Lines 820 to 831 in 9a039b7

func (c *Command) Float64Flag(name, description string, variable *float64) *Command {
c.flags.Float64Var(variable, name, *variable, description)
c.flagCount++
return c
}
// Float32Flag - Adds a float32 flag to the command
func (c *Command) Float32Flag(name, description string, variable *float32) *Command {
c.flags.Var(newFloat32Value(*variable, variable), name, description)
c.flagCount++
return c
}

clir/cli.go

Lines 115 to 125 in 9a039b7

// BoolFlag - Adds a boolean flag to the root command.
func (c *Cli) BoolFlag(name, description string, variable *bool) *Cli {
c.rootCommand.BoolFlag(name, description, variable)
return c
}
// StringFlag - Adds a string flag to the root command.
func (c *Cli) StringFlag(name, description string, variable *string) *Cli {
c.rootCommand.StringFlag(name, description, variable)
return c
}

Using the functional paradigm, we can simplify to this:

cli.WithFlags(
  clir.BoolFlag("name", "desc", &boolVar),
  clir.Float64Flag("lorum", "ipsum", &floatVar),
  ...
)

All the flag code is thus shared and you just have this in cli/command

diff --git a/cli.go b/cli.go
index 47a0849..ffc475c 100644
--- a/cli.go
+++ b/cli.go
@@ -112,6 +112,13 @@ func (c *Cli) PostRun(callback func(*Cli) error) {
    c.postRunCommand = callback
 }
 
+func (c *Cli) WithFlags(flags ...flagFunc) *Cli {
+   for _, f := range flags {
+       f(c.rootCommand)
+   }
+   return c
+}
+

diff --git a/command.go b/command.go
index 5ac8754..4a1282e 100644
--- a/command.go
+++ b/command.go
 
+func (c *Command) WithFlags(flags ...flagFunc) *Command {
+   for _, f := range flags {
+       f(c)
+   }
+   return c
+}
+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant