github.com/jenkins-x/jx-api@v0.0.24/pkg/util/files.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  const (
    11  	DefaultWritePermissions = 0760
    12  )
    13  
    14  // FileExists checks if path exists and is a file
    15  func FileExists(path string) (bool, error) {
    16  	fileInfo, err := os.Stat(path)
    17  	if err == nil {
    18  		return !fileInfo.IsDir(), nil
    19  	}
    20  	if os.IsNotExist(err) {
    21  		return false, nil
    22  	}
    23  	return false, errors.Wrapf(err, "failed to check if file exists %s", path)
    24  }
    25  
    26  // DeleteFile deletes a file from the operating system. This should NOT be used to delete any sensitive information
    27  // because it can easily be recovered. Use DestroyFile to delete sensitive information
    28  func DeleteFile(fileName string) (err error) {
    29  	if fileName != "" {
    30  		exists, err := FileExists(fileName)
    31  		if err != nil {
    32  			return fmt.Errorf("Could not check if file exists %s due to %s", fileName, err)
    33  		}
    34  
    35  		if exists {
    36  			err = os.Remove(fileName)
    37  			if err != nil {
    38  				return errors.Wrapf(err, "Could not remove file due to %s", fileName)
    39  			}
    40  		}
    41  	} else {
    42  		return fmt.Errorf("Filename is not valid")
    43  	}
    44  	return nil
    45  }