Improving slice and map support
- Dominant language
- Go
- Stars
- 3.2k
- Forks
- 188
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 2
Description
After rethinking of #355, I came to a conclusion that it'd be useful to have the following approach to work with slices and maps in Kong:
A slice or map of struct (e.g. `[]SomeStruct` or `map[string]SomeStruct`) isn't ignored by Kong as well as it isn't ignored if the struct has a slice or map field:
```go
type SomeStruct struct {
List []NestedStruct
Dict map[string]NestedStruct
}
type NestedStruct struct {
Count int
Text string
}
```
I.e. if we have:
```go
var CLI struct {
Command struct {
Data1 []SomeStruct
Data2 map[string]SomeStruct
} `cmd:""`
}
```
Then we have the following flags (total 8):
```
Command.Data1.#.List.#.Count
Command.Data1.#.List.#.Text
Command.Data1.#.Dict.?.Count
Command.Data1.#.Dict.?.Text
Command.Data2.?.List.#.Count
Command.Data2.?.List.#.Text
Command.Data2.?.Dict.?.Count
Command.Data2.?.Dict.?.Text
```
Those flags should be displayed in the help.
Prefixes (`prefix` and `envPrefix`) should work the same way as for regular flags with one exception:
Symbols `#` and `?` will be used for a slice index and map key respectively:
```go
var CLI struct {
Command struct {
Data1 []SomeStruct `envprefix:"DATA1_#_"`
Data2 map[string]SomeStruct `cmd:"" envprefix:"DATA2_?_"`
} `cmd:"" envprefix:"COMMAND_"`
}
type SomeStruct struct {
List []NestedStruct `envprefix:"LIST_#_"`
Dict map[string]NestedStruct `envprefix:"DICT_?_"`
}
type NestedStruct struct {
Count int `env:"COUNT"`
Text string `env:"TEXT"`
}
```
An example of `.env`:
```sh
COMMAND_DATA1_0_LIST_0_COUNT=5
COMMAND_DATA1_0_LIST_0_TEXT="AAAAA"
COMMAND_DATA1_0_LIST_1_COUNT=3
COMMAND_DATA1_0_LIST_1_TEXT="AAA"
COMMAND_DATA1_0_DICT_MAPKEY_COUNT=1
COMMAND_DATA1_0_DICT_MAPKEY_TEXT="A"
COMMAND_DATA1_0_DICT_ANOTHERKEY_COUNT=4
COMMAND_DATA1_0_DICT_ANOTHERKEY_TEXT="AAAA"
COMMAND_DATA1_1_LIST_0_COUNT=7
COMMAND_DATA1_1_LIST_0_TEXT="AAAAAAA"
COMMAND_DATA1_1_DICT_MAPKEY_COUNT=1
COMMAND_DATA1_1_DICT_MAPKEY_TEXT="A"
```
The vars with the same slice indexes (map keys) will refer to the same slice (map) element. I.e. `COMMAND_DATA1_0_LIST_0_COUNT=5` and `COMMAND_DATA1_0_LIST_0_TEXT="AAAAA"` will fill up the same `NestedStruct`.
If a slice was prefilled with a resolver, the data from `.env` is appended to the slice so that the prefilled data can't be overridden (the indexes are just unique identifiers). On the contrary, map elements can be overridden.
Fields of every element of a slice or map should be validated with the specified Kong rules (`enum`, `required` etc.).
WDYT?
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.