2019-01-05 22:44:33 +00:00
|
|
|
package fileutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2024-08-24 22:02:33 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2019-01-05 22:44:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// CopyDir copies a directory from source to dest and all
|
|
|
|
// of its sub-directories. It doesn't stop if it finds an error
|
|
|
|
// during the copy. Returns an error if any.
|
2024-08-24 22:02:33 +00:00
|
|
|
func CopyDir(source, dest string) error {
|
2019-01-05 22:44:33 +00:00
|
|
|
// Get properties of source.
|
2024-08-24 22:02:33 +00:00
|
|
|
srcinfo, err := os.Stat(source)
|
2019-01-05 22:44:33 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the destination directory.
|
2024-08-24 22:02:33 +00:00
|
|
|
err = os.MkdirAll(dest, srcinfo.Mode())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
dir, err := os.Open(source)
|
2019-01-05 22:44:33 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-08-24 22:02:33 +00:00
|
|
|
defer dir.Close()
|
2019-01-05 22:44:33 +00:00
|
|
|
|
|
|
|
obs, err := dir.Readdir(-1)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var errs []error
|
|
|
|
|
|
|
|
for _, obj := range obs {
|
2024-08-24 22:02:33 +00:00
|
|
|
fsource := filepath.Join(source, obj.Name())
|
|
|
|
fdest := filepath.Join(dest, obj.Name())
|
2019-01-05 22:44:33 +00:00
|
|
|
|
|
|
|
if obj.IsDir() {
|
|
|
|
// Create sub-directories, recursively.
|
2024-08-24 22:02:33 +00:00
|
|
|
err = CopyDir(fsource, fdest)
|
2019-01-05 22:44:33 +00:00
|
|
|
if err != nil {
|
|
|
|
errs = append(errs, err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// Perform the file copy.
|
2024-08-24 22:02:33 +00:00
|
|
|
err = CopyFile(fsource, fdest)
|
2019-01-05 22:44:33 +00:00
|
|
|
if err != nil {
|
|
|
|
errs = append(errs, err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var errString string
|
|
|
|
for _, err := range errs {
|
|
|
|
errString += err.Error() + "\n"
|
|
|
|
}
|
|
|
|
|
|
|
|
if errString != "" {
|
|
|
|
return errors.New(errString)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|