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 record(&self) {
135 *self.journal.borrow_mut() = Some(Vec::new());
136 }
137
138 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 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 pub fn dir(&self) -> &Path {
159 &self.dir
160 }
161
162 pub fn reports_dir(&self) -> PathBuf {
164 self.dir.join(REPORTS_DIR)
165 }
166
167 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 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 if let Some(old) = task.path.replace(path)
202 && Some(&old) != task.path.as_ref()
203 {
204 let _ = fs::remove_file(old);
206 }
207 Ok(())
208 }
209
210 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 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 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 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 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
250pub(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
262pub fn find_project(start: &Path) -> Option<PathBuf> {
264 start.ancestors().map(|dir| dir.join(PROJECT_DIR)).find(|dir| dir.is_dir())
265}
266
267fn 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;