-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdecent_copy.go
51 lines (43 loc) · 994 Bytes
/
decent_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
// Package decentcopy copy files in simple form
package decentcopy
import (
"io"
"os"
)
// ExecOnErrorWhileDefer is executed when the file.Close() function returns an
// error while closing the source or destination files.
var ExecOnErrorWhileDefer func(error)
// Copy use to copy files
func Copy(filepathOrigin, filepathDestiny string) error {
srcInfo, err := os.Stat(filepathOrigin)
if err != nil {
return err
}
srcFile, err := os.Open(filepathOrigin)
if err != nil {
return err
}
defer func() {
err := srcFile.Close()
if ExecOnErrorWhileDefer != nil {
ExecOnErrorWhileDefer(err)
}
}()
destFile, err := os.Create(filepathDestiny)
if err != nil {
return err
}
defer func() {
err := destFile.Close()
if ExecOnErrorWhileDefer != nil {
ExecOnErrorWhileDefer(err)
}
}()
if _, err := io.Copy(destFile, srcFile); err != nil {
return err
}
if err := os.Chmod(filepathDestiny, srcInfo.Mode()); err != nil {
return err
}
return destFile.Sync()
}