Skip to content

Instantly share code, notes, and snippets.

@jawher
Created May 30, 2019 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jawher/8b3720e5a166e5219397ce2b8c8f7ddb to your computer and use it in GitHub Desktop.
Save jawher/8b3720e5a166e5219397ce2b8c8f7ddb to your computer and use it in GitHub Desktop.
mow.cli enum custom type
package enum
import (
"fmt"
"strings"
"github.com/pkg/errors"
)
type Value struct {
Value string
Desc string
}
func New(values ...Value) *Enum {
return &Enum{
Values: values,
}
}
type Enum struct {
Values []Value
Value string
}
func (e *Enum) Set(v string) error {
for _, s := range e.Values {
if v == s.Value {
e.Value = v
return nil
}
}
possible := make([]string, len(e.Values))
for i, v := range e.Values {
possible[i] = fmt.Sprintf("%q", v.Value)
}
return errors.Errorf("invalid value %q. Must be one of: %s", v, strings.Join(possible, ", "))
}
func (e *Enum) Desc(desc string) string {
var res strings.Builder
res.WriteString(desc)
res.WriteString("\n")
for i, v := range e.Values {
if i > 0 {
res.WriteString("\n")
}
res.WriteString(" - ")
res.WriteString(v.Value)
res.WriteString(": ")
res.WriteString(v.Desc)
}
return res.String()
}
func (e *Enum) String() string {
return e.Value
}
package main
import (
"fmt"
"os"
cli "github.com/jawher/mow.cli"
)
func main() {
app := cli.App("enum", "enum usage example")
mode := enum.New(
enum.Value{
Value: "read", Desc: "read mode",
},
enum.Value{
Value: "write", Desc: "write mode",
})
app.VarOpt("m", mode, mode.Desc("file open mode"))
force := app.BoolOpt("f force", false, "force open")
app.Action = func() {
fmt.Printf("mode: %v\n", mode.Value)
fmt.Printf("force: %v\n", *force)
}
app.Run(os.Args)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment