CopyDirectory

This commit is contained in:
tengge1 2020-03-31 21:56:06 +08:00
parent 4e104a7328
commit ebd64bcbaf
2 changed files with 53 additions and 2 deletions

View File

@ -1,8 +1,41 @@
package helper
// CopyDirectory copy one directory and its content to another
func CopyDirectory(sourceDirName, destDirName string) {
import (
"fmt"
"io"
"io/ioutil"
"os"
)
// CopyDirectory copy one directory and its content to another
func CopyDirectory(sourceDirName, destDirName string) error {
children, err := ioutil.ReadDir(sourceDirName)
if err != nil {
return err
}
for _, child := range children {
sourcePath := fmt.Sprintf("%v/%v", sourceDirName, child.Name())
destPath := fmt.Sprintf("%v/%v", destDirName, child.Name())
if child.IsDir() {
_, err = os.Stat(destPath)
if !os.IsExist(err) {
os.MkdirAll(destPath, 0777)
}
} else {
writer, err := os.Create(destPath)
if err != nil {
return err
}
defer writer.Close()
reader, err := os.Open(sourcePath)
if err != nil {
return err
}
defer reader.Close()
io.Copy(writer, reader)
}
}
return nil
}
// RemoveEmptyDirectory remove empty folder under path

View File

@ -3,6 +3,8 @@ package helper
import (
"os"
"testing"
"io/ioutil"
)
func TestCopyDirectory(t *testing.T) {
@ -16,3 +18,19 @@ func TestRemoveEmptyDirectory(t *testing.T) {
func TestTempDir(t *testing.T) {
t.Log(os.TempDir())
}
func TestWalk(t *testing.T) {
children, err := ioutil.ReadDir("./")
if err != nil {
t.Error(err)
return
}
for _, child := range children {
childType := "file"
if child.IsDir() {
childType = "dir"
}
t.Logf("%v\t%v", child.Name(), childType)
}
}