github.com/opentofu/opentofu@v1.7.1/internal/copy/copy_file.go (about)

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