-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
64 lines (59 loc) · 1.2 KB
/
file.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
package copier
import (
"io"
"io/fs"
"os"
)
func doesFileExist(path string) (exists, isFolder bool, err error) {
var stat os.FileInfo
stat, err = os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return
}
if stat.IsDir() {
isFolder = true
return
}
exists = true
return
}
// copyFileContents 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 it's contents
// will be replaced by the contents of the source file.
// Inspired by: https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang
func copyFileContents(src, dst string, wp *WriteProgress) error {
var err error
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if wp != nil {
var fi fs.FileInfo
fi, err = in.Stat()
if err != nil {
return err
}
wp.SetGoal(uint64(fi.Size()))
_, err = io.Copy(out, io.TeeReader(in, wp))
} else {
_, err = io.Copy(out, in)
}
if err != nil {
return err
}
return out.Sync()
}