-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy.go
82 lines (68 loc) · 1.58 KB
/
Copy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package File
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"github.com/Synertry/GoSysUtils/File/internal"
)
// Copy copies a file from src to dst. If src and dst files exist, and are the same, then return success.
// Otherwise, copy the file contents from src to dst.
func Copy(src, dst string) (err error) {
sfi, err := os.Stat(src)
if err != nil {
return
}
if !sfi.Mode().IsRegular() { // cannot copy non-regular files (e.g., directories, symlinks, devices, etc.)
return fmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err := os.Stat(dst)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return
}
}
/*if err = os.Link(src, dst); err == nil { // I see problems here with network paths
return
}*/
err = copyContents(src, dst)
if err != nil {
return
}
return internal.SetStats(&sfi, &dst)
}
// copyContents is the core function of Copy to copy file contents
func copyContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer func() {
errCi := in.Close()
if err == nil {
err = errCi
}
}()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
errCo := out.Close()
if err == nil {
err = errCo
}
}()
if _, err = io.Copy(out, in); err != nil { // core copy
return fmt.Errorf("core function copy failed: %w", err)
}
return out.Sync() // flush
}