1 // Package cp offers simple file and directory copying for Go.
12 var errCopyFileWithDir = errors.New("dir argument to CopyFile")
14 // CopyFile copies the file with path src to dst. The new file must not exist.
15 // It is created with the same permissions as src.
16 func CopyFile(dst, src string) error {
17 rf, err := os.Open(src)
22 rstat, err := rf.Stat()
27 return errCopyFileWithDir
30 wf, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, rstat.Mode())
34 if _, err := io.Copy(wf, rf); err != nil {
41 // CopyAll copies the file or (recursively) the directory at src to dst.
42 // Permissions are preserved. dst must not already exist.
43 func CopyAll(dst, src string) error {
44 return filepath.Walk(src, makeWalkFn(dst, src))
47 func makeWalkFn(dst, src string) filepath.WalkFunc {
48 return func(path string, info os.FileInfo, err error) error {
52 dstPath := filepath.Join(dst, strings.TrimPrefix(path, src))
54 return os.Mkdir(dstPath, info.Mode())
56 return CopyFile(dstPath, path)