2f1c5a19f1
The io/ioutil package has been deprecated as of Go 1.16 [1]. This commit replaces the existing io/ioutil functions with their new definitions in io and os packages. [1]: https://golang.org/doc/go1.16#ioutil Signed-off-by: Eng Zer Jun <engzerjun@gmail.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
73 lines
1.2 KiB
Go
73 lines
1.2 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
// CopyFile copy file
|
|
func CopyFile(source string, dest string) (err error) {
|
|
sourcefile, err := os.Open(source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
defer sourcefile.Close()
|
|
|
|
destfile, err := os.Create(dest)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
defer destfile.Close()
|
|
|
|
_, err = io.Copy(destfile, sourcefile)
|
|
if err == nil {
|
|
sourceinfo, err := os.Stat(source)
|
|
if err != nil {
|
|
_ = os.Chmod(dest, sourceinfo.Mode())
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// CopyDir recursive copy of directory
|
|
func CopyDir(source string, dest string) (err error) {
|
|
// get properties of source dir
|
|
sourceinfo, err := os.Stat(source)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// create dest dir
|
|
|
|
err = os.MkdirAll(dest, sourceinfo.Mode())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
objects, err := os.ReadDir(source)
|
|
|
|
for _, obj := range objects {
|
|
sourcefilepointer := source + "/" + obj.Name()
|
|
|
|
destinationfilepointer := dest + "/" + obj.Name()
|
|
|
|
if obj.IsDir() {
|
|
// create sub-directories - recursively
|
|
err = CopyDir(sourcefilepointer, destinationfilepointer)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
} else {
|
|
// perform copy
|
|
err = CopyFile(sourcefilepointer, destinationfilepointer)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
}
|
|
}
|
|
return err
|
|
}
|