Milestone 1: sync engine and lunesync CLI

Rust workspace with core (watch, settle, save, sync over a plain Git
remote, keep-both on same-line edits, offline queueing, tidy) and the
lunesync CLI (device, add, run, service, status, checkpoint, tidy,
history). Tests cover byte-exact round trips, keep-both, offline
catch-up and adopting an existing vault.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 23:11:24 +07:00
commit 25b8be5bbd
18 changed files with 3601 additions and 0 deletions

99
core/src/config.rs Normal file
View File

@@ -0,0 +1,99 @@
//! User config: device label and the list of vaults, stored as TOML in the OS config dir.
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
/// Label for this device, used to sign every history entry (S7).
#[serde(default)]
pub device_name: Option<String>,
/// How often to check the remote for new changes, in seconds.
#[serde(default)]
pub poll_seconds: Option<u64>,
#[serde(default, rename = "vault")]
pub vaults: Vec<VaultConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VaultConfig {
pub name: String,
pub path: PathBuf,
pub remote: String,
pub branch: String,
}
/// Directory holding `config.toml`. `LUNE_HOME` overrides it (handy for running two devices on one machine).
pub fn config_dir() -> Result<PathBuf> {
if let Some(home) = std::env::var_os("LUNE_HOME") {
return Ok(PathBuf::from(home));
}
let base = dirs::config_dir().context("can't find the config folder for this user")?;
Ok(base.join("lune"))
}
impl Config {
pub fn path() -> Result<PathBuf> {
Ok(config_dir()?.join("config.toml"))
}
pub fn load() -> Result<Config> {
let path = Self::path()?;
match std::fs::read_to_string(&path) {
Ok(text) => toml::from_str(&text).with_context(|| format!("can't read {}", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Config::default()),
Err(e) => Err(e).with_context(|| format!("can't read {}", path.display())),
}
}
pub fn save(&self) -> Result<()> {
let path = Self::path()?;
std::fs::create_dir_all(path.parent().unwrap())?;
let tmp = path.with_extension("toml.tmp");
std::fs::write(&tmp, toml::to_string_pretty(self)?)?;
std::fs::rename(&tmp, &path)?;
Ok(())
}
pub fn device_label(&self) -> String {
self.device_name.clone().unwrap_or_else(default_device_name)
}
pub fn poll_interval(&self) -> std::time::Duration {
std::time::Duration::from_secs(self.poll_seconds.unwrap_or(3).max(1))
}
pub fn find(&self, name: &str) -> Option<&VaultConfig> {
self.vaults.iter().find(|v| v.name.eq_ignore_ascii_case(name))
}
/// Picks a vault: by name if given, else the one containing `cwd`, else the only one.
pub fn pick(&self, name: Option<&str>, cwd: &Path) -> Result<&VaultConfig> {
if let Some(name) = name {
return self.find(name).with_context(|| format!("no vault named \"{name}\""));
}
if let Some(v) = self.containing(cwd) {
return Ok(v);
}
match self.vaults.as_slice() {
[] => bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>`"),
[only] => Ok(only),
_ => bail!("more than one vault — say which with --vault <name>"),
}
}
/// The vault whose folder contains `path`, if any.
pub fn containing(&self, path: &Path) -> Option<&VaultConfig> {
let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
self.vaults.iter().find(|v| {
let root = std::fs::canonicalize(&v.path).unwrap_or_else(|_| v.path.clone());
path.starts_with(root)
})
}
}
pub fn default_device_name() -> String {
let host = gethostname::gethostname().to_string_lossy().into_owned();
host.split('.').next().unwrap_or("this device").to_string()
}

11
core/src/lib.rs Normal file
View File

@@ -0,0 +1,11 @@
//! Lune's sync engine: keeps every copy of a vault current through a plain Git remote.
pub use git2;
pub mod config;
pub mod names;
pub mod remote;
pub mod runner;
pub mod state;
pub mod tidy;
pub mod vault;

83
core/src/names.rs Normal file
View File

@@ -0,0 +1,83 @@
//! File-name helpers: "kept both" copies, case-clash renames, and path conversions.
use std::path::{Path, PathBuf};
/// Vault-relative path with forward slashes, as Git stores it.
pub fn slash_path(p: &Path) -> String {
p.to_string_lossy().replace('\\', "/")
}
pub fn bytes_path(b: &[u8]) -> PathBuf {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
PathBuf::from(std::ffi::OsStr::from_bytes(b))
}
#[cfg(not(unix))]
PathBuf::from(String::from_utf8_lossy(b).into_owned())
}
/// Splits `dir/name.ext` into (`dir/name`, `.ext`). Dotfiles like `.env` have no extension.
fn split_ext(path: &str) -> (&str, &str) {
let file_start = path.rfind('/').map_or(0, |i| i + 1);
match path[file_start..].rfind('.') {
Some(dot) if dot > 0 => path.split_at(file_start + dot),
_ => (path, ""),
}
}
/// `runbook.md` → `runbook (Codex's version).md`; n > 1 adds a number.
pub fn copy_name(path: &str, label: &str, n: usize) -> String {
let (stem, ext) = split_ext(path);
let num = if n > 1 { format!(" {n}") } else { String::new() };
format!("{stem} ({label}'s version{num}){ext}")
}
/// `Notes.md` → `Notes (name clash).md`; n > 1 adds a number.
pub fn clash_name(path: &str, n: usize) -> String {
let (stem, ext) = split_ext(path);
let num = if n > 1 { format!(" {n}") } else { String::new() };
format!("{stem} (name clash{num}){ext}")
}
/// `runbook (from Codex).md`: what a copy becomes when both are kept for good.
pub fn kept_name(original: &str, label: &str, n: usize) -> String {
let (stem, ext) = split_ext(original);
let num = if n > 1 { format!(" {n}") } else { String::new() };
format!("{stem} (from {label}{num}){ext}")
}
/// If `path` is a kept-both copy, returns (original path, device label).
pub fn parse_copy(path: &str) -> Option<(String, String)> {
const MARK: &str = "'s version";
let file_start = path.rfind('/').map_or(0, |i| i + 1);
let name = &path[file_start..];
let v = name.rfind(MARK)?;
let open = name[..v].rfind(" (")?;
let label = &name[open + 2..v];
let rest = &name[v + MARK.len()..];
let close = rest.find(')')?;
let num = &rest[..close];
let num_ok = num.is_empty() || (num.len() > 1 && num.starts_with(' ') && num[1..].bytes().all(|b| b.is_ascii_digit()));
let ext = &rest[close + 1..];
if label.is_empty() || !num_ok || !(ext.is_empty() || ext.starts_with('.')) {
return None;
}
Some((format!("{}{}{}", &path[..file_start], &name[..open], ext), label.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn copy_names_round_trip() {
for (p, l, n) in [("runbook.md", "Codex", 1), ("ops/vm list.md", "Hermes", 2), (".env", "VPS", 1), ("a.tar.gz", "x", 1), ("README", "Mac", 3)] {
let c = copy_name(p, l, n);
assert_eq!(parse_copy(&c), Some((p.to_string(), l.to_string())), "{c}");
}
assert_eq!(copy_name("ops/runbook.md", "Codex", 1), "ops/runbook (Codex's version).md");
assert_eq!(parse_copy("notes/plain.md"), None);
assert_eq!(parse_copy("Sen's version.md"), None);
}
}

68
core/src/remote.rs Normal file
View File

@@ -0,0 +1,68 @@
//! Talking to the Git remote with whatever credentials the user already has (SSH agent, key files, credential helper).
use git2::{Cred, CredentialType, ErrorClass, ErrorCode, RemoteCallbacks};
use std::path::PathBuf;
pub fn callbacks<'a>() -> RemoteCallbacks<'a> {
let mut tried_agent = false;
let mut keys = default_key_files().into_iter();
let mut tried_helper = false;
let mut cb = RemoteCallbacks::new();
cb.credentials(move |url, username, allowed| {
let user = username.unwrap_or("git");
if allowed.contains(CredentialType::USERNAME) {
return Cred::username(user);
}
if allowed.contains(CredentialType::SSH_KEY) {
if !tried_agent {
tried_agent = true;
if std::env::var_os("SSH_AUTH_SOCK").is_some() {
return Cred::ssh_key_from_agent(user);
}
}
if let Some(key) = keys.next() {
return Cred::ssh_key(user, None, &key, None);
}
}
if allowed.contains(CredentialType::USER_PASS_PLAINTEXT) && !tried_helper {
tried_helper = true;
if let Ok(config) = git2::Config::open_default() {
return Cred::credential_helper(&config, url, username);
}
}
if allowed.contains(CredentialType::DEFAULT) {
return Cred::default();
}
Err(git2::Error::from_str("no working credentials for the remote"))
});
cb
}
fn default_key_files() -> Vec<PathBuf> {
let Some(home) = dirs::home_dir() else { return vec![] };
["id_ed25519", "id_ecdsa", "id_rsa"]
.iter()
.map(|n| home.join(".ssh").join(n))
.filter(|p| p.exists())
.collect()
}
/// Turns a remote failure into plain words for `status` and the run log.
pub fn describe_error(e: &anyhow::Error) -> String {
if let Some(g) = e.downcast_ref::<git2::Error>() {
if g.code() == ErrorCode::Auth {
return "the remote didn't accept our sign-in (check your SSH key or Git credentials)".into();
}
if matches!(g.class(), ErrorClass::Net | ErrorClass::Ssh | ErrorClass::Http | ErrorClass::Os)
|| g.code() == ErrorCode::Eof
{
return format!("offline — can't reach the remote ({})", g.message());
}
return g.message().to_string();
}
format!("{e:#}")
}
pub fn is_offline(e: &anyhow::Error) -> bool {
describe_error(e).starts_with("offline")
}

228
core/src/runner.rs Normal file
View File

@@ -0,0 +1,228 @@
//! The background loop: watch → settle → save → sync, for one vault.
use crate::config::VaultConfig;
use crate::remote;
use crate::state::{self, SyncState};
use crate::vault::{SyncReport, Vault};
use anyhow::{Result, bail};
use notify::{EventKind, RecursiveMode, Watcher};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::mpsc;
use std::time::{Duration, Instant};
/// Timing for bursts of edits (S2).
#[derive(Debug, Clone, Copy)]
pub struct Timing {
/// A burst ends after this much quiet...
pub quiet: Duration,
/// ...or at the latest this long after it started.
pub cap: Duration,
/// When a burst is cut at the cap, files changed more recently than this wait for the next one.
pub settle: Duration,
}
impl Default for Timing {
fn default() -> Self {
Timing { quiet: Duration::from_secs(5), cap: Duration::from_secs(60), settle: Duration::from_secs(2) }
}
}
/// Tracks the current burst of edits.
#[derive(Debug, Default)]
pub struct Burst {
started: Option<Instant>,
last: Option<Instant>,
touched: HashMap<String, Instant>,
}
impl Burst {
pub fn touch(&mut self, path: String, now: Instant) {
self.started.get_or_insert(now);
self.last = Some(now);
self.touched.insert(path, now);
}
pub fn is_idle(&self) -> bool {
self.started.is_none()
}
pub fn due(&self, now: Instant, t: &Timing) -> bool {
match (self.started, self.last) {
(Some(s), Some(l)) => now - l >= t.quiet || now - s >= t.cap,
_ => false,
}
}
/// Ends the burst. Returns files still changing, which must not be saved yet; they start the next burst.
pub fn take(&mut self, now: Instant, t: &Timing) -> HashSet<String> {
let unsettled: HashMap<String, Instant> =
self.touched.drain().filter(|(_, at)| now - *at < t.settle).collect();
let skip = unsettled.keys().cloned().collect();
*self = Burst::default();
if !unsettled.is_empty() {
self.started = Some(now);
self.last = unsettled.values().max().copied();
self.touched = unsettled;
}
skip
}
}
pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync);
/// Runs forever for one vault. `log(vault, message)` prints progress.
pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: Log) -> Result<()> {
let vault = Vault::open(cfg, label)?;
let Some(_running) = state::try_run_lock(&vault.git_dir)? else {
bail!("{} is already being synced by another lunesync run", cfg.name);
};
let (tx, rx) = mpsc::channel();
let mut watcher = notify::recommended_watcher(move |ev| {
let _ = tx.send(ev);
})?;
watcher.watch(&vault.root, RecursiveMode::Recursive)?;
let say = |m: &str| log(&vault.name, m);
say(&format!("watching {} as {}", vault.root.display(), label));
let mut burst = Burst::default();
let mut rescan_at = Instant::now(); // pick up anything changed while we weren't running
let mut sync_at = Instant::now();
let mut backoff = poll;
let mut was_waiting = false;
loop {
let first = rx.recv_timeout(Duration::from_millis(250));
for ev in first.into_iter().chain(rx.try_iter()) {
match ev {
Ok(ev) if !matches!(ev.kind, EventKind::Access(_)) => {
for p in ev.paths {
if let Some(rel) = relevant(&vault, &p) {
burst.touch(rel, Instant::now());
}
}
}
Ok(_) => {}
Err(e) => say(&format!("file watcher hiccup: {e}")),
}
}
let now = Instant::now();
let rescan = now >= rescan_at && burst.is_idle();
if rescan || burst.due(now, &timing) {
let skip = burst.take(now, &timing);
rescan_at = now + Duration::from_secs(60);
let _op = state::op_lock(&vault.git_dir)?;
match vault.save_changes(None, &skip) {
Ok(Some(saved)) => {
say(&format!("saved: {}", saved.message));
sync_at = now;
}
Ok(None) => {}
Err(e) => say(&format!("couldn't save changes: {e:#}")),
}
}
if Instant::now() >= sync_at {
let _op = state::op_lock(&vault.git_dir)?;
let result = vault.sync();
let mut st = SyncState::load(&vault.git_dir);
st.last_attempt = Some(chrono::Utc::now().timestamp());
match result {
Ok(report) => {
st.last_error = None;
if !report.waiting_for_local_edits {
st.last_synced = st.last_attempt;
}
if report.waiting_for_local_edits && !was_waiting {
say("new changes are waiting until your current edits settle");
}
was_waiting = report.waiting_for_local_edits;
print_report(&report, &say);
backoff = poll;
sync_at = Instant::now() + poll;
}
Err(e) => {
let msg = remote::describe_error(&e);
if st.last_error.as_deref() != Some(msg.as_str()) {
say(&format!("{msg} — will keep trying"));
}
st.last_error = Some(msg);
backoff = (backoff * 2).min(Duration::from_secs(60));
sync_at = Instant::now() + backoff;
}
}
if let Err(e) = st.save(&vault.git_dir) {
say(&format!("couldn't record sync status: {e:#}"));
}
}
}
}
/// Vault-relative path for a watcher event, or None for our own files and ignored ones.
fn relevant(vault: &Vault, p: &Path) -> Option<String> {
let rel = p.strip_prefix(&vault.root).ok()?;
if rel.as_os_str().is_empty() || rel.starts_with(".git") {
return None;
}
if vault.is_ignored(rel) {
return None;
}
Some(crate::names::slash_path(rel))
}
fn print_report(r: &SyncReport, say: &dyn Fn(&str)) {
if !r.received.is_empty() {
let from: Vec<&str> = r.from.iter().map(String::as_str).collect();
let who = if from.is_empty() { String::new() } else { format!(" from {}", from.join(", ")) };
say(&format!("received {}{who}", count_notes(&r.received)));
}
for (note, copy) in &r.kept_both {
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
}
for (old, new) in &r.case_renamed {
say(&format!("{old} clashed with another name differing only by case — renamed to {new}"));
}
if r.shared > 0 {
say(&format!("shared {} change{}", r.shared, if r.shared == 1 { "" } else { "s" }));
}
}
fn count_notes(files: &[String]) -> String {
match files {
[one] => one.clone(),
many => format!("{} notes", many.len()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn burst_ends_after_quiet_or_cap_and_holds_back_unsettled_files() {
let t = Timing::default();
let t0 = Instant::now();
let s = Duration::from_secs;
let mut b = Burst::default();
assert!(!b.due(t0, &t));
b.touch("a.md".into(), t0);
b.touch("b.md".into(), t0 + s(3));
assert!(!b.due(t0 + s(7), &t));
assert!(b.due(t0 + s(8), &t));
assert!(b.take(t0 + s(8), &t).is_empty());
assert!(!b.due(t0 + s(100), &t));
// A file written every second never goes quiet: the cap ends the burst without it.
let mut b = Burst::default();
b.touch("done.md".into(), t0);
for i in 0..=60 {
b.touch("log.md".into(), t0 + s(i));
}
assert!(b.due(t0 + s(60), &t));
let skip = b.take(t0 + s(60), &t);
assert_eq!(skip, HashSet::from(["log.md".to_string()]));
assert!(b.due(t0 + s(65), &t), "the still-changing file starts the next burst");
}
}

113
core/src/state.rs Normal file
View File

@@ -0,0 +1,113 @@
//! Per-vault bookkeeping inside `.git/lune/`: the app marker, process locks and the last sync outcome.
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::path::{Path, PathBuf};
/// Folder inside `.git/` that holds everything the app keeps per vault.
pub fn lune_dir(git_dir: &Path) -> PathBuf {
git_dir.join("lune")
}
/// Marker proving the app manages this folder (A9). `created` is true only when the app made the folder itself.
#[derive(Debug, Serialize, Deserialize)]
pub struct Marker {
pub managed_by: String,
pub vault: String,
pub created_folder: bool,
pub added_at: i64,
}
pub fn write_marker(git_dir: &Path, vault: &str, created_folder: bool) -> Result<()> {
let dir = lune_dir(git_dir);
std::fs::create_dir_all(&dir)?;
let marker = Marker {
managed_by: "lune".into(),
vault: vault.into(),
created_folder,
added_at: chrono::Utc::now().timestamp(),
};
std::fs::write(dir.join("vault.toml"), toml::to_string_pretty(&marker)?)?;
Ok(())
}
pub fn read_marker(git_dir: &Path) -> Option<Marker> {
let text = std::fs::read_to_string(lune_dir(git_dir).join("vault.toml")).ok()?;
toml::from_str(&text).ok()
}
/// Outcome of the last sync attempt, written by whoever ran it and read by `status`.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct SyncState {
/// Unix time of the last fully successful sync.
pub last_synced: Option<i64>,
/// Unix time of the last attempt, successful or not.
pub last_attempt: Option<i64>,
/// Plain-words reason the last attempt failed, if it did.
pub last_error: Option<String>,
/// Paths that differed only by letter case and were renamed or reported.
#[serde(default)]
pub case_clashes: Vec<String>,
}
impl SyncState {
pub fn load(git_dir: &Path) -> SyncState {
std::fs::read_to_string(lune_dir(git_dir).join("state.json"))
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default()
}
pub fn save(&self, git_dir: &Path) -> Result<()> {
let dir = lune_dir(git_dir);
std::fs::create_dir_all(&dir)?;
let tmp = dir.join("state.json.tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(self)?)?;
std::fs::rename(&tmp, dir.join("state.json"))?;
Ok(())
}
}
/// An OS file lock that is released when dropped (or when the process dies).
pub struct Lock(#[allow(dead_code)] File);
fn open_lock(git_dir: &Path, name: &str) -> Result<File> {
let dir = lune_dir(git_dir);
std::fs::create_dir_all(&dir)?;
OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(dir.join(name))
.with_context(|| format!("can't open lock in {}", dir.display()))
}
/// Held by `lunesync run` for its whole life: one watcher per vault, and lets `status` see it's running.
pub fn try_run_lock(git_dir: &Path) -> Result<Option<Lock>> {
let file = open_lock(git_dir, "run.lock")?;
match file.try_lock() {
Ok(()) => Ok(Some(Lock(file))),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(e)) => Err(e.into()),
}
}
pub fn is_running(git_dir: &Path) -> bool {
matches!(try_run_lock(git_dir), Ok(None))
}
/// Serializes every change to the vault's history between the background runner and one-off commands.
pub fn op_lock(git_dir: &Path) -> Result<Lock> {
let file = open_lock(git_dir, "op.lock")?;
file.lock()?;
// We hold the only right to touch the history now, so an old index lock is from a killed run.
let stale = git_dir.join("index.lock");
let old = std::fs::metadata(&stale)
.and_then(|m| m.modified())
.is_ok_and(|t| t.elapsed().unwrap_or_default().as_secs() > 30);
if old {
let _ = std::fs::remove_file(stale);
}
Ok(Lock(file))
}

69
core/src/tidy.rs Normal file
View File

@@ -0,0 +1,69 @@
//! Notes where both versions were kept, and resolving them (`lunesync tidy`).
use crate::names;
use crate::vault::{Saved, Vault};
use anyhow::{Result, bail};
use std::collections::HashSet;
#[derive(Debug, Clone, PartialEq)]
pub struct KeptBoth {
pub note: String,
pub copy: String,
/// Device whose version was saved beside the note.
pub label: String,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Keep {
Mine,
Theirs,
Both,
}
pub fn list(vault: &Vault) -> Result<Vec<KeptBoth>> {
let mut out: Vec<KeptBoth> = vault
.tracked_files()?
.into_iter()
.filter(|p| vault.root.join(p).exists())
.filter_map(|copy| names::parse_copy(&copy).map(|(note, label)| KeptBoth { note, copy, label }))
.collect();
out.sort_by(|a, b| (&a.note, &a.copy).cmp(&(&b.note, &b.copy)));
Ok(out)
}
/// Resolves the pair for `file` (the note or its copy). "Mine" is this device's version.
/// The caller holds the vault's op lock.
pub fn keep(vault: &Vault, file: &str, choice: Keep) -> Result<Option<Saved>> {
let all = list(vault)?;
let pairs: Vec<&KeptBoth> = match all.iter().find(|k| k.copy == file) {
Some(k) => vec![k],
None => all.iter().filter(|k| k.note == file).collect(),
};
let note = match pairs.as_slice() {
[] => bail!("{file} has no kept-both versions to tidy"),
[one] => one.note.clone(),
many if choice == Keep::Both => many[0].note.clone(),
many => {
let copies: Vec<&str> = many.iter().map(|k| k.copy.as_str()).collect();
bail!("{file} has several kept versions — name the one you mean: {}", copies.join(", "))
}
};
for k in pairs {
let copy = vault.root.join(&k.copy);
let original = vault.root.join(&k.note);
let copy_is_mine = k.label.eq_ignore_ascii_case(&vault.label);
match choice {
Keep::Both => {
let new = (1..)
.map(|n| names::kept_name(&k.note, &k.label, n))
.find(|p| !vault.root.join(p).exists())
.unwrap();
std::fs::rename(&copy, vault.root.join(new))?;
}
Keep::Mine if copy_is_mine => std::fs::rename(&copy, &original)?,
Keep::Theirs if !copy_is_mine => std::fs::rename(&copy, &original)?,
_ => std::fs::remove_file(&copy)?,
}
}
vault.save_changes(Some(&format!("Tidied {note}")), &HashSet::new())
}

551
core/src/vault.rs Normal file
View File

@@ -0,0 +1,551 @@
//! 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::names;
use crate::remote;
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,
}
/// A burst of edits saved as one history entry.
#[derive(Debug)]
pub struct Saved {
pub id: Oid,
pub message: String,
pub files: Vec<String>,
}
/// 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,
}
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,
})
}
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).
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
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 sig = self.signature()?;
let parents: Vec<&Commit> = parent.iter().collect();
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
Ok(Some(Saved { id, message, files }))
}
/// 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(())
}
/// Pushes local history. Returns false if the remote moved on meanwhile (fetch and try again).
fn push(&self) -> Result<bool> {
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);
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 rejected.borrow().is_some() {
return Ok(false);
}
if let Some(head) = self.head_commit()? {
self.repo.reference(&self.remote_ref(), head.id(), true, "lune: shared")?;
}
Ok(true)
}
/// One sync round: fetch, combine, write the result to disk, share local history.
pub fn sync(&self) -> Result<SyncReport> {
let mut report = SyncReport::default();
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)?;
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 self.push()? {
report.shared += ahead;
return Ok(report);
}
}
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)?;
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, &self.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())))?;
report.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))?;
}
}
}
}
}
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])?)
}
/// 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(())
}
/// 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())
}
}
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}");
}
format!("Updated {} 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 };
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(())
}