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, Write};
10use std::path::{Path, PathBuf};
11use std::sync::atomic::{AtomicU32, Ordering};
12use std::time::Duration;
13
14pub(crate) const TAGS_FILE: &str = "tags.md";
16
17pub const PROJECT_DIR: &str = ".brain";
19
20pub(crate) const LAST_ID_FILE: &str = "last-id";
24
25pub(crate) const REPORTS_DIR: &str = "reports";
27
28#[derive(Debug)]
30pub struct Store {
31 dir: PathBuf,
33 journal: RefCell<Option<Vec<Change>>>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Change {
40 pub path: PathBuf,
42 pub before: Option<String>,
44 pub after: Option<String>,
46}
47
48#[derive(Debug, PartialEq, Eq)]
50pub enum UndoError {
51 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
65pub 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 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 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(¢ral, label) {
108 Ok(repo) => repo,
109 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 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 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 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 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 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 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 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 pub fn record(&self) {
188 *self.journal.borrow_mut() = Some(Vec::new());
189 }
190
191 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 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 pub fn dir(&self) -> &Path {
212 &self.dir
213 }
214
215 pub fn reports_dir(&self) -> PathBuf {
217 self.dir.join(REPORTS_DIR)
218 }
219
220 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 pub fn load(&self) -> Result<(Vec<Task>, Vec<String>)> {
233 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 pub fn save(&self, task: &mut Task) -> Result<()> {
258 let path = self.dir.join(file_name(task));
259 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 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 if let Some(old) = task.path.replace(path)
277 && Some(&old) != task.path.as_ref()
278 {
279 let _ = fs::remove_file(old);
281 }
282 Ok(())
283 }
284
285 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 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 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 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 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 static HELD: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
329}
330
331#[derive(Debug)]
333pub struct BrainLock {
334 file: Option<fs::File>,
336 path: PathBuf,
338}
339
340impl Drop for BrainLock {
341 fn drop(&mut self) {
342 if self.file.is_some() {
344 HELD.with(|held| held.borrow_mut().retain(|p| *p != self.path));
345 }
346 }
347}
348
349fn lock_path(dir: &Path) -> Result<PathBuf> {
351 Ok(cache_dir_of(dir, "locks")?.with_extension("lock"))
352}
353
354pub(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 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
376const TEMP_CACHE: &str = "kanbrain-cache";
378
379pub(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
385fn 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 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
407const CUT_WRITE_AGE: Duration = Duration::from_secs(60 * 60);
409
410fn 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
430fn 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
444fn is_number(text: &str) -> bool {
446 !text.is_empty() && text.bytes().all(|b| b.is_ascii_digit())
447}
448
449pub(crate) fn cache_of(dir: &Path) -> Result<[PathBuf; 2]> {
452 Ok([lock_path(dir)?, cache_dir_of(dir, "backups")?])
453}
454
455pub(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
465pub(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
488pub(crate) fn file_name(task: &Task) -> String {
490 format!("{:04}-{}.md", task.id, slugify(&task.title))
491}
492
493pub(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
501fn 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
509pub fn find_project(start: &Path) -> Option<PathBuf> {
511 start.ancestors().map(|dir| dir.join(PROJECT_DIR)).find(|dir| dir.is_dir())
512}
513
514fn 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;