-
Notifications
You must be signed in to change notification settings - Fork 26
/
copy.go
127 lines (105 loc) · 2.21 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package fs
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
)
// Copy will move a source file or directory to a destination. For directories,
// move will remap relative symlinks ensuring that they align with the
// destination directory. If the destination exists prior to invocation, it
// will be removed.
func Copy(source, destination string) error {
err := os.Remove(destination)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to copy: destination exists: %w", err)
}
}
info, err := os.Stat(source)
if err != nil {
return err
}
if info.IsDir() {
err = copyDirectory(source, destination)
if err != nil {
return err
}
} else {
err = copyFile(source, destination)
if err != nil {
return err
}
}
return nil
}
func copyFile(source, destination string) error {
sourceFile, err := os.Open(source)
if err != nil {
return err
}
defer sourceFile.Close()
destinationFile, err := os.Create(destination)
if err != nil {
return err
}
defer destinationFile.Close()
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
info, err := sourceFile.Stat()
if err != nil {
return err
}
err = os.Chmod(destination, info.Mode())
if err != nil {
return err
}
return nil
}
func copyDirectory(source, destination string) error {
err := filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
path, err = filepath.Rel(source, path)
if err != nil {
return err
}
switch {
case info.IsDir():
err = os.Mkdir(filepath.Join(destination, path), os.ModePerm)
if err != nil {
return err
}
case (info.Mode() & os.ModeSymlink) != 0:
err = copyLink(source, destination, path)
if err != nil {
return err
}
default:
err = copyFile(filepath.Join(source, path), filepath.Join(destination, path))
if err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return nil
}
func copyLink(source, destination, path string) error {
link, err := os.Readlink(filepath.Join(source, path))
if err != nil {
return err
}
err = os.Symlink(link, filepath.Join(destination, path))
if err != nil {
return err
}
return nil
}