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;
10use std::path::{Path, PathBuf};
11
12/// Tag color assignments; lives next to the task files but isn't a task.
13const TAGS_FILE: &str = "tags.md";
14
15/// A project's own data folder, found by walking up from the current directory like `.git`.
16pub const PROJECT_DIR: &str = ".brain";
17
18/// Settings file of older versions (`- track: on|off`); time is always tracked now, so it's only
19/// kept out of the task files.
20const CONFIG_FILE: &str = "config.md";
21
22/// The highest id the folder has given an entry, so ids are never handed out twice: a link to a deleted
23/// entry, left in a file edited by hand or in a copy that was offline, would otherwise point at the
24/// unrelated entry that took its number. Not markdown, so it's never read as an entry.
25const LAST_ID_FILE: &str = "last-id";
26
27/// Subfolder for markdown report exports; never read back.
28const REPORTS_DIR: &str = "reports";
29
30/// The data folder where tasks are stored.
31#[derive(Debug)]
32pub struct Store {
33    /// Absolute or relative path of the folder; created on open.
34    dir: PathBuf,
35    /// While recording (see [`Store::record`]), each file written or deleted as it was before.
36    journal: RefCell<Option<Vec<Change>>>,
37}
38
39/// A file a change wrote or deleted: what it held before and after, `None` where it didn't exist.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Change {
42    /// The file.
43    pub path: PathBuf,
44    /// Its contents before the change.
45    pub before: Option<String>,
46    /// Its contents after the change, filled in by [`Store::recorded`].
47    pub after: Option<String>,
48}
49
50/// Why changes can't be undone.
51#[derive(Debug, PartialEq, Eq)]
52pub enum UndoError {
53    /// Another program, or a later change, wrote this file since: undoing would lose that.
54    ChangedSince(String),
55}
56
57impl std::fmt::Display for UndoError {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        match self {
60            Self::ChangedSince(name) => write!(f, "can't undo: {name} changed since"),
61        }
62    }
63}
64
65impl std::error::Error for UndoError {}
66
67/// Puts the files `changes` wrote back as they were before, last change first. Nothing is written
68/// unless every file still holds what the changes left in it.
69///
70/// # Errors
71///
72/// [`UndoError::ChangedSince`] when a file was changed since, or the error of a write that failed.
73pub fn undo(changes: &[Change]) -> Result<()> {
74    for change in changes {
75        if fs::read_to_string(&change.path).ok() != change.after {
76            let name = change.path.file_name().unwrap_or_default().to_string_lossy().into_owned();
77            return Err(UndoError::ChangedSince(name).into());
78        }
79    }
80    for change in changes.iter().rev() {
81        match &change.before {
82            Some(text) => write_file(&change.path, text)?,
83            None => fs::remove_file(&change.path).with_context(|| format!("removing {}", change.path.display()))?,
84        }
85    }
86    Ok(())
87}
88
89impl Store {
90    /// The nearest `.brain/` in the current directory or above it, so each project's repository
91    /// keeps its own; else the central brain (`$KANBRAIN_DIR`, else the platform data dir, e.g.
92    /// `~/.local/share/kanbrain`).
93    pub fn open() -> Result<Self> {
94        let cwd = std::env::current_dir().context("reading the current directory")?;
95        match find_project(&cwd) {
96            Some(dir) => Self::at(dir),
97            None => Self::at(projects::central_dir()?),
98        }
99    }
100
101    /// The brain of the project registered as `name` (`central` for the central one), from anywhere;
102    /// without a name, the one [`Store::open`] finds.
103    pub fn open_named(name: Option<&str>) -> Result<Self> {
104        match name {
105            None => Self::open(),
106            Some(projects::CENTRAL) => Self::at(projects::central_dir()?),
107            Some(label) => Self::at(projects::find(&projects::central_dir()?, label)?.dir),
108        }
109    }
110
111    /// The project's name: the one on its card (`project.md`), else the folder holding `.brain/`;
112    /// `None` for the central brain.
113    pub fn project(&self) -> Option<String> {
114        if let Some((name, _)) = projects::read_repo_card(&self.dir) {
115            return Some(name);
116        }
117        if self.dir.file_name()? != PROJECT_DIR {
118            return None;
119        }
120        let root = self.dir.parent()?;
121        // `.brain` given relatively has an empty parent: the current directory.
122        let root = if root.as_os_str().is_empty() { std::env::current_dir().ok()? } else { root.to_path_buf() };
123        Some(root.file_name()?.to_string_lossy().into_owned())
124    }
125
126    /// A store in `dir`, created if missing.
127    pub fn at(dir: impl Into<PathBuf>) -> Result<Self> {
128        let dir = dir.into();
129        fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
130        Ok(Self { dir, journal: RefCell::new(None) })
131    }
132
133    /// Starts recording the files written or deleted from now on, so they can be put back (see [`undo`]).
134    pub fn record(&self) {
135        *self.journal.borrow_mut() = Some(Vec::new());
136    }
137
138    /// Stops recording, and returns what was recorded, with what each file holds now.
139    pub fn recorded(&self) -> Vec<Change> {
140        let mut changes = self.journal.borrow_mut().take().unwrap_or_default();
141        for change in &mut changes {
142            change.after = fs::read_to_string(&change.path).ok();
143        }
144        changes.retain(|c| c.before != c.after);
145        changes
146    }
147
148    /// Keeps `path` as it is now, the first time it's about to change while recording.
149    fn remember(&self, path: &Path) {
150        if let Some(journal) = self.journal.borrow_mut().as_mut()
151            && !journal.iter().any(|c| c.path == path)
152        {
153            journal.push(Change { path: path.to_path_buf(), before: fs::read_to_string(path).ok(), after: None });
154        }
155    }
156
157    /// The data folder.
158    pub fn dir(&self) -> &Path {
159        &self.dir
160    }
161
162    /// Where report exports are written.
163    pub fn reports_dir(&self) -> PathBuf {
164        self.dir.join(REPORTS_DIR)
165    }
166
167    /// Returns the parsed tasks plus a warning for every file that could not be read.
168    pub fn load(&self) -> Result<(Vec<Task>, Vec<String>)> {
169        let mut tasks = Vec::new();
170        let mut warnings = Vec::new();
171        let entries = fs::read_dir(&self.dir).with_context(|| format!("reading {}", self.dir.display()))?;
172        for entry in entries {
173            let path = entry?.path();
174            if !is_task_file(&path) {
175                continue;
176            }
177            let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
178            let parsed =
179                fs::read_to_string(&path).map_err(|e| e.to_string()).and_then(|text| Task::from_markdown(&text));
180            match parsed {
181                Ok(mut task) => {
182                    task.path = Some(path);
183                    tasks.push(task);
184                }
185                Err(e) => warnings.push(format!("{name}: {e}")),
186            }
187        }
188        Ok((tasks, warnings))
189    }
190
191    /// Writes atomically and renames the file when the title (slug) changed.
192    pub fn save(&self, task: &mut Task) -> Result<()> {
193        let name = format!("{:04}-{}.md", task.id, slugify(&task.title));
194        let path = self.dir.join(&name);
195        self.remember(&path);
196        if let Some(old) = &task.path {
197            self.remember(old);
198        }
199        write_file(&path, &task.to_markdown())?;
200        // A new title means a new file name: remove the file saved under the old one.
201        if let Some(old) = task.path.replace(path)
202            && Some(&old) != task.path.as_ref()
203        {
204            // The old name only matters if it still exists; a failure here leaves a stale copy, not lost data.
205            let _ = fs::remove_file(old);
206        }
207        Ok(())
208    }
209
210    /// Removes the task's file. Refuses anything outside the data folder.
211    pub fn delete(&self, task: &Task) -> Result<()> {
212        let Some(path) = &task.path else { return Ok(()) };
213        if !path.starts_with(&self.dir) {
214            bail!("refusing to delete {}: not in {}", path.display(), self.dir.display());
215        }
216        self.remember(path);
217        fs::remove_file(path).with_context(|| format!("deleting {}", path.display()))
218    }
219
220    /// The highest id given so far, as `last-id` keeps it; 0 when it's missing (a folder from an older
221    /// version) or unreadable, and then the entries' own ids are all there is to go by.
222    pub fn last_id(&self) -> u32 {
223        fs::read_to_string(self.dir.join(LAST_ID_FILE)).ok().and_then(|text| text.trim().parse().ok()).unwrap_or(0)
224    }
225
226    /// Writes `last-id`.
227    pub fn save_last_id(&self, id: u32) -> Result<()> {
228        let path = self.dir.join(LAST_ID_FILE);
229        write_file(&path, &format!("{id}\n"))
230    }
231
232    /// Reads `tags.md`; no file means no colors assigned yet.
233    pub fn load_tag_colors(&self) -> Result<TagColors> {
234        let path = self.dir.join(TAGS_FILE);
235        match fs::read_to_string(&path) {
236            Ok(text) => Ok(TagColors::parse(&text)),
237            Err(e) if e.kind() == ErrorKind::NotFound => Ok(TagColors::default()),
238            Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
239        }
240    }
241
242    /// Writes `tags.md`.
243    pub fn save_tag_colors(&self, colors: &TagColors) -> Result<()> {
244        let path = self.dir.join(TAGS_FILE);
245        self.remember(&path);
246        write_file(&path, &colors.to_markdown())
247    }
248}
249
250/// Writes `text` to `path`, creating its folder if missing. It goes to a hidden temporary file beside it
251/// first, then takes the file's place in one rename: a crash or a full disk can never leave a file half
252/// written, be it an entry, `tags.md` or a repository's `CLAUDE.md`. The watcher ignores hidden files.
253pub(crate) fn write_file(path: &Path, text: &str) -> Result<()> {
254    let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
255    fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
256    let name = path.file_name().with_context(|| format!("{} isn't a file", path.display()))?;
257    let tmp = dir.join(format!(".{}.tmp", name.to_string_lossy()));
258    fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
259    fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))
260}
261
262/// The nearest `.brain/` folder in `start` or one of its parents.
263pub fn find_project(start: &Path) -> Option<PathBuf> {
264    start.ancestors().map(|dir| dir.join(PROJECT_DIR)).find(|dir| dir.is_dir())
265}
266
267/// Task files are the `.md` files in the folder, except the tag colors, the project's card, the
268/// central brain's list of projects and the old settings.
269fn is_task_file(path: &Path) -> bool {
270    let other = [TAGS_FILE, CONFIG_FILE, projects::PROJECT_FILE, projects::REGISTRY_FILE];
271    path.extension().is_some_and(|e| e == "md") && path.file_name().is_some_and(|n| !other.iter().any(|o| n == *o))
272}
273
274#[cfg(test)]
275#[path = "../tests/store.rs"]
276mod tests;