1use std::collections::{BTreeSet, HashSet};
9use std::path::{Path, PathBuf};
10
11use gitpoulpi_config::LocalMarkdownSettings;
12
13use super::frontmatter::{Document, Frontmatter};
14use crate::{Error, Result};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Issue {
19 pub id: u64,
20 pub path: PathBuf,
21 pub title: String,
22 pub status: String,
23 pub assignees: Vec<String>,
24 pub labels: Vec<String>,
25 pub milestone: Option<String>,
26 pub created: String,
27 pub updated: String,
29}
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct NewNote {
34 pub title: String,
35 pub body: String,
36 pub assignees: Vec<String>,
37 pub labels: Vec<String>,
38 pub milestone: Option<String>,
39 pub status: String,
41}
42
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct Patch {
46 pub title: Option<String>,
47 pub status: Option<String>,
48 pub assignees: Option<Vec<String>>,
49 pub labels: Option<Vec<String>>,
50 pub milestone: Option<Option<String>>,
52}
53
54#[derive(Debug, Clone, Default, PartialEq, Eq)]
56pub struct UsedValues {
57 pub assignees: Vec<String>,
58 pub labels: Vec<String>,
59 pub milestones: Vec<String>,
60 pub statuses: Vec<String>,
62}
63
64pub struct Store {
65 dir: PathBuf,
66 settings: LocalMarkdownSettings,
67}
68
69fn local(msg: impl Into<String>) -> Error {
70 Error::Local(msg.into())
71}
72
73pub fn id_from_file_name(name: &str) -> Option<u64> {
75 let stem = name
76 .strip_suffix(".md")
77 .or_else(|| name.strip_suffix(".MD"))?;
78 let digits: String = stem.chars().take_while(char::is_ascii_digit).collect();
79 if digits.is_empty() || digits.len() > 9 {
80 return None;
81 }
82 let rest = &stem[digits.len()..];
84 if !(rest.is_empty() || rest.starts_with(['-', '_', ' '])) {
85 return None;
86 }
87 let mut after = rest.chars().skip(1);
88 if digits.len() == 4
89 && rest.starts_with('-')
90 && after.next().is_some_and(|c| c.is_ascii_digit())
91 && after.next().is_some_and(|c| c.is_ascii_digit())
92 && after.next() == Some('-')
93 {
94 return None;
95 }
96 digits.parse().ok()
97}
98
99pub fn slug(title: &str) -> String {
101 let mut out = String::new();
102 let mut dash = false;
103 for c in title.chars() {
104 if c.is_alphanumeric() {
105 out.extend(c.to_lowercase());
106 dash = false;
107 } else if !dash && !out.is_empty() {
108 out.push('-');
109 dash = true;
110 }
111 }
112 let out = out.trim_end_matches('-');
113 let cut: String = out.chars().take(50).collect();
114 let cut = cut.trim_end_matches('-');
115 if cut.is_empty() {
116 "issue".to_string()
117 } else {
118 cut.to_string()
119 }
120}
121
122fn civil(days: i64) -> (i64, u32, u32) {
124 let z = days + 719_468;
125 let era = z.div_euclid(146_097);
126 let doe = z.rem_euclid(146_097);
127 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
128 let y = yoe + era * 400;
129 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
130 let mp = (5 * doy + 2) / 153;
131 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
132 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
133 (if m <= 2 { y + 1 } else { y }, m, d)
134}
135
136pub fn iso_datetime(unix: i64) -> String {
138 let (y, m, d) = civil(unix.div_euclid(86_400));
139 let secs = unix.rem_euclid(86_400);
140 format!(
141 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}",
142 secs / 3600,
143 secs % 3600 / 60,
144 secs % 60
145 )
146}
147
148fn unix_now() -> i64 {
149 std::time::SystemTime::now()
150 .duration_since(std::time::UNIX_EPOCH)
151 .map(|d| d.as_secs() as i64)
152 .unwrap_or(0)
153}
154
155fn mtime_unix(path: &Path) -> i64 {
156 std::fs::metadata(path)
157 .and_then(|m| m.modified())
158 .ok()
159 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
160 .map(|d| d.as_secs() as i64)
161 .unwrap_or(0)
162}
163
164fn read_issue(path: &Path) -> Option<(Issue, Document)> {
165 let name = path.file_name()?.to_str()?;
166 let text = std::fs::read(path).ok()?;
167 let text = String::from_utf8_lossy(&text).into_owned();
168 let doc = Document::parse(&text);
169 let empty = Frontmatter::default();
170 let front = doc.front.as_ref().unwrap_or(&empty);
171 let id = front
172 .scalar("id")
173 .and_then(|v| v.trim().parse::<u64>().ok())
174 .or_else(|| id_from_file_name(name))?;
175 let title = front
176 .scalar("title")
177 .filter(|t| !t.trim().is_empty())
178 .or_else(|| {
179 doc.body
180 .lines()
181 .find_map(|l| l.strip_prefix("# ").map(|t| t.trim().to_string()))
182 })
183 .unwrap_or_else(|| {
184 let stem = name.trim_end_matches(".md").trim_end_matches(".MD");
185 let rest = stem.trim_start_matches(|c: char| c.is_ascii_digit());
186 rest.trim_start_matches(['-', '_', ' ']).replace('-', " ")
187 });
188 let milestone = front.scalar("milestone").filter(|m| !m.trim().is_empty());
189 let issue = Issue {
190 id,
191 path: path.to_path_buf(),
192 title,
193 status: front
194 .scalar("status")
195 .map(|s| s.trim().to_string())
196 .filter(|s| !s.is_empty())
197 .unwrap_or_else(|| "todo".to_string()),
198 assignees: front.list("assignees"),
199 labels: front.list("labels"),
200 milestone,
201 created: front.scalar("created").unwrap_or_default(),
202 updated: front
203 .scalar("updated")
204 .unwrap_or_else(|| iso_datetime(mtime_unix(path))),
205 };
206 Some((issue, doc))
207}
208
209impl Store {
210 pub fn new(dir: impl Into<PathBuf>, settings: LocalMarkdownSettings) -> Self {
211 Self {
212 dir: dir.into(),
213 settings,
214 }
215 }
216
217 pub fn dir(&self) -> &Path {
218 &self.dir
219 }
220
221 pub fn settings(&self) -> &LocalMarkdownSettings {
222 &self.settings
223 }
224
225 fn note_paths(&self) -> Result<Vec<PathBuf>> {
227 let entries = std::fs::read_dir(&self.dir)
228 .map_err(|e| local(format!("cannot read `{}`: {e}", self.dir.display())))?;
229 let mut paths: Vec<PathBuf> = entries
230 .filter_map(|e| e.ok())
231 .map(|e| e.path())
232 .filter(|p| {
233 p.is_file()
234 && p.extension().is_some_and(|x| x.eq_ignore_ascii_case("md"))
235 && p.file_name()
236 .and_then(|n| n.to_str())
237 .is_some_and(|n| !n.starts_with('.'))
238 })
239 .collect();
240 paths.sort();
241 Ok(paths)
242 }
243
244 pub fn list(&self) -> Result<Vec<Issue>> {
247 let mut seen = HashSet::new();
248 let mut out: Vec<Issue> = self
249 .note_paths()?
250 .iter()
251 .filter_map(|p| read_issue(p))
252 .map(|(i, _)| i)
253 .filter(|i| seen.insert(i.id))
254 .collect();
255 out.sort_by_key(|i| i.id);
256 Ok(out)
257 }
258
259 pub fn get(&self, id: u64) -> Result<Issue> {
260 self.list()?
261 .into_iter()
262 .find(|i| i.id == id)
263 .ok_or_else(|| local(format!("no issue {id} in `{}`", self.dir.display())))
264 }
265
266 pub fn next_id(&self) -> Result<u64> {
270 let mut max = 0;
271 for path in self.note_paths()? {
272 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
273 max = max.max(id_from_file_name(name).unwrap_or(0));
274 }
275 if let Some((issue, _)) = read_issue(&path) {
276 max = max.max(issue.id);
277 }
278 }
279 Ok(max + 1)
280 }
281
282 pub fn used_values(&self) -> Result<UsedValues> {
285 let issues = self.list()?;
286 let unique = |all: Vec<String>| {
287 let mut seen = BTreeSet::new();
288 let mut out = Vec::new();
289 for v in all {
290 if seen.insert(v.to_lowercase()) {
291 out.push(v);
292 }
293 }
294 out.sort_by_key(|v| v.to_lowercase());
295 out
296 };
297 let mut statuses = self.settings.status_order();
298 for issue in &issues {
299 if !statuses
300 .iter()
301 .any(|s| s.eq_ignore_ascii_case(&issue.status))
302 {
303 statuses.push(issue.status.clone());
304 }
305 }
306 Ok(UsedValues {
307 assignees: unique(issues.iter().flat_map(|i| i.assignees.clone()).collect()),
308 labels: unique(issues.iter().flat_map(|i| i.labels.clone()).collect()),
309 milestones: unique(issues.iter().filter_map(|i| i.milestone.clone()).collect()),
310 statuses,
311 })
312 }
313
314 pub fn create(&self, new: &NewNote) -> Result<Issue> {
316 let title = new.title.trim();
317 if title.is_empty() {
318 return Err(local("an issue needs a title"));
319 }
320 if !self.dir.is_dir() {
321 return Err(local(format!("`{}` is not a folder", self.dir.display())));
322 }
323 let status = if new.status.trim().is_empty() {
324 self.settings.status_order().remove(0)
325 } else {
326 new.status.trim().to_string()
327 };
328 let now = unix_now();
329 let eol = "\n";
330 let mut front = Frontmatter::default();
331 let mut id = self.next_id()?;
332 let mut path;
333 loop {
334 path = self.dir.join(format!("{id}-{}.md", slug(title)));
335 if !path.exists() {
336 break;
337 }
338 id += 1;
339 }
340 front.set_number("id", id, eol);
341 front.set_scalar("title", title, eol);
342 front.set_scalar("status", &status, eol);
343 front.set_list("assignees", &new.assignees, eol);
344 front.set_list("labels", &new.labels, eol);
345 front.set_scalar("milestone", new.milestone.as_deref().unwrap_or(""), eol);
346 front.set_scalar("created", &iso_datetime(now)[..10], eol);
347 front.set_scalar("updated", &iso_datetime(now), eol);
348 let mut doc = Document::parse("");
349 *doc.ensure_front() = front;
350 let mut text = doc.render();
351 if !new.body.is_empty() {
352 text.push_str(new.body.trim_end_matches(['\r', '\n']));
353 text.push('\n');
354 }
355 write_atomic(&path, &text)?;
356 read_issue(&path)
357 .map(|(i, _)| i)
358 .ok_or_else(|| local("the new note could not be read back"))
359 }
360
361 pub fn update(&self, id: u64, patch: &Patch) -> Result<Issue> {
363 let issue = self.get(id)?;
364 let text = std::fs::read(&issue.path)
365 .map_err(|e| local(format!("cannot read `{}`: {e}", issue.path.display())))?;
366 let mut doc = Document::parse(&String::from_utf8_lossy(&text));
367 let eol = doc.eol;
368 let had_front = doc.front.is_some();
369 let front = doc.ensure_front();
370 if !had_front {
371 front.set_number("id", id, eol);
372 front.set_scalar("title", &issue.title, eol);
373 } else if front.scalar("id").is_none() {
374 front.set_number("id", id, eol);
375 }
376 if let Some(title) = &patch.title {
377 front.set_scalar("title", title, eol);
378 }
379 if let Some(status) = &patch.status {
380 front.set_scalar("status", status, eol);
381 }
382 if let Some(list) = &patch.assignees {
383 front.set_list("assignees", list, eol);
384 }
385 if let Some(list) = &patch.labels {
386 front.set_list("labels", list, eol);
387 }
388 if let Some(milestone) = &patch.milestone {
389 front.set_scalar("milestone", milestone.as_deref().unwrap_or(""), eol);
390 }
391 front.set_scalar("updated", &iso_datetime(unix_now()), eol);
392 write_atomic(&issue.path, &doc.render())?;
393 read_issue(&issue.path)
394 .map(|(i, _)| i)
395 .ok_or_else(|| local("the note could not be read back"))
396 }
397
398 pub fn fingerprint(dir: &Path) -> u64 {
401 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
402 let mut feed = |bytes: &[u8]| {
403 for b in bytes {
404 hash ^= u64::from(*b);
405 hash = hash.wrapping_mul(0x0100_0000_01b3);
406 }
407 };
408 let Ok(entries) = std::fs::read_dir(dir) else {
409 return 0;
410 };
411 let mut rows: Vec<(String, u64, i64)> = entries
412 .filter_map(|e| e.ok())
413 .filter_map(|e| {
414 let name = e.file_name().to_string_lossy().into_owned();
415 if !name.to_ascii_lowercase().ends_with(".md") {
416 return None;
417 }
418 let meta = e.metadata().ok()?;
419 let modified = meta
420 .modified()
421 .ok()
422 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
423 .map(|d| d.as_nanos() as i64)
424 .unwrap_or(0);
425 Some((name, meta.len(), modified))
426 })
427 .collect();
428 rows.sort();
429 for (name, len, modified) in rows {
430 feed(name.as_bytes());
431 feed(&len.to_le_bytes());
432 feed(&modified.to_le_bytes());
433 }
434 hash
435 }
436}
437
438pub fn write_atomic(path: &Path, text: &str) -> Result<()> {
441 let name = path
442 .file_name()
443 .and_then(|n| n.to_str())
444 .ok_or_else(|| local("bad note path"))?;
445 let tmp = path.with_file_name(format!(".{name}.gitpoulpi-tmp"));
446 std::fs::write(&tmp, text.as_bytes())
447 .map_err(|e| local(format!("cannot write `{}`: {e}", tmp.display())))?;
448 std::fs::rename(&tmp, path).map_err(|e| {
449 let _ = std::fs::remove_file(&tmp);
450 local(format!("cannot replace `{}`: {e}", path.display()))
451 })
452}
453
454#[cfg(test)]
455mod tests {
456 use super::*;
457
458 fn store(dir: &Path) -> Store {
459 Store::new(dir, LocalMarkdownSettings::default())
460 }
461
462 const UNKNOWN: &str = "---\nid: 7\ntitle: Seven\nstatus: doing\ncssclasses: wide\nlabels: [bug]\nrating: 4.5\n---\nBody stays.\n\n- [ ] item\n";
463
464 #[test]
465 fn ids_are_max_plus_one_and_file_names_count() {
466 let dir = tempfile::tempdir().unwrap();
467 let s = store(dir.path());
468 assert_eq!(s.next_id().unwrap(), 1);
469 std::fs::write(dir.path().join("7-seven.md"), UNKNOWN).unwrap();
470 std::fs::write(dir.path().join("20-raw.md"), "no frontmatter\n").unwrap();
471 std::fs::write(dir.path().join("2026-10-14 standup.md"), "x\n").unwrap();
472 assert_eq!(s.next_id().unwrap(), 21);
473 let made = s
474 .create(&NewNote {
475 title: "Crash on empty name!".into(),
476 body: "Steps".into(),
477 labels: vec!["bug".into()],
478 ..NewNote::default()
479 })
480 .unwrap();
481 assert_eq!(made.id, 21);
482 assert_eq!(
483 made.path.file_name().unwrap().to_str().unwrap(),
484 "21-crash-on-empty-name.md"
485 );
486 assert_eq!(made.status, "todo");
487 assert_eq!(made.labels, ["bug"]);
488 let text = std::fs::read_to_string(&made.path).unwrap();
489 assert!(text.starts_with("---\nid: 21\ntitle: Crash on empty name!\nstatus: todo\nassignees: []\nlabels: [bug]\nmilestone:\ncreated: "));
490 assert!(text.ends_with("---\nSteps\n"));
491 }
492
493 #[test]
494 fn an_edit_keeps_unknown_keys_and_the_body_byte_for_byte() {
495 let dir = tempfile::tempdir().unwrap();
496 let s = store(dir.path());
497 let path = dir.path().join("7-seven.md");
498 std::fs::write(&path, UNKNOWN).unwrap();
499 let after = s
500 .update(
501 7,
502 &Patch {
503 status: Some("done".into()),
504 labels: Some(vec!["bug".into(), "ui".into()]),
505 ..Patch::default()
506 },
507 )
508 .unwrap();
509 assert_eq!(after.status, "done");
510 let text = std::fs::read_to_string(&path).unwrap();
511 let want_head = "---\nid: 7\ntitle: Seven\nstatus: done\ncssclasses: wide\nlabels: [bug, ui]\nrating: 4.5\nupdated: ";
512 assert!(text.starts_with(want_head), "{text}");
513 assert!(text.ends_with("---\nBody stays.\n\n- [ ] item\n"));
514 assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
516 }
517
518 #[test]
519 fn crlf_notes_stay_crlf() {
520 let dir = tempfile::tempdir().unwrap();
521 let s = store(dir.path());
522 let path = dir.path().join("3-x.md");
523 std::fs::write(
524 &path,
525 UNKNOWN.replace('\n', "\r\n").replace("id: 7", "id: 3"),
526 )
527 .unwrap();
528 s.update(
529 3,
530 &Patch {
531 assignees: Some(vec!["kai".into()]),
532 ..Patch::default()
533 },
534 )
535 .unwrap();
536 let bytes = std::fs::read(&path).unwrap();
537 let text = String::from_utf8(bytes).unwrap();
538 assert!(text.contains("assignees: [kai]\r\n"));
539 assert!(!text.replace("\r\n", "").contains('\n'));
540 }
541
542 #[test]
543 fn reading_is_lenient() {
544 let dir = tempfile::tempdir().unwrap();
545 let s = store(dir.path());
546 std::fs::write(dir.path().join("5-from-name.md"), "---\ntitle: T\n---\nb\n").unwrap();
548 std::fs::write(dir.path().join("6-x.md"), "# Heading title\ntext\n").unwrap();
550 std::fs::write(dir.path().join("readme.md"), "hello\n").unwrap();
552 std::fs::write(dir.path().join(".hidden.md"), "---\nid: 9\n---\n").unwrap();
553 std::fs::write(dir.path().join("5-zzz.md"), "---\nid: 5\ntitle: dup\n---\n").unwrap();
555 let all = s.list().unwrap();
556 let ids: Vec<u64> = all.iter().map(|i| i.id).collect();
557 assert_eq!(ids, [5, 6]);
558 assert_eq!(all[0].status, "todo");
559 assert_eq!(all[0].title, "T");
560 assert_eq!(all[1].title, "Heading title");
561 s.update(
563 6,
564 &Patch {
565 status: Some("doing".into()),
566 ..Patch::default()
567 },
568 )
569 .unwrap();
570 let text = std::fs::read_to_string(dir.path().join("6-x.md")).unwrap();
571 assert!(text.starts_with("---\nid: 6\ntitle: Heading title\nstatus: doing\nupdated: "));
572 assert!(text.ends_with("---\n# Heading title\ntext\n"));
573 }
574
575 #[test]
576 fn used_values_feed_the_pickers() {
577 let dir = tempfile::tempdir().unwrap();
578 let s = store(dir.path());
579 std::fs::write(dir.path().join("7-seven.md"), UNKNOWN).unwrap();
580 s.create(&NewNote {
581 title: "b".into(),
582 labels: vec!["Bug".into(), "ui".into()],
583 assignees: vec!["kai".into()],
584 milestone: Some("v0.1".into()),
585 status: "review".into(),
586 ..NewNote::default()
587 })
588 .unwrap();
589 let v = s.used_values().unwrap();
590 assert_eq!(v.labels, ["bug", "ui"]);
591 assert_eq!(v.assignees, ["kai"]);
592 assert_eq!(v.milestones, ["v0.1"]);
593 assert_eq!(v.statuses, ["todo", "doing", "done", "review"]);
594 }
595
596 #[test]
597 fn the_fingerprint_moves_with_the_folder() {
598 let dir = tempfile::tempdir().unwrap();
599 let before = Store::fingerprint(dir.path());
600 std::fs::write(dir.path().join("1-a.md"), "x").unwrap();
601 let one = Store::fingerprint(dir.path());
602 assert_ne!(before, one);
603 std::fs::write(dir.path().join("1-a.md"), "xy").unwrap();
604 assert_ne!(one, Store::fingerprint(dir.path()));
605 std::fs::write(dir.path().join("notes.txt"), "ignored").unwrap();
606 assert_eq!(
607 Store::fingerprint(dir.path()),
608 Store::fingerprint(dir.path())
609 );
610 }
611
612 #[test]
613 fn slugs_and_dates() {
614 assert_eq!(slug(" Fix: the Thing / now!! "), "fix-the-thing-now");
615 assert_eq!(slug("***"), "issue");
616 assert_eq!(slug("Été à Paris"), "été-à-paris");
617 assert_eq!(iso_datetime(0), "1970-01-01T00:00:00");
618 assert_eq!(iso_datetime(1_792_000_000), "2026-10-14T17:46:40");
619 assert_eq!(id_from_file_name("12-x.md"), Some(12));
620 assert_eq!(id_from_file_name("12.md"), Some(12));
621 assert_eq!(id_from_file_name("12abc.md"), None);
622 assert_eq!(id_from_file_name("x.md"), None);
623 }
624}