use std::path::PathBuf;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Syncable {
pub name: &'static str,
pub source: &'static str,
pub hot_reloads: bool,
}
pub const SYNCABLE: &[Syncable] = &[
Syncable {
name: crate::config_layers::SYNCED_CONFIG_NAME,
source: "config.json",
hot_reloads: true,
},
Syncable {
name: "keybindings.json",
source: "keybindings.json",
hot_reloads: true,
},
Syncable {
name: "snippets.json",
source: "snippets.json",
hot_reloads: true,
},
Syncable {
name: "triggers.json",
source: "triggers.json",
hot_reloads: true,
},
Syncable {
name: "matchers.json",
source: "matchers.json",
hot_reloads: true,
},
Syncable {
name: "macros.json",
source: "macros.json",
hot_reloads: true,
},
];
#[cfg(test)]
pub const NEVER_SYNC: &[(&str, &str)] = &[
(
"config.json",
"carries MCP consent and trust-on-first-use fingerprints; see #262",
),
(
"config.local.json",
"the machine-local layer is machine-local by definition",
),
(
"history",
"local history snapshots are per-machine working state",
),
(
"command_history.json",
"command history is per-machine working state",
),
];
#[derive(Debug)]
pub struct ConfigWatch {
files: Vec<(PathBuf, Option<Stamp>)>,
next: std::time::Instant,
}
pub(crate) type Stamp = (std::time::SystemTime, u64);
pub(crate) fn stamp(path: &std::path::Path) -> Option<Stamp> {
let meta = std::fs::metadata(path).ok()?;
Some((meta.modified().ok()?, meta.len()))
}
impl ConfigWatch {
pub const INTERVAL: std::time::Duration = std::time::Duration::from_secs(2);
pub fn new(paths: Vec<PathBuf>) -> Self {
let files = paths
.into_iter()
.map(|p| {
let s = stamp(&p);
(p, s)
})
.collect();
ConfigWatch {
files,
next: std::time::Instant::now() + Self::INTERVAL,
}
}
pub fn poll(&mut self, now: std::time::Instant) -> Vec<PathBuf> {
if now < self.next {
return Vec::new();
}
self.next = now + Self::INTERVAL;
let mut changed = Vec::new();
for (path, seen) in &mut self.files {
let current = stamp(path);
if current != *seen {
let before = std::mem::replace(seen, current);
if !is_own_write(path, before, current) {
changed.push(path.clone());
}
}
}
changed
}
pub fn watch(&mut self, path: PathBuf) {
if !self.files.iter().any(|(p, _)| *p == path) {
let s = stamp(&path);
self.files.push((path, s));
}
}
pub fn note(&mut self, path: &std::path::Path) {
if let Some((_, seen)) = self.files.iter_mut().find(|(p, _)| p == path) {
*seen = stamp(path);
}
}
pub fn set_paths(&mut self, paths: Vec<PathBuf>) {
let mut known = std::mem::take(&mut self.files);
self.files = paths
.into_iter()
.map(|p| match known.iter().position(|(q, _)| *q == p) {
Some(i) => known.swap_remove(i),
None => {
let s = stamp(&p);
(p, s)
}
})
.collect();
}
#[cfg(test)]
pub fn watches(&self, path: &std::path::Path) -> bool {
self.files.iter().any(|(p, _)| p == path)
}
}
static OWN_WRITES: std::sync::Mutex<Vec<(PathBuf, Option<Stamp>, Stamp)>> =
std::sync::Mutex::new(Vec::new());
pub fn note_own_write(path: &std::path::Path, before: Option<Stamp>) {
let Some(after) = stamp(path) else {
return;
};
record_own_write(path, before, after);
}
pub fn write_own(path: &std::path::Path, contents: impl AsRef<[u8]>) -> std::io::Result<()> {
use std::io::Write;
let before = stamp(path);
let mut file = std::fs::File::create(path)?;
file.write_all(contents.as_ref())?;
let meta = file.metadata()?;
if let Ok(modified) = meta.modified() {
record_own_write(path, before, (modified, meta.len()));
}
Ok(())
}
fn record_own_write(path: &std::path::Path, before: Option<Stamp>, after: Stamp) {
let mut own = OWN_WRITES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match own.iter_mut().find(|(p, _, _)| p == path) {
Some((_, pre, post)) => {
if Some(*post) != before {
*pre = before;
}
*post = after;
}
None => own.push((path.to_path_buf(), before, after)),
}
}
fn is_own_write(path: &std::path::Path, seen: Option<Stamp>, current: Option<Stamp>) -> bool {
let mut own = OWN_WRITES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(i) = own.iter().position(|(p, _, _)| p == path) else {
return false;
};
let (_, pre, post) = own.swap_remove(i);
pre == seen && Some(post) == current
}
pub fn local_files() -> Vec<(Syncable, PathBuf)> {
let dir = crate::paths::config_dir();
let out = projection_dir();
SYNCABLE
.iter()
.filter_map(|s| Some((*s, local_source(s, &dir, &out)?)))
.collect()
}
fn projection_dir() -> PathBuf {
crate::paths::croft_cache_dir().join("config-sync")
}
pub fn local_source(s: &Syncable, dir: &std::path::Path, out: &std::path::Path) -> Option<PathBuf> {
let src = dir.join(s.source);
if s.source == s.name {
return src.is_file().then_some(src);
}
let text = std::fs::read_to_string(&src).ok()?;
let doc: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&text).ok()?;
let projected = crate::config_layers::synced_projection(&doc)?;
let json = serde_json::to_string_pretty(&projected).ok()? + "\n";
std::fs::create_dir_all(out).ok()?;
let path = out.join(s.name);
std::fs::write(&path, json).ok()?;
Some(path)
}
pub fn host_excluded(host: &str, excluded: &[String]) -> bool {
excluded.iter().any(|h| h.eq_ignore_ascii_case(host))
}
pub fn apply_exclusions(
files: Vec<(Syncable, PathBuf)>,
excluded: &[String],
) -> (Vec<(Syncable, PathBuf)>, Vec<&'static str>) {
let mut keep = Vec::new();
let mut skipped = Vec::new();
for (s, p) in files {
if excluded.iter().any(|e| e == s.name) {
skipped.push(s.name);
} else {
keep.push((s, p));
}
}
(keep, skipped)
}
pub fn watched_local_paths() -> Vec<PathBuf> {
let dir = crate::paths::config_dir();
SYNCABLE.iter().map(|s| dir.join(s.source)).collect()
}
pub fn repush_targets(changed: &[PathBuf], dir: &std::path::Path) -> Vec<(Syncable, PathBuf)> {
repush_targets_into(changed, dir, &projection_dir())
}
fn repush_targets_into(
changed: &[PathBuf],
dir: &std::path::Path,
out: &std::path::Path,
) -> Vec<(Syncable, PathBuf)> {
changed
.iter()
.filter(|p| p.parent() == Some(dir) && p.is_file())
.filter_map(|p| {
let name = p.file_name()?.to_str()?;
let s = SYNCABLE.iter().find(|s| s.source == name)?;
Some((*s, local_source(s, dir, out)?))
})
.collect()
}
pub fn remote_dest(host: &str, name: &str) -> String {
format!("{host}:.config/croft/{name}")
}
pub fn content_hash(bytes: &[u8]) -> String {
use sha2::Digest;
format!("{:x}", sha2::Sha256::digest(bytes))
}
pub fn remote_hash_script() -> String {
let names: Vec<&str> = SYNCABLE.iter().map(|s| s.name).collect();
let names = names.join(" ");
format!(
"echo {HASHES_HEADER}; cd ~/.config/croft 2>/dev/null || exit 0; for f in {names}; do [ -f \"$f\" ] || continue; \
if command -v sha256sum >/dev/null 2>&1; then sha256sum \"$f\"; else shasum -a 256 \"$f\"; fi; done"
)
}
pub const HASHES_HEADER: &str = "croft-config-hashes";
pub fn parse_remote_listing(out: &str) -> Option<std::collections::BTreeMap<String, String>> {
let mut lines = out.lines().skip_while(|l| l.trim().is_empty());
(lines.next()?.trim() == HASHES_HEADER).then(|| parse_remote_hashes(out))
}
pub fn parse_remote_hashes(out: &str) -> std::collections::BTreeMap<String, String> {
out.lines()
.filter_map(|l| {
let (hash, name) = l.trim().split_once(char::is_whitespace)?;
let name = name.trim().trim_start_matches('*');
let known = SYNCABLE.iter().any(|s| s.name == name);
(known && hash.len() == 64).then(|| (name.to_string(), hash.to_ascii_lowercase()))
})
.collect()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FileState {
#[serde(default)]
pub pushed: Option<String>,
#[serde(default)]
pub kept: Option<(String, String)>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SyncState {
#[serde(default)]
pub hosts: std::collections::BTreeMap<String, std::collections::BTreeMap<String, FileState>>,
}
impl SyncState {
pub fn path() -> PathBuf {
crate::paths::croft_cache_dir().join("config-sync.json")
}
pub fn load(path: &std::path::Path) -> SyncState {
std::fs::read_to_string(path)
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default()
}
pub fn save(&self, path: &std::path::Path) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let text = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
std::fs::write(path, text)
}
pub fn file(&self, host: &str, name: &str) -> Option<&FileState> {
self.hosts.get(&host.to_ascii_lowercase())?.get(name)
}
pub fn file_mut(&mut self, host: &str, name: &str) -> &mut FileState {
self.hosts
.entry(host.to_ascii_lowercase())
.or_default()
.entry(name.to_string())
.or_default()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Plan {
Push,
UpToDate,
Kept,
Conflict,
}
pub fn plan(local: &str, remote: Option<&str>, state: Option<&FileState>) -> Plan {
let Some(remote) = remote else {
return Plan::Push;
};
if remote == local {
return Plan::UpToDate;
}
let state = state.cloned().unwrap_or_default();
if state
.kept
.as_ref()
.is_some_and(|(r, l)| r == remote && l == local)
{
return Plan::Kept;
}
if state.pushed.as_deref() == Some(remote) {
return Plan::Push;
}
Plan::Conflict
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_push_never_overwrites_a_copy_edited_on_the_remote() {
let pushed = |h: &str| FileState {
pushed: Some(h.into()),
kept: None,
};
assert_eq!(plan("L2", None, None), Plan::Push);
assert_eq!(plan("L2", Some("L1"), Some(&pushed("L1"))), Plan::Push);
assert_eq!(plan("L2", Some("L2"), None), Plan::UpToDate);
assert_eq!(plan("L2", Some("R"), Some(&pushed("L1"))), Plan::Conflict);
assert_eq!(plan("L2", Some("R"), None), Plan::Conflict);
let kept = FileState {
pushed: Some("L1".into()),
kept: Some(("R".into(), "L2".into())),
};
assert_eq!(plan("L2", Some("R"), Some(&kept)), Plan::Kept);
assert_eq!(plan("L3", Some("R"), Some(&kept)), Plan::Conflict);
assert_eq!(plan("L2", Some("R2"), Some(&kept)), Plan::Conflict);
}
#[test]
fn remote_hashes_parse_for_syncable_names_only() {
let h = "a".repeat(64);
let out = format!("{h} keybindings.json\n{h} *snippets.json\n{h} config.json\nnoise\n");
let got = parse_remote_hashes(&out);
assert_eq!(got.len(), 2, "{got:?}");
assert_eq!(got.get("snippets.json"), Some(&h));
assert!(!got.contains_key("config.json"));
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".config/croft");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("keybindings.json"), "{}\n").unwrap();
std::fs::write(dir.join("config.json"), "{}\n").unwrap();
let out = std::process::Command::new("sh")
.args(["-c", &remote_hash_script()])
.env("HOME", home.path())
.output()
.unwrap();
assert!(out.status.success());
let got = parse_remote_listing(&String::from_utf8_lossy(&out.stdout)).unwrap();
assert_eq!(
got.into_iter().collect::<Vec<_>>(),
[(String::from("keybindings.json"), content_hash(b"{}\n"))]
);
assert_eq!(content_hash(b"").len(), 64);
}
#[test]
fn an_empty_listing_reads_as_unknown_not_absent() {
assert_eq!(parse_remote_listing(""), None);
let h = "a".repeat(64);
assert_eq!(parse_remote_listing(&format!("{h} snippets.json\n")), None);
let got = parse_remote_listing(&format!("{HASHES_HEADER}\n{h} snippets.json\n")).unwrap();
assert_eq!(got.get("snippets.json"), Some(&h));
let home = tempfile::tempdir().unwrap();
let out = std::process::Command::new("sh")
.args(["-c", &remote_hash_script()])
.env("HOME", home.path())
.output()
.unwrap();
assert_eq!(
parse_remote_listing(&String::from_utf8_lossy(&out.stdout)),
Some(Default::default())
);
}
#[test]
fn sync_state_round_trips_per_host_case_insensitively() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("s.json");
let mut st = SyncState::default();
st.file_mut("DevBox", "keybindings.json").pushed = Some("x".into());
st.save(&path).unwrap();
let back = SyncState::load(&path);
assert_eq!(
back.file("devbox", "keybindings.json")
.and_then(|f| f.pushed.as_deref()),
Some("x")
);
assert_eq!(
SyncState::load(&dir.path().join("none")),
SyncState::default()
);
}
#[test]
fn the_trust_carrying_config_never_becomes_syncable() {
for (never, why) in NEVER_SYNC {
assert!(
!SYNCABLE.iter().any(|s| s.name == *never),
"{never} must never sync: {why}"
);
}
}
#[test]
fn every_syncable_name_is_a_bare_file_name() {
for s in SYNCABLE {
assert!(
!s.name.contains('/') && !s.name.contains('\\') && !s.name.contains(".."),
"{} must be a bare file name, not a path",
s.name
);
assert!(!s.name.is_empty(), "an empty name would sync the dir");
}
}
#[test]
fn the_destination_stays_inside_the_remote_config_dir() {
assert_eq!(
remote_dest("box", "keybindings.json"),
"box:.config/croft/keybindings.json"
);
for s in SYNCABLE {
let dest = remote_dest("h", s.name);
assert!(
dest.starts_with("h:.config/croft/"),
"{dest} escaped the remote config dir"
);
}
}
#[test]
fn a_missing_file_is_skipped_rather_than_pushed_empty() {
let listed = local_files();
for (_, path) in &listed {
assert!(
path.is_file(),
"{} was listed but is not a file",
path.display()
);
}
}
#[test]
fn a_live_repush_sends_only_changed_syncable_files_that_exist() {
let dir = tempfile::tempdir().unwrap();
let keys = dir.path().join("keybindings.json");
let gone = dir.path().join("snippets.json");
let other = dir.path().join("config.json");
std::fs::write(&keys, "[]").unwrap();
std::fs::write(&other, "{}").unwrap();
let elsewhere = tempfile::tempdir().unwrap();
let stray = elsewhere.path().join("keybindings.json");
std::fs::write(&stray, "[]").unwrap();
let got = repush_targets(&[keys.clone(), gone, other, stray], dir.path());
assert_eq!(got.len(), 1);
assert_eq!((got[0].0.name, &got[0].1), ("keybindings.json", &keys));
}
#[test]
fn every_syncable_file_reloads_live() {
assert!(SYNCABLE.iter().all(|s| s.hot_reloads), "{SYNCABLE:?}");
}
#[test]
fn the_watch_reports_a_changed_created_or_deleted_file_once() {
let dir = tempfile::tempdir().unwrap();
let kept = dir.path().join("keybindings.json");
let fresh = dir.path().join("snippets.json");
std::fs::write(&kept, "[]").unwrap();
let mut watch = ConfigWatch::new(vec![kept.clone(), fresh.clone()]);
let t0 = std::time::Instant::now();
let later = |n: u32| t0 + ConfigWatch::INTERVAL * n;
assert!(watch.poll(later(1)).is_empty(), "nothing changed yet");
std::fs::write(&kept, r#"[{"key": "ctrl+k"}]"#).unwrap();
std::fs::write(&fresh, "{}").unwrap();
assert!(watch.poll(later(1)).is_empty());
assert_eq!(watch.poll(later(2)), vec![kept.clone(), fresh.clone()]);
assert!(watch.poll(later(3)).is_empty(), "reported once");
std::fs::remove_file(&fresh).unwrap();
assert_eq!(watch.poll(later(4)), vec![fresh]);
}
#[test]
fn a_change_croft_noted_itself_is_not_reported_again() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("keybindings.json");
std::fs::write(&file, "[]").unwrap();
let mut watch = ConfigWatch::new(vec![file.clone()]);
std::fs::write(&file, "[ ]").unwrap();
watch.note(&file);
let later = std::time::Instant::now() + ConfigWatch::INTERVAL * 2;
assert!(watch.poll(later).is_empty());
}
#[test]
fn write_own_is_croft_s_own_but_an_unseen_outside_edit_it_carries_is_not() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("keybindings.json");
let mut watch = ConfigWatch::new(vec![file.clone()]);
let later = |n: u32| std::time::Instant::now() + ConfigWatch::INTERVAL * n;
write_own(&file, "[]").unwrap();
assert!(watch.poll(later(2)).is_empty(), "croft's own write");
std::fs::write(&file, r#"[{"key": "ctrl+k"}]"#).unwrap();
assert_eq!(watch.poll(later(4)), vec![file.clone()]);
std::fs::write(&file, r#"[{"key": "ctrl+j"}, {}]"#).unwrap();
write_own(&file, r#"[{"key": "ctrl+j"}, {}, {}]"#).unwrap();
assert_eq!(watch.poll(later(6)), vec![file], "the outside edit");
}
#[test]
fn set_paths_keeps_what_it_knew_and_drops_what_left() {
let dir = tempfile::tempdir().unwrap();
let kept = dir.path().join("config.json");
let old_root = dir.path().join("old.json");
let new_root = dir.path().join("new.json");
for f in [&kept, &old_root, &new_root] {
std::fs::write(f, "{}").unwrap();
}
let mut watch = ConfigWatch::new(vec![kept.clone(), old_root.clone()]);
std::fs::write(&kept, r#"{ "theme": "dark" }"#).unwrap();
watch.set_paths(vec![kept.clone(), new_root.clone()]);
assert!(watch.watches(&new_root) && !watch.watches(&old_root));
std::fs::write(&old_root, r#"{ "theme": "light" }"#).unwrap();
let later = std::time::Instant::now() + ConfigWatch::INTERVAL * 2;
assert_eq!(
watch.poll(later),
vec![kept],
"the new file was not changed"
);
}
#[test]
fn croft_s_own_settings_save_is_not_reported_but_a_later_edit_is() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("config.json");
std::fs::write(&file, "{}").unwrap();
let mut watch = ConfigWatch::new(vec![file.clone()]);
let mut prefs = crate::prefs::Prefs::load_for_update(&file).unwrap();
prefs.osk_split = true;
prefs.save(&file).unwrap();
let t0 = std::time::Instant::now();
assert!(watch.poll(t0 + ConfigWatch::INTERVAL * 2).is_empty());
std::fs::write(&file, r#"{ "render_whitespace": "all" }"#).unwrap();
assert_eq!(watch.poll(t0 + ConfigWatch::INTERVAL * 4), vec![file]);
}
#[test]
fn a_croft_save_carrying_an_unseen_outside_edit_is_reported() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("config.json");
std::fs::write(&file, "{}").unwrap();
let mut watch = ConfigWatch::new(vec![file.clone()]);
std::fs::write(&file, r#"{ "render_whitespace": "all" }"#).unwrap();
let mut prefs = crate::prefs::Prefs::load_for_update(&file).unwrap();
prefs.osk_split = true;
prefs.save(&file).unwrap();
let t0 = std::time::Instant::now();
assert_eq!(
watch.poll(t0 + ConfigWatch::INTERVAL * 2),
vec![file.clone()]
);
let mut prefs = crate::prefs::Prefs::load_for_update(&file).unwrap();
prefs.osk_split = false;
prefs.save(&file).unwrap();
let mut prefs = crate::prefs::Prefs::load_for_update(&file).unwrap();
prefs.vim_mode = true;
prefs.save(&file).unwrap();
assert!(watch.poll(t0 + ConfigWatch::INTERVAL * 4).is_empty());
}
#[test]
fn an_excluded_host_is_matched_case_insensitively() {
let excluded = vec![String::from("Shared-Box")];
assert!(host_excluded("shared-box", &excluded));
assert!(!host_excluded("dev", &excluded));
assert!(!host_excluded("shared-box", &[]));
}
#[test]
fn excluded_files_stay_home_and_are_named() {
let files: Vec<(Syncable, PathBuf)> = SYNCABLE
.iter()
.map(|s| (*s, PathBuf::from(s.name)))
.collect();
let (keep, skipped) = apply_exclusions(files, &[String::from("keybindings.json")]);
assert_eq!(skipped, vec!["keybindings.json"]);
assert!(keep.iter().all(|(s, _)| s.name != "keybindings.json"));
assert_eq!(
keep.len(),
SYNCABLE.len() - 1,
"only the excluded one stays"
);
}
#[test]
fn config_json_travels_as_a_projection_without_trust() {
let dir = tempfile::tempdir().unwrap();
let out = tempfile::tempdir().unwrap();
let config = dir.path().join("config.json");
std::fs::write(
&config,
r#"{ "theme": "light", "mcp_consented": ["srv"], "mcp_tool_fingerprints": {"srv": "f"} }"#,
)
.unwrap();
let got = repush_targets_into(std::slice::from_ref(&config), dir.path(), out.path());
assert_eq!(got.len(), 1);
let (s, path) = &got[0];
assert_eq!(s.name, crate::config_layers::SYNCED_CONFIG_NAME);
assert_ne!(path, &config, "config.json itself never travels");
let sent: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
assert_eq!(sent, serde_json::json!({ "theme": "light" }));
std::fs::write(&config, r#"{ "mcp_consented": ["srv"] }"#).unwrap();
assert!(
repush_targets_into(std::slice::from_ref(&config), dir.path(), out.path()).is_empty(),
"nothing shareable, nothing pushed"
);
std::fs::write(&config, "not json").unwrap();
assert!(
repush_targets_into(std::slice::from_ref(&config), dir.path(), out.path()).is_empty(),
"an unreadable config pushes nothing rather than an empty layer"
);
}
#[test]
fn the_watch_covers_the_projections_source() {
let watched = watched_local_paths();
assert!(
watched.iter().any(|p| p.ends_with("config.json")),
"{watched:?}"
);
assert!(
!watched
.iter()
.any(|p| p.ends_with(crate::config_layers::SYNCED_CONFIG_NAME)),
"the synced layer is written by other machines, not watched for pushing"
);
}
}