preserve mtime when copying files (#1026)

* make it possible to preserve mtime and atime when copying files

Preserving other attributes like ownership, ctime or btime of a file is
desired but currently not possible to implement in a portable way with go.

Fixes #869
Relates to #779

* FIXUP use cp-compatible default for not-preserving mode
This commit is contained in:
raslop authored and GitHub committed 2023-05-21 19:41:01 +03:00
1 parent 24bba6288d
commit fdb320d30c
7 files changed
+76 -13

No files matched your search

+23 -1
View File
@@ -5,6 +5,7 @@ import (
"io"
"os"
"path/filepath"
"github.com/djherbis/times"
)
func copySize(srcs []string) (int64, error) {
@@ -33,6 +34,17 @@ func copySize(srcs []string) (int64, error) {
}
func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
var dst_mode os.FileMode = 0666
preserve_timestamps := false
for _, s := range gOpts.preserve {
switch s {
case "timestamps":
preserve_timestamps = true
case "mode":
dst_mode = info.Mode()
}
}
buf := make([]byte, 4096)
r, err := os.Open(src)
@@ -41,7 +53,7 @@ func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
}
defer r.Close()
w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode())
w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, dst_mode)
if err != nil {
return err
}
@@ -70,6 +82,16 @@ func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
return err
}
if preserve_timestamps {
ts := times.Get(info)
mtime := info.ModTime();
atime := ts.AccessTime();
if err := os.Chtimes(dst, atime, mtime); err != nil {
os.Remove(dst)
return err
}
}
return nil
}