| 1 | package memory |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | |
| 8 | fileencoding "reasonix/internal/fileutil/encoding" |
| 9 | ) |
| 10 | |
| 11 | // readIndexIn treats a missing index as empty, but does not hide other read errors. |
| 12 | func readIndexIn(dir string) ([]byte, error) { |
| 13 | existing, err := fileencoding.ReadFileUTF8(filepath.Join(dir, indexFile)) |
| 14 | if os.IsNotExist(err) { |
| 15 | return nil, nil |
| 16 | } |
| 17 | return existing, err |
| 18 | } |
| 19 | |
| 20 | // indexLinesExceptIn returns the managed MEMORY.md lines keyed by filename stem, |
| 21 | // dropping the entry for name and reporting whether it was present. |
| 22 | func indexLinesExceptIn(dir, name string) (map[string]string, bool, error) { |
| 23 | existing, err := readIndexIn(dir) |
| 24 | if err != nil { |
| 25 | return nil, false, err |
| 26 | } |
| 27 | keep := map[string]string{} |
| 28 | contains := false |
| 29 | for line := range strings.SplitSeq(string(existing), "\n") { |
| 30 | if mt := indexLineRe.FindStringSubmatch(line); mt != nil { |
| 31 | if mt[1] == name { |
| 32 | contains = true |
| 33 | } else { |
| 34 | keep[mt[1]] = strings.TrimRight(line, "\r") |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | return keep, contains, nil |
| 39 | } |
| 40 | |
| 41 | func removeMemoryFromDir(path, name string) error { |
| 42 | dir := filepath.Dir(path) |
| 43 | lines, _, err := indexLinesExceptIn(dir, name) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | if err := os.Remove(path); err != nil && !os.IsNotExist(err) { |
| 48 | return err |
| 49 | } |
| 50 | return flushIndexIn(dir, lines) |
| 51 | } |
| 52 |