-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfoldercompare.go
70 lines (59 loc) · 1.54 KB
/
foldercompare.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
package foldercompare
import (
"os"
"path/filepath"
"strings"
)
// FolderSnapshot keeps the state of a folder
type FolderSnapshot struct {
path string
filesMap map[string]os.FileInfo
// size int
}
// CreateSnapshot creates a snapshot of a folder
func CreateSnapshot(folderPath string) (*FolderSnapshot, error) {
// get the absolute path
var absPath, err1 = filepath.Abs(folderPath)
if err1 != nil {
return nil, err1
}
// initialize the snapshot
var snapshot = FolderSnapshot{
path: absPath,
filesMap: map[string]os.FileInfo{},
}
// get folder info
// filepath.Walk flattens a directory to /dir/subdir/filename
var err2 = filepath.Walk(absPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
var key = strings.Replace(path, absPath, "", -1)
if key != "" {
snapshot.filesMap[strings.Replace(path, absPath, "", -1)] = info
}
return nil
})
if err2 != nil {
return nil, err2
}
return &snapshot, nil
}
// CompareSnapshots compares 2 folder states
func CompareSnapshots(firstFolder FolderSnapshot, secondFolder FolderSnapshot) float32 {
var similiarCount float32
for p1, f := range firstFolder.filesMap {
var elem, ok = secondFolder.filesMap[p1]
if ok && f.Size() == elem.Size() {
similiarCount++
}
}
//return 1 - ((similiarCount * 2) / float32(len(firstFolder.filesMap)+len(secondFolder.filesMap)))
return 1 - similiarCount/float32(maxInt(len(firstFolder.filesMap), len(secondFolder.filesMap)))
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}