github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/imageengine/buildah/util.go (about)

     1  // Copyright © 2022 Alibaba Group Holding Ltd.
     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 buildah
    16  
    17  import (
    18  	"os"
    19  
    20  	"path/filepath"
    21  
    22  	"github.com/pkg/errors"
    23  )
    24  
    25  // DiscoverKubefile tries to find a Kubefile within the provided `path`.
    26  func DiscoverKubefile(path string) (foundFile string, err error) {
    27  	// Test for existence of the file
    28  	target, err := os.Stat(path)
    29  	if err != nil {
    30  		return "", errors.Wrap(err, "discovering Kubefile")
    31  	}
    32  
    33  	switch mode := target.Mode(); {
    34  	case mode.IsDir():
    35  		// If the path is a real directory, we assume a Kubefile within it
    36  		kubefile := filepath.Join(path, "Kubefile")
    37  
    38  		// Test for existence of the Kubefile file
    39  		file, err := os.Stat(kubefile)
    40  		if err != nil {
    41  			return "", errors.Wrap(err, "cannot find Kubefile in context directory")
    42  		}
    43  
    44  		// The file exists, now verify the correct mode
    45  		if mode := file.Mode(); mode.IsRegular() {
    46  			foundFile = kubefile
    47  		} else {
    48  			return "", errors.Errorf("assumed Kubefile %q is not a file", kubefile)
    49  		}
    50  
    51  	case mode.IsRegular():
    52  		// If the context dir is a file, we assume this as Kubefile
    53  		foundFile = path
    54  	}
    55  
    56  	return foundFile, nil
    57  }