Last active
January 17, 2023 15:19
-
-
Save zivkovicmilos/6ad3193f0a48ee802f25f1d02baef7ed to your computer and use it in GitHub Desktop.
Minor example of ff/cli and ff/toml usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
arr = ["gno", "land", "👍"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"os" | |
"github.com/peterbourgon/ff/v3" | |
"github.com/peterbourgon/ff/v3/ffcli" | |
"github.com/peterbourgon/ff/v3/fftoml" | |
) | |
// stringArr defines the custom flag type | |
// that represents an array of string values. | |
// Example taken from: | |
// https://github.com/peterbourgon/ff/blob/fe611a8e5a9483e716da5c57644b8d48540d3913/fftest/vars.go#L118-L135 | |
type stringArr []string | |
// String is a required output method for the flag | |
func (s *stringArr) String() string { | |
return "whatever" | |
} | |
// Set is a required output method for the flag. | |
// This is where our custom type manipulation actually happens | |
func (s *stringArr) Set(value string) error { | |
*s = append(*s, value) | |
return nil | |
} | |
func main() { | |
const ( | |
configFlagName = "config" | |
) | |
var ( | |
// Example storage for our array type | |
myStrArr stringArr | |
// Define a basic flag set for the command "example" | |
fs = flag.NewFlagSet("example", flag.ContinueOnError) | |
// Define the flag for the config path | |
_ = fs.String(configFlagName, "", "the TOML config file") | |
) | |
// Register the flag type. | |
// This array can be populated using: | |
// ... --arr "value1" --arr "value2" ... | |
fs.Var(&myStrArr, "arr", "array string input") | |
example := &ffcli.Command{ | |
Name: "example", | |
ShortUsage: "example [<arg> ...]", | |
ShortHelp: "Example command that showcases arrays and TOMLs", | |
FlagSet: fs, | |
Exec: func(_ context.Context, _ []string) error { | |
// Print out the array arguments that were parsed. | |
// For either .toml usage or explicit flag usage, | |
// the FS vars should be filled | |
fmt.Printf("Received an %d element string array: %v\n", len(myStrArr), myStrArr) | |
return nil | |
}, | |
Options: []ff.Option{ | |
ff.WithConfigFileFlag(configFlagName), | |
ff.WithConfigFileParser(fftoml.Parser), | |
}, | |
} | |
if err := example.ParseAndRun( | |
context.Background(), | |
os.Args[1:], | |
); err != nil { | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment