From 608a0553d72795e08b43dffdba7968f1e93b8484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arda=20G=C3=BC=C3=A7l=C3=BC?= Date: Thu, 21 Nov 2024 13:22:39 +0300 Subject: [PATCH] Use generic sets rather than deprecated sets.String Kubernetes-commit: c3f15fd707a092e6cb7d96b84b81ada1f118d759 --- pkg/cmd/apiresources/apiresources.go | 8 +++--- pkg/cmd/auth/cani.go | 6 ++-- pkg/cmd/auth/whoami.go | 2 +- pkg/cmd/config/get_contexts.go | 2 +- pkg/cmd/config/navigation_step_parser.go | 6 ++-- pkg/cmd/create/create_role.go | 2 +- pkg/cmd/create/create_token.go | 4 +-- pkg/cmd/describe/describe.go | 2 +- pkg/cmd/drain/drain.go | 2 +- pkg/cmd/edit/edit_test.go | 4 +-- pkg/cmd/events/events.go | 2 +- pkg/cmd/get/get.go | 2 +- pkg/cmd/patch/patch.go | 4 +-- pkg/cmd/portforward/portforward.go | 10 +++---- pkg/cmd/set/env/env_parse.go | 2 +- pkg/cmd/set/env/env_resolve.go | 4 +-- pkg/cmd/set/helper.go | 4 +-- pkg/cmd/set/set_subject.go | 6 ++-- pkg/cmd/taint/utils.go | 4 +-- pkg/cmd/util/helpers.go | 2 +- pkg/describe/describe.go | 36 ++++++++++++------------ pkg/util/fieldpath/fieldpath.go | 4 +-- pkg/util/qos/qos.go | 2 +- pkg/util/rbac/rbac.go | 7 +++-- pkg/util/resource/resource.go | 2 +- 25 files changed, 65 insertions(+), 64 deletions(-) diff --git a/pkg/cmd/apiresources/apiresources.go b/pkg/cmd/apiresources/apiresources.go index c8a344bf..6c2dadc9 100644 --- a/pkg/cmd/apiresources/apiresources.go +++ b/pkg/cmd/apiresources/apiresources.go @@ -123,11 +123,11 @@ func NewCmdAPIResources(restClientGetter genericclioptions.RESTClientGetter, ioS // Validate checks to the APIResourceOptions to see if there is sufficient information run the command func (o *APIResourceOptions) Validate() error { - supportedOutputTypes := sets.NewString("", "wide", "name") + supportedOutputTypes := sets.New[string]("", "wide", "name") if !supportedOutputTypes.Has(o.Output) { return fmt.Errorf("--output %v is not available", o.Output) } - supportedSortTypes := sets.NewString("", "name", "kind") + supportedSortTypes := sets.New[string]("", "name", "kind") if len(o.SortBy) > 0 { if !supportedSortTypes.Has(o.SortBy) { return fmt.Errorf("--sort-by accepts only name or kind") @@ -193,11 +193,11 @@ func (o *APIResourceOptions) RunAPIResources() error { continue } // filter to resources that support the specified verbs - if len(o.Verbs) > 0 && !sets.NewString(resource.Verbs...).HasAll(o.Verbs...) { + if len(o.Verbs) > 0 && !sets.New[string](resource.Verbs...).HasAll(o.Verbs...) { continue } // filter to resources that belong to the specified categories - if len(o.Categories) > 0 && !sets.NewString(resource.Categories...).HasAll(o.Categories...) { + if len(o.Categories) > 0 && !sets.New[string](resource.Categories...).HasAll(o.Categories...) { continue } resources = append(resources, groupResource{ diff --git a/pkg/cmd/auth/cani.go b/pkg/cmd/auth/cani.go index 9f055a16..3b5261c2 100644 --- a/pkg/cmd/auth/cani.go +++ b/pkg/cmd/auth/cani.go @@ -105,10 +105,10 @@ var ( # List all allowed actions in namespace "foo" kubectl auth can-i --list --namespace=foo`) - resourceVerbs = sets.NewString("get", "list", "watch", "create", "update", "patch", "delete", "deletecollection", "use", "bind", "impersonate", "*", "approve", "sign", "escalate", "attest") - nonResourceURLVerbs = sets.NewString("get", "put", "post", "head", "options", "delete", "patch", "*") + resourceVerbs = sets.New[string]("get", "list", "watch", "create", "update", "patch", "delete", "deletecollection", "use", "bind", "impersonate", "*", "approve", "sign", "escalate", "attest") + nonResourceURLVerbs = sets.New[string]("get", "put", "post", "head", "options", "delete", "patch", "*") // holds all the server-supported resources that cannot be discovered by clients. i.e. users and groups for the impersonate verb - nonStandardResourceNames = sets.NewString("users", "groups") + nonStandardResourceNames = sets.New[string]("users", "groups") ) // NewCmdCanI returns an initialized Command for 'auth can-i' sub command diff --git a/pkg/cmd/auth/whoami.go b/pkg/cmd/auth/whoami.go index 2ecc036f..8d1bb44e 100644 --- a/pkg/cmd/auth/whoami.go +++ b/pkg/cmd/auth/whoami.go @@ -250,7 +250,7 @@ func printTableSelfSubjectAccessReview(obj runtime.Object, out io.Writer) error } if len(ui.Extra) > 0 { - for _, k := range sets.StringKeySet(ui.Extra).List() { + for _, k := range sets.List(sets.KeySet(ui.Extra)) { v := ui.Extra[k] _, err := fmt.Fprintf(w, "Extra: %s\t%v\n", k, v) if err != nil { diff --git a/pkg/cmd/config/get_contexts.go b/pkg/cmd/config/get_contexts.go index 0ca41e20..6e27a457 100644 --- a/pkg/cmd/config/get_contexts.go +++ b/pkg/cmd/config/get_contexts.go @@ -89,7 +89,7 @@ func NewCmdConfigGetContexts(streams genericiooptions.IOStreams, configAccess cl // Complete assigns GetContextsOptions from the args. func (o *GetContextsOptions) Complete(cmd *cobra.Command, args []string) error { - supportedOutputTypes := sets.NewString("", "name") + supportedOutputTypes := sets.New[string]("", "name") if !supportedOutputTypes.Has(o.outputFormat) { return fmt.Errorf("--output %v is not available in kubectl config get-contexts; resetting to default output format", o.outputFormat) } diff --git a/pkg/cmd/config/navigation_step_parser.go b/pkg/cmd/config/navigation_step_parser.go index cc3ca5bf..a0d1dcf1 100644 --- a/pkg/cmd/config/navigation_step_parser.go +++ b/pkg/cmd/config/navigation_step_parser.go @@ -55,7 +55,7 @@ func newNavigationSteps(path string) (*navigationSteps, error) { if err != nil { return nil, err } - nextPart := findNameStep(individualParts[currPartIndex:], sets.StringKeySet(mapValueOptions)) + nextPart := findNameStep(individualParts[currPartIndex:], sets.KeySet(mapValueOptions)) steps = append(steps, navigationStep{nextPart, mapValueType}) currPartIndex += len(strings.Split(nextPart, ".")) @@ -98,7 +98,7 @@ func (s *navigationSteps) moreStepsRemaining() bool { // findNameStep takes the list of parts and a set of valid tags that can be used after the name. It then walks the list of parts // until it find a valid "next" tag or until it reaches the end of the parts and then builds the name back up out of the individual parts -func findNameStep(parts []string, typeOptions sets.String) string { +func findNameStep(parts []string, typeOptions sets.Set[string]) string { if len(parts) == 0 { return "" } @@ -136,7 +136,7 @@ func getPotentialTypeValues(typeValue reflect.Type) (map[string]reflect.Type, er return ret, nil } -func findKnownValue(parts []string, valueOptions sets.String) int { +func findKnownValue(parts []string, valueOptions sets.Set[string]) int { for i := range parts { if valueOptions.Has(parts[i]) { return i diff --git a/pkg/cmd/create/create_role.go b/pkg/cmd/create/create_role.go index dd78549d..8ff8e167 100644 --- a/pkg/cmd/create/create_role.go +++ b/pkg/cmd/create/create_role.go @@ -425,7 +425,7 @@ func generateResourcePolicyRules(mapper meta.RESTMapper, verbs []string, resourc // Create separate rule for each of the api group. rules := []rbacv1.PolicyRule{} - for _, g := range sets.StringKeySet(groupResourceMapping).List() { + for _, g := range sets.List(sets.KeySet(groupResourceMapping)) { rule := rbacv1.PolicyRule{} rule.Verbs = verbs rule.Resources = groupResourceMapping[g] diff --git a/pkg/cmd/create/create_token.go b/pkg/cmd/create/create_token.go index 7f751a47..ce8c749e 100644 --- a/pkg/cmd/create/create_token.go +++ b/pkg/cmd/create/create_token.go @@ -149,7 +149,7 @@ func NewCmdCreateToken(f cmdutil.Factory, ioStreams genericiooptions.IOStreams) cmd.Flags().DurationVar(&o.Duration, "duration", o.Duration, "Requested lifetime of the issued token. If not set or if set to 0, the lifetime will be determined by the server automatically. The server may return a token with a longer or shorter lifetime.") cmd.Flags().StringVar(&o.BoundObjectKind, "bound-object-kind", o.BoundObjectKind, "Kind of an object to bind the token to. "+ - "Supported kinds are "+strings.Join(sets.StringKeySet(boundObjectKindToAPIVersions()).List(), ", ")+". "+ + "Supported kinds are "+strings.Join(sets.List(sets.KeySet(boundObjectKindToAPIVersions())), ", ")+". "+ "If set, --bound-object-name must be provided.") cmd.Flags().StringVar(&o.BoundObjectName, "bound-object-name", o.BoundObjectName, "Name of an object to bind the token to. "+ "The token will expire when the object is deleted. "+ @@ -227,7 +227,7 @@ func (o *TokenOptions) Validate() error { } } else { if _, ok := boundObjectKindToAPIVersions()[o.BoundObjectKind]; !ok { - return fmt.Errorf("supported --bound-object-kind values are %s", strings.Join(sets.StringKeySet(boundObjectKindToAPIVersions()).List(), ", ")) + return fmt.Errorf("supported --bound-object-kind values are %s", strings.Join(sets.List(sets.KeySet(boundObjectKindToAPIVersions())), ", ")) } if len(o.BoundObjectName) == 0 { return fmt.Errorf("--bound-object-name is required if --bound-object-kind is provided") diff --git a/pkg/cmd/describe/describe.go b/pkg/cmd/describe/describe.go index be5c1ce5..c7d4d771 100644 --- a/pkg/cmd/describe/describe.go +++ b/pkg/cmd/describe/describe.go @@ -193,7 +193,7 @@ func (o *DescribeOptions) Run() error { allErrs = append(allErrs, err) } - errs := sets.NewString() + errs := sets.New[string]() first := true for _, info := range infos { mapping := info.ResourceMapping() diff --git a/pkg/cmd/drain/drain.go b/pkg/cmd/drain/drain.go index a4b71a42..a4aa93fd 100644 --- a/pkg/cmd/drain/drain.go +++ b/pkg/cmd/drain/drain.go @@ -326,7 +326,7 @@ func (o *DrainCmdOptions) RunDrain() error { return err } - drainedNodes := sets.NewString() + drainedNodes := sets.New[string]() var fatal []error remainingNodes := []string{} diff --git a/pkg/cmd/edit/edit_test.go b/pkg/cmd/edit/edit_test.go index a5552b9d..7bb8113a 100644 --- a/pkg/cmd/edit/edit_test.go +++ b/pkg/cmd/edit/edit_test.go @@ -172,7 +172,7 @@ func TestEdit(t *testing.T) { t.Setenv("KUBE_EDITOR", "testdata/test_editor.sh") t.Setenv("KUBE_EDITOR_CALLBACK", server.URL+"/callback") - testcases := sets.NewString() + testcases := sets.New[string]() filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error { if err != nil { return err @@ -194,7 +194,7 @@ func TestEdit(t *testing.T) { t.Fatalf("Error locating edit testcases") } - for _, testcaseName := range testcases.List() { + for _, testcaseName := range testcases.UnsortedList() { t.Run(testcaseName, func(t *testing.T) { i = 0 name = testcaseName diff --git a/pkg/cmd/events/events.go b/pkg/cmd/events/events.go index cb4e0e60..b217f9e3 100644 --- a/pkg/cmd/events/events.go +++ b/pkg/cmd/events/events.go @@ -188,7 +188,7 @@ func (flags *EventsFlags) ToOptions() (*EventsOptions, error) { } if len(o.FilterTypes) > 0 { - o.FilterTypes = sets.NewString(o.FilterTypes...).List() + o.FilterTypes = sets.List(sets.New[string](o.FilterTypes...)) } var printer printers.ResourcePrinter diff --git a/pkg/cmd/get/get.go b/pkg/cmd/get/get.go index f4652392..d84ed3d3 100644 --- a/pkg/cmd/get/get.go +++ b/pkg/cmd/get/get.go @@ -486,7 +486,7 @@ func (o *GetOptions) Run(f cmdutil.Factory, args []string) error { } allErrs := []error{} - errs := sets.NewString() + errs := sets.New[string]() infos, err := r.Infos() if err != nil { allErrs = append(allErrs, err) diff --git a/pkg/cmd/patch/patch.go b/pkg/cmd/patch/patch.go index 81340596..d67b978e 100644 --- a/pkg/cmd/patch/patch.go +++ b/pkg/cmd/patch/patch.go @@ -137,7 +137,7 @@ func NewCmdPatch(f cmdutil.Factory, ioStreams genericiooptions.IOStreams) *cobra cmd.Flags().StringVarP(&o.Patch, "patch", "p", "", "The patch to be applied to the resource JSON file.") cmd.Flags().StringVar(&o.PatchFile, "patch-file", "", "A file containing a patch to be applied to the resource.") - cmd.Flags().StringVar(&o.PatchType, "type", "strategic", fmt.Sprintf("The type of patch being provided; one of %v", sets.StringKeySet(patchTypes).List())) + cmd.Flags().StringVar(&o.PatchType, "type", "strategic", fmt.Sprintf("The type of patch being provided; one of %v", sets.List(sets.KeySet(patchTypes)))) cmdutil.AddDryRunFlag(cmd) cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, "identifying the resource to update") cmd.Flags().BoolVar(&o.Local, "local", o.Local, "If true, patch will operate on the content of the file, not the server-side resource.") @@ -194,7 +194,7 @@ func (o *PatchOptions) Validate() error { } if len(o.PatchType) != 0 { if _, ok := patchTypes[strings.ToLower(o.PatchType)]; !ok { - return fmt.Errorf("--type must be one of %v, not %q", sets.StringKeySet(patchTypes).List(), o.PatchType) + return fmt.Errorf("--type must be one of %v, not %q", sets.List(sets.KeySet(patchTypes)), o.PatchType) } } return nil diff --git a/pkg/cmd/portforward/portforward.go b/pkg/cmd/portforward/portforward.go index 30519e81..c38ac458 100644 --- a/pkg/cmd/portforward/portforward.go +++ b/pkg/cmd/portforward/portforward.go @@ -247,7 +247,7 @@ func convertPodNamedPortToNumber(ports []string, pod corev1.Pod) ([]string, erro return converted, nil } -func checkUDPPorts(udpOnlyPorts sets.Int, ports []string, obj metav1.Object) error { +func checkUDPPorts(udpOnlyPorts sets.Set[int], ports []string, obj metav1.Object) error { for _, port := range ports { _, remotePort := splitPort(port) portNum, err := strconv.Atoi(remotePort) @@ -281,8 +281,8 @@ func checkUDPPorts(udpOnlyPorts sets.Int, ports []string, obj metav1.Object) err // checkUDPPortInService returns an error if remote port in Service is a UDP port // TODO: remove this check after #47862 is solved func checkUDPPortInService(ports []string, svc *corev1.Service) error { - udpPorts := sets.NewInt() - tcpPorts := sets.NewInt() + udpPorts := sets.New[int]() + tcpPorts := sets.New[int]() for _, port := range svc.Spec.Ports { portNum := int(port.Port) switch port.Protocol { @@ -298,8 +298,8 @@ func checkUDPPortInService(ports []string, svc *corev1.Service) error { // checkUDPPortInPod returns an error if remote port in Pod is a UDP port // TODO: remove this check after #47862 is solved func checkUDPPortInPod(ports []string, pod *corev1.Pod) error { - udpPorts := sets.NewInt() - tcpPorts := sets.NewInt() + udpPorts := sets.New[int]() + tcpPorts := sets.New[int]() for _, ct := range pod.Spec.Containers { for _, ctPort := range ct.Ports { portNum := int(ctPort.ContainerPort) diff --git a/pkg/cmd/set/env/env_parse.go b/pkg/cmd/set/env/env_parse.go index 5f46237d..a316d97b 100644 --- a/pkg/cmd/set/env/env_parse.go +++ b/pkg/cmd/set/env/env_parse.go @@ -61,7 +61,7 @@ func SplitEnvironmentFromResources(args []string) (resources, envArgs []string, // envVarType is for making errors more specific to user intentions. func parseIntoEnvVar(spec []string, defaultReader io.Reader, envVarType string) ([]v1.EnvVar, []string, bool, error) { env := []v1.EnvVar{} - exists := sets.NewString() + exists := sets.New[string]() var remove []string usedStdin := false for _, envSpec := range spec { diff --git a/pkg/cmd/set/env/env_resolve.go b/pkg/cmd/set/env/env_resolve.go index 3ac1dd3a..038fdb65 100644 --- a/pkg/cmd/set/env/env_resolve.go +++ b/pkg/cmd/set/env/env_resolve.go @@ -158,11 +158,11 @@ func splitMaybeSubscriptedPath(fieldPath string) (string, string, bool) { // formatMap formats map[string]string to a string. func formatMap(m map[string]string) (fmtStr string) { // output with keys in sorted order to provide stable output - keys := sets.NewString() + keys := sets.New[string]() for key := range m { keys.Insert(key) } - for _, key := range keys.List() { + for _, key := range sets.List(keys) { fmtStr += fmt.Sprintf("%v=%q\n", key, m[key]) } fmtStr = strings.TrimSuffix(fmtStr, "\n") diff --git a/pkg/cmd/set/helper.go b/pkg/cmd/set/helper.go index 249beaea..f5101aa1 100644 --- a/pkg/cmd/set/helper.go +++ b/pkg/cmd/set/helper.go @@ -19,7 +19,7 @@ package set import ( "strings" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/strategicpatch" @@ -139,7 +139,7 @@ func findEnv(env []v1.EnvVar, name string) (v1.EnvVar, bool) { // If a variable is both added and removed, the removal takes precedence. func updateEnv(existing []v1.EnvVar, env []v1.EnvVar, remove []string) []v1.EnvVar { out := []v1.EnvVar{} - covered := sets.NewString(remove...) + covered := sets.New[string](remove...) for _, e := range existing { if covered.Has(e.Name) { continue diff --git a/pkg/cmd/set/set_subject.go b/pkg/cmd/set/set_subject.go index aa767643..30e035bc 100644 --- a/pkg/cmd/set/set_subject.go +++ b/pkg/cmd/set/set_subject.go @@ -206,7 +206,7 @@ func (o *SubjectOptions) Validate() error { func (o *SubjectOptions) Run(fn updateSubjects) error { patches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) { subjects := []rbacv1.Subject{} - for _, user := range sets.NewString(o.Users...).List() { + for _, user := range sets.List(sets.New[string](o.Users...)) { subject := rbacv1.Subject{ Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, @@ -214,7 +214,7 @@ func (o *SubjectOptions) Run(fn updateSubjects) error { } subjects = append(subjects, subject) } - for _, group := range sets.NewString(o.Groups...).List() { + for _, group := range sets.List(sets.New[string](o.Groups...)) { subject := rbacv1.Subject{ Kind: rbacv1.GroupKind, APIGroup: rbacv1.GroupName, @@ -222,7 +222,7 @@ func (o *SubjectOptions) Run(fn updateSubjects) error { } subjects = append(subjects, subject) } - for _, sa := range sets.NewString(o.ServiceAccounts...).List() { + for _, sa := range sets.List(sets.New[string](o.ServiceAccounts...)) { tokens := strings.Split(sa, ":") namespace := tokens[0] name := tokens[1] diff --git a/pkg/cmd/taint/utils.go b/pkg/cmd/taint/utils.go index 9d2807f9..bdc29624 100644 --- a/pkg/cmd/taint/utils.go +++ b/pkg/cmd/taint/utils.go @@ -38,7 +38,7 @@ const ( // It also validates the spec. For example, the form `` may be used to remove a taint, but not to add one. func parseTaints(spec []string) ([]corev1.Taint, []corev1.Taint, error) { var taints, taintsToRemove []corev1.Taint - uniqueTaints := map[corev1.TaintEffect]sets.String{} + uniqueTaints := map[corev1.TaintEffect]sets.Set[string]{} for _, taintSpec := range spec { if strings.HasSuffix(taintSpec, "-") { @@ -62,7 +62,7 @@ func parseTaints(spec []string) ([]corev1.Taint, []corev1.Taint, error) { } // add taint to existingTaints for uniqueness check if len(uniqueTaints[newTaint.Effect]) == 0 { - uniqueTaints[newTaint.Effect] = sets.String{} + uniqueTaints[newTaint.Effect] = sets.Set[string]{} } uniqueTaints[newTaint.Effect].Insert(newTaint.Key) diff --git a/pkg/cmd/util/helpers.go b/pkg/cmd/util/helpers.go index 653aa784..6d0982da 100644 --- a/pkg/cmd/util/helpers.go +++ b/pkg/cmd/util/helpers.go @@ -222,7 +222,7 @@ func checkErr(err error, handleErr func(string, int)) { func statusCausesToAggrError(scs []metav1.StatusCause) utilerrors.Aggregate { errs := make([]error, 0, len(scs)) - errorMsgs := sets.NewString() + errorMsgs := sets.New[string]() for _, sc := range scs { // check for duplicate error messages and skip them msg := fmt.Sprintf("%s: %s", sc.Field, sc.Message) diff --git a/pkg/describe/describe.go b/pkg/describe/describe.go index 75b1662e..db03fc34 100644 --- a/pkg/describe/describe.go +++ b/pkg/describe/describe.go @@ -97,7 +97,7 @@ const ( var ( // globally skipped annotations - skipAnnotations = sets.NewString(corev1.LastAppliedConfigAnnotation) + skipAnnotations = sets.New[string](corev1.LastAppliedConfigAnnotation) // DescriberFn gives a way to easily override the function for unit testing if needed DescriberFn DescriberFunc = Describer @@ -1449,10 +1449,10 @@ func printCSIPersistentVolumeSource(csi *corev1.CSIPersistentVolumeSource, w Pre } func printCSIPersistentVolumeAttributesMultiline(w PrefixWriter, title string, annotations map[string]string) { - printCSIPersistentVolumeAttributesMultilineIndent(w, "", title, "\t", annotations, sets.NewString()) + printCSIPersistentVolumeAttributesMultilineIndent(w, "", title, "\t", annotations, sets.New[string]()) } -func printCSIPersistentVolumeAttributesMultilineIndent(w PrefixWriter, initialIndent, title, innerIndent string, attributes map[string]string, skip sets.String) { +func printCSIPersistentVolumeAttributesMultilineIndent(w PrefixWriter, initialIndent, title, innerIndent string, attributes map[string]string, skip sets.Set[string]) { w.Write(LEVEL_2, "%s%s:%s", initialIndent, title, innerIndent) if len(attributes) == 0 { @@ -2128,8 +2128,8 @@ func describeVolumeClaimTemplates(templates []corev1.PersistentVolumeClaim, w Pr for _, pvc := range templates { w.Write(LEVEL_1, "Name:\t%s\n", pvc.Name) w.Write(LEVEL_1, "StorageClass:\t%s\n", storageutil.GetPersistentVolumeClaimClass(&pvc)) - printLabelsMultilineWithIndent(w, " ", "Labels", "\t", pvc.Labels, sets.NewString()) - printLabelsMultilineWithIndent(w, " ", "Annotations", "\t", pvc.Annotations, sets.NewString()) + printLabelsMultilineWithIndent(w, " ", "Labels", "\t", pvc.Labels, sets.New[string]()) + printLabelsMultilineWithIndent(w, " ", "Annotations", "\t", pvc.Annotations, sets.New[string]()) if capacity, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage]; ok { w.Write(LEVEL_1, "Capacity:\t%s\n", capacity.String()) } else { @@ -3340,7 +3340,7 @@ func describeEndpointSliceV1beta1(eps *discoveryv1beta1.EndpointSlice, events *c w.Write(LEVEL_2, "TargetRef:\t%s/%s\n", endpoint.TargetRef.Kind, endpoint.TargetRef.Name) } - printLabelsMultilineWithIndent(w, " ", "Topology", "\t", endpoint.Topology, sets.NewString()) + printLabelsMultilineWithIndent(w, " ", "Topology", "\t", endpoint.Topology, sets.New[string]()) } } @@ -3368,7 +3368,7 @@ func (d *ServiceAccountDescriber) Describe(namespace, name string, describerSett // missingSecrets is the set of all secrets present in the // serviceAccount but not present in the set of existing secrets. - missingSecrets := sets.NewString() + missingSecrets := sets.New[string]() secrets := corev1.SecretList{} err = runtimeresource.FollowContinue(&metav1.ListOptions{Limit: describerSettings.ChunkSize}, func(options metav1.ListOptions) (runtime.Object, error) { @@ -3385,7 +3385,7 @@ func (d *ServiceAccountDescriber) Describe(namespace, name string, describerSett if err == nil { // existingSecrets is the set of all secrets remaining on a // service account that are not present in the "tokens" slice. - existingSecrets := sets.NewString() + existingSecrets := sets.New[string]() for _, s := range secrets.Items { if s.Type == corev1.SecretTypeServiceAccountToken { @@ -3418,7 +3418,7 @@ func (d *ServiceAccountDescriber) Describe(namespace, name string, describerSett return describeServiceAccount(serviceAccount, tokens, missingSecrets, events) } -func describeServiceAccount(serviceAccount *corev1.ServiceAccount, tokens []corev1.Secret, missingSecrets sets.String, events *corev1.EventList) (string, error) { +func describeServiceAccount(serviceAccount *corev1.ServiceAccount, tokens []corev1.Secret, missingSecrets sets.Set[string], events *corev1.EventList) (string, error) { return tabbedString(func(out io.Writer) error { w := NewPrefixWriter(out) w.Write(LEVEL_0, "Name:\t%s\n", serviceAccount.Name) @@ -3452,7 +3452,7 @@ func describeServiceAccount(serviceAccount *corev1.ServiceAccount, tokens []core mountHeader: mountSecretNames, tokenHeader: tokenSecretNames, } - for _, header := range sets.StringKeySet(types).List() { + for _, header := range sets.List(sets.KeySet(types)) { names := types[header] if len(names) == 0 { w.Write(LEVEL_0, "%s\t\n", header) @@ -5150,11 +5150,11 @@ func (fn typeFunc) Describe(exact interface{}, extra ...interface{}) (string, er // printLabelsMultiline prints multiple labels with a proper alignment. func printLabelsMultiline(w PrefixWriter, title string, labels map[string]string) { - printLabelsMultilineWithIndent(w, "", title, "\t", labels, sets.NewString()) + printLabelsMultilineWithIndent(w, "", title, "\t", labels, sets.New[string]()) } // printLabelsMultiline prints multiple labels with a user-defined alignment. -func printLabelsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, labels map[string]string, skip sets.String) { +func printLabelsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, labels map[string]string, skip sets.Set[string]) { w.Write(LEVEL_0, "%s%s:%s", initialIndent, title, innerIndent) if len(labels) == 0 { @@ -5568,7 +5568,7 @@ func backendStringer(backend *networkingv1beta1.IngressBackend) string { // * a node-role.kubernetes.io/="" label // * a kubernetes.io/role="" label func findNodeRoles(node *corev1.Node) []string { - roles := sets.NewString() + roles := sets.New[string]() for k, v := range node.Labels { switch { case strings.HasPrefix(k, LabelNodeRolePrefix): @@ -5580,14 +5580,14 @@ func findNodeRoles(node *corev1.Node) []string { roles.Insert(v) } } - return roles.List() + return sets.List(roles) } // ingressLoadBalancerStatusStringerV1 behaves mostly like a string interface and converts the given status to a string. // `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes. func ingressLoadBalancerStatusStringerV1(s networkingv1.IngressLoadBalancerStatus, wide bool) string { ingress := s.Ingress - result := sets.NewString() + result := sets.New[string]() for i := range ingress { if ingress[i].IP != "" { result.Insert(ingress[i].IP) @@ -5596,7 +5596,7 @@ func ingressLoadBalancerStatusStringerV1(s networkingv1.IngressLoadBalancerStatu } } - r := strings.Join(result.List(), ",") + r := strings.Join(sets.List(result), ",") if !wide && len(r) > LoadBalancerWidth { r = r[0:(LoadBalancerWidth-3)] + "..." } @@ -5607,7 +5607,7 @@ func ingressLoadBalancerStatusStringerV1(s networkingv1.IngressLoadBalancerStatu // `wide` indicates whether the returned value is meant for --o=wide output. If not, it's clipped to 16 bytes. func ingressLoadBalancerStatusStringerV1beta1(s networkingv1beta1.IngressLoadBalancerStatus, wide bool) string { ingress := s.Ingress - result := sets.NewString() + result := sets.New[string]() for i := range ingress { if ingress[i].IP != "" { result.Insert(ingress[i].IP) @@ -5616,7 +5616,7 @@ func ingressLoadBalancerStatusStringerV1beta1(s networkingv1beta1.IngressLoadBal } } - r := strings.Join(result.List(), ",") + r := strings.Join(sets.List(result), ",") if !wide && len(r) > LoadBalancerWidth { r = r[0:(LoadBalancerWidth-3)] + "..." } diff --git a/pkg/util/fieldpath/fieldpath.go b/pkg/util/fieldpath/fieldpath.go index af512af8..80a406e1 100644 --- a/pkg/util/fieldpath/fieldpath.go +++ b/pkg/util/fieldpath/fieldpath.go @@ -30,11 +30,11 @@ import ( // FormatMap formats map[string]string to a string. func FormatMap(m map[string]string) (fmtStr string) { // output with keys in sorted order to provide stable output - keys := sets.NewString() + keys := sets.New[string]() for key := range m { keys.Insert(key) } - for _, key := range keys.List() { + for _, key := range sets.List(keys) { fmtStr += fmt.Sprintf("%v=%q\n", key, m[key]) } fmtStr = strings.TrimSuffix(fmtStr, "\n") diff --git a/pkg/util/qos/qos.go b/pkg/util/qos/qos.go index 1b102a0f..aed4be6c 100644 --- a/pkg/util/qos/qos.go +++ b/pkg/util/qos/qos.go @@ -22,7 +22,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" ) -var supportedQoSComputeResources = sets.NewString(string(core.ResourceCPU), string(core.ResourceMemory)) +var supportedQoSComputeResources = sets.New[string](string(core.ResourceCPU), string(core.ResourceMemory)) func isSupportedQoSComputeResource(name core.ResourceName) bool { return supportedQoSComputeResources.Has(string(name)) diff --git a/pkg/util/rbac/rbac.go b/pkg/util/rbac/rbac.go index b5d1f2d5..d42b368a 100644 --- a/pkg/util/rbac/rbac.go +++ b/pkg/util/rbac/rbac.go @@ -17,10 +17,11 @@ limitations under the License. package rbac import ( - rbacv1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/util/sets" "reflect" "strings" + + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/util/sets" ) type simpleResource struct { @@ -43,7 +44,7 @@ func CompactRules(rules []rbacv1.PolicyRule) ([]rbacv1.PolicyRule, error) { if existingRule.Verbs == nil { existingRule.Verbs = []string{} } - existingVerbs := sets.NewString(existingRule.Verbs...) + existingVerbs := sets.New[string](existingRule.Verbs...) for _, verb := range rule.Verbs { if !existingVerbs.Has(verb) { existingRule.Verbs = append(existingRule.Verbs, verb) diff --git a/pkg/util/resource/resource.go b/pkg/util/resource/resource.go index 80da5fdd..736a2600 100644 --- a/pkg/util/resource/resource.go +++ b/pkg/util/resource/resource.go @@ -254,7 +254,7 @@ func convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity return strconv.FormatInt(m, 10), nil } -var standardContainerResources = sets.NewString( +var standardContainerResources = sets.New[string]( string(corev1.ResourceCPU), string(corev1.ResourceMemory), string(corev1.ResourceEphemeralStorage),