github.com/muratcelep/terraform@v1.1.0-beta2-not-internal-4/not-internal/copy/copy_file.go (about)

     1  package copy
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  )
     7  
     8  // From: https://gist.github.com/m4ng0squ4sh/92462b38df26839a3ca324697c8cba04
     9  
    10  // CopyFile copies the contents of the file named src to the file named
    11  // by dst. The file will be created if it does not already exist. If the
    12  // destination file exists, all it's contents will be replaced by the contents
    13  // of the source file. The file mode will be copied from the source and
    14  // the copied data is synced/flushed to stable storage.
    15  func CopyFile(src, dst string) (err error) {
    16  	in, err := os.Open(src)
    17  	if err != nil {
    18  		return
    19  	}
    20  	defer in.Close()
    21  
    22  	out, err := os.Create(dst)
    23  	if err != nil {
    24  		return
    25  	}
    26  	defer func() {
    27  		if e := out.Close(); e != nil {
    28  			err = e
    29  		}
    30  	}()
    31  
    32  	_, err = io.Copy(out, in)
    33  	if err != nil {
    34  		return
    35  	}
    36  
    37  	err = out.Sync()
    38  	if err != nil {
    39  		return
    40  	}
    41  
    42  	si, err := os.Stat(src)
    43  	if err != nil {
    44  		return
    45  	}
    46  	err = os.Chmod(dst, si.Mode())
    47  	if err != nil {
    48  		return
    49  	}
    50  
    51  	return
    52  }