github.com/kubernetes/utils@v0.0.0-20190308190857-21c4ce38f2a7/path/file.go (about)

     1  /*
     2  Copyright 2017 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 path
    18  
    19  import (
    20  	"errors"
    21  	"os"
    22  )
    23  
    24  // LinkTreatment is the base type for constants used by Exists that indicate
    25  // how symlinks are treated for existence checks.
    26  type LinkTreatment int
    27  
    28  const (
    29  	// CheckFollowSymlink follows the symlink and verifies that the target of
    30  	// the symlink exists.
    31  	CheckFollowSymlink LinkTreatment = iota
    32  
    33  	// CheckSymlinkOnly does not follow the symlink and verfies only that they
    34  	// symlink itself exists.
    35  	CheckSymlinkOnly
    36  )
    37  
    38  // ErrInvalidLinkTreatment indicates that the link treatment behavior requested
    39  // is not a valid behavior.
    40  var ErrInvalidLinkTreatment = errors.New("unknown link behavior")
    41  
    42  // Exists checks if specified file, directory, or symlink exists. The behavior
    43  // of the test depends on the linkBehaviour argument. See LinkTreatment for
    44  // more details.
    45  func Exists(linkBehavior LinkTreatment, filename string) (bool, error) {
    46  	var err error
    47  
    48  	if linkBehavior == CheckFollowSymlink {
    49  		_, err = os.Stat(filename)
    50  	} else if linkBehavior == CheckSymlinkOnly {
    51  		_, err = os.Lstat(filename)
    52  	} else {
    53  		return false, ErrInvalidLinkTreatment
    54  	}
    55  
    56  	if os.IsNotExist(err) {
    57  		return false, nil
    58  	} else if err != nil {
    59  		return false, err
    60  	}
    61  	return true, nil
    62  }
    63  
    64  // ReadDirNoStat returns a string of files/directories contained
    65  // in dirname without calling lstat on them.
    66  func ReadDirNoStat(dirname string) ([]string, error) {
    67  	if dirname == "" {
    68  		dirname = "."
    69  	}
    70  
    71  	f, err := os.Open(dirname)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	defer f.Close()
    76  
    77  	return f.Readdirnames(-1)
    78  }