sigs.k8s.io/kubebuilder/v3@v3.14.0/pkg/plugin/filter.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 plugin
    18  
    19  import (
    20  	"strings"
    21  
    22  	"sigs.k8s.io/kubebuilder/v3/pkg/config"
    23  )
    24  
    25  // FilterPluginsByKey returns the set of plugins that match the provided key (may be not-fully qualified)
    26  func FilterPluginsByKey(plugins []Plugin, key string) ([]Plugin, error) {
    27  	name, ver := SplitKey(key)
    28  	hasVersion := ver != ""
    29  	var version Version
    30  	if hasVersion {
    31  		if err := version.Parse(ver); err != nil {
    32  			return nil, err
    33  		}
    34  	}
    35  
    36  	filtered := make([]Plugin, 0, len(plugins))
    37  	for _, plugin := range plugins {
    38  		if !strings.HasPrefix(plugin.Name(), name) {
    39  			continue
    40  		}
    41  		if hasVersion && plugin.Version().Compare(version) != 0 {
    42  			continue
    43  		}
    44  		filtered = append(filtered, plugin)
    45  	}
    46  	return filtered, nil
    47  }
    48  
    49  // FilterPluginsByProjectVersion returns the set of plugins that support the provided project version
    50  func FilterPluginsByProjectVersion(plugins []Plugin, projectVersion config.Version) []Plugin {
    51  	filtered := make([]Plugin, 0, len(plugins))
    52  	for _, plugin := range plugins {
    53  		for _, supportedVersion := range plugin.SupportedProjectVersions() {
    54  			if supportedVersion.Compare(projectVersion) == 0 {
    55  				filtered = append(filtered, plugin)
    56  				break
    57  			}
    58  		}
    59  	}
    60  	return filtered
    61  }