1use 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
12const TAGS_FILE: &str = "tags.md";
14
15pub const PROJECT_DIR: &str = ".brain";
17
18const CONFIG_FILE: &str = "config.md";
21
22const LAST_ID_FILE: &str = "last-id";
26
27const REPORTS_DIR: &str = "reports";
29
30#[derive(Debug)]
32pub struct Store {
33 dir: PathBuf,
35 journal: RefCell<Option<Vec<Change>>>,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Change {
42 pub path: PathBuf,
44 pub before: Option<String>,
46 pub after: Option<String>,
48}
49
50#[derive(Debug, PartialEq, Eq)]
52pub enum UndoError {
53 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
67pub 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 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 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 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 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 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 pub fn lock(&self) -> Result<BrainLock> {
141 let path = lock_path(&self.dir)?;
142 if let Some(parent) = path.parent() {
143 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
144 }
145 let file = fs::OpenOptions::new()
146 .create(true)
147 .truncate(false)
148 .write(true)
149 .open(&path)
150 .with_context(|| format!("opening {}", path.display()))?;
151 fs4::FileExt::lock(&file).with_context(|| format!("locking {}", path.display()))?;
152 Ok(BrainLock(file))
153 }
154
155 pub fn record(&self) {
157 *self.journal.borrow_mut() = Some(Vec::new());
158 }
159
160 pub fn recorded(&self) -> Vec<Change> {
162 let mut changes = self.journal.borrow_mut().take().unwrap_or_default();
163 for change in &mut changes {
164 change.after = fs::read_to_string(&change.path).ok();
165 }
166 changes.retain(|c| c.before != c.after);
167 changes
168 }
169
170 fn remember(&self, path: &Path) {
172 if let Some(journal) = self.journal.borrow_mut().as_mut()
173 && !journal.iter().any(|c| c.path == path)
174 {
175 journal.push(Change { path: path.to_path_buf(), before: fs::read_to_string(path).ok(), after: None });
176 }
177 }
178
179 pub fn dir(&self) -> &Path {
181 &self.dir
182 }
183
184 pub fn reports_dir(&self) -> PathBuf {
186 self.dir.join(REPORTS_DIR)
187 }
188
189 pub fn load(&self) -> Result<(Vec<Task>, Vec<String>)> {
191 let mut tasks = Vec::new();
192 let mut warnings = Vec::new();
193 let entries = fs::read_dir(&self.dir).with_context(|| format!("reading {}", self.dir.display()))?;
194 for entry in entries {
195 let path = entry?.path();
196 if !is_task_file(&path) {
197 continue;
198 }
199 let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
200 let parsed =
201 fs::read_to_string(&path).map_err(|e| e.to_string()).and_then(|text| Task::from_markdown(&text));
202 match parsed {
203 Ok(mut task) => {
204 task.path = Some(path);
205 tasks.push(task);
206 }
207 Err(e) => warnings.push(format!("{name}: {e}")),
208 }
209 }
210 Ok((tasks, warnings))
211 }
212
213 pub fn save(&self, task: &mut Task) -> Result<()> {
215 let name = format!("{:04}-{}.md", task.id, slugify(&task.title));
216 let path = self.dir.join(&name);
217 self.remember(&path);
218 if let Some(old) = &task.path {
219 self.remember(old);
220 }
221 write_file(&path, &task.to_markdown())?;
222 if let Some(old) = task.path.replace(path)
224 && Some(&old) != task.path.as_ref()
225 {
226 let _ = fs::remove_file(old);
228 }
229 Ok(())
230 }
231
232 pub fn delete(&self, task: &Task) -> Result<()> {
234 let Some(path) = &task.path else { return Ok(()) };
235 if !path.starts_with(&self.dir) {
236 bail!("refusing to delete {}: not in {}", path.display(), self.dir.display());
237 }
238 self.remember(path);
239 fs::remove_file(path).with_context(|| format!("deleting {}", path.display()))
240 }
241
242 pub fn last_id(&self) -> u32 {
245 fs::read_to_string(self.dir.join(LAST_ID_FILE)).ok().and_then(|text| text.trim().parse().ok()).unwrap_or(0)
246 }
247
248 pub fn save_last_id(&self, id: u32) -> Result<()> {
250 let path = self.dir.join(LAST_ID_FILE);
251 write_file(&path, &format!("{id}\n"))
252 }
253
254 pub fn load_tag_colors(&self) -> Result<TagColors> {
256 let path = self.dir.join(TAGS_FILE);
257 match fs::read_to_string(&path) {
258 Ok(text) => Ok(TagColors::parse(&text)),
259 Err(e) if e.kind() == ErrorKind::NotFound => Ok(TagColors::default()),
260 Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
261 }
262 }
263
264 pub fn save_tag_colors(&self, colors: &TagColors) -> Result<()> {
266 let path = self.dir.join(TAGS_FILE);
267 self.remember(&path);
268 write_file(&path, &colors.to_markdown())
269 }
270}
271
272#[derive(Debug)]
274pub struct BrainLock(#[expect(dead_code, reason = "held only for its lock, released on drop")] fs::File);
275
276fn lock_path(dir: &Path) -> Result<PathBuf> {
280 let dir = dir.canonicalize().with_context(|| format!("reading {}", dir.display()))?;
281 let hash = dir
282 .as_os_str()
283 .as_encoded_bytes()
284 .iter()
285 .fold(0xcbf2_9ce4_8422_2325_u64, |hash, &byte| (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3));
286 let cache = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
287 Ok(cache.join("kanbrain").join("locks").join(format!("{hash:016x}.lock")))
288}
289
290pub(crate) fn write_file(path: &Path, text: &str) -> Result<()> {
294 let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
295 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
296 let name = path.file_name().with_context(|| format!("{} isn't a file", path.display()))?;
297 let tmp = dir.join(format!(".{}.tmp", name.to_string_lossy()));
298 fs::write(&tmp, text).with_context(|| format!("writing {}", tmp.display()))?;
299 fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))
300}
301
302pub fn find_project(start: &Path) -> Option<PathBuf> {
304 start.ancestors().map(|dir| dir.join(PROJECT_DIR)).find(|dir| dir.is_dir())
305}
306
307fn is_task_file(path: &Path) -> bool {
310 let other = [TAGS_FILE, CONFIG_FILE, projects::PROJECT_FILE, projects::REGISTRY_FILE];
311 path.extension().is_some_and(|e| e == "md") && path.file_name().is_some_and(|n| !other.iter().any(|o| n == *o))
312}
313
314#[cfg(test)]
315#[path = "../tests/store.rs"]
316mod tests;