Skip to main content

kanbrain_core/
store.rs

1//! The data folder: one `NNNN-slug.md` file per task, `tags.md`, and exported reports in `reports/`.
2
3use crate::model::{Task, slugify};
4use crate::projects;
5use crate::tags::TagColors;
6use anyhow::{Context, Result, bail};
7use std::cell::RefCell;
8use std::fs;
9use std::io::{ErrorKind, Write};
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicU32, Ordering};
12use std::time::Duration;
13
14/// Tag color assignments; lives next to the task files but isn't a task.
15pub(crate) const TAGS_FILE: &str = "tags.md";
16
17/// A project's own data folder, found by walking up from the current directory like `.git`.
18pub const PROJECT_DIR: &str = ".brain";
19
20/// The highest id the folder has given an entry, so ids are never handed out twice: a link to a deleted
21/// entry, left in a file edited by hand or in a copy that was offline, would otherwise point at the
22/// unrelated entry that took its number. Not markdown, so it's never read as an entry.
23pub(crate) const LAST_ID_FILE: &str = "last-id";
24
25/// Subfolder for markdown report exports; never read back.
26pub(crate) const REPORTS_DIR: &str = "reports";
27
28/// The data folder where tasks are stored.
29#[derive(Debug)]
30pub struct Store {
31    /// Absolute or relative path of the folder; created on open.
32    dir: PathBuf,
33    /// While recording (see [`Store::record`]), each file written or deleted as it was before.
34    journal: RefCell<Option<Vec<Change>>>,
35}
36
37/// A file a change wrote or deleted: what it held before and after, `None` where it didn't exist.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Change {
40    /// The file.
41    pub path: PathBuf,
42    /// Its contents before the change.
43    pub before: Option<String>,
44    /// Its contents after the change, filled in by [`Store::recorded`].
45    pub after: Option<String>,
46}
47
48/// Why changes can't be undone.
49#[derive(Debug, PartialEq, Eq)]
50pub enum UndoError {
51    /// Another program, or a later change, wrote this file since: undoing would lose that.
52    ChangedSince(String),
53}
54
55impl std::fmt::Display for UndoError {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            Self::ChangedSince(name) => write!(f, "can't undo: {name} changed since"),
59        }
60    }
61}
62
63impl std::error::Error for UndoError {}
64
65/// Puts the files `changes` wrote back as they were before, last change first. Nothing is written
66/// unless every file still holds what the changes left in it.
67///
68/// # Errors
69///
70/// [`UndoError::ChangedSince`] when a file was changed since, or the error of a write that failed.
71pub fn undo(changes: &[Change]) -> Result<()> {
72    for change in changes {
73        if fs::read_to_string(&change.path).ok() != change.after {
74            let name = change.path.file_name().unwrap_or_default().to_string_lossy().into_owned();
75            return Err(UndoError::ChangedSince(name).into());
76        }
77    }
78    for change in changes.iter().rev() {
79        match &change.before {
80            Some(text) => write_file(&change.path, text)?,
81            None => fs::remove_file(&change.path).with_context(|| format!("removing {}", change.path.display()))?,
82        }
83    }
84    Ok(())
85}
86
87impl Store {
88    /// The nearest `.brain/` in the current directory or above it, so each project's repository
89    /// keeps its own; else the central brain (`$KANBRAIN_DIR`, else the platform data dir, e.g.
90    /// `~/.local/share/kanbrain`).
91    pub fn open() -> Result<Self> {
92        let cwd = std::env::current_dir().context("reading the current directory")?;
93        match find_project(&cwd) {
94            Some(dir) => Self::at(dir),
95            None => Self::at(projects::central_dir()?),
96        }
97    }
98
99    /// The brain of the project registered as `name` (`central` for the central one), from anywhere;
100    /// without a name, the one [`Store::open`] finds.
101    pub fn open_named(name: Option<&str>) -> Result<Self> {
102        match name {
103            None => Self::open(),
104            Some(projects::CENTRAL) => Self::at(projects::central_dir()?),
105            Some(label) => {
106                let central = projects::central_dir()?;
107                let repo = match projects::find(&central, label) {
108                    Ok(repo) => repo,
109                    // In any case, as projects' names are, unless a project has it.
110                    Err(_) if label.eq_ignore_ascii_case(projects::CENTRAL) => return Self::at(central),
111                    Err(e) => return Err(e),
112                };
113                if !repo.dir.is_dir() {
114                    bail!("{} is gone: `kb --project {label} deinit` takes it out", repo.dir.display());
115                }
116                Self::at(repo.dir)
117            }
118        }
119    }
120
121    /// The project's name: the one on its card (`project.md`), else the folder holding `.brain/`;
122    /// `None` for the central brain.
123    pub fn project(&self) -> Option<String> {
124        if let Some(projects::RepoCard { project: name, .. }) = projects::read_repo_card(&self.dir) {
125            return Some(name);
126        }
127        if self.dir.file_name()? != PROJECT_DIR {
128            return None;
129        }
130        let root = self.dir.parent()?;
131        // `.brain` given relatively has an empty parent: the current directory.
132        let root = if root.as_os_str().is_empty() { std::env::current_dir().ok()? } else { root.to_path_buf() };
133        Some(root.file_name()?.to_string_lossy().into_owned())
134    }
135
136    /// A store in `dir`, created if missing.
137    pub fn at(dir: impl Into<PathBuf>) -> Result<Self> {
138        let dir = dir.into();
139        if !dir.is_dir() {
140            fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
141            // A brain made now is in this version's format: without the file it would read as format 1 once there's
142            // a 2, and have the migrations it doesn't need run over it.
143            let format = format!("{}\n", crate::migrate::FORMAT);
144            write_file(&dir.join(crate::migrate::FORMAT_FILE), &format)?;
145        }
146        Ok(Self { dir, journal: RefCell::new(None) })
147    }
148
149    /// Takes this brain's write lock, waiting while another program holds it, until the returned guard is
150    /// dropped. Each `kb` that changes entries reads every file, changes some and writes them back: an agent
151    /// running several at once (one per subagent) would otherwise have the last one write over the others'
152    /// changes, or two `add`s take the same id. The lock is released when the process ends, however it ends.
153    ///
154    /// The lock file lives in the user's cache folder, named after the brain's folder, so `.brain/` (often
155    /// committed) gets no extra file. Taking it again on a thread that holds it gets a guard that does nothing:
156    /// the app holds every brain's while it acts, and managing projects takes some of them itself.
157    pub fn lock(&self) -> Result<BrainLock> {
158        let path = lock_path(&self.dir)?;
159        if HELD.with(|held| held.borrow().contains(&path)) {
160            return Ok(BrainLock { file: None, path });
161        }
162        if let Some(parent) = path.parent() {
163            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
164        }
165        let mut file = fs::OpenOptions::new()
166            .create(true)
167            .truncate(false)
168            .write(true)
169            .open(&path)
170            .with_context(|| format!("opening {}", path.display()))?;
171        fs4::FileExt::lock(&file).with_context(|| format!("locking {}", path.display()))?;
172        // Which brain it's for, in one write ending in a newline, so the cache can be tidied once the brain is gone.
173        if file.metadata().is_ok_and(|m| m.len() == 0) {
174            let brain = self.dir.canonicalize().with_context(|| format!("reading {}", self.dir.display()))?;
175            file.write_all(format!("{}\n", brain.display()).as_bytes())
176                .with_context(|| format!("writing {}", path.display()))?;
177        }
178        // Only once nothing can fail: an error drops `file`, releasing the lock, and a path left in `HELD` would
179        // have every later `lock` on this thread hand back a guard that holds nothing.
180        HELD.with(|held| held.borrow_mut().push(path.clone()));
181        forget_gone_temp_brains(&path);
182        forget_cut_writes(&self.dir);
183        Ok(BrainLock { file: Some(file), path })
184    }
185
186    /// Starts recording the files written or deleted from now on, so they can be put back (see [`undo`]).
187    pub fn record(&self) {
188        *self.journal.borrow_mut() = Some(Vec::new());
189    }
190
191    /// Stops recording, and returns what was recorded, with what each file holds now.
192    pub fn recorded(&self) -> Vec<Change> {
193        let mut changes = self.journal.borrow_mut().take().unwrap_or_default();
194        for change in &mut changes {
195            change.after = fs::read_to_string(&change.path).ok();
196        }
197        changes.retain(|c| c.before != c.after);
198        changes
199    }
200
201    /// Keeps `path` as it is now, the first time it's about to change while recording.
202    fn remember(&self, path: &Path) {
203        if let Some(journal) = self.journal.borrow_mut().as_mut()
204            && !journal.iter().any(|c| c.path == path)
205        {
206            journal.push(Change { path: path.to_path_buf(), before: fs::read_to_string(path).ok(), after: None });
207        }
208    }
209
210    /// The data folder.
211    pub fn dir(&self) -> &Path {
212        &self.dir
213    }
214
215    /// Where report exports are written.
216    pub fn reports_dir(&self) -> PathBuf {
217        self.dir.join(REPORTS_DIR)
218    }
219
220    /// The ids of the entries' files, by their names (`0005-fix-login.md` is 5), read or not: an entry whose file
221    /// doesn't parse is still there, and links to it must stay.
222    pub(crate) fn file_ids(&self) -> std::collections::HashSet<u32> {
223        let Ok(entries) = fs::read_dir(&self.dir) else { return std::collections::HashSet::new() };
224        entries
225            .filter_map(|entry| entry.ok()?.path().file_name()?.to_str().map(str::to_string))
226            .filter(|name| is_task_file(Path::new(name)))
227            .filter_map(|name| name.split('-').next()?.parse().ok())
228            .collect()
229    }
230
231    /// Returns the parsed tasks plus a warning for every file that could not be read.
232    pub fn load(&self) -> Result<(Vec<Task>, Vec<String>)> {
233        // Every read goes through here: a brain a newer kanbrain wrote is refused before anything misreads it.
234        crate::migrate::check(&self.dir)?;
235        let mut tasks = Vec::new();
236        let mut warnings = Vec::new();
237        let entries = fs::read_dir(&self.dir).with_context(|| format!("reading {}", self.dir.display()))?;
238        for entry in entries {
239            let path = entry?.path();
240            if !is_task_file(&path) {
241                continue;
242            }
243            let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
244            let parsed = read_text(&path).map_err(|e| e.to_string()).and_then(|text| Task::from_markdown(&text));
245            match parsed {
246                Ok(mut task) => {
247                    task.path = Some(path);
248                    tasks.push(task);
249                }
250                Err(e) => warnings.push(format!("{name}: {e}")),
251            }
252        }
253        Ok((tasks, warnings))
254    }
255
256    /// Writes atomically and renames the file when the title (slug) changed.
257    pub fn save(&self, task: &mut Task) -> Result<()> {
258        let path = self.dir.join(file_name(task));
259        // A name that differs only in case (renamed by hand or by a sync tool) is kept: on a case-insensitive file
260        // system it's the same file, and removing the "old" one after writing the new would delete the only copy.
261        let path = match &task.path {
262            Some(old) if old.parent() == Some(self.dir.as_path()) && same_ignoring_case(old, &path) => old.clone(),
263            _ => path,
264        };
265        // A file there that isn't this entry's is one that didn't parse (a sync conflict's, a hand edit's): writing
266        // over it would lose what it holds.
267        if task.path.as_ref() != Some(&path) && path.exists() {
268            bail!("{} is there and couldn't be read as #{}: fix or move it, then try again", path.display(), task.id);
269        }
270        self.remember(&path);
271        if let Some(old) = &task.path {
272            self.remember(old);
273        }
274        write_file(&path, &task.to_markdown())?;
275        // A new title means a new file name: remove the file saved under the old one.
276        if let Some(old) = task.path.replace(path)
277            && Some(&old) != task.path.as_ref()
278        {
279            // The old name only matters if it still exists; a failure here leaves a stale copy, not lost data.
280            let _ = fs::remove_file(old);
281        }
282        Ok(())
283    }
284
285    /// Removes the task's file. Refuses anything outside the data folder.
286    pub fn delete(&self, task: &Task) -> Result<()> {
287        let Some(path) = &task.path else { return Ok(()) };
288        if !path.starts_with(&self.dir) {
289            bail!("refusing to delete {}: not in {}", path.display(), self.dir.display());
290        }
291        self.remember(path);
292        fs::remove_file(path).with_context(|| format!("deleting {}", path.display()))
293    }
294
295    /// The highest id given so far, as `last-id` keeps it; 0 when it's missing (a folder from an older
296    /// version) or unreadable, and then the entries' own ids are all there is to go by.
297    pub fn last_id(&self) -> u32 {
298        read_text(&self.dir.join(LAST_ID_FILE)).ok().and_then(|text| text.trim().parse().ok()).unwrap_or(0)
299    }
300
301    /// Writes `last-id`.
302    pub fn save_last_id(&self, id: u32) -> Result<()> {
303        let path = self.dir.join(LAST_ID_FILE);
304        write_file(&path, &format!("{id}\n"))
305    }
306
307    /// Reads `tags.md`; no file means no colors assigned yet.
308    pub fn load_tag_colors(&self) -> Result<TagColors> {
309        let path = self.dir.join(TAGS_FILE);
310        match read_text(&path) {
311            Ok(text) => Ok(TagColors::parse(&text)),
312            Err(e) if e.kind() == ErrorKind::NotFound => Ok(TagColors::default()),
313            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
314        }
315    }
316
317    /// Writes `tags.md`.
318    pub fn save_tag_colors(&self, colors: &TagColors) -> Result<()> {
319        let path = self.dir.join(TAGS_FILE);
320        self.remember(&path);
321        write_file(&path, &colors.to_markdown())
322    }
323}
324
325thread_local! {
326    /// The lock files this thread holds. `flock` on a second handle of the same file waits for the first, so a
327    /// thread taking a lock it holds would wait for itself forever.
328    static HELD: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
329}
330
331/// A brain's write lock, held until dropped (see [`Store::lock`]).
332#[derive(Debug)]
333pub struct BrainLock {
334    /// The locked file, whose handle holds the lock; `None` for a lock the thread already held.
335    file: Option<fs::File>,
336    /// The lock file.
337    path: PathBuf,
338}
339
340impl Drop for BrainLock {
341    fn drop(&mut self) {
342        // The handle closes after this, releasing the lock.
343        if self.file.is_some() {
344            HELD.with(|held| held.borrow_mut().retain(|p| *p != self.path));
345        }
346    }
347}
348
349/// Where the lock of the brain in `dir` is: `<cache>/kanbrain/locks/<key>.lock` (see [`cache_dir_of`]).
350fn lock_path(dir: &Path) -> Result<PathBuf> {
351    Ok(cache_dir_of(dir, "locks")?.with_extension("lock"))
352}
353
354/// `<cache>/kanbrain/<kind>/<key>`, where the user's cache keeps something about the brain in `dir` (its lock, its
355/// backups) out of `.brain/`, which is often committed. The key is [`fnv1a`] of the folder's canonical path, which
356/// two `kb` builds must agree on. A brain in
357/// the system's temporary folder (a test's, a try-out) keeps it in `<tmp>/kanbrain-cache/<kind>/<key>` instead, so
358/// a throwaway brain leaves nothing in the user's cache, and what it leaves there goes once it's gone (see
359/// [`forget_gone_temp_brains`]); under `/tmp`, in `/tmp/kanbrain-cache`.
360pub(crate) fn cache_dir_of(dir: &Path, kind: &str) -> Result<PathBuf> {
361    let dir = dir.canonicalize().with_context(|| format!("reading {}", dir.display()))?;
362    let hash = fnv1a(dir.as_os_str().as_encoded_bytes());
363    // `/tmp` first, whatever `TMPDIR` says: two processes on one brain must agree on its lock, and some set
364    // `TMPDIR` to a folder inside `/tmp` (Claude Code does) while others don't.
365    let tmp = std::env::temp_dir();
366    let roots = [cfg!(unix).then(|| PathBuf::from("/tmp")), Some(tmp.clone())];
367    let cache = roots
368        .into_iter()
369        .flatten()
370        .filter_map(|root| root.canonicalize().ok())
371        .find(|root| dir.starts_with(root))
372        .map_or_else(|| dirs::cache_dir().unwrap_or(tmp).join("kanbrain"), |root| root.join(TEMP_CACHE));
373    Ok(cache.join(kind).join(format!("{hash:016x}")))
374}
375
376/// The folder of the system's temporary folder where brains there keep what the user's cache would.
377const TEMP_CACHE: &str = "kanbrain-cache";
378
379/// The 64-bit FNV-1a hash of `bytes`: for what must come out the same from every build, which std's hasher doesn't
380/// promise across Rust versions.
381pub(crate) fn fnv1a(bytes: &[u8]) -> u64 {
382    bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3))
383}
384
385/// Deletes what brains in the system's temporary folder left in its cache once each is gone, as a test's or a
386/// try-out's is: nothing can ask for it after. Run as one of them is locked (`lock`, its lock file), so that cache
387/// tidies itself as throwaway brains come and go; the user's own is left alone. A lock file names its brain on its
388/// first line; one that doesn't yet (being written, or from an older version) is kept.
389fn forget_gone_temp_brains(lock: &Path) {
390    let Some(locks) = lock.parent().filter(|locks| locks.parent().is_some_and(|c| c.ends_with(TEMP_CACHE))) else {
391        return;
392    };
393    let Ok(entries) = fs::read_dir(locks) else { return };
394    for entry in entries.flatten() {
395        let path = entry.path();
396        let named = fs::read_to_string(&path).ok().and_then(|text| Some(PathBuf::from(text.strip_suffix('\n')?)));
397        if named.is_some_and(|brain| !brain.exists()) {
398            // Another `kb` may be tidying too: whichever gets there first deletes them.
399            let _ = fs::remove_file(&path);
400            if let (Some(cache), Some(key)) = (locks.parent(), path.file_stem()) {
401                let _ = fs::remove_dir_all(cache.join("backups").join(key));
402            }
403        }
404    }
405}
406
407/// How old a write's temporary file has to be to count as a crash's leftover: no write takes that long.
408const CUT_WRITE_AGE: Duration = Duration::from_secs(60 * 60);
409
410/// Deletes the temporary files of writes a crash cut short (see [`write_file`]) in the brain in `dir` and its
411/// folders, best effort. Each has a name of its own, so no later write replaces it. Run once its lock is taken,
412/// when nothing else writes there; the age spares writes made without the lock, as `init` does.
413fn forget_cut_writes(dir: &Path) {
414    let folders = fs::read_dir(dir).into_iter().flatten().flatten().filter(|e| e.file_type().is_ok_and(|t| t.is_dir()));
415    let files = std::iter::once(dir.to_path_buf())
416        .chain(folders.map(|folder| folder.path()))
417        .filter_map(|folder| fs::read_dir(folder).ok())
418        .flatten()
419        .flatten();
420    for file in files {
421        let name = file.file_name();
422        let name = name.to_string_lossy();
423        let age = file.metadata().and_then(|m| m.modified()).ok().and_then(|at| at.elapsed().ok());
424        if is_cut_write(&name) && age.is_some_and(|age| age > CUT_WRITE_AGE) {
425            let _ = fs::remove_file(file.path());
426        }
427    }
428}
429
430/// Whether `name` is a temporary file of [`write_file`]'s: `.NAME.PID-N.tmp`, or `.NAME.tmp` as versions before 0.4.0
431/// named them, where NAME is a file kanbrain writes (`*.md`, `format`, `last-id`). A central brain may be a notes
432/// vault, where other programs leave hidden `.tmp` files of their own.
433fn is_cut_write(name: &str) -> bool {
434    let Some(written) = name.strip_prefix('.').and_then(|n| n.strip_suffix(".tmp")) else { return false };
435    let written = match written.rsplit_once('.') {
436        Some((file, write)) if write.split_once('-').is_some_and(|(pid, n)| is_number(pid) && is_number(n)) => file,
437        _ => written,
438    };
439    Path::new(written).extension().is_some_and(|ext| ext == "md")
440        || written == crate::migrate::FORMAT_FILE
441        || written == LAST_ID_FILE
442}
443
444/// Whether `text` is digits only, and some.
445fn is_number(text: &str) -> bool {
446    !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
447}
448
449/// What the cache keeps about the brain in `dir`, its lock file and its backups, to delete once the brain is: nothing
450/// asks for them after. Found while the brain is still there, since the key comes from its canonical path.
451pub(crate) fn cache_of(dir: &Path) -> Result<[PathBuf; 2]> {
452    Ok([lock_path(dir)?, cache_dir_of(dir, "backups")?])
453}
454
455/// Reads a text file people may edit, without the byte-order mark some editors (Notepad, older Windows ones) put
456/// first: left in, it hides a file's first line, an entry's `# title` among them.
457pub(crate) fn read_text(path: &Path) -> std::io::Result<String> {
458    let text = fs::read_to_string(path)?;
459    Ok(match text.strip_prefix('\u{feff}') {
460        Some(rest) => rest.to_string(),
461        None => text,
462    })
463}
464
465/// Writes `text` to `path`, creating its folder if missing. It goes to a hidden temporary file beside it
466/// first, flushed to disk, then takes the file's place in one rename: a crash or a full disk can never leave a
467/// file half written, be it an entry, `tags.md` or a repository's `CLAUDE.md`. The temporary file's name is this
468/// write's own, so two programs writing the same file can't swap halves of each other's. The watcher ignores
469/// hidden files.
470pub(crate) fn write_file(path: &Path, text: &str) -> Result<()> {
471    static WRITES: AtomicU32 = AtomicU32::new(0);
472    let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
473    fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
474    let name = path.file_name().with_context(|| format!("{} isn't a file", path.display()))?;
475    let write = WRITES.fetch_add(1, Ordering::Relaxed);
476    let tmp = dir.join(format!(".{}.{}-{write}.tmp", name.to_string_lossy(), std::process::id()));
477    let written = fs::File::create(&tmp).and_then(|mut file| {
478        file.write_all(text.as_bytes())?;
479        file.sync_all()
480    });
481    if let Err(e) = written.and_then(|()| fs::rename(&tmp, path)) {
482        let _ = fs::remove_file(&tmp);
483        return Err(e).with_context(|| format!("writing {}", path.display()));
484    }
485    Ok(())
486}
487
488/// The name `task`'s file is saved under: `0005-fix-login.md`.
489pub(crate) fn file_name(task: &Task) -> String {
490    format!("{:04}-{}.md", task.id, slugify(&task.title))
491}
492
493/// Whether `name` starts as [`file_name`] names an entry: four digits or more, `-`, a lowercase ASCII letter (a slug's).
494/// A slug starting with a digit is left out, so that a notes vault's `2026-10-15.md` isn't taken for one.
495pub(crate) fn entry_named(name: &str) -> bool {
496    let digits = name.chars().take_while(char::is_ascii_digit).count();
497    digits >= 4
498        && name[digits..].strip_prefix('-').is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_lowercase()))
499}
500
501/// Whether two file names in one folder are the same but for case, which a case-insensitive file system (macOS,
502/// Windows) takes for one file.
503fn same_ignoring_case(a: &Path, b: &Path) -> bool {
504    a.file_name()
505        .zip(b.file_name())
506        .is_some_and(|(a, b)| a.to_string_lossy().eq_ignore_ascii_case(&b.to_string_lossy()))
507}
508
509/// The nearest `.brain/` folder in `start` or one of its parents.
510pub fn find_project(start: &Path) -> Option<PathBuf> {
511    start.ancestors().map(|dir| dir.join(PROJECT_DIR)).find(|dir| dir.is_dir())
512}
513
514/// Task files are the `.md` files in the folder, except the tag colors, the project's card and the
515/// central brain's list of projects.
516fn is_task_file(path: &Path) -> bool {
517    let other = [TAGS_FILE, projects::PROJECT_FILE, projects::REGISTRY_FILE];
518    path.extension().is_some_and(|e| e == "md") && path.file_name().is_some_and(|n| !other.iter().any(|o| n == *o))
519}
520
521#[cfg(test)]
522#[path = "../tests/store.rs"]
523mod tests;