//! M8 step 2: in a GBrain vault a clash never makes a second page. Lines both sides added are all kept (incoming //! first); a rewrite of the same lines keeps the incoming one in place and this device's version waits in //! `.git/lune/tidy/`. Obsidian vaults keep making `(Label's version).md` copies, as before. use git2::{ObjectType, Repository, TreeWalkMode, TreeWalkResult}; use lune_core::config::VaultKind; use lune_core::names; use lune_core::tidy::{self, Keep}; use lune_core::vault::{self, Vault}; use std::collections::HashSet; use std::fs; use std::path::{Path, PathBuf}; use tempfile::TempDir; struct World { tmp: TempDir, remote: PathBuf, kind: VaultKind, } impl World { fn new(kind: VaultKind) -> World { let tmp = TempDir::new().unwrap(); let remote = tmp.path().join("remote.git"); Repository::init_bare(&remote).unwrap(); World { tmp, remote, kind } } fn device(&self, label: &str) -> Vault { let (mut cfg, _, err) = vault::add("Brain", &self.tmp.path().join(label), self.remote.to_str().unwrap(), label).unwrap(); assert_eq!(err, None); cfg.kind = self.kind; vault::apply_kind_ignores(&Repository::open(&cfg.path).unwrap(), self.kind).unwrap(); Vault::open(&cfg, label).unwrap() } } fn write(v: &Vault, rel: &str, bytes: impl AsRef<[u8]>) { let p = v.root.join(rel); fs::create_dir_all(p.parent().unwrap()).unwrap(); fs::write(p, bytes).unwrap(); } fn read(v: &Vault, rel: &str) -> Vec { fs::read(v.root.join(rel)).unwrap_or_else(|e| panic!("{rel}: {e}")) } fn save_and_sync(v: &Vault) -> vault::SyncReport { v.save_changes(None, &HashSet::new()).unwrap(); v.sync().unwrap() } fn files(root: &Path) -> Vec { fn walk(root: &Path, dir: &Path, out: &mut Vec) { for e in fs::read_dir(dir).unwrap() { let p = e.unwrap().path(); let rel = p.strip_prefix(root).unwrap().to_string_lossy().into_owned(); if rel == ".git" { continue; } if p.is_dir() { walk(root, &p, out); } else { out.push(rel); } } } let mut out = vec![]; walk(root, root, &mut out); out.sort(); out } /// True if any commit reachable from any ref in `repo` has a tree holding a kept-both copy path. fn copy_anywhere_in_history(repo: &Repository) -> bool { let mut walk = repo.revwalk().unwrap(); for r in repo.references().unwrap() { if let Ok(oid) = r.unwrap().peel_to_commit().map(|c| c.id()) { walk.push(oid).unwrap(); } } walk.any(|id| { let tree = repo.find_commit(id.unwrap()).unwrap().tree().unwrap(); let mut found = false; tree.walk(TreeWalkMode::PreOrder, |dir, e| { if e.kind() == Some(ObjectType::Blob) { found |= names::parse_copy(&format!("{dir}{}", e.name().unwrap())).is_some(); } TreeWalkResult::Ok }) .unwrap(); found }) } const PAGE: &str = "# Ada\n\nShe builds engines.\n\n## Timeline\n- 2020: joined\n"; fn two(w: &World) -> (Vault, Vault) { let a = w.device("Codex"); write(&a, "people/ada.md", PAGE); save_and_sync(&a); let b = w.device("Hermes"); (a, b) } #[test] fn both_append_to_the_same_page_and_both_entries_stay_incoming_first() { let w = World::new(VaultKind::Gbrain); let (a, b) = two(&w); write(&a, "people/ada.md", format!("{PAGE}- 2021: Codex met her\n")); write(&b, "people/ada.md", format!("{PAGE}- 2021: Hermes read her paper\n")); save_and_sync(&a); let report = save_and_sync(&b); assert_eq!(report.joined, vec!["people/ada.md".to_string()]); assert!(report.kept_both.is_empty() && report.to_tidy.is_empty()); let want = format!("{PAGE}- 2021: Codex met her\n- 2021: Hermes read her paper\n"); assert_eq!(read(&b, "people/ada.md"), want.as_bytes(), "incoming (Codex) first, then this device's"); a.sync().unwrap(); assert_eq!(read(&a, "people/ada.md"), want.as_bytes()); assert_eq!(files(&a.root), ["people/ada.md"]); assert_eq!(files(&b.root), ["people/ada.md"]); assert!(tidy::list(&a).unwrap().is_empty() && tidy::list(&b).unwrap().is_empty()); assert!(!copy_anywhere_in_history(a.repo()) && !copy_anywhere_in_history(b.repo())); assert!(!copy_anywhere_in_history(&Repository::open(&w.remote).unwrap())); } #[test] fn appending_to_a_page_without_a_final_newline_still_joins() { let w = World::new(VaultKind::Gbrain); let a = w.device("Codex"); write(&a, "p.md", "title\nlast"); save_and_sync(&a); let b = w.device("Hermes"); write(&a, "p.md", "title\nlast\ncodex"); write(&b, "p.md", "title\nlast\nhermes"); save_and_sync(&a); let r = save_and_sync(&b); assert_eq!(r.joined.len(), 1, "{r:?}"); assert_eq!(read(&b, "p.md"), b"title\nlast\ncodex\nhermes"); } #[test] fn rewriting_the_same_paragraph_keeps_the_incoming_one_and_tidies_ours() { let w = World::new(VaultKind::Gbrain); let (a, b) = two(&w); let codex = PAGE.replace("She builds engines.", "She builds steam engines."); let hermes = PAGE.replace("She builds engines.", "She designs analytical engines."); write(&a, "people/ada.md", &codex); write(&b, "people/ada.md", &hermes); save_and_sync(&a); let report = save_and_sync(&b); assert_eq!(report.to_tidy, vec!["people/ada.md".to_string()]); assert_eq!(read(&b, "people/ada.md"), codex.as_bytes(), "incoming stays in place"); assert_eq!(files(&b.root), ["people/ada.md"], "no copy in the folder"); a.sync().unwrap(); assert_eq!(files(&a.root), ["people/ada.md"]); assert_eq!(read(&a, "people/ada.md"), codex.as_bytes()); assert!(!copy_anywhere_in_history(a.repo()) && !copy_anywhere_in_history(b.repo())); assert!(!copy_anywhere_in_history(&Repository::open(&w.remote).unwrap())); // Hermes's version is kept byte-exact on its device only, inside .git/lune/tidy. let entries = tidy::entries(&b.git_dir); assert_eq!(entries.len(), 1); assert_eq!((entries[0].note.as_str(), entries[0].label.as_str(), entries[0].source.as_str()), ("people/ada.md", "Hermes", "sync")); assert_eq!(tidy::mine_bytes(&b.git_dir, &entries[0].id).unwrap(), hermes.as_bytes()); assert!(tidy::entries(&a.git_dir).is_empty()); // This device's own entries stay in history, as for Obsidian; only the folder has to stay clean. // And it shows under Notes to tidy, not as a file. let listed = tidy::list(&b).unwrap(); assert_eq!(listed.len(), 1); assert!(listed[0].local && listed[0].copy.starts_with(".git/")); // Sync keeps working with it waiting. write(&a, "other.md", "still syncing\n"); save_and_sync(&a); b.sync().unwrap(); assert_eq!(read(&b, "other.md"), b"still syncing\n"); assert_eq!(tidy::list(&b).unwrap().len(), 1); } fn clash(w: &World) -> (Vault, Vault, String, String) { let (a, b) = two(w); let codex = PAGE.replace("She builds engines.", "She builds steam engines."); let hermes = PAGE.replace("She builds engines.", "She designs analytical engines."); write(&a, "people/ada.md", &codex); write(&b, "people/ada.md", &hermes); save_and_sync(&a); save_and_sync(&b); a.sync().unwrap(); (a, b, codex, hermes) } #[test] fn tidy_keep_mine_reaches_the_other_device() { let w = World::new(VaultKind::Gbrain); let (a, b, _, hermes) = clash(&w); tidy::keep(&b, "people/ada.md", Keep::Mine).unwrap().unwrap(); assert!(tidy::entries(&b.git_dir).is_empty() && tidy::list(&b).unwrap().is_empty()); b.sync().unwrap(); a.sync().unwrap(); assert_eq!(read(&a, "people/ada.md"), hermes.as_bytes()); assert_eq!(files(&a.root), ["people/ada.md"]); } #[test] fn tidy_keep_theirs_drops_ours_and_changes_nothing_elsewhere() { let w = World::new(VaultKind::Gbrain); let (a, b, codex, _) = clash(&w); let saved = tidy::keep(&b, "people/ada.md", Keep::Theirs).unwrap(); assert!(saved.is_none()); assert!(tidy::list(&b).unwrap().is_empty()); assert_eq!(read(&b, "people/ada.md"), codex.as_bytes()); b.sync().unwrap(); a.sync().unwrap(); assert_eq!(read(&a, "people/ada.md"), codex.as_bytes()); } #[test] fn tidy_keep_both_writes_both_into_the_one_note() { let w = World::new(VaultKind::Gbrain); let (a, b, codex, hermes) = clash(&w); tidy::keep(&b, "people/ada.md", Keep::Both).unwrap().unwrap(); assert_eq!(files(&b.root), ["people/ada.md"]); let text = String::from_utf8(read(&b, "people/ada.md")).unwrap(); assert!(text.starts_with(&codex), "the one in place comes first"); assert!(text.ends_with(&hermes), "this device's version follows, exact"); assert!(text.contains("Kept from Hermes's version"), "{text}"); assert!(tidy::entries(&b.git_dir).is_empty()); b.sync().unwrap(); a.sync().unwrap(); assert_eq!(read(&a, "people/ada.md"), text.as_bytes()); assert_eq!(files(&a.root), ["people/ada.md"]); } const FAKE_KEY: &str = "AWS_KEY=AKIAIOSFODNN7EXAMPLE\n"; #[test] fn a_held_note_in_a_gbrain_vault_is_kept_aside_not_copied_and_stays_held() { let w = World::new(VaultKind::Gbrain); let a = w.device("Codex"); write(&a, "ops.md", "ops\n"); save_and_sync(&a); let b = w.device("Hermes"); let held = format!("ops\n{FAKE_KEY}"); write(&a, "ops.md", &held); a.save_changes(None, &HashSet::new()).unwrap(); assert_eq!(a.secret_holds().unwrap().len(), 1); write(&b, "ops.md", "ops\nnew runbook link\n"); save_and_sync(&b); let report = a.sync().unwrap(); assert_eq!(report.held_to_tidy, vec!["ops.md".to_string()]); assert!(report.set_aside.is_empty()); assert_eq!(read(&a, "ops.md"), b"ops\nnew runbook link\n"); assert_eq!(files(&a.root), ["ops.md"], "no copy in the folder"); assert!(a.secret_holds().unwrap().is_empty(), "the working note is the plain incoming one"); // Still held (P2, X6): counts as a held secret everywhere a held note does, so the vault is red, not just amber. let held_notes: Vec = a.all_secret_holds().unwrap().into_iter().map(|n| n.path).collect(); assert_eq!(held_notes, ["ops.md"]); let cfg = lune_core::config::VaultConfig { name: "Brain".into(), path: a.root.clone(), remote: w.remote.to_str().unwrap().into(), branch: "main".into(), kind: VaultKind::Gbrain, ..Default::default() }; let st = lune_core::status::of(&cfg, "Codex"); assert_eq!(st.level, "secret"); assert_eq!(st.secrets.len(), 1); assert_eq!(st.secrets[0].path, "ops.md"); let entries = tidy::entries(&a.git_dir); assert_eq!(entries.len(), 1); assert!(entries[0].held); assert_eq!(tidy::mine_bytes(&a.git_dir, &entries[0].id).unwrap(), held.as_bytes()); // "Not a secret" / "Replace with a pointer" work on the kept-aside version too. let (entry, hits) = tidy::held_aside_hits(&a, "ops.md", None).unwrap().unwrap(); tidy::replace_held_aside(&a, &entry, &hits, None, "search prod in Secrets Manager").unwrap(); assert!(a.all_secret_holds().unwrap().is_empty(), "no longer held once the secret is replaced"); assert!(String::from_utf8(tidy::mine_bytes(&a.git_dir, &entry.id).unwrap()).unwrap().contains("Secrets Manager")); // Put the original back for the next check. tidy::put(&a.git_dir, &entry, held.as_bytes()).unwrap(); assert_eq!(a.all_secret_holds().unwrap().len(), 1); // Putting it back brings the secret check back with it: held, not shared. tidy::keep(&a, "ops.md", Keep::Mine).unwrap(); assert_eq!(read(&a, "ops.md"), held.as_bytes()); let holds: Vec = a.secret_holds().unwrap().into_iter().map(|n| n.path).collect(); assert_eq!(holds, ["ops.md"]); a.sync().unwrap(); b.sync().unwrap(); assert!(!String::from_utf8(read(&b, "ops.md")).unwrap().contains("AKIA"), "the key never travelled"); assert!(!copy_anywhere_in_history(a.repo())); } #[test] fn undo_in_a_gbrain_vault_keeps_the_brought_back_version_and_tidies_the_other() { let w = World::new(VaultKind::Gbrain); let a = w.device("Codex"); for i in 0..20 { write(&a, &format!("notes/{i:02}.md"), format!("note {i}\nline two\n")); } save_and_sync(&a); let b = w.device("Hermes"); for i in 0..10 { fs::remove_file(a.root.join(format!("notes/{i:02}.md"))).unwrap(); } a.save_changes(None, &HashSet::new()).unwrap(); write(&b, "notes/03.md", "note 3\nline two\nedited on hermes\n"); save_and_sync(&b); a.sync().unwrap(); let clashes = a.undo_held().unwrap(); assert_eq!(clashes.to_tidy, vec!["notes/03.md".to_string()]); assert!(clashes.copies.is_empty()); assert_eq!(files(&a.root).len(), 20, "no extra note"); assert_eq!(read(&a, "notes/03.md"), b"note 3\nline two\n", "what the undo brought back is in place"); let entries = tidy::entries(&a.git_dir); assert_eq!(entries.len(), 1); assert_eq!(tidy::mine_bytes(&a.git_dir, &entries[0].id).unwrap(), b"note 3\nline two\nedited on hermes\n"); assert!(!copy_anywhere_in_history(a.repo())); } #[test] fn obsidian_vaults_still_make_version_copies() { let w = World::new(VaultKind::Obsidian); let (a, b, codex, hermes) = clash(&w); assert_eq!(read(&b, "people/ada.md"), codex.as_bytes()); assert_eq!(read(&b, "people/ada (Hermes's version).md"), hermes.as_bytes()); assert!(tidy::entries(&b.git_dir).is_empty()); assert_eq!(tidy::list(&b).unwrap().len(), 1); assert!(!tidy::list(&b).unwrap()[0].local); assert_eq!(read(&a, "people/ada (Hermes's version).md"), hermes.as_bytes()); // Both appended: still a copy for Obsidian (as today). let w = World::new(VaultKind::Obsidian); let (a, b) = two(&w); write(&a, "people/ada.md", format!("{PAGE}- codex\n")); write(&b, "people/ada.md", format!("{PAGE}- hermes\n")); save_and_sync(&a); let r = save_and_sync(&b); assert_eq!(r.kept_both.len(), 1); assert!(r.joined.is_empty() && r.to_tidy.is_empty()); } #[test] fn the_kind_is_read_when_the_clash_happens() { // A vault opened as Obsidian, then marked GBrain while it runs: the next clash makes no copy. let w = World::new(VaultKind::Obsidian); let (a, b) = two(&w); vault::apply_kind_ignores(b.repo(), VaultKind::Gbrain).unwrap(); write(&a, "people/ada.md", PAGE.replace("engines", "steam engines")); write(&b, "people/ada.md", PAGE.replace("engines", "analytical engines")); save_and_sync(&a); let r = save_and_sync(&b); assert_eq!(r.to_tidy.len(), 1); assert_eq!(files(&b.root), ["people/ada.md"]); }