-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
89 lines (71 loc) · 1.58 KB
/
database.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
package main
import (
"encoding/json"
"io/fs"
"os"
"path/filepath"
)
type FilePath string
type FileHash string
type FileHashDatabase map[FilePath]FileHash
func SetupFileHashDatabase(paths []string) (FileHashDatabase, error) {
fileHashDatabase := FileHashDatabase{}
//// Walk through all files and directories
for _, path := range paths {
stat, err := os.Stat(path)
if err != nil {
continue
}
if !stat.IsDir() {
// Files
// Calculate hashes & append to new database
addHashFileToDatabase(path, fileHashDatabase)
} else {
// Directories
filepath.WalkDir(
path,
func(path string, d fs.DirEntry, err error) error {
if d.IsDir() || err != nil {
return nil
}
// Calculate hashes & append to new database
addHashFileToDatabase(path, fileHashDatabase)
return nil
},
)
}
}
return fileHashDatabase, nil
}
func addHashFileToDatabase(path string, db FileHashDatabase) error {
hash, err := HashFile(path)
if err != nil {
return err
}
db[FilePath(path)] = FileHash(hash)
return nil
}
func LoadFileHashDatabase(databasePath string) (FileHashDatabase, error) {
dbBytes, err := os.ReadFile(databasePath)
if err != nil {
return nil, err
}
var db FileHashDatabase
err = json.Unmarshal([]byte(dbBytes), &db)
if err != nil {
return nil, err
}
return db, nil
}
func SaveFileHashDatabase(db FileHashDatabase, databasePath string) error {
jsonBytes, err := json.Marshal(db)
if err != nil {
return err
}
fileDB, err := os.Create(databasePath)
if err != nil {
return err
}
fileDB.Write(jsonBytes)
return nil
}