1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-12 08:42:29 +08:00

feat(fileutil): add CopyDir func (#180)

* add fileutil.CopyDir

* remove debug code
This commit is contained in:
yunxuan
2024-02-25 20:25:00 +08:00
committed by GitHub
parent aebab7c944
commit 0eeaa06055
7 changed files with 141 additions and 1 deletions

View File

@@ -113,6 +113,65 @@ func CreateDir(absPath string) error {
return os.MkdirAll(absPath, os.ModePerm)
}
// CopyDir copy src directory to dst directory, it will copy all files and directories recursively.
// the access permission will be the same as the source directory.
// if dstPath exists, it will return an error.
// Play: https://go.dev/play/p/YAyFTA_UuPb
func CopyDir(srcPath string, dstPath string) error {
if !IsDir(srcPath) {
return errors.New("source path is not a directory")
}
var err error
srcPath, err = filepath.Abs(srcPath)
if err != nil {
return err
}
if IsExist(dstPath) {
return errors.New("destination path already exists")
}
dstPath, err = filepath.Abs(dstPath)
if err != nil {
return err
}
// get srcPath's file info
srcFileInfo, err := os.Stat(srcPath)
if err != nil {
return err
}
// create dstPath with srcPath's mode
err = os.MkdirAll(dstPath, srcFileInfo.Mode())
if err != nil {
return err
}
err = filepath.Walk(srcPath, func(path string, info os.FileInfo, err error) error {
if srcPath == path {
return nil
}
curDstPath := filepath.Join(dstPath, filepath.Base(path))
if info.IsDir() {
err = CopyDir(path, curDstPath)
if err != nil {
return err
}
} else {
err = CopyFile(path, curDstPath)
if err != nil {
return err
}
err = os.Chmod(curDstPath, info.Mode())
if err != nil {
return err
}
}
return err
})
return err
}
// IsDir checks if the path is directory or not.
// Play: https://go.dev/play/p/WkVwEKqtOWk
func IsDir(path string) bool {
@@ -377,7 +436,7 @@ func UnZip(zipFile string, destPath string) error {
defer zipReader.Close()
for _, f := range zipReader.File {
//issue#62: fix ZipSlip bug
// issue#62: fix ZipSlip bug
path, err := safeFilepathJoin(destPath, f.Name)
if err != nil {
return err

View File

@@ -3,6 +3,8 @@ package fileutil
import (
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/duke-git/lancet/v2/internal"
@@ -544,3 +546,23 @@ func TestReadlineFile(t *testing.T) {
internal.NewAssert(t, "TestReadlineFile").Equal(line, lineRead)
}
}
func TestCopyDir(t *testing.T) {
assert := internal.NewAssert(t, "TestCopyDir")
src := "./testdata"
dest := "./testdata_copy"
err := CopyDir(src, dest)
assert.IsNil(err)
assert.Equal(true, IsExist(dest))
filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
destPath := strings.Replace(path, src, dest, 1)
assert.Equal(true, IsExist(destPath))
return nil
})
os.RemoveAll(dest)
}

1
fileutil/testdata/test01/demo2.csv vendored Normal file
View File

@@ -0,0 +1 @@
makj1
1 makj1