github.com/keikoproj/manny@v0.0.0-20210726112440-8571e4c99ced/utils/file.go (about)

     1  package utils
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  )
     9  
    10  const (
    11  	ErrDestinationIsDir  = "Destination is a directory: "
    12  	ErrDestinationExists = "Destination already exists: "
    13  )
    14  
    15  // ValidateAndWrite checks that a location does not exist and that it is not a directory
    16  func ValidateAndWrite(location string, bytes []byte) (bool, error) {
    17  	// validation
    18  	location = filepath.Clean(location)
    19  	if fl, err := os.Stat(location); !os.IsNotExist(err) {
    20  		if fl.Mode().IsDir() {
    21  			return false, errors.New(ErrDestinationIsDir + location)
    22  		}
    23  
    24  		return false, errors.New(ErrDestinationExists + location)
    25  	}
    26  
    27  	// write
    28  	err := ioutil.WriteFile(location, bytes, 0644)
    29  	if err != nil {
    30  		return false, err
    31  	}
    32  
    33  	return true, nil
    34  }