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:
333
cli/src/main.rs
Normal file
333
cli/src/main.rs
Normal file
@@ -0,0 +1,333 @@
|
||||
mod service;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use chrono::{Local, TimeZone};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use lune_core::config::{Config, VaultConfig};
|
||||
use lune_core::runner::{self, Timing};
|
||||
use lune_core::state::{self, SyncState};
|
||||
use lune_core::tidy::{self, Keep};
|
||||
use lune_core::vault::{self, Added, Vault};
|
||||
use lune_core::remote;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "lunesync", version, about = "Keeps every copy of your vaults in sync.")]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Show or set this device's label (e.g. Codex, Hermes)
|
||||
Device {
|
||||
#[command(subcommand)]
|
||||
action: Option<DeviceCmd>,
|
||||
},
|
||||
/// Start syncing a folder: downloads into an empty folder, adopts one that already has notes
|
||||
Add {
|
||||
name: String,
|
||||
folder: PathBuf,
|
||||
#[arg(long)]
|
||||
remote: String,
|
||||
},
|
||||
/// Keep every vault in sync, in the foreground
|
||||
Run,
|
||||
/// Keep `lunesync run` going in the background (launchd / systemd)
|
||||
Service {
|
||||
#[command(subcommand)]
|
||||
action: ServiceCmd,
|
||||
},
|
||||
/// How each vault is doing
|
||||
Status { vault: Option<String> },
|
||||
/// Save a named point in history right now and share it
|
||||
Checkpoint {
|
||||
message: String,
|
||||
#[arg(long)]
|
||||
vault: Option<String>,
|
||||
},
|
||||
/// List notes where both versions were kept, or pick one
|
||||
Tidy {
|
||||
#[command(subcommand)]
|
||||
action: Option<TidyCmd>,
|
||||
#[arg(long)]
|
||||
vault: Option<String>,
|
||||
},
|
||||
/// Recent history entries and which device made them
|
||||
History {
|
||||
#[arg(long)]
|
||||
vault: Option<String>,
|
||||
#[arg(short = 'n', default_value_t = 15)]
|
||||
count: usize,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum DeviceCmd {
|
||||
/// Set the label shown on everything this device shares
|
||||
Name { label: String },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ServiceCmd {
|
||||
/// Install and start the background service
|
||||
Install {
|
||||
/// Only show what would be installed
|
||||
#[arg(long)]
|
||||
print: bool,
|
||||
},
|
||||
/// Stop and remove the background service
|
||||
Uninstall,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum TidyCmd {
|
||||
/// Keep one version (mine = this device's), or both as separate notes
|
||||
Keep { choice: KeepArg, file: PathBuf },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, ValueEnum)]
|
||||
enum KeepArg {
|
||||
Mine,
|
||||
Theirs,
|
||||
Both,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(e) = run_cli(Cli::parse()) {
|
||||
eprintln!("lunesync: {e:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run_cli(cli: Cli) -> Result<()> {
|
||||
let mut config = Config::load()?;
|
||||
let cwd = std::env::current_dir()?;
|
||||
match cli.command {
|
||||
Command::Device { action: None } => println!("This device is \"{}\".", config.device_label()),
|
||||
Command::Device { action: Some(DeviceCmd::Name { label }) } => {
|
||||
let label = label.trim().to_string();
|
||||
if label.is_empty() {
|
||||
bail!("the label can't be empty");
|
||||
}
|
||||
config.device_name = Some(label.clone());
|
||||
config.save()?;
|
||||
println!("This device is now \"{label}\". Everything it shares will carry that name.");
|
||||
}
|
||||
Command::Add { name, folder, remote } => add(&mut config, &name, &folder, &remote)?,
|
||||
Command::Run => run(&config)?,
|
||||
Command::Service { action: ServiceCmd::Install { print } } => service::install(print)?,
|
||||
Command::Service { action: ServiceCmd::Uninstall } => service::uninstall()?,
|
||||
Command::Status { vault } => {
|
||||
let vaults: Vec<&VaultConfig> = match vault {
|
||||
Some(n) => vec![config.find(&n).with_context(|| format!("no vault named \"{n}\""))?],
|
||||
None => config.vaults.iter().collect(),
|
||||
};
|
||||
if vaults.is_empty() {
|
||||
println!("No vaults yet. Add one with `lunesync add <name> <folder> --remote <url>`.");
|
||||
}
|
||||
println!("Device: {}", config.device_label());
|
||||
for v in vaults {
|
||||
print_status(v, &config.device_label());
|
||||
}
|
||||
}
|
||||
Command::Checkpoint { message, vault } => {
|
||||
let cfg = config.pick(vault.as_deref(), &cwd)?;
|
||||
let v = Vault::open(cfg, &config.device_label())?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
v.checkpoint(&message)?;
|
||||
println!("Checkpoint \"{message}\" saved in {}.", v.name);
|
||||
share_now(&v);
|
||||
}
|
||||
Command::Tidy { action: None, vault } => {
|
||||
let list: Vec<&VaultConfig> = match vault {
|
||||
Some(n) => vec![config.pick(Some(&n), &cwd)?],
|
||||
None => config.vaults.iter().collect(),
|
||||
};
|
||||
let mut any = false;
|
||||
for cfg in list {
|
||||
let v = Vault::open(cfg, &config.device_label())?;
|
||||
for k in tidy::list(&v)? {
|
||||
if !any {
|
||||
println!("Notes changed in two places (both versions kept):");
|
||||
}
|
||||
any = true;
|
||||
println!(" {:<12} {} ← {}", v.name, k.note, k.copy);
|
||||
}
|
||||
}
|
||||
if any {
|
||||
println!("\nPick one with `lunesync tidy keep mine|theirs|both <file>` (mine = this device's version).");
|
||||
} else {
|
||||
println!("Nothing to tidy.");
|
||||
}
|
||||
}
|
||||
Command::Tidy { action: Some(TidyCmd::Keep { choice, file }), vault } => {
|
||||
let (cfg, rel) = locate(&config, vault.as_deref(), &cwd, &file)?;
|
||||
let v = Vault::open(cfg, &config.device_label())?;
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
let choice = match choice {
|
||||
KeepArg::Mine => Keep::Mine,
|
||||
KeepArg::Theirs => Keep::Theirs,
|
||||
KeepArg::Both => Keep::Both,
|
||||
};
|
||||
match tidy::keep(&v, &rel, choice)? {
|
||||
Some(saved) => println!("{}.", saved.message),
|
||||
None => println!("Nothing changed."),
|
||||
}
|
||||
share_now(&v);
|
||||
}
|
||||
Command::History { vault, count } => {
|
||||
let cfg = config.pick(vault.as_deref(), &cwd)?;
|
||||
let v = Vault::open(cfg, &config.device_label())?;
|
||||
let Some(head) = v.head_commit()? else {
|
||||
println!("No history yet.");
|
||||
return Ok(());
|
||||
};
|
||||
let repo = v.repo();
|
||||
let mut walk = repo.revwalk()?;
|
||||
walk.set_sorting(lune_core::git2::Sort::TIME)?;
|
||||
walk.push(head.id())?;
|
||||
for id in walk.take(count) {
|
||||
let c = repo.find_commit(id?)?;
|
||||
let when = Local.timestamp_opt(c.time().seconds(), 0).single().map(|t| t.format("%Y-%m-%d %H:%M").to_string());
|
||||
println!(
|
||||
"{} {:<10} {}",
|
||||
when.unwrap_or_default(),
|
||||
c.author().name().unwrap_or("?"),
|
||||
c.summary().ok().flatten().unwrap_or("")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add(config: &mut Config, name: &str, folder: &Path, remote: &str) -> Result<()> {
|
||||
if config.find(name).is_some() {
|
||||
bail!("there's already a vault named \"{name}\"");
|
||||
}
|
||||
let folder = if folder.is_absolute() { folder.to_path_buf() } else { std::env::current_dir()?.join(folder) };
|
||||
let label = config.device_label();
|
||||
let (cfg, added, sync_error) = vault::add(name, &folder, remote, &label)?;
|
||||
match added {
|
||||
Added::Downloaded(n) => println!("Downloaded {name}: {n} files in {}.", cfg.path.display()),
|
||||
Added::Adopted(n) => println!("Adopted {name}: {n} files in {}, nothing moved or rewritten.", cfg.path.display()),
|
||||
Added::StartedEmpty => println!("Started {name} in {} (the remote is empty).", cfg.path.display()),
|
||||
}
|
||||
if let Some(e) = sync_error {
|
||||
println!("Not shared yet: {e}. `lunesync run` will keep trying.");
|
||||
}
|
||||
config.vaults.push(cfg);
|
||||
config.save()?;
|
||||
println!("Next: `lunesync run` to keep it in sync (or `lunesync service install` to run it in the background).");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run(config: &Config) -> Result<()> {
|
||||
if config.vaults.is_empty() {
|
||||
bail!("no vaults yet — add one with `lunesync add <name> <folder> --remote <url>`");
|
||||
}
|
||||
let label = config.device_label();
|
||||
let poll = config.poll_interval();
|
||||
let log = |vault: &str, msg: &str| println!("{} {vault:<10} {msg}", Local::now().format("%H:%M:%S"));
|
||||
std::thread::scope(|s| {
|
||||
for cfg in &config.vaults {
|
||||
let label = &label;
|
||||
s.spawn(move || {
|
||||
loop {
|
||||
match runner::run(cfg, label, poll, Timing::default(), &log) {
|
||||
Ok(()) => return,
|
||||
Err(e) if format!("{e}").contains("already being synced") => {
|
||||
log(&cfg.name, &format!("{e:#}"));
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
log(&cfg.name, &format!("stopped: {e:#} — retrying in 30 s"));
|
||||
std::thread::sleep(std::time::Duration::from_secs(30));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// After a one-off command, try to share right away; the runner picks it up otherwise.
|
||||
fn share_now(v: &Vault) {
|
||||
match v.sync() {
|
||||
Ok(r) if r.waiting_for_local_edits => println!("Will share once your current edits settle."),
|
||||
Ok(_) => {
|
||||
println!("Shared.");
|
||||
let mut st = SyncState::load(&v.git_dir);
|
||||
st.last_synced = Some(chrono::Utc::now().timestamp());
|
||||
st.last_attempt = st.last_synced;
|
||||
st.last_error = None;
|
||||
let _ = st.save(&v.git_dir);
|
||||
}
|
||||
Err(e) => println!("Not shared yet ({}); it will go out when the remote is reachable.", remote::describe_error(&e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn print_status(cfg: &VaultConfig, label: &str) {
|
||||
println!("\n{} — {}", cfg.name, cfg.path.display());
|
||||
let v = match Vault::open(cfg, label) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
println!(" Can't open: {e:#}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let st = SyncState::load(&v.git_dir);
|
||||
let waiting = v.waiting_files().unwrap_or(0);
|
||||
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
|
||||
let headline = match &st.last_error {
|
||||
Some(e) if e.starts_with("offline") => format!("Offline · waiting to sync · {changes}"),
|
||||
Some(e) => format!("Can't sync: {e}{}", if waiting > 0 { format!(" · {changes} waiting") } else { String::new() }),
|
||||
None if waiting > 0 => format!("Waiting to sync · {changes}"),
|
||||
None if st.last_synced.is_some() => format!("Synced {}", ago(st.last_synced.unwrap())),
|
||||
None => "Not synced yet".to_string(),
|
||||
};
|
||||
println!(" {headline}");
|
||||
if let Some(t) = st.last_synced {
|
||||
println!(" Last sync: {} ({})", Local.timestamp_opt(t, 0).unwrap().format("%Y-%m-%d %H:%M:%S"), ago(t));
|
||||
}
|
||||
let to_tidy = tidy::list(&v).map(|l| l.len()).unwrap_or(0);
|
||||
if to_tidy > 0 {
|
||||
println!(" {to_tidy} note{} to tidy — see `lunesync tidy`", if to_tidy == 1 { "" } else { "s" });
|
||||
}
|
||||
if !st.case_clashes.is_empty() {
|
||||
println!(" Names differing only by case: {}", st.case_clashes.join(", "));
|
||||
}
|
||||
if !state::is_running(&v.git_dir) {
|
||||
println!(" Not running — start `lunesync run` or `lunesync service install`");
|
||||
}
|
||||
}
|
||||
|
||||
fn ago(unix: i64) -> String {
|
||||
let secs = (chrono::Utc::now().timestamp() - unix).max(0);
|
||||
match secs {
|
||||
0..=59 => "just now".into(),
|
||||
60..=3599 => format!("{} min ago", secs / 60),
|
||||
3600..=86399 => format!("{} h ago", secs / 3600),
|
||||
_ => format!("{} days ago", secs / 86400),
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds the vault and vault-relative path for a file given as absolute, relative to here, or relative to the vault.
|
||||
fn locate<'a>(config: &'a Config, vault: Option<&str>, cwd: &Path, file: &Path) -> Result<(&'a VaultConfig, String)> {
|
||||
let abs = if file.is_absolute() { file.to_path_buf() } else { cwd.join(file) };
|
||||
let abs = match (abs.parent().and_then(|p| std::fs::canonicalize(p).ok()), abs.file_name()) {
|
||||
(Some(dir), Some(name)) => dir.join(name),
|
||||
_ => abs,
|
||||
};
|
||||
if let Some(cfg) = vault.map_or_else(|| config.containing(&abs), |n| config.find(n))
|
||||
&& let Ok(root) = std::fs::canonicalize(&cfg.path)
|
||||
&& let Ok(rel) = abs.strip_prefix(&root)
|
||||
{
|
||||
return Ok((cfg, rel.to_string_lossy().replace('\\', "/")));
|
||||
}
|
||||
let cfg = config.pick(vault, cwd)?;
|
||||
Ok((cfg, file.to_string_lossy().replace('\\', "/")))
|
||||
}
|
||||
Reference in New Issue
Block a user