CopyFile copies the contents of the file named src to the file named by dst. The file will be created if it does not already exist. If the destination file exists, all its contents will be replaced by the contents of the source file. The file mode will be copied from the source and the copied data i
(src string, dst string)
| 24 | // of the source file. The file mode will be copied from the source and |
| 25 | // the copied data is synced/flushed to stable storage. Credit @m4ng0squ4sh https://gist.github.com/m4ng0squ4sh/92462b38df26839a3ca324697c8cba04 |
| 26 | func CopyFile(src string, dst string) error { |
| 27 | in, err := os.Open(src) |
| 28 | if err != nil { |
| 29 | return err |
| 30 | } |
| 31 | defer util.CheckClose(in) |
| 32 | out, err := os.Create(dst) |
| 33 | if err != nil { |
| 34 | return fmt.Errorf("failed to create file %v, err: %v", src, err) |
| 35 | } |
| 36 | defer util.CheckClose(out) |
| 37 | _, err = io.Copy(out, in) |
| 38 | if err != nil { |
| 39 | return fmt.Errorf("failed to copy file from %v to %v err: %v", src, dst, err) |
| 40 | } |
| 41 | |
| 42 | err = out.Sync() |
| 43 | if err != nil { |
| 44 | return err |
| 45 | } |
| 46 | |
| 47 | // os.Chmod fails on long path (> 256 characters) on windows. |
| 48 | // A description of this problem with golang is at https://github.com/golang/dep/issues/774#issuecomment-311560825 |
| 49 | // It could end up fixed in a future version of golang. |
| 50 | if !nodeps.IsWindows() { |
| 51 | si, err := os.Stat(src) |
| 52 | if err != nil { |
| 53 | return err |
| 54 | } |
| 55 | |
| 56 | err = util.Chmod(dst, si.Mode()) |
| 57 | if err != nil { |
| 58 | return fmt.Errorf("failed to chmod file %v to mode %v, err=%v", dst, si.Mode(), err) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | return nil |
| 63 | } |
| 64 | |
| 65 | // CopyDir recursively copies a directory tree, attempting to preserve permissions. |
| 66 | // Source directory must exist, destination directory must *not* exist. |