Files
2026-10-11 21:36:20 -06:00

116 lines
2.9 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
)
type FileEntry struct {
FilePath string `json:"file_path"`
FileName string `json:"file_name"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
}
type Progress struct {
Current string
Indexed int
Skipped int
Errors int
Bytes int64
}
// BuildIndex walks root, hashing regular files of at least minSize bytes.
// onProgress (optional) is called after each file is handled.
func BuildIndex(ctx context.Context, root string, minSize int64, onProgress func(Progress)) ([]FileEntry, Progress, error) {
entries := []FileEntry{}
var p Progress
skip := map[string]bool{
filepath.Join(root, indexFileName): true,
filepath.Join(root, indexFileName+".tmp"): true,
filepath.Join(root, configFileName): true,
filepath.Join(root, logFileName): true,
}
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if ctxErr := ctx.Err(); ctxErr != nil {
return ctxErr
}
if err != nil {
p.Errors++
if d != nil && d.IsDir() {
return fs.SkipDir
}
return nil
}
if d.IsDir() {
if path == filepath.Join(root, trashDir) {
return fs.SkipDir
}
return nil
}
if !d.Type().IsRegular() || skip[path] {
return nil
}
info, err := d.Info()
if err != nil {
p.Errors++
return nil
}
p.Current = path
if info.Size() < minSize {
p.Skipped++
} else if hash, err := HashFile(path, info.Size()); err != nil {
p.Errors++
} else {
entries = append(entries, FileEntry{path, d.Name(), info.Size(), hash})
p.Indexed++
p.Bytes += info.Size()
}
if onProgress != nil {
onProgress(p)
}
return nil
})
return entries, p, err
}
// WriteIndex writes the index atomically as a JSON array and returns its path.
func WriteIndex(root string, entries []FileEntry) (string, error) {
out := filepath.Join(root, indexFileName)
data, err := json.MarshalIndent(entries, "", " ")
if err != nil {
return "", err
}
tmp := out + ".tmp"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
return "", err
}
return out, os.Rename(tmp, out)
}
// LoadIndex reads an existing index, dropping entries whose files no longer exist
// or whose size changed. It returns the entries and the number dropped.
func LoadIndex(root string) ([]FileEntry, int, string, error) {
path := filepath.Join(root, indexFileName)
data, err := os.ReadFile(path)
if err != nil {
return nil, 0, path, err
}
var all []FileEntry
if err := json.Unmarshal(data, &all); err != nil {
return nil, 0, path, fmt.Errorf("parsing %s: %w", indexFileName, err)
}
entries := make([]FileEntry, 0, len(all))
for _, e := range all {
if st, err := os.Lstat(e.FilePath); err == nil && st.Mode().IsRegular() && st.Size() == e.FileSize {
entries = append(entries, e)
}
}
return entries, len(all) - len(entries), path, nil
}