Files
lune/core/src/vault.rs
Adnan Zahir ac5dba46df 0.1.5: uploading checks everything first; no silent joining
- Before anything is made on the team, upload checks the vault the way the
  hub will (the hub's per-entry check now lives in core): a vault on one
  device only holds every line that looks like a secret as a red card to
  decide; lines marked "not a secret" are told to the team's hub at upload;
  history with a flagged entry offers a fresh start. A refused upload no
  longer leaves an empty vault on the team.
- A vault on one device joins a same-named team vault only when they share
  history; otherwise the team's vault arrives beside it in its own folder.
  (A failed upload's empty vault had silently swallowed Brain.)
- The upload sheet follows the vault live and waits for those decisions.
- Full checks of such a vault are cached by content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:23:28 +07:00

936 lines
40 KiB
Rust

//! One vault on disk: setting it up, saving bursts of edits as history entries, and syncing with the remote.
use crate::config::VaultConfig;
use crate::guard::{self, Damage, HeldBurst};
use crate::names;
use crate::remote;
use crate::secrets::{self, Hit};
use crate::state;
use anyhow::{Context, Result, bail};
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
use git2::{
AutotagOption, Commit, ConfigLevel, Direction, ErrorCode, FetchOptions, FileMode, IndexAddOption,
IndexEntry, Oid, PushOptions, Repository, RepositoryInitOptions, Signature, Sort, StatusOptions, TreeWalkMode,
TreeWalkResult,
};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
/// Ignored on every device: per-device Obsidian state, trash and OS junk.
const DEFAULT_IGNORES: &str = "\
# lune defaults
/.obsidian/workspace*.json
/.obsidian/cache
/.trash/
.DS_Store
Thumbs.db
";
/// Bytes in = bytes out: no line-ending, encoding or filter rewriting, whatever the vault's own attributes say.
const BYTE_EXACT_ATTRIBUTES: &str = "* -text -eol -ident -filter -working-tree-encoding\n";
pub struct Vault {
pub name: String,
pub root: PathBuf,
pub git_dir: PathBuf,
pub branch: String,
pub label: String,
repo: Repository,
last_refusal: RefCell<Option<String>>,
}
/// A burst of edits saved as one history entry.
#[derive(Debug)]
pub struct Saved {
pub id: Oid,
pub message: String,
pub files: Vec<String>,
/// Set when the runaway guard held this burst back.
pub held: Option<Damage>,
}
/// A note whose change is held back because it seems to contain a secret.
#[derive(Debug, Clone)]
pub struct SecretNote {
pub path: String,
pub hits: Vec<Hit>,
}
/// What one sync round did, in terms the run log can print.
#[derive(Debug, Default)]
pub struct SyncReport {
/// Files that changed locally because of others' edits.
pub received: Vec<String>,
/// Device labels those edits came from.
pub from: BTreeSet<String>,
/// (note, copy saved beside it) for every same-lines clash.
pub kept_both: Vec<(String, String)>,
/// (old path, new path) for files renamed because their names differed only by case.
pub case_renamed: Vec<(String, String)>,
/// Number of local history entries that went out.
pub shared: usize,
/// Incoming changes touch a file that is still being edited here; they'll land after it settles.
pub waiting_for_local_edits: bool,
/// (note, copy) for held notes moved aside so an incoming version could land.
pub set_aside: Vec<(String, String)>,
/// A big change is held here, so nothing from this device was shared.
pub holding: bool,
/// Local changes not shared because this device's person only has read access.
pub read_only: bool,
}
impl Vault {
pub fn open(cfg: &VaultConfig, label: &str) -> Result<Vault> {
let repo = Repository::open(&cfg.path)
.with_context(|| format!("can't open the vault folder {}", cfg.path.display()))?;
let root = repo.workdir().context("vault has no working folder")?.to_path_buf();
let root = std::fs::canonicalize(&root).unwrap_or(root);
Ok(Vault {
name: cfg.name.clone(),
git_dir: repo.path().to_path_buf(),
root,
branch: cfg.branch.clone(),
label: label.to_string(),
repo,
last_refusal: RefCell::new(None),
})
}
pub fn repo(&self) -> &Repository {
&self.repo
}
fn branch_ref(&self) -> String {
format!("refs/heads/{}", self.branch)
}
fn remote_ref(&self) -> String {
format!("refs/remotes/origin/{}", self.branch)
}
fn signature(&self) -> Result<Signature<'static>> {
let slug: String = self
.label
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' })
.collect();
Ok(Signature::now(&self.label, &format!("{slug}@lune.device"))?)
}
pub fn head_commit(&self) -> Result<Option<Commit<'_>>> {
match self.repo.find_reference(&self.branch_ref()) {
Ok(r) => Ok(Some(r.peel_to_commit()?)),
Err(e) if e.code() == ErrorCode::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn remote_commit(&self) -> Result<Option<Commit<'_>>> {
match self.repo.find_reference(&self.remote_ref()) {
Ok(r) => Ok(Some(r.peel_to_commit()?)),
Err(e) if e.code() == ErrorCode::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
pub fn is_ignored(&self, rel: &Path) -> bool {
self.repo.is_path_ignored(rel).unwrap_or(false)
}
/// Saves every changed file as one history entry, except paths in `skip` (still being written)
/// and notes that seem to contain a secret. A runaway burst is saved but held (S6).
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
self.save(message, skip, true)
}
/// Like `save_changes`, without the runaway guard: for changes the app makes on the owner's say-so.
pub fn save_unguarded(&self, message: Option<&str>) -> Result<Option<Saved>> {
self.save(message, &HashSet::new(), false)
}
fn save(&self, message: Option<&str>, skip: &HashSet<String>, guarded: bool) -> Result<Option<Saved>> {
let mut skip = skip.clone();
skip.extend(self.secret_holds()?.into_iter().map(|n| n.path));
let mut index = self.repo.index()?;
index.read(false)?;
let mut filter = |p: &Path, _: &[u8]| -> i32 { if skip.contains(&names::slash_path(p)) { 1 } else { 0 } };
index.add_all(["*"], IndexAddOption::DEFAULT, Some(&mut filter))?;
index.update_all(["*"], Some(&mut filter))?;
index.write()?;
let tree = self.repo.find_tree(index.write_tree()?)?;
let parent = self.head_commit()?;
let old_tree = parent.as_ref().map(|c| c.tree()).transpose()?;
let diff = self.repo.diff_tree_to_tree(old_tree.as_ref(), Some(&tree), None)?;
let files: Vec<String> = diff
.deltas()
.filter_map(|d| d.new_file().path().or(d.old_file().path()).map(names::slash_path))
.collect();
if files.is_empty() {
return Ok(None);
}
let message = match message {
Some(m) => m.to_string(),
None => describe_files(&diff),
};
let damage = match &old_tree {
Some(old) if guarded => Some(guard::assess(&self.repo, old, &tree)?).filter(|d| d.is_runaway()),
_ => None,
};
let sig = self.signature()?;
let parents: Vec<&Commit> = parent.iter().collect();
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
if let Some(d) = damage {
let mut held = guard::load(&self.git_dir);
held.push(HeldBurst {
id: id.to_string(),
message: message.clone(),
removed: d.removed,
rewritten: d.rewritten,
total: d.total,
at: chrono::Utc::now().timestamp(),
});
guard::save(&self.git_dir, &held)?;
}
Ok(Some(Saved { id, message, files, held: damage }))
}
/// Changed notes (not yet saved) that seem to contain a secret on a new line.
pub fn secret_holds(&self) -> Result<Vec<SecretNote>> {
static SCANNED: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<Oid, Vec<Hit>>>> =
std::sync::LazyLock::new(Default::default);
let allowed = secrets::load_allowed(&self.git_dir);
// A vault on this device only hasn't shared anything with where it may go next (a team), so every line counts.
let local = self.is_local();
let head_tree = if local { None } else { self.head_commit()?.map(|c| c.tree()).transpose()? };
let mut known_blobs: Option<HashSet<Oid>> = None;
let mut opts = StatusOptions::new();
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false).include_unmodified(local);
let mut out = vec![];
for entry in self.repo.statuses(Some(&mut opts))?.iter() {
let st = entry.status();
if st.is_wt_deleted() || st.is_index_deleted() {
continue;
}
let Ok(path) = entry.path() else { continue };
let Ok(bytes) = std::fs::read(self.root.join(path)) else { continue };
let old = match head_tree.as_ref().and_then(|t| t.get_path(Path::new(path)).ok()) {
Some(e) => Some(self.repo.find_blob(e.id())?.content().to_vec()),
None if local => None,
None => {
// A new file whose exact bytes are already in the vault (a copy or a move) was already shared.
let known = known_blobs.get_or_insert_with(|| blob_ids(head_tree.as_ref()));
if known.contains(&Oid::hash_object(git2::ObjectType::Blob, &bytes)?) {
continue;
}
None
}
};
let hits = if local {
// Every note is checked each time here, so results are kept by content: only edits cost a scan.
let id = Oid::hash_object(git2::ObjectType::Blob, &bytes)?;
let mut cache = SCANNED.lock().unwrap();
let all = cache.entry(id).or_insert_with(|| secrets::scan_bytes(&bytes, None, &HashSet::new()));
all.iter().filter(|h| !allowed.contains(&h.line_hash)).cloned().collect()
} else {
secrets::scan_bytes(&bytes, old.as_deref(), &allowed)
};
if !hits.is_empty() {
out.push(SecretNote { path: path.to_string(), hits });
}
}
Ok(out)
}
/// Owner says the held big change was intended: share it.
pub fn share_held(&self) -> Result<Vec<HeldBurst>> {
let held = guard::load(&self.git_dir);
guard::save(&self.git_dir, &[])?;
Ok(held)
}
/// Owner says the held big change was a mistake: bring back exactly what it removed or rewrote.
/// Notes edited elsewhere meanwhile keep both versions. The caller holds the op lock.
pub fn undo_held(&self) -> Result<Vec<(String, String)>> {
let held = guard::load(&self.git_dir);
let mut kept_both = vec![];
for h in held.iter().rev() {
let burst = self.repo.find_commit(Oid::from_str(&h.id)?)?;
let head = self.head_commit()?.context("nothing to undo")?;
let mut index = self.repo.revert_commit(&burst, &head, 0, None)?;
self.keep_both(&mut index, &mut kept_both)?;
let reverted = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
// Notes the burst added stay: undo only brings back what it removed or rewrote.
let added = self.repo.diff_tree_to_tree(Some(&burst.parent(0)?.tree()?), Some(&burst.tree()?), None)?;
let head_tree = head.tree()?;
let mut keep = TreeUpdateBuilder::new();
for d in added.deltas().filter(|d| d.status() == git2::Delta::Added) {
if let Some(p) = d.new_file().path()
&& let Ok(e) = head_tree.get_path(p)
{
keep.upsert(p, e.id(), file_mode(e.filemode()));
}
}
let tree = self.repo.find_tree(keep.create_updated(&self.repo, &reverted)?)?;
if tree.id() == head.tree_id() {
continue;
}
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, &format!("Undid: {}", h.message), &tree, &[&head])?;
self.move_to(id).map_err(|e| {
if e.code() == ErrorCode::Conflict {
anyhow::anyhow!("some of those notes are being edited right now — try again in a few seconds")
} else {
e.into()
}
})?;
}
guard::save(&self.git_dir, &[])?;
Ok(kept_both)
}
/// Points the vault at a new remote (e.g. moving onto the hub). Its next sync shares everything there.
pub fn relink(&self, url: &str) -> Result<()> {
if self.is_local() {
self.repo.remote("origin", url)?;
return Ok(());
}
self.repo.remote_set_url("origin", url)?;
if let Ok(mut r) = self.repo.find_reference(&self.remote_ref()) {
r.delete()?;
}
Ok(())
}
/// Where this vault shares its history now, if anywhere.
pub fn remote_url(&self) -> Option<String> {
self.repo.find_remote("origin").ok().and_then(|r| r.url().ok().map(String::from))
}
/// Makes the folder share where its settings say: their remote, or nowhere for a vault on this device only.
/// The settings are what the app shows, so they win. Returns whether anything changed.
pub fn follow(&self, remote: &str) -> Result<bool> {
match (self.remote_url(), remote.is_empty()) {
(None, true) => Ok(false),
(Some(_), true) => self.unlink().map(|_| true),
(Some(url), false) if url == remote => Ok(false),
_ => self.relink(remote).map(|_| true),
}
}
/// A vault with no remote lives on this device only: it keeps saving history, and shares nowhere.
pub fn is_local(&self) -> bool {
self.repo.find_remote("origin").is_err()
}
/// Stops sharing with the remote; the notes and their history stay here.
pub fn unlink(&self) -> Result<()> {
if !self.is_local() {
self.repo.remote_delete("origin")?;
}
Ok(())
}
/// Whether this vault's history and the one at `url` share entries: the same vault, kept in two places.
pub fn shares_history_with(&self, url: &str) -> Result<bool> {
const PROBE: &str = "refs/lune/probe";
let mut remote = self.repo.remote_anonymous(url)?;
let mut opts = FetchOptions::new();
opts.remote_callbacks(remote::callbacks());
opts.download_tags(AutotagOption::None);
remote.fetch(&[format!("+{}:{PROBE}", self.branch_ref())], Some(&mut opts), None)?;
let theirs = self.repo.find_reference(PROBE).ok().and_then(|r| r.target());
let ours = self.head_commit()?.map(|c| c.id());
let shared = match (ours, theirs) {
(Some(a), Some(b)) => self.repo.merge_base(a, b).is_ok(),
_ => false,
};
if let Ok(mut r) = self.repo.find_reference(PROBE) {
r.delete()?;
}
Ok(shared)
}
/// Starts history over with just the current notes (the old history stays only on this device).
/// Returns where history was, to go back if needed.
pub fn fresh_start(&self, message: &str) -> Result<Oid> {
let head = self.head_commit()?.context("the vault is empty")?;
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, message, &head.tree()?, &[])?;
self.repo.reference(&self.branch_ref(), id, true, "lune: fresh start")?;
Ok(head.id())
}
pub fn reset_history(&self, id: Oid) -> Result<()> {
self.repo.reference(&self.branch_ref(), id, true, "lune: put back")?;
Ok(())
}
/// After moving onto a remote whose history is unrelated (e.g. a fresh start on the hub), combine the
/// notes as one new entry on top of the remote's history, so this device's old history stays here.
pub fn join_unrelated(&self) -> Result<bool> {
self.fetch()?;
let (Some(local), Some(remote)) = (self.head_commit()?, self.remote_commit()?) else { return Ok(false) };
if self.repo.merge_base(local.id(), remote.id()).is_ok() {
return Ok(false);
}
let mut index = self.repo.merge_commits(&local, &remote, None)?;
let mut kept = vec![];
self.keep_both(&mut index, &mut kept)?;
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let sig = self.signature()?;
let id = self.repo.commit(None, &sig, &sig, &format!("Joined the shared copy from {}", self.label), &tree, &[&remote])?;
self.move_to(id)?;
Ok(true)
}
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
pub fn checkpoint(&self, message: &str) -> Result<Oid> {
if let Some(saved) = self.save_changes(Some(message), &HashSet::new())? {
return Ok(saved.id);
}
let head = self.head_commit()?.context("the vault is empty — nothing to checkpoint yet")?;
let sig = self.signature()?;
Ok(self.repo.commit(Some(&self.branch_ref()), &sig, &sig, message, &head.tree()?, &[&head])?)
}
pub fn fetch(&self) -> Result<()> {
let mut remote = self.repo.find_remote("origin")?;
let mut opts = FetchOptions::new();
opts.remote_callbacks(remote::callbacks());
opts.download_tags(AutotagOption::None);
let spec = format!("+{}:{}", self.branch_ref(), self.remote_ref());
remote.fetch(&[spec], Some(&mut opts), None)?;
Ok(())
}
/// This device's role in the vault, as last told by the hub. None for plain Git remotes.
pub fn role(&self) -> Option<String> {
std::fs::read_to_string(state::lune_dir(&self.git_dir).join("role")).ok().map(|s| s.trim().to_string())
}
/// Pushes local history. Returns false if it was refused (the remote moved on, or said no).
fn push(&self) -> Result<bool> {
let mut remote = self.repo.find_remote("origin")?;
let rejected = RefCell::new(None::<String>);
let said = RefCell::new(String::new());
let mut cb = remote::callbacks();
cb.push_update_reference(|_, status| {
if let Some(s) = status {
*rejected.borrow_mut() = Some(s.to_string());
}
Ok(())
});
cb.sideband_progress(|text| {
said.borrow_mut().push_str(&String::from_utf8_lossy(text));
true
});
let mut opts = PushOptions::new();
opts.remote_callbacks(cb);
let spec = format!("{0}:{0}", self.branch_ref());
if let Err(e) = remote.push(&[spec], Some(&mut opts)) {
if e.code() == ErrorCode::NotFastForward || e.message().contains("fast") {
return Ok(false);
}
return Err(e.into());
}
drop(opts);
if let Some(status) = rejected.borrow().clone() {
let said: Vec<String> = said.borrow().lines().filter(|l| l.contains("lune:")).map(|l| l.replace("lune:", "").trim().to_string()).collect();
*self.last_refusal.borrow_mut() = Some(if said.is_empty() { status } else { said.join("; ") });
return Ok(false);
}
if let Some(head) = self.head_commit()? {
self.repo.reference(&self.remote_ref(), head.id(), true, "lune: shared")?;
}
Ok(true)
}
/// Sends this device's whole history to `dst` on the remote (the hub's handover area for this device).
pub fn hand_over(&self, dst: &str) -> Result<()> {
self.push_handover(&self.branch_ref(), dst)
}
/// The current notes as one entry, for a handover the hub refused because older history has something that
/// looks like a secret (P3): every such line is replaced with `pointer`. It sits on top of the last shared
/// state, so reviewing it shows just what this device changed. Returns what was handed over.
pub fn hand_over_current(&self, dst: &str, pointer: &str) -> Result<Oid> {
let head = self.head_commit()?.context("nothing to hand over")?;
let tree = head.tree()?;
let mut cleaned = vec![];
tree.walk(TreeWalkMode::PreOrder, |dir, e| {
if let Ok(blob) = e.to_object(&self.repo).and_then(|o| o.peel_to_blob()) {
let hits = secrets::scan_bytes(blob.content(), None, &HashSet::new());
if !hits.is_empty() {
let text = String::from_utf8_lossy(blob.content()).into_owned();
cleaned.push((format!("{dir}{}", e.name().unwrap_or_default()), secrets::replace_with_pointer(&text, &hits, None, pointer)));
}
}
TreeWalkResult::Ok
})?;
let mut update = TreeUpdateBuilder::new();
for (path, text) in &cleaned {
update.upsert(path, self.repo.blob(text.as_bytes())?, FileMode::Blob);
}
let tree = self.repo.find_tree(update.create_updated(&self.repo, &tree)?)?;
let parent = self.remote_commit()?;
let sig = self.signature()?;
let message = format!("Handed over by {} ({} with possible secrets removed)", self.label, cleaned.len());
let id = self.repo.commit(None, &sig, &sig, &message, &tree, &parent.iter().collect::<Vec<_>>())?;
const TEMP: &str = "refs/lune/handover";
self.repo.reference(TEMP, id, true, "lune: handover")?;
let sent = self.push_handover(TEMP, dst);
if let Ok(mut r) = self.repo.find_reference(TEMP) {
let _ = r.delete();
}
sent.map(|_| id)
}
fn push_handover(&self, src: &str, dst: &str) -> Result<()> {
let mut remote = self.repo.find_remote("origin")?;
let rejected = RefCell::new(None::<String>);
let mut cb = remote::callbacks();
cb.push_update_reference(|_, status| {
if let Some(s) = status {
*rejected.borrow_mut() = Some(s.to_string());
}
Ok(())
});
let mut opts = PushOptions::new();
opts.remote_callbacks(cb);
remote.push(&[format!("+{src}:{dst}")], Some(&mut opts))?;
drop(opts);
if let Some(why) = rejected.into_inner() {
bail!("the hub didn't take the handover: {why}");
}
Ok(())
}
/// One sync round: fetch, combine, write the result to disk, share local history.
pub fn sync(&self) -> Result<SyncReport> {
let mut report = SyncReport::default();
if self.is_local() {
return Ok(report);
}
for _ in 0..3 {
self.fetch()?;
let local = self.head_commit()?;
let incoming = self.remote_commit()?;
let target = match (&local, &incoming) {
(_, None) => None,
(None, Some(r)) => Some(r.id()),
(Some(l), Some(r)) if l.id() == r.id() => None,
(Some(l), Some(r)) => {
let (ahead, behind) = self.repo.graph_ahead_behind(l.id(), r.id())?;
match (ahead, behind) {
(_, 0) => None,
(0, _) => Some(r.id()),
_ => Some(self.combine(l, r, &mut report)?),
}
}
};
if let Some(target) = target {
let target = self.fix_case_clashes(target, &mut report)?;
let incoming = incoming.as_ref().unwrap();
self.note_incoming(local.as_ref(), incoming, target, &mut report)?;
self.set_aside_held_notes(target, &mut report)?;
match self.move_to(target) {
Ok(()) => {}
Err(e) if e.code() == ErrorCode::Conflict => {
report.waiting_for_local_edits = true;
return Ok(report);
}
Err(e) => return Err(e.into()),
}
}
let Some(local) = self.head_commit()? else { return Ok(report) };
let ahead = match self.remote_commit()? {
Some(r) if r.id() == local.id() => 0,
Some(r) => self.repo.graph_ahead_behind(local.id(), r.id())?.0,
None => 1,
};
if ahead == 0 {
return Ok(report);
}
if !guard::load(&self.git_dir).is_empty() {
report.holding = true;
return Ok(report);
}
if self.role().is_some_and(|r| !crate::hub::can_edit(&r)) {
report.read_only = true;
return Ok(report);
}
if self.push()? {
report.shared += ahead;
return Ok(report);
}
// Refused without the remote having moved on: the remote said no, so say why.
let before = self.remote_commit()?.map(|c| c.id());
self.fetch()?;
if self.remote_commit()?.map(|c| c.id()) == before {
let why = self.last_refusal.borrow().clone().unwrap_or_else(|| "no reason given".into());
bail!("the hub refused these changes: {why}");
}
}
bail!("the remote kept changing while sharing; will try again shortly")
}
/// Combines two lines of history. Same-lines clashes keep both: incoming in place, ours beside it (S4).
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
let mut index = self.repo.merge_commits(local, incoming, None)?;
self.keep_both(&mut index, &mut report.kept_both)?;
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
let from = incoming.author().name().unwrap_or("another device").to_string();
let mut message = format!("Combined changes from {from}");
if !report.kept_both.is_empty() {
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
}
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
}
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it (S4).
fn keep_both(&self, index: &mut git2::Index, kept_both: &mut Vec<(String, String)>) -> Result<()> {
keep_both(index, &self.label, kept_both)
}
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
/// nothing is overwritten; everywhere, report them.
fn fix_case_clashes(&self, target: Oid, report: &mut SyncReport) -> Result<Oid> {
let commit = self.repo.find_commit(target)?;
let tree = commit.tree()?;
let mut files: Vec<(String, Oid, i32)> = vec![];
tree.walk(TreeWalkMode::PreOrder, |dir, entry| {
if entry.kind() == Some(git2::ObjectType::Blob) {
files.push((format!("{dir}{}", entry.name().unwrap_or("")), entry.id(), entry.filemode()));
}
TreeWalkResult::Ok
})?;
let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (i, (p, _, _)) in files.iter().enumerate() {
groups.entry(p.to_lowercase()).or_default().push(i);
}
let clashes: Vec<Vec<usize>> = groups.into_values().filter(|g| g.len() > 1).collect();
if clashes.is_empty() {
return Ok(target);
}
let ignorecase = self.repo.config()?.get_bool("core.ignorecase").unwrap_or(false);
let mut st = state::SyncState::load(&self.git_dir);
st.case_clashes = clashes.iter().flatten().map(|&i| files[i].0.clone()).collect();
st.save(&self.git_dir)?;
if !ignorecase {
return Ok(target);
}
let mut taken: HashSet<String> = files.iter().map(|f| f.0.to_lowercase()).collect();
let mut update = TreeUpdateBuilder::new();
for group in clashes {
for &i in &group[1..] {
let (path, id, mode) = &files[i];
let new = (1..)
.map(|n| names::clash_name(path, n))
.find(|p| !taken.contains(&p.to_lowercase()))
.unwrap();
taken.insert(new.to_lowercase());
update.remove(path.as_str());
update.upsert(new.as_str(), *id, file_mode(*mode));
report.case_renamed.push((path.clone(), new));
}
}
let tree = self.repo.find_tree(update.create_updated(&self.repo, &tree)?)?;
let names: Vec<String> = report.case_renamed.iter().map(|(a, b)| format!("{a} → {b}")).collect();
let message = format!("Renamed notes whose names differed only by case: {}", names.join(", "));
let sig = self.signature()?;
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[&commit])?)
}
fn note_incoming(&self, local: Option<&Commit>, incoming: &Commit, target: Oid, report: &mut SyncReport) -> Result<()> {
let old_tree = local.map(|c| c.tree()).transpose()?;
let new_tree = self.repo.find_commit(target)?.tree()?;
let diff = self.repo.diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), None)?;
report.received = diff
.deltas()
.filter_map(|d| d.new_file().path().or(d.old_file().path()).map(names::slash_path))
.collect();
let mut walk = self.repo.revwalk()?;
walk.set_sorting(Sort::TOPOLOGICAL)?;
walk.push(incoming.id())?;
if let Some(l) = local {
walk.hide(l.id())?;
}
for id in walk {
let c = self.repo.find_commit(id?)?;
if let Ok(name) = c.author().name()
&& name != self.label
{
report.from.insert(name.to_string());
}
}
Ok(())
}
/// A held note can't take an incoming version in place, and must not wait for it either:
/// move the local version beside it (still held) and put back the saved one so the update lands.
fn set_aside_held_notes(&self, target: Oid, report: &mut SyncReport) -> Result<()> {
let held = self.secret_holds()?;
if held.is_empty() {
return Ok(());
}
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
let target_tree = self.repo.find_commit(target)?.tree()?;
for note in held {
let p = Path::new(&note.path);
let current = head_tree.as_ref().and_then(|t| t.get_path(p).ok()).map(|e| e.id());
let incoming = target_tree.get_path(p).ok().map(|e| e.id());
if current == incoming {
continue;
}
let copy = (1..)
.map(|n| names::copy_name(&note.path, &self.label, n))
.find(|c| !self.root.join(c).exists() && target_tree.get_path(Path::new(c)).is_err())
.unwrap();
std::fs::rename(self.root.join(p), self.root.join(&copy))?;
if let Some(id) = current {
std::fs::write(self.root.join(p), self.repo.find_blob(id)?.content())?;
}
report.set_aside.push((note.path, copy));
}
Ok(())
}
/// Writes `target` to the folder without touching anything that's still being edited, then makes it current.
fn move_to(&self, target: Oid) -> Result<(), git2::Error> {
let commit = self.repo.find_commit(target)?;
let mut co = CheckoutBuilder::new();
co.safe();
self.repo.checkout_tree(commit.as_object(), Some(&mut co))?;
self.repo.reference(&self.branch_ref(), target, true, "lune: synced")?;
Ok(())
}
/// Files changed here that haven't reached the remote yet (saved or not).
pub fn waiting_files(&self) -> Result<usize> {
let mut files: HashSet<String> = HashSet::new();
if let Some(head) = self.head_commit()? {
let base = match self.remote_commit()? {
Some(r) => match self.repo.merge_base(head.id(), r.id()) {
Ok(b) => Some(self.repo.find_commit(b)?.tree()?),
Err(_) => None,
},
None => None,
};
let diff = self.repo.diff_tree_to_tree(base.as_ref(), Some(&head.tree()?), None)?;
files.extend(diff.deltas().filter_map(|d| d.new_file().path().map(names::slash_path)));
}
let mut opts = StatusOptions::new();
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false);
for s in self.repo.statuses(Some(&mut opts))?.iter() {
if let Ok(p) = s.path() {
files.insert(p.to_string());
}
}
Ok(files.len())
}
/// Every tracked file name, for the tidy list.
pub fn tracked_files(&self) -> Result<Vec<String>> {
let mut index = self.repo.index()?;
index.read(false)?;
Ok(index.iter().map(|e| String::from_utf8_lossy(&e.path).into_owned()).collect())
}
}
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it labeled
/// with `label` (S4). Used for syncing, undo, and keeping handovers on the hub.
pub fn keep_both(index: &mut git2::Index, label: &str, kept_both: &mut Vec<(String, String)>) -> Result<()> {
if index.has_conflicts() {
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
for c in conflicts {
for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() {
let _ = index.conflict_remove(&names::bytes_path(&e.path));
}
match (c.our, c.their) {
(Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => {
let note = String::from_utf8_lossy(&theirs.path).into_owned();
let copy = (1..)
.map(|n| names::copy_name(&note, label, n))
.find(|p| index.get_path(Path::new(p), 0).is_none())
.unwrap();
index.add(&stage0(&theirs, None))?;
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
kept_both.push((note, copy));
}
// Different paths, or one side removed the note: keep whatever still exists.
(ours, theirs) => {
for e in [ours, theirs].into_iter().flatten() {
index.add(&stage0(&e, None))?;
}
}
}
}
}
Ok(())
}
fn blob_ids(tree: Option<&git2::Tree>) -> HashSet<Oid> {
let mut ids = HashSet::new();
if let Some(t) = tree {
let _ = t.walk(TreeWalkMode::PreOrder, |_, e| {
ids.insert(e.id());
TreeWalkResult::Ok
});
}
ids
}
fn stage0(e: &IndexEntry, path: Option<&[u8]>) -> IndexEntry {
let mut e = IndexEntry { path: e.path.clone(), ..*e };
e.flags = 0;
e.flags_extended = 0;
if let Some(p) = path {
e.path = p.to_vec();
}
e
}
fn file_mode(mode: i32) -> FileMode {
match mode {
0o100755 => FileMode::BlobExecutable,
0o120000 => FileMode::Link,
_ => FileMode::Blob,
}
}
fn describe_files(diff: &git2::Diff) -> String {
let deltas: Vec<_> = diff.deltas().collect();
if let [d] = deltas.as_slice() {
let path = d.new_file().path().or(d.old_file().path()).map(names::slash_path).unwrap_or_default();
let verb = match d.status() {
git2::Delta::Added | git2::Delta::Untracked => "Added",
git2::Delta::Deleted => "Removed",
git2::Delta::Renamed => "Renamed",
_ => "Updated",
};
return format!("{verb} {path}");
}
let verb = match deltas.iter().map(|d| d.status()).collect::<Vec<_>>() {
s if s.iter().all(|&x| x == git2::Delta::Deleted) => "Removed",
s if s.iter().all(|&x| matches!(x, git2::Delta::Added | git2::Delta::Untracked)) => "Added",
_ => "Updated",
};
format!("{verb} {} notes", deltas.len())
}
/// What `add` did with the folder.
pub enum Added {
Downloaded(usize),
Adopted(usize),
StartedEmpty,
}
/// Sets up `path` as a vault shared through `remote`: clones into an empty folder, adopts an existing one.
/// A failed first sync isn't fatal: the vault is set up and the runner will retry.
pub fn add(name: &str, path: &Path, remote_url: &str, label: &str) -> Result<(VaultConfig, Added, Option<String>)> {
let existed = path.exists();
if existed && !path.is_dir() {
bail!("{} is a file, not a folder", path.display());
}
let empty = !existed || std::fs::read_dir(path)?.next().is_none();
std::fs::create_dir_all(path)?;
let path = std::fs::canonicalize(path)?;
let repo = if path.join(".git").exists() {
let repo = Repository::open(&path)?;
match repo.find_remote("origin") {
Ok(r) if r.url().ok() != Some(remote_url) => {
bail!("this folder already syncs with {} — not changing that", r.url().unwrap_or("?"))
}
Ok(_) => {}
Err(_) => {
repo.remote("origin", remote_url)?;
}
}
repo
} else {
let mut opts = RepositoryInitOptions::new();
opts.no_reinit(true);
let repo = Repository::init_opts(&path, &opts)?;
repo.remote("origin", remote_url)?;
repo
};
let branch = match repo.head() {
Ok(h) if h.is_branch() => h.shorthand().unwrap_or("main").to_string(),
_ => {
let b = remote_default_branch(&repo)?.unwrap_or_else(|| "main".into());
repo.set_head(&format!("refs/heads/{b}"))?;
b
}
};
configure(&repo)?;
let git_dir = repo.path().to_path_buf();
state::write_marker(&git_dir, name, !existed)?;
drop(repo);
let cfg = VaultConfig { name: name.into(), path: path.clone(), remote: remote_url.into(), branch, hub_vault: None, hub_url: None };
let vault = Vault::open(&cfg, label)?;
let _op = state::op_lock(&git_dir)?;
vault.save_changes(Some(&format!("Added the vault on {label}")), &HashSet::new())?;
let sync_error = vault.sync().err().map(|e| remote::describe_error(&e));
let count = vault.tracked_files()?.len();
let added = match empty {
true if count == 0 => Added::StartedEmpty,
true => Added::Downloaded(count),
false => Added::Adopted(count),
};
Ok((cfg, added, sync_error))
}
/// The remote's main line name, or None if the remote is empty. Fails if the remote can't be reached.
fn remote_default_branch(repo: &Repository) -> Result<Option<String>> {
let mut remote = repo.find_remote("origin")?;
let conn = remote
.connect_auth(Direction::Fetch, Some(remote::callbacks()), None)
.map_err(anyhow::Error::from)
.map_err(|e| anyhow::anyhow!("can't reach the remote: {}", remote::describe_error(&e)))?;
let name = conn
.default_branch()
.ok()
.and_then(|b| b.as_str().ok().and_then(|s| s.strip_prefix("refs/heads/")).map(String::from));
if name.is_some() {
return Ok(name);
}
// Some servers don't advertise HEAD; fall back to whatever line exists.
let heads: Vec<String> = conn
.list()?
.iter()
.filter_map(|h| h.name().strip_prefix("refs/heads/").map(String::from))
.collect();
Ok(["main", "master"]
.iter()
.find(|b| heads.iter().any(|h| h == *b))
.map(|b| b.to_string())
.or_else(|| heads.into_iter().next()))
}
/// Byte-exact settings and the default ignore list. Lives inside `.git/`, so the vault's files are untouched.
pub fn configure(repo: &Repository) -> Result<()> {
let mut cfg = repo.config()?.open_level(ConfigLevel::Local)?;
cfg.set_bool("core.autocrlf", false)?;
cfg.set_str("core.safecrlf", "false")?;
let info = repo.path().join("info");
std::fs::create_dir_all(&info)?;
std::fs::write(info.join("attributes"), BYTE_EXACT_ATTRIBUTES)?;
let exclude = info.join("exclude");
let current = std::fs::read_to_string(&exclude).unwrap_or_default();
if !current.contains("# lune defaults") {
let sep = if current.is_empty() || current.ends_with('\n') { "" } else { "\n" };
std::fs::write(&exclude, format!("{current}{sep}{DEFAULT_IGNORES}"))?;
}
Ok(())
}