0.1.4: settings decide where a vault shares; leaving always finishes
- A folder found sharing somewhere other than its settings say is set back (every 30 s, under the vault's op lock). Two programs racing — the 0.1.1 CLI upload against the 0.1.2 app's check-in — had left Brain's settings on the hub and its folder on Gitea, so it kept "syncing" to the wrong place. - Leaving hands over to the vault's own hub, never to wherever the folder points. If the hub refuses the history (an older entry has a possible secret), the device hands over its current notes as one entry with those lines replaced, instead of retrying forever with the folder read-only. - The app says "leaving" while that's in progress instead of "Synced". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -190,6 +190,8 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
};
|
||||
let _op = state::op_lock(&v.git_dir)?;
|
||||
// The handover goes to this vault's own hub, whatever the folder was last pointed at.
|
||||
v.follow(&vc.remote)?;
|
||||
|
||||
let mut head = None;
|
||||
if !d.without_saving {
|
||||
@@ -205,8 +207,14 @@ pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<Strin
|
||||
if !d.without_saving
|
||||
&& let Some(h) = v.head_commit()?
|
||||
{
|
||||
v.hand_over(&format!("refs/handover/{}", d.id))?;
|
||||
head = Some(h.id().to_string());
|
||||
let dst = format!("refs/handover/{}", d.id);
|
||||
head = Some(match v.hand_over(&dst) {
|
||||
Ok(()) => h.id().to_string(),
|
||||
// Older history has something that looks like a secret, which the hub never takes: hand over the
|
||||
// current notes instead, those lines replaced. Otherwise this device could never finish leaving.
|
||||
Err(e) if format!("{e:#}").contains("didn't take the handover") => v.hand_over_current(&dst, REDACTED)?.to_string(),
|
||||
Err(e) => return Err(e),
|
||||
});
|
||||
}
|
||||
link.departure_done(d.id, head)?;
|
||||
|
||||
|
||||
@@ -105,6 +105,16 @@ pub fn is_running(git_dir: &Path) -> bool {
|
||||
matches!(try_run_lock(git_dir), Ok(None))
|
||||
}
|
||||
|
||||
/// Like `op_lock`, but gives up at once if someone else holds it.
|
||||
pub fn try_op_lock(git_dir: &Path) -> Result<Option<Lock>> {
|
||||
let file = open_lock(git_dir, "op.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()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")?;
|
||||
|
||||
@@ -118,6 +118,7 @@ pub fn of(cfg: &VaultConfig, label: &str) -> VaultStatus {
|
||||
let changes = format!("{waiting} change{}", if waiting == 1 { "" } else { "s" });
|
||||
let (level, headline) = match &st.last_error {
|
||||
_ if v.is_local() => ("current", "Only on this device · not shared".to_string()),
|
||||
_ if state::lune_dir(&v.git_dir).join("leaving").exists() => ("behind", "Access ended · leaving: handing over what wasn't shared".to_string()),
|
||||
None if out.read_only && waiting > 0 => ("current", format!("Up to date · {changes} kept here, not shared (you have read access)")),
|
||||
None if out.read_only => ("current", "Up to date (read access)".to_string()),
|
||||
Some(e) if e == remote::TOO_OLD => ("behind", format!("Update Lune to keep syncing · {changes} saved here")),
|
||||
|
||||
@@ -20,6 +20,7 @@ pub fn supervise(log: fn(&str, &str)) -> Result<()> {
|
||||
let mut hub_check = Instant::now();
|
||||
// Each hub's last complaint, so an unreachable hub isn't logged every 30 s.
|
||||
let mut hub_said: HashMap<String, String> = HashMap::new();
|
||||
let mut follow_at = Instant::now();
|
||||
while !STOP.load(Ordering::Relaxed) {
|
||||
let mut config = Config::load()?;
|
||||
config.use_hub_credentials();
|
||||
@@ -56,6 +57,10 @@ pub fn supervise(log: fn(&str, &str)) -> Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if Instant::now() >= follow_at {
|
||||
follow_at = Instant::now() + Duration::from_secs(30);
|
||||
follow_settings(log);
|
||||
}
|
||||
// A vault that left (access ended) can come back later at the same place.
|
||||
started.retain(|p| config.vaults.iter().any(|v| &v.path == p));
|
||||
for cfg in &config.vaults {
|
||||
@@ -92,6 +97,23 @@ pub fn supervise(log: fn(&str, &str)) -> Result<()> {
|
||||
}
|
||||
|
||||
/// Asks every running vault to save what has settled and share now (the menu's "Share now").
|
||||
/// Puts back any vault folder that shares somewhere other than its settings say, which another program (or an
|
||||
/// older Lune) can leave behind. Done under the vault's op lock, with the settings read again inside it.
|
||||
fn follow_settings(log: fn(&str, &str)) {
|
||||
let Ok(config) = Config::load() else { return };
|
||||
for cfg in &config.vaults {
|
||||
let Ok(v) = crate::vault::Vault::open(cfg, &config.device_label()) else { continue };
|
||||
let Ok(Some(_op)) = crate::state::try_op_lock(&v.git_dir) else { continue };
|
||||
let Some(now) = Config::load().ok().and_then(|c| c.vaults.into_iter().find(|x| x.path == cfg.path)) else { continue };
|
||||
match v.follow(&now.remote) {
|
||||
Ok(true) if now.remote.is_empty() => log(&now.name, "set back to this device only, as its settings say"),
|
||||
Ok(true) => log(&now.name, &format!("set back to sharing with {}, as its settings say", crate::upload::remote_host(&now.remote))),
|
||||
Ok(false) => {}
|
||||
Err(e) => log(&now.name, &format!("couldn't match its settings: {e:#}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn share_now(config: &Config) {
|
||||
for vc in &config.vaults {
|
||||
let dir = crate::state::lune_dir(&vc.path.join(".git"));
|
||||
|
||||
@@ -290,6 +290,22 @@ impl Vault {
|
||||
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()
|
||||
@@ -400,6 +416,45 @@ impl Vault {
|
||||
|
||||
/// 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();
|
||||
@@ -411,7 +466,7 @@ impl Vault {
|
||||
});
|
||||
let mut opts = PushOptions::new();
|
||||
opts.remote_callbacks(cb);
|
||||
remote.push(&[format!("+{}:{dst}", self.branch_ref())], Some(&mut opts))?;
|
||||
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}");
|
||||
|
||||
Reference in New Issue
Block a user