62159
Sy
symb / files
symb / internal / delta / snapshot.go
2.1 KB
1package delta 2 3import ( 4 "io/fs" 5 "os" 6 "path/filepath" 7 "time" 8) 9 10// FileSnapshot holds mtime+size+content for change detection and undo. 11type FileSnapshot struct { 12 ModTime time.Time 13 Size int64 14 Content []byte // pre-read for undo; nil for large files 15} 16 17// maxSnapshotFileSize is the max file size we pre-read for undo (1 MB). 18const maxSnapshotFileSize = 1 << 20 19 20// skipDirs are directories skipped during snapshot walks. 21var skipDirs = map[string]bool{ 22 ".git": true, "node_modules": true, "__pycache__": true, 23 ".venv": true, "vendor": true, ".cache": true, ".next": true, 24 "dist": true, "build": true, "target": true, 25} 26 27// SnapshotDir walks root and returns a map of relative path -> FileSnapshot. 28// Files under maxSnapshotFileSize have their content pre-read for undo. 29func SnapshotDir(root string) map[string]FileSnapshot { 30 snap := make(map[string]FileSnapshot) 31 _ = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { 32 if err != nil { 33 return nil 34 } 35 if d.IsDir() { 36 if skipDirs[d.Name()] { 37 return filepath.SkipDir 38 } 39 return nil 40 } 41 rel, err := filepath.Rel(root, path) 42 if err != nil { 43 return nil 44 } 45 info, err := d.Info() 46 if err != nil { 47 return nil 48 } 49 fs := FileSnapshot{ModTime: info.ModTime(), Size: info.Size()} 50 if info.Size() <= maxSnapshotFileSize { 51 fs.Content, _ = os.ReadFile(path) 52 } 53 snap[rel] = fs 54 return nil 55 }) 56 return snap 57} 58 59// RecordDeltas compares pre/post snapshots and records deltas for undo. 60func RecordDeltas(dt *Tracker, root string, pre, post map[string]FileSnapshot) { 61 // New or modified files. 62 for rel, postInfo := range post { 63 absPath := filepath.Join(root, rel) 64 preInfo, existed := pre[rel] 65 if !existed { 66 dt.RecordCreate(absPath) 67 continue 68 } 69 if preInfo.ModTime != postInfo.ModTime || preInfo.Size != postInfo.Size { 70 dt.RecordModify(absPath, preInfo.Content) 71 } 72 } 73 // Deleted files — existed in pre but not in post. 74 for rel, preInfo := range pre { 75 if _, exists := post[rel]; !exists { 76 absPath := filepath.Join(root, rel) 77 if preInfo.Content != nil { 78 dt.RecordModify(absPath, preInfo.Content) 79 } 80 } 81 } 82}