87 lines
2.0 KiB
Go
87 lines
2.0 KiB
Go
package source
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"forever-files/db"
|
|
"forever-files/types"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"path"
|
|
)
|
|
|
|
// the purpose of this package is to gather information about the source files for the backup
|
|
// it will store the information in a database
|
|
// information to gather:
|
|
// - file name
|
|
// - file path
|
|
// - file size
|
|
// - file hash
|
|
// - modified date
|
|
|
|
func GatherInfo(path string, db db.DB) {
|
|
err := walkDir(path, db)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func walkDir(dirPath string, db db.DB) error {
|
|
// get list of files in directory
|
|
directoryEntries, err := os.ReadDir(dirPath)
|
|
if err != nil {
|
|
return fmt.Errorf("error reading directory: %w", err)
|
|
}
|
|
for _, entry := range directoryEntries {
|
|
if entry.IsDir() {
|
|
err = walkDir(path.Join(dirPath, entry.Name()), db)
|
|
if err != nil {
|
|
return fmt.Errorf("error walking directory: %w", err)
|
|
}
|
|
} else {
|
|
// gather info
|
|
fileInfo, err := entry.Info()
|
|
if err != nil {
|
|
log.Default().Printf("error getting file info: %v", err)
|
|
continue
|
|
}
|
|
hash, err := hashFile(path.Join(dirPath, entry.Name()))
|
|
if err != nil {
|
|
log.Default().Printf("error hashing file: %v", err)
|
|
continue
|
|
}
|
|
// store info
|
|
fmt.Printf("Name: %v, Size: %v, Modified Date: %v, Hash: %v\n", fileInfo.Name(), fileInfo.Size(), fileInfo.ModTime(), hash)
|
|
err = db.StoreFile(types.FileMetadata{
|
|
Name: fileInfo.Name(),
|
|
Path: dirPath,
|
|
Size: fileInfo.Size(),
|
|
Hash: hash,
|
|
ModifiedDate: fileInfo.ModTime(),
|
|
BackedUp: false,
|
|
})
|
|
if err != nil {
|
|
log.Default().Printf("error storing file metadata: %v", err)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hashFile(filePath string) ([]byte, error) {
|
|
file, err := os.Open(filePath)
|
|
if err != nil {
|
|
return []byte{}, fmt.Errorf("error opening file for hashing: %w", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
h := sha256.New()
|
|
if _, err := io.Copy(h, file); err != nil {
|
|
return []byte{}, fmt.Errorf("error hashing file: %w", err)
|
|
}
|
|
|
|
return h.Sum(nil), nil
|
|
}
|