github.com/turtlemonvh/terraform@v0.6.9-0.20151204001754-8e40b6b855e8/config/module/copy_dir.go (about) 1 package module 2 3 import ( 4 "io" 5 "os" 6 "path/filepath" 7 "strings" 8 ) 9 10 // copyDir copies the src directory contents into dst. Both directories 11 // should already exist. 12 func copyDir(dst, src string) error { 13 src, err := filepath.EvalSymlinks(src) 14 if err != nil { 15 return err 16 } 17 18 walkFn := func(path string, info os.FileInfo, err error) error { 19 if err != nil { 20 return err 21 } 22 if path == src { 23 return nil 24 } 25 26 if strings.HasPrefix(filepath.Base(path), ".") { 27 // Skip any dot files 28 if info.IsDir() { 29 return filepath.SkipDir 30 } else { 31 return nil 32 } 33 } 34 35 // The "path" has the src prefixed to it. We need to join our 36 // destination with the path without the src on it. 37 dstPath := filepath.Join(dst, path[len(src):]) 38 39 // If we have a directory, make that subdirectory, then continue 40 // the walk. 41 if info.IsDir() { 42 if path == filepath.Join(src, dst) { 43 // dst is in src; don't walk it. 44 return nil 45 } 46 47 if err := os.MkdirAll(dstPath, 0755); err != nil { 48 return err 49 } 50 51 return nil 52 } 53 54 // If we have a file, copy the contents. 55 srcF, err := os.Open(path) 56 if err != nil { 57 return err 58 } 59 defer srcF.Close() 60 61 dstF, err := os.Create(dstPath) 62 if err != nil { 63 return err 64 } 65 defer dstF.Close() 66 67 if _, err := io.Copy(dstF, srcF); err != nil { 68 return err 69 } 70 71 // Chmod it 72 return os.Chmod(dstPath, info.Mode()) 73 } 74 75 return filepath.Walk(src, walkFn) 76 }