PackageManager just because
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

128 lines
2.0 KiB

package Filesystem
import (
"PackageManager/Client/Database"
"crypto/md5"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func HashFile(path string) (string, error) {
var (
Md5Hash string
hashBytes [16]byte
file *os.File
e error
)
file, e = os.Open(path)
if e != nil {
panic(e)
}
defer file.Close()
body, e := ioutil.ReadAll(file)
if e != nil {
panic(e)
}
//Get the 16 bytes hash
hashBytes = md5.Sum(body)
//Convert the bytes to a string
Md5Hash = fmt.Sprintf("%x", hashBytes)
return Md5Hash, nil
}
func UpdateFilesystemHash() error {
var (
fileHash string
rows []Database.FilesystemHashRow
e error
)
e = filepath.Walk(".", func(path string, info os.FileInfo, e error) error {
if e != nil {
return e
}
// Ignore hidden files
if strings.HasPrefix(info.Name(), ".") || strings.HasPrefix(path, ".") {
return nil
}
// Ignore directories
if info.IsDir() {
return nil
}
fileHash, e = HashFile(path)
if e != nil {
return e
}
rows = append(rows, Database.FilesystemHashRow{
Path: path,
Hash: fileHash,
UpdatedAt: info.ModTime(),
})
// TODO: If len(rows) > x, update the db and clear out rows, and continue
return nil
})
if e != nil {
panic(e)
}
return Database.FindOrCreateFileHash(rows)
}
func GetFilesystemDiff() error {
var (
fileHash string
hashes []string = []string{}
e error
)
e = filepath.Walk(".", func(path string, info os.FileInfo, e error) error {
if e != nil {
return e
}
// Ignore hidden files
if strings.HasPrefix(info.Name(), ".") || strings.HasPrefix(path, ".") {
return nil
}
// Ignore directories
if info.IsDir() {
return nil
}
fileHash, e = HashFile(path)
if e != nil {
return e
}
hashes = append(hashes, fileHash)
// TODO: If len(rows) > x, update the db and clear out rows, and continue
return nil
})
dirty, e := Database.FindModifiedFiles(hashes)
fmt.Println(dirty)
return e
}