terraform/config/module/copy_dir.go

77 lines
1.4 KiB
Go
Raw Normal View History

2014-09-27 00:22:26 +02:00
package module
import (
"io"
"os"
"path/filepath"
2014-09-27 01:11:13 +02:00
"strings"
2014-09-27 00:22:26 +02:00
)
// copyDir copies the src directory contents into dst. Both directories
// should already exist.
func copyDir(dst, src string) error {
2014-09-27 01:21:33 +02:00
src, err := filepath.EvalSymlinks(src)
if err != nil {
return err
}
2014-09-27 00:22:26 +02:00
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
2014-09-27 01:21:33 +02:00
if path == src {
return nil
}
2014-09-27 00:22:26 +02:00
if strings.HasPrefix(filepath.Base(path), ".") {
2014-09-27 01:11:13 +02:00
// Skip any dot files
if info.IsDir() {
return filepath.SkipDir
} else {
return nil
}
2014-09-27 01:11:13 +02:00
}
// The "path" has the src prefixed to it. We need to join our
// destination with the path without the src on it.
dstPath := filepath.Join(dst, path[len(src):])
2014-09-27 00:22:26 +02:00
// If we have a directory, make that subdirectory, then continue
// the walk.
if info.IsDir() {
if path == filepath.Join(src, dst) {
// dst is in src; don't walk it.
return nil
}
2014-09-27 00:22:26 +02:00
if err := os.MkdirAll(dstPath, 0755); err != nil {
return err
}
return nil
2014-09-27 00:22:26 +02:00
}
// If we have a file, copy the contents.
srcF, err := os.Open(path)
if err != nil {
return err
}
defer srcF.Close()
dstF, err := os.Create(dstPath)
if err != nil {
return err
}
defer dstF.Close()
if _, err := io.Copy(dstF, srcF); err != nil {
return err
}
// Chmod it
return os.Chmod(dstPath, info.Mode())
}
return filepath.Walk(src, walkFn)
}