1use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24use std::sync::Mutex;
25
26use serde::Deserialize;
27use serde_norway::{Mapping, Value};
28
29use crate::{
30 Change, Context, Error, Found, Kind, Memory, New, Problem, Provider, Scope, split_id, time,
31};
32
33pub const INDEX: &str = "MEMORY.md";
35
36const TITLE_MAX: usize = 60;
38const NAME_MAX: usize = 48;
39
40#[derive(Debug)]
41pub struct Files {
42 user: Option<PathBuf>,
43 host: PathBuf,
44 sessions: PathBuf,
45 write: Mutex<()>,
48}
49
50impl Files {
51 pub fn new(user: Option<PathBuf>, host: PathBuf, sessions: PathBuf) -> Files {
55 Files {
56 user,
57 host,
58 sessions,
59 write: Mutex::new(()),
60 }
61 }
62
63 pub fn project_root(cwd: &Path) -> PathBuf {
66 crate::project_root(cwd)
67 }
68
69 pub fn dir(&self, cx: &Context, scope: Scope) -> Result<PathBuf, Error> {
71 match scope {
72 Scope::User => self.user.clone().ok_or_else(|| {
73 Error::Invalid("the user scope needs a configuration directory".into())
74 }),
75 Scope::Host => Ok(self.host.clone()),
76 Scope::Project => Ok(crate::project_of(cx)?.join(".dreamer").join("memory")),
77 Scope::Session => Ok(self.sessions.join(crate::session_of(cx)?)),
78 }
79 }
80
81 fn locate(&self, cx: &Context, id: &str) -> Result<(Scope, PathBuf), Error> {
82 let (scope, name) = split_id(id)?;
83 Ok((scope, self.dir(cx, scope)?.join(format!("{name}.md"))))
84 }
85
86 fn lock(&self) -> std::sync::MutexGuard<'_, ()> {
87 self.write.lock().unwrap_or_else(|e| e.into_inner())
88 }
89
90 fn scopes(&self, cx: &Context, scope: Option<Scope>) -> Vec<Scope> {
91 match scope {
92 Some(s) => vec![s],
93 None => crate::reach(cx)
94 .into_iter()
95 .filter(|s| *s != Scope::User || self.user.is_some())
96 .collect(),
97 }
98 }
99
100 fn existing(&self, cx: &Context, id: &str) -> Result<(Scope, PathBuf, Entry), Error> {
101 let (scope, path) = self.locate(cx, id)?;
102 if !path.is_file() {
103 return Err(Error::NotFound(id.to_owned()));
104 }
105 let entry = read(&path, scope).map_err(Error::Malformed)?;
106 Ok((scope, path, entry))
107 }
108}
109
110#[derive(Debug)]
113struct Entry {
114 memory: Memory,
115 extra: BTreeMap<String, Value>,
116}
117
118#[derive(Debug, Default, Deserialize)]
119struct Front {
120 name: Option<String>,
121 description: Option<String>,
122 #[serde(rename = "type", alias = "kind")]
123 kind: Option<String>,
124 #[serde(default)]
125 links: Vec<String>,
126 created: Option<Value>,
127 updated: Option<Value>,
128 #[serde(flatten)]
129 extra: BTreeMap<String, Value>,
130}
131
132fn split(text: &str) -> Option<(&str, &str)> {
134 let t = text.strip_prefix('\u{feff}').unwrap_or(text);
135 let rest = t
136 .strip_prefix("---\n")
137 .or_else(|| t.strip_prefix("---\r\n"))?;
138 let mut at = 0;
139 for line in rest.split_inclusive('\n') {
140 if line.trim_end_matches(['\r', '\n']) == "---" {
141 return Some((&rest[..at], &rest[at + line.len()..]));
142 }
143 at += line.len();
144 }
145 None
146}
147
148fn stamp(v: Option<&Value>) -> Option<u64> {
149 match v? {
150 Value::String(s) => time::parse(s),
151 Value::Number(n) => n.as_u64(),
152 _ => None,
153 }
154}
155
156fn file_name(path: &Path) -> String {
157 path.file_stem()
158 .map(|s| s.to_string_lossy().into_owned())
159 .unwrap_or_default()
160}
161
162fn read(path: &Path, scope: Scope) -> Result<Entry, Problem> {
163 let problem = |message: String| Problem {
164 path: path.to_path_buf(),
165 message,
166 };
167 let meta = std::fs::metadata(path).map_err(|e| problem(e.to_string()))?;
168 let mtime = meta
169 .modified()
170 .ok()
171 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
172 .map_or(0, |d| d.as_millis() as u64);
173 let text = std::fs::read_to_string(path).map_err(|e| problem(e.to_string()))?;
174 let (yaml, body) = split(&text).ok_or_else(|| {
175 problem("no frontmatter: the file must start with a `---` block holding `type:`".into())
176 })?;
177 let front: Front = if yaml.trim().is_empty() {
178 Front::default()
179 } else {
180 serde_norway::from_str(yaml).map_err(|e| problem(format!("frontmatter: {e}")))?
181 };
182 let kinds = || {
183 Kind::ALL
184 .iter()
185 .map(|k| k.name())
186 .collect::<Vec<_>>()
187 .join(", ")
188 };
189 let kind = match front.kind.as_deref() {
190 None => return Err(problem(format!("no `type:` ({})", kinds()))),
191 Some(k) => Kind::from_name(k.trim())
192 .ok_or_else(|| problem(format!("`type: {k}` is not one of {}", kinds())))?,
193 };
194 let name = file_name(path);
195 let title = front
196 .name
197 .map(|n| n.trim().to_owned())
198 .filter(|n| !n.is_empty())
199 .unwrap_or_else(|| name.clone());
200 let created = stamp(front.created.as_ref()).unwrap_or(mtime);
201 let updated = stamp(front.updated.as_ref()).unwrap_or(0).max(mtime);
203 let body = body
204 .strip_prefix("\r\n")
205 .or_else(|| body.strip_prefix('\n'))
206 .unwrap_or(body);
207 Ok(Entry {
208 memory: Memory {
209 id: format!("{}/{name}", scope.name()),
210 scope,
211 kind,
212 title,
213 description: front.description.unwrap_or_default().trim().to_owned(),
214 text: body.trim_end().to_owned(),
215 links: front.links,
216 created_unix_ms: created,
217 updated_unix_ms: updated,
218 path: Some(path.to_path_buf()),
219 score: None,
220 },
221 extra: front.extra,
222 })
223}
224
225pub(crate) fn one_line(text: &str) -> String {
227 text.split_whitespace().collect::<Vec<_>>().join(" ")
228}
229
230pub(crate) fn shorten(text: &str, max: usize) -> String {
231 if text.chars().count() <= max {
232 return text.to_owned();
233 }
234 let mut s: String = text.chars().take(max - 1).collect();
235 s = s.trim_end().to_owned();
236 s.push('…');
237 s
238}
239
240pub(crate) fn title_of(text: &str) -> String {
242 let first = text
243 .lines()
244 .map(|l| l.trim().trim_start_matches('#').trim())
245 .find(|l| !l.is_empty())
246 .unwrap_or("memory");
247 shorten(first, TITLE_MAX)
248}
249
250pub(crate) fn slug(title: &str) -> String {
252 let mut s = String::new();
253 for c in title.chars().flat_map(char::to_lowercase) {
254 if c.is_alphanumeric() {
255 s.push(c);
256 } else if !s.is_empty() && !s.ends_with('-') {
257 s.push('-');
258 }
259 if s.chars().count() >= NAME_MAX {
260 break;
261 }
262 }
263 let s = s.trim_end_matches('-').to_owned();
264 if s.is_empty() || s == "memory" {
265 "note".into()
266 } else {
267 s
268 }
269}
270
271fn write_atomic(path: &Path, text: &str) -> Result<(), Error> {
274 let io = |e: std::io::Error| Error::Io(format!("{}: {e}", path.display()));
275 let tmp = path.with_file_name(format!(".{}.tmp", file_name(path)));
276 std::fs::write(&tmp, text).map_err(io)?;
277 std::fs::rename(&tmp, path).map_err(|e| {
278 let _ = std::fs::remove_file(&tmp);
279 io(e)
280 })
281}
282
283fn set_time(path: &Path, unix_ms: u64) -> Result<(), Error> {
287 let at = std::time::UNIX_EPOCH + std::time::Duration::from_millis(unix_ms);
288 std::fs::File::options()
289 .write(true)
290 .open(path)
291 .and_then(|f| f.set_modified(at))
292 .map_err(|e| Error::Io(format!("{}: {e}", path.display())))
293}
294
295fn render(m: &Memory, extra: &BTreeMap<String, Value>) -> Result<String, Error> {
296 let mut map = Mapping::new();
297 let s = |v: &str| Value::String(v.to_owned());
298 map.insert(s("name"), s(&m.title));
299 map.insert(s("description"), s(&m.description));
300 map.insert(s("type"), s(m.kind.name()));
301 if !m.links.is_empty() {
302 map.insert(
303 s("links"),
304 Value::Sequence(m.links.iter().map(|l| s(l)).collect()),
305 );
306 }
307 map.insert(s("created"), s(&time::format(m.created_unix_ms)));
308 map.insert(s("updated"), s(&time::format(m.updated_unix_ms)));
309 for (k, v) in extra {
310 if ![
311 "name",
312 "description",
313 "type",
314 "kind",
315 "links",
316 "created",
317 "updated",
318 ]
319 .contains(&k.as_str())
320 {
321 map.insert(s(k), v.clone());
322 }
323 }
324 let yaml =
325 serde_norway::to_string(&Value::Mapping(map)).map_err(|e| Error::Io(e.to_string()))?;
326 Ok(format!("---\n{yaml}---\n\n{}\n", m.text.trim_end()))
327}
328
329fn index_line(m: &Memory, file: &str) -> String {
331 let target = if file.contains([' ', '(', ')', '<', '>']) {
332 format!("<{file}>")
333 } else {
334 file.to_owned()
335 };
336 let title = m.title.replace(['[', ']'], "");
337 if m.description.is_empty() {
338 format!("- [{title}]({target})")
339 } else {
340 format!("- [{title}]({target}) — {}", m.description)
341 }
342}
343
344fn set_index(dir: &Path, file: &str, line: Option<String>) -> Result<(), Error> {
347 let path = dir.join(INDEX);
348 let old = match std::fs::read_to_string(&path) {
349 Ok(t) => t,
350 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
351 Err(e) => return Err(Error::Io(format!("{}: {e}", path.display()))),
352 };
353 let points = |l: &str| l.contains(&format!("]({file})")) || l.contains(&format!("](<{file}>)"));
354 let mut out: Vec<String> = Vec::new();
355 let mut line = line;
356 let mut placed = false;
357 for l in old.lines() {
358 if points(l) {
359 if !placed && let Some(new) = line.take() {
360 out.push(new);
361 }
362 placed = true;
363 } else {
364 out.push(l.to_owned());
365 }
366 }
367 if let Some(new) = line {
368 out.push(new);
369 }
370 let mut text = out.join("\n");
371 if !text.is_empty() {
372 text.push('\n');
373 }
374 if text == old {
375 return Ok(());
376 }
377 write_atomic(&path, &text)
378}
379
380impl Provider for Files {
381 fn name(&self) -> &'static str {
382 "files"
383 }
384
385 fn remember(&self, cx: &Context, new: New) -> Result<Memory, Error> {
386 if new.text.trim().is_empty() {
387 return Err(Error::Invalid("a memory needs text".into()));
388 }
389 let dir = self.dir(cx, new.scope)?;
390 let io = |e: std::io::Error| Error::Io(format!("{}: {e}", dir.display()));
391 let _guard = self.lock();
392 std::fs::create_dir_all(&dir).map_err(io)?;
393 let title = new
394 .title
395 .as_deref()
396 .map(one_line)
397 .filter(|t| !t.is_empty())
398 .unwrap_or_else(|| title_of(&new.text));
399 let description = new
400 .description
401 .as_deref()
402 .map(one_line)
403 .filter(|d| !d.is_empty())
404 .unwrap_or_else(|| title.clone());
405 let base = slug(&title);
406 let name = (1..)
407 .map(|n| {
408 if n == 1 {
409 base.clone()
410 } else {
411 format!("{base}-{n}")
412 }
413 })
414 .find(|n| !dir.join(format!("{n}.md")).exists())
415 .unwrap_or(base);
416 let path = dir.join(format!("{name}.md"));
417 let now = time::now_ms();
418 let m = Memory {
419 id: format!("{}/{name}", new.scope.name()),
420 scope: new.scope,
421 kind: new.kind,
422 title,
423 description,
424 text: new.text.trim_end().to_owned(),
425 links: new.links,
426 created_unix_ms: now,
427 updated_unix_ms: now,
428 path: Some(path.clone()),
429 score: None,
430 };
431 write_atomic(&path, &render(&m, &BTreeMap::new())?)?;
432 set_time(&path, m.updated_unix_ms)?;
433 let file = format!("{name}.md");
434 set_index(&dir, &file, Some(index_line(&m, &file)))?;
435 read(&path, new.scope)
436 .map(|e| e.memory)
437 .map_err(Error::Malformed)
438 }
439
440 fn list(&self, cx: &Context, scope: Option<Scope>, kind: Option<Kind>) -> Result<Found, Error> {
441 let mut found = Found::default();
442 for s in self.scopes(cx, scope) {
443 let dir = self.dir(cx, s)?;
444 let entries = match std::fs::read_dir(&dir) {
445 Ok(e) => e,
446 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
447 Err(e) => return Err(Error::Io(format!("{}: {e}", dir.display()))),
448 };
449 let mut paths: Vec<PathBuf> = entries
450 .filter_map(Result::ok)
451 .map(|e| e.path())
452 .filter(|p| {
453 let n = p
454 .file_name()
455 .map(|n| n.to_string_lossy())
456 .unwrap_or_default();
457 n.ends_with(".md") && n != INDEX && !n.starts_with('.') && p.is_file()
458 })
459 .collect();
460 paths.sort();
461 for p in paths {
462 match read(&p, s) {
463 Ok(e) if kind.is_none_or(|k| k == e.memory.kind) => {
464 found.items.push(e.memory);
465 }
466 Ok(_) => {}
467 Err(problem) => found.problems.push(problem),
468 }
469 }
470 }
471 found.items.sort_by(|a, b| {
472 b.updated_unix_ms
473 .cmp(&a.updated_unix_ms)
474 .then(a.id.cmp(&b.id))
475 });
476 Ok(found)
477 }
478
479 fn get(&self, cx: &Context, id: &str) -> Result<Memory, Error> {
480 self.existing(cx, id).map(|(_, _, e)| e.memory)
481 }
482
483 fn update(&self, cx: &Context, id: &str, change: Change) -> Result<Memory, Error> {
484 let _guard = self.lock();
485 let (scope, path, entry) = self.existing(cx, id)?;
486 let mut m = entry.memory;
487 if let Some(t) = change.text {
488 if t.trim().is_empty() {
489 return Err(Error::Invalid("a memory needs text".into()));
490 }
491 m.text = t.trim_end().to_owned();
492 }
493 if let Some(k) = change.kind {
494 m.kind = k;
495 }
496 if let Some(t) = change.title.as_deref().map(one_line) {
497 if t.is_empty() {
498 return Err(Error::Invalid("a title cannot be empty".into()));
499 }
500 m.title = t;
501 }
502 if let Some(d) = change.description.as_deref() {
503 m.description = one_line(d);
504 }
505 if let Some(l) = change.links {
506 m.links = l;
507 }
508 m.updated_unix_ms = time::now_ms().max(m.updated_unix_ms);
509 write_atomic(&path, &render(&m, &entry.extra)?)?;
510 set_time(&path, m.updated_unix_ms)?;
511 let file = format!("{}.md", file_name(&path));
512 if let Some(dir) = path.parent() {
513 set_index(dir, &file, Some(index_line(&m, &file)))?;
514 }
515 read(&path, scope)
516 .map(|e| e.memory)
517 .map_err(Error::Malformed)
518 }
519
520 fn put(&self, cx: &Context, m: &Memory) -> Result<Memory, Error> {
521 if m.text.trim().is_empty() {
522 return Err(Error::Invalid("a memory needs text".into()));
523 }
524 let (scope, name) = split_id(&m.id)?;
525 if scope != m.scope {
526 return Err(Error::Invalid(format!(
527 "`{}` is not in the {} scope",
528 m.id,
529 m.scope.name()
530 )));
531 }
532 let dir = self.dir(cx, scope)?;
533 let io = |e: std::io::Error| Error::Io(format!("{}: {e}", dir.display()));
534 let _guard = self.lock();
535 std::fs::create_dir_all(&dir).map_err(io)?;
536 let path = dir.join(format!("{name}.md"));
537 let extra = read(&path, scope).map(|e| e.extra).unwrap_or_default();
539 let mut m = m.clone();
540 m.text = m.text.trim_end().to_owned();
541 write_atomic(&path, &render(&m, &extra)?)?;
542 set_time(&path, m.updated_unix_ms)?;
543 let file = format!("{name}.md");
544 set_index(&dir, &file, Some(index_line(&m, &file)))?;
545 read(&path, scope)
546 .map(|e| e.memory)
547 .map_err(Error::Malformed)
548 }
549
550 fn forget(&self, cx: &Context, id: &str) -> Result<Memory, Error> {
551 let _guard = self.lock();
552 let (_, path, entry) = self.existing(cx, id)?;
553 std::fs::remove_file(&path).map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
554 if let Some(dir) = path.parent() {
555 set_index(dir, &format!("{}.md", file_name(&path)), None)?;
556 }
557 Ok(entry.memory)
558 }
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 #[test]
566 fn titles_and_names_come_from_the_text() {
567 assert_eq!(title_of("\n## Use tabs\nmore"), "Use tabs");
568 assert_eq!(slug("Use tabs, not spaces!"), "use-tabs-not-spaces");
569 assert_eq!(slug("???"), "note");
570 assert_eq!(slug("Grüße aus Köln"), "grüße-aus-köln");
571 assert!(split_id("user/x").is_ok());
572 for bad in [
573 "x",
574 "nope/x",
575 "user/",
576 "user/../x",
577 "user/.hidden",
578 "user/MEMORY",
579 ] {
580 assert!(split_id(bad).is_err(), "{bad}");
581 }
582 }
583
584 #[test]
585 fn frontmatter_needs_its_fences() {
586 assert_eq!(split("---\na: 1\n---\nbody"), Some(("a: 1\n", "body")));
587 assert_eq!(
588 split("---\r\na: 1\r\n---\r\n\r\nbody"),
589 Some(("a: 1\r\n", "\r\nbody"))
590 );
591 assert_eq!(split("a: 1\n---\nbody"), None);
592 assert_eq!(split("---\na: 1\n"), None);
593 }
594}