2019-01-05 22:44:33 +00:00
|
|
|
package fileutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
2020-07-15 15:12:13 +00:00
|
|
|
"os"
|
2019-01-05 22:44:33 +00:00
|
|
|
"path/filepath"
|
|
|
|
|
|
|
|
"github.com/spf13/afero"
|
|
|
|
)
|
|
|
|
|
|
|
|
// CopyFile copies a file from source to dest and returns
|
|
|
|
// an error if any.
|
2020-05-31 23:12:36 +00:00
|
|
|
func CopyFile(fs afero.Fs, source, dest string) error {
|
2019-01-05 22:44:33 +00:00
|
|
|
// Open the source file.
|
|
|
|
src, err := fs.Open(source)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer src.Close()
|
|
|
|
|
|
|
|
// Makes the directory needed to create the dst
|
|
|
|
// file.
|
|
|
|
err = fs.MkdirAll(filepath.Dir(dest), 0666)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the destination file.
|
2020-07-15 15:12:13 +00:00
|
|
|
dst, err := fs.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0775)
|
2019-01-05 22:44:33 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer dst.Close()
|
|
|
|
|
|
|
|
// Copy the contents of the file.
|
|
|
|
_, err = io.Copy(dst, src)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Copy the mode if the user can't
|
|
|
|
// open the file.
|
|
|
|
info, err := fs.Stat(source)
|
|
|
|
if err != nil {
|
|
|
|
err = fs.Chmod(dest, info.Mode())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|