From 6f4d83a2c564d278c0e838df0e4f62f52c15b7df Mon Sep 17 00:00:00 2001 From: Michael Sverdlov Date: Thu, 31 Aug 2023 11:46:17 +0300 Subject: [PATCH] copy dir Signed-off-by: Michael Sverdlov --- utils/fileutils.go | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/utils/fileutils.go b/utils/fileutils.go index 5aa3dfad..40498d66 100644 --- a/utils/fileutils.go +++ b/utils/fileutils.go @@ -3,6 +3,7 @@ package utils import ( "bufio" "encoding/json" + "errors" "fmt" "golang.org/x/exp/slices" "io" @@ -415,15 +416,15 @@ func CopyDir(fromPath, toPath string, includeDirs bool, excludeNames []string) e if slices.Contains(excludeNames, filepath.Base(v)) { continue } - - dir, err := IsDirExists(v, false) + var exists bool + exists, err = IsDirExists(v, false) if err != nil { return err } - if dir { + if exists { toPath := toPath + GetFileSeparator() + filepath.Base(v) - err := CopyDir(v, toPath, true, nil) + err = CopyDir(v, toPath, true, nil) if err != nil { return err } @@ -440,31 +441,29 @@ func CopyDir(fromPath, toPath string, includeDirs bool, excludeNames []string) e func CopyFile(dst, src string) (err error) { srcFile, err := os.Open(src) if err != nil { - return err + return } defer func() { - e := srcFile.Close() - if err == nil { - err = e - } + err = errors.Join(err, srcFile.Close()) }() + srcInfo, err := srcFile.Stat() + if err != nil { + return + } fileName, _ := GetFileAndDirFromPath(src) dstPath, err := CreateFilePath(dst, fileName) if err != nil { - return err + return } - dstFile, err := os.Create(dstPath) + dstFile, err := os.OpenFile(dstPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, srcInfo.Mode()) if err != nil { - return err + return } defer func() { - e := dstFile.Close() - if err == nil { - err = e - } + err = errors.Join(err, dstFile.Close()) }() _, err = io.Copy(dstFile, srcFile) - return err + return } func GetFileSeparator() string {