https://github.com/mmatczuk/anyflag
Generic implementation of Cobra Value and SliceValue types
https://github.com/mmatczuk/anyflag
cli cobra flags go golang slice struct value
Last synced: 6 months ago
JSON representation
Generic implementation of Cobra Value and SliceValue types
- Host: GitHub
- URL: https://github.com/mmatczuk/anyflag
- Owner: mmatczuk
- License: apache-2.0
- Created: 2022-09-22T09:38:48.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-07-09T09:03:39.000Z (almost 2 years ago)
- Last Synced: 2025-04-16T02:13:32.584Z (about 1 year ago)
- Topics: cli, cobra, flags, go, golang, slice, struct, value
- Language: Go
- Homepage:
- Size: 35.2 KB
- Stars: 16
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Anyflag
[](https://github.com/mmatczuk/anyflag/actions/workflows/go.yml)
[](https://goreportcard.com/report/github.com/mmatczuk/anyflag)
Anyflag is an implementation of [Cobra](https://github.com/spf13/cobra) `pflag.Value` and `pflag.SliceValue` interfaces using Go Generics.
To bind your custom type to a flag, all you have to do is specify the value type and parser function, and you are done, no boilerplate.
It supports any type including, but not limited to: enums, maps, slices, structs, struct pointers.
It also supports defining custom String() functions to redact passwords, see [redact example](examples/redact/cmd.go).
## Installation
```bash
go get github.com/mmatczuk/anyflag
```
## Examples
This example shows how `anytype` can be used for JSON encoded maps.
```go
func parseJSONMap(val string) (map[string]interface{}, error) {
var m map[string]interface{}
return m, json.Unmarshal([]byte(val), &m)
}
func newCommand() *cobra.Command {
var m map[string]interface{}
cmd := &cobra.Command{
Use: "json-map",
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintln(cmd.OutOrStdout(), m)
},
}
fs := cmd.Flags()
value := anyflag.NewValue[map[string]interface{}](nil, &m, parseJSONMap)
fs.VarP(value, "map", "", "map")
return cmd
}
func main() {
newCommand().Execute()
}
```
More examples can be found in [examples](examples) directory.
## License
This project is based on [spf13/pflag](https://github.com/spf13/pflag) licensed under the BSD 3-Clause "New" or "Revised" License