-
Notifications
You must be signed in to change notification settings - Fork 25
/
utils.go
103 lines (91 loc) · 2.19 KB
/
utils.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
package collector
import (
"errors"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
blog "github.com/ccpaging/log4go"
)
func dirExists(dir string) (bool, error) {
fi, err := os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
// dir doesn't exist
return false, nil
} else {
// other error
blog.Error(err, ": Error while looking up directory: ", dir)
return false, err
}
}
if !fi.IsDir() {
err = errors.New("A file already exists with this name: " + dir)
return false, err
}
return true, nil
}
func CreateDirIfNotExist(dir string) (err error) {
exists, err := dirExists(dir)
if err != nil {
blog.Error(err, ": Error while querying dir: ", dir)
return err
}
if !exists {
err = os.MkdirAll(dir, 0755)
if err != nil {
blog.Error(err, ": Error in creating dir: ", dir)
return err
}
}
return nil
}
func copy(src, dest string) {
// Read all content of src to data
data, err := ioutil.ReadFile(src)
if err != nil {
blog.Error(err, ": Error in reading from file: ", src)
return
}
// Write data to dest
err = ioutil.WriteFile(dest, data, 0755)
if err != nil {
blog.Error(err, ": Error in writing to file: ", dest)
return
}
}
// copyDir copies all files from srcDir to destDir
func CopyDir(srcDir, destDir string) {
existsSrc, err1 := dirExists(srcDir)
existsDest, err2 := dirExists(destDir)
if err1 != nil || err2 != nil {
//detailed error handling inside dirExists
return
}
if !existsSrc || !existsDest {
blog.Error("Src/Dest directories don't exist: srcdir: " + srcDir + " destdir: " + destDir)
return
}
files, err := ioutil.ReadDir(srcDir)
if err != nil {
blog.Error(err, ": Error in reading contents of ", srcDir)
return
}
for _, file := range files {
copy(srcDir+"/"+file.Name(), destDir+"/"+file.Name())
}
}
// CopyDirTree copies all files from srcDir to destDir
func CopyDirTree(srcDir, destDir string) {
srcs, err := filepath.Glob(srcDir)
if err != nil {
blog.Exit(err, ": Error in generating matches for", srcDir)
}
args := []string{"-rp"}
dirs := append(args, append(srcs, destDir)...)
cpCmd := exec.Command("cp", dirs...)
err = cpCmd.Run()
if err != nil {
blog.Exit(err, ": Error in copying", srcDir, " to ", destDir)
}
}