sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/cli/resource.go (about) 1 /* 2 Copyright 2022 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package cli 18 19 import ( 20 "fmt" 21 "strings" 22 23 "github.com/spf13/pflag" 24 25 "sigs.k8s.io/kubebuilder/v3/pkg/model/resource" 26 ) 27 28 const ( 29 groupPresent = "group flag present but empty" 30 versionPresent = "version flag present but empty" 31 kindPresent = "kind flag present but empty" 32 ) 33 34 // resourceOptions contains the information required to build a new resource.Resource. 35 type resourceOptions struct { 36 resource.GVK 37 } 38 39 func bindResourceFlags(fs *pflag.FlagSet) *resourceOptions { 40 options := &resourceOptions{} 41 42 fs.StringVar(&options.Group, "group", "", "resource Group") 43 fs.StringVar(&options.Version, "version", "", "resource Version") 44 fs.StringVar(&options.Kind, "kind", "", "resource Kind") 45 46 return options 47 } 48 49 // validate verifies that all the fields have valid values. 50 func (opts resourceOptions) validate() error { 51 // Check that the required flags did not get a flag as their value. 52 // We can safely look for a '-' as the first char as none of the fields accepts it. 53 // NOTE: We must do this for all the required flags first or we may output the wrong 54 // error as flags may seem to be missing because Cobra assigned them to another flag. 55 if strings.HasPrefix(opts.Group, "-") { 56 return fmt.Errorf(groupPresent) 57 } 58 if strings.HasPrefix(opts.Version, "-") { 59 return fmt.Errorf(versionPresent) 60 } 61 if strings.HasPrefix(opts.Kind, "-") { 62 return fmt.Errorf(kindPresent) 63 } 64 65 // We do not check here if the GVK values are empty because that would 66 // make them mandatory and some plugins may want to set default values. 67 // Instead, this is checked by resource.GVK.Validate() 68 69 return nil 70 } 71 72 // newResource creates a new resource from the options 73 func (opts resourceOptions) newResource() *resource.Resource { 74 return &resource.Resource{ 75 GVK: resource.GVK{ // Remove whitespaces to prevent values like " " pass validation 76 Group: strings.TrimSpace(opts.Group), 77 Domain: strings.TrimSpace(opts.Domain), 78 Version: strings.TrimSpace(opts.Version), 79 Kind: strings.TrimSpace(opts.Kind), 80 }, 81 Plural: resource.RegularPlural(opts.Kind), 82 API: &resource.API{}, 83 Webhooks: &resource.Webhooks{}, 84 } 85 }