Add hello world example and add more options

This commit is contained in:
Evan Fiordeliso 2023-11-10 00:49:44 -05:00
parent c32ce2efcd
commit def39983fd
5 changed files with 64 additions and 2 deletions

View File

@ -2,6 +2,9 @@ package cmd
import "go.fifitido.net/cmd/flags"
type RunFunc func(args []string)
type RunErrFunc func(args []string) error
type Command struct {
Name string
ShortDescription string
@ -10,8 +13,8 @@ type Command struct {
Arguments []*Argument
Flags []flags.Flag
Subcommands []*Command
Run func(args []string)
RunE func(args []string) error
Run RunFunc
RunE RunErrFunc
isRoot bool
}

View File

@ -0,0 +1,28 @@
package main
import (
"fmt"
"os"
"go.fifitido.net/cmd"
)
var root = cmd.NewRoot(
cmd.WithShortDescription("Example command"),
cmd.WithLongDescription(`An example command to show how to use go.fifitido.net/cmd
this example is just a simple hello world program to show
the basics of the library.`),
cmd.WithArgument("name", false),
cmd.WithRunFunc(func(args []string) {
if len(args) == 0 {
fmt.Println("Hello World!")
} else {
fmt.Printf("Hello %s!\n", args[0])
}
}),
)
func main() {
root.Execute(os.Args)
}

View File

@ -0,0 +1,5 @@
module go.fifitido.net/cmd/examples/hello-world
go 1.21.3
require go.fifitido.net/cmd v0.0.0-20231110043437-c32ce2efcd5f

View File

@ -0,0 +1,2 @@
go.fifitido.net/cmd v0.0.0-20231110043437-c32ce2efcd5f h1:v+sjO+t6cGEtDhStOnuypYBrkOMO4suiDVxL93rOUCs=
go.fifitido.net/cmd v0.0.0-20231110043437-c32ce2efcd5f/go.mod h1:8SaDxCG1m6WwShUlZApSbNleCvV7oTfqZIyYu4aAqO0=

View File

@ -4,6 +4,18 @@ import "go.fifitido.net/cmd/flags"
type Option func(*Command)
func WithShortDescription(s string) Option {
return func(c *Command) {
c.ShortDescription = s
}
}
func WithLongDescription(s string) Option {
return func(c *Command) {
c.LongDescription = s
}
}
func WithArgument(name string, required bool) Option {
return func(c *Command) {
c.Arguments = append(c.Arguments, &Argument{name, required})
@ -39,3 +51,15 @@ func WithSubcommands(ss []*Command) Option {
c.Subcommands = append(c.Subcommands, ss...)
}
}
func WithRunFunc(r RunFunc) Option {
return func(c *Command) {
c.Run = r
}
}
func WithRunErrFunc(r RunErrFunc) Option {
return func(c *Command) {
c.RunE = r
}
}