github.com/jk-he/cni@v0.8.1/pkg/invoke/find.go (about)

     1  // Copyright 2015 CNI authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package invoke
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  	"path/filepath"
    21  	"strings"
    22  )
    23  
    24  // FindInPath returns the full path of the plugin by searching in the provided path
    25  func FindInPath(plugin string, paths []string) (string, error) {
    26  	if plugin == "" {
    27  		return "", fmt.Errorf("no plugin name provided")
    28  	}
    29  
    30  	if strings.ContainsRune(plugin, os.PathSeparator) {
    31  		return "", fmt.Errorf("invalid plugin name: %s", plugin)
    32  	}
    33  
    34  	if len(paths) == 0 {
    35  		return "", fmt.Errorf("no paths provided")
    36  	}
    37  
    38  	for _, path := range paths {
    39  		for _, fe := range ExecutableFileExtensions {
    40  			fullpath := filepath.Join(path, plugin) + fe
    41  			if fi, err := os.Stat(fullpath); err == nil && fi.Mode().IsRegular() {
    42  				return fullpath, nil
    43  			}
    44  		}
    45  	}
    46  
    47  	return "", fmt.Errorf("failed to find plugin %q in path %s", plugin, paths)
    48  }