forked from kelseyhightower/confd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
90 lines (83 loc) · 2.11 KB
/
util.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
package template
import (
"fmt"
"os"
"path"
"path/filepath"
"github.com/kelseyhightower/confd/log"
)
// fileInfo describes a configuration file and is returned by fileStat.
type fileInfo struct {
Uid uint32
Gid uint32
Mode os.FileMode
Md5 string
}
func appendPrefix(prefix string, keys []string) []string {
s := make([]string, len(keys))
for i, k := range keys {
s[i] = path.Join(prefix, k)
}
return s
}
// isFileExist reports whether path exits.
func isFileExist(fpath string) bool {
if _, err := os.Stat(fpath); os.IsNotExist(err) {
return false
}
return true
}
// sameConfig reports whether src and dest config files are equal.
// Two config files are equal when they have the same file contents and
// Unix permissions. The owner, group, and mode must match.
// It return false in other cases.
func sameConfig(src, dest string) (bool, error) {
if !isFileExist(dest) {
return false, nil
}
d, err := fileStat(dest)
if err != nil {
return false, err
}
s, err := fileStat(src)
if err != nil {
return false, err
}
if d.Uid != s.Uid {
log.Info(fmt.Sprintf("%s has UID %d should be %d", dest, d.Uid, s.Uid))
}
if d.Gid != s.Gid {
log.Info(fmt.Sprintf("%s has GID %d should be %d", dest, d.Gid, s.Gid))
}
if d.Mode != s.Mode {
log.Info(fmt.Sprintf("%s has mode %s should be %s", dest, os.FileMode(d.Mode), os.FileMode(s.Mode)))
}
if d.Md5 != s.Md5 {
log.Info(fmt.Sprintf("%s has md5sum %s should be %s", dest, d.Md5, s.Md5))
}
if d.Uid != s.Uid || d.Gid != s.Gid || d.Mode != s.Mode || d.Md5 != s.Md5 {
return false, nil
}
return true, nil
}
// recursiveFindFiles find files with pattern in the root with depth.
func recursiveFindFiles(root string, pattern string) ([]string, error) {
files := make([]string, 0)
findfile := func(path string, f os.FileInfo, err error) (inner error) {
if err != nil {
return
}
if f.IsDir() {
return
} else if match, innerr := filepath.Match(pattern, f.Name()); innerr == nil && match {
files = append(files, path)
}
return
}
err := filepath.Walk(root, findfile)
if len(files) == 0 {
return files, err
} else {
return files, err
}
}