-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfile_ops.go
More file actions
88 lines (83 loc) · 1.76 KB
/
file_ops.go
File metadata and controls
88 lines (83 loc) · 1.76 KB
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
package main
import (
"io"
"os"
"path/filepath"
)
func copyDirectory(source, target string) error {
info, err := os.Stat(source)
if err != nil {
return err
}
if !info.IsDir() {
return copyFileIfExists(source, target)
}
return filepath.WalkDir(source, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
relative, err := filepath.Rel(source, path)
if err != nil {
return err
}
if relative == "." {
return os.MkdirAll(target, info.Mode().Perm())
}
dest := filepath.Join(target, relative)
if entry.IsDir() {
entryInfo, err := entry.Info()
if err != nil {
return err
}
return os.MkdirAll(dest, entryInfo.Mode().Perm())
}
entryInfo, err := entry.Info()
if err != nil {
return err
}
return copyFile(path, dest, entryInfo.Mode().Perm())
})
}
func copyFile(source, target string, perm os.FileMode) error {
input, err := os.Open(source)
if err != nil {
return err
}
defer input.Close()
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
output, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
if err != nil {
return err
}
_, copyErr := io.Copy(output, input)
closeErr := output.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}
func replaceDirectory(target, source string) error {
if err := os.RemoveAll(target); err != nil {
return err
}
if !isDir(source) {
return nil
}
return copyDirectory(source, target)
}
func directorySize(path string) int64 {
var total int64
_ = filepath.WalkDir(path, func(path string, entry os.DirEntry, err error) error {
if err != nil || entry.IsDir() {
return nil
}
info, err := entry.Info()
if err == nil {
total += info.Size()
}
return nil
})
return total
}