cli-runtime: Return defined error from Builder

There is a custom error message returned from resource.Builder when
SingleResourceType is set and multiple resources types are specified,
which makes it impossible to check for the condition in code easily.

This patch adds resource.ErrMultipleResourceTypes that is returned
precisely in this case so that it can be checked.

This patch also removes an extra custom error message in kubectl get,
which is actually never reached, because the builder fails before.
This commit is contained in:
Ondra Kupka 2025-08-04 22:48:57 +02:00
parent 4f1ac4f7ac
commit 82896feebb
3 changed files with 8 additions and 7 deletions

View file

@ -129,6 +129,10 @@ Example resource specifications include:
var StdinMultiUseError = errors.New("standard input cannot be used for multiple arguments")
// ErrMultipleResourceTypes is returned when Builder.SingleResourceType() was called,
// but multiple resource types were specified.
var ErrMultipleResourceTypes = errors.New("you may only specify a single resource type")
// TODO: expand this to include other errors.
func IsUsageError(err error) bool {
if err == nil {
@ -813,7 +817,7 @@ func (b *Builder) mappingFor(resourceOrKindArg string) (*meta.RESTMapping, error
func (b *Builder) resourceMappings() ([]*meta.RESTMapping, error) {
if len(b.resources) > 1 && b.singleResourceType {
return nil, fmt.Errorf("you may only specify a single resource type")
return nil, ErrMultipleResourceTypes
}
mappings := []*meta.RESTMapping{}
seen := map[schema.GroupVersionKind]bool{}
@ -849,7 +853,7 @@ func (b *Builder) resourceTupleMappings() (map[string]*meta.RESTMapping, error)
canonical[mapping.Resource] = struct{}{}
}
if len(canonical) > 1 && b.singleResourceType {
return nil, fmt.Errorf("you may only specify a single resource type")
return nil, ErrMultipleResourceTypes
}
return mappings, nil
}

View file

@ -1367,8 +1367,8 @@ func TestSingleResourceType(t *testing.T) {
SingleResourceType().
ResourceTypeOrNameArgs(true, "pods,services")
if b.Do().Err() == nil {
t.Errorf("unexpected non-error")
if err := b.Do().Err(); !errors.Is(err, ErrMultipleResourceTypes) {
t.Errorf("unexpected error: %s", err)
}
}

View file

@ -629,9 +629,6 @@ func (o *GetOptions) watch(f cmdutil.Factory, args []string) error {
}
return err
}
if multipleGVKsRequested(infos) {
return i18n.Errorf("watch is only supported on individual resources and resource collections - more than 1 resource was found")
}
info := infos[0]
mapping := info.ResourceMapping()