CopyDir Copy all files to the target directory, if the file already exists, it will be overwritten. Remove target file if the source file is not exist.
(source string, target string, excludeDir ...string)
| 76 | // CopyDir Copy all files to the target directory, if the file already exists, it will be overwritten. |
| 77 | // Remove target file if the source file is not exist. |
| 78 | func CopyDir(source string, target string, excludeDir ...string) error { |
| 79 | if err := os.MkdirAll(target, 0755); err != nil { |
| 80 | return err |
| 81 | } |
| 82 | if err := filepath.Walk(source, func(path string, info os.FileInfo, err error) error { |
| 83 | if err != nil { |
| 84 | return err |
| 85 | } |
| 86 | if info.IsDir() { |
| 87 | if len(excludeDir) > 0 { |
| 88 | for _, dir := range excludeDir { |
| 89 | if info.IsDir() && info.Name() == dir { |
| 90 | return filepath.SkipDir |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | return nil |
| 95 | } |
| 96 | relPath, err := filepath.Rel(source, path) |
| 97 | if err != nil { |
| 98 | return err |
| 99 | } |
| 100 | targetPath := filepath.Join(target, relPath) |
| 101 | if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil { |
| 102 | return err |
| 103 | } |
| 104 | if err := copyForce(path, targetPath); err != nil { |
| 105 | return err |
| 106 | } |
| 107 | return nil |
| 108 | }); err != nil { |
| 109 | return err |
| 110 | } |
| 111 | |
| 112 | if err := filepath.Walk(target, func(path string, info os.FileInfo, err error) error { |
| 113 | if err != nil { |
| 114 | return err |
| 115 | } |
| 116 | if info.IsDir() { |
| 117 | if len(excludeDir) > 0 { |
| 118 | for _, dir := range excludeDir { |
| 119 | if info.IsDir() && info.Name() == dir { |
| 120 | return filepath.SkipDir |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | return nil |
| 125 | } |
| 126 | relPath, err := filepath.Rel(target, path) |
| 127 | if err != nil { |
| 128 | return err |
| 129 | } |
| 130 | targetPath := filepath.Join(target, relPath) |
| 131 | sourcePath := filepath.Join(source, relPath) |
| 132 | // if source file is not exist, remove target file |
| 133 | if _, err := os.Stat(sourcePath); os.IsNotExist(err) { |
| 134 | if err := SafeRemove(targetPath); err != nil { |
| 135 | return err |
no test coverage detected