Merge pull request #6030 from thaJeztah/flag_multiple_completion

opts: ListOpts: implement cobra.SliceValue to fix shell completion
This commit is contained in:
Sebastiaan van Stijn 2025-04-23 13:51:11 +02:00 committed by GitHub
commit 81a5db6b82
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 4 deletions

View File

@ -84,6 +84,16 @@ func (opts *ListOpts) GetAll() []string {
return *opts.values
}
// GetSlice returns the values of slice.
//
// It implements [cobra.SliceValue] to allow shell completion to be provided
// multiple times.
//
// [cobra.SliceValue]: https://pkg.go.dev/github.com/spf13/cobra@v1.9.1#SliceValue
func (opts *ListOpts) GetSlice() []string {
return *opts.values
}
// GetAllOrEmpty returns the values of the slice
// or an empty slice when there are no values.
func (opts *ListOpts) GetAllOrEmpty() []string {

View File

@ -112,6 +112,7 @@ func TestMapOpts(t *testing.T) {
}
}
//nolint:gocyclo // ignore "cyclomatic complexity 17 is too high"
func TestListOptsWithoutValidator(t *testing.T) {
o := NewListOpts(nil)
err := o.Set("foo")
@ -145,12 +146,13 @@ func TestListOptsWithoutValidator(t *testing.T) {
if o.String() != "[bar bar]" {
t.Errorf("%s != [bar bar]", o.String())
}
listOpts := o.GetAll()
if len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" {
if listOpts := o.GetAll(); len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" {
t.Errorf("Expected [[bar bar]], got [%v]", listOpts)
}
mapListOpts := o.GetMap()
if len(mapListOpts) != 1 {
if listOpts := o.GetSlice(); len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" {
t.Errorf("Expected [[bar bar]], got [%v]", listOpts)
}
if mapListOpts := o.GetMap(); len(mapListOpts) != 1 {
t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts)
}
}