-
Notifications
You must be signed in to change notification settings - Fork 753
/
Copy pathcp.go
100 lines (86 loc) · 2.14 KB
/
cp.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
package cp
import (
"fmt"
"io"
"os"
)
func TouchFile(filePath string) error {
file, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
return file.Close()
}
func cp(src, dst string) error {
sourceFileStat, err := os.Stat(src)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", src)
}
source, err := os.Open(src)
if err != nil {
return err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, source)
return err
}
func CopyFile(src, dst string) (err error) {
dstTmp := fmt.Sprintf("%s.tmp", dst)
if err := cp(src, dstTmp); err != nil {
return fmt.Errorf("failed to copy file: %s", err)
}
err = os.Rename(dstTmp, dst)
if err != nil {
return fmt.Errorf("failed to rename file: %s", err)
}
si, err := os.Stat(src)
if err != nil {
return fmt.Errorf("failed to stat file: %s", err)
}
err = os.Chmod(dst, si.Mode())
if err != nil {
return fmt.Errorf("failed to chmod file: %s", err)
}
return nil
}
func InstallBinaries(pluginBins []string, hostCNIBinPath string) error {
for _, plugin := range pluginBins {
target := fmt.Sprintf("%s/%s", hostCNIBinPath, plugin)
source := fmt.Sprintf("%s", plugin)
if err := CopyFile(source, target); err != nil {
return fmt.Errorf("Failed to install %s: %s", target, err)
}
fmt.Printf("Installed %s\n", target)
}
return nil
}
func InstallBinariesFromDir(readDir string, hostCNIBinPath string, excludeBins map[string]bool) error {
bins, err := os.ReadDir(readDir)
if err != nil {
return fmt.Errorf("failed to read directory %s, error: %s", readDir, err)
}
for _, file := range bins {
// Only copy files
if !file.Type().IsRegular() {
continue
}
// Exclude binaries in deny-list
if _, ok := excludeBins[file.Name()]; ok {
continue
}
target := fmt.Sprintf("%s/%s", hostCNIBinPath, file.Name())
source := fmt.Sprintf("%s", file.Name())
if err := CopyFile(source, target); err != nil {
return fmt.Errorf("Failed to install %s: %s", target, err)
}
}
return nil
}