use super::*;
pub(super) fn read_remote_hashes(
mut command: Command,
) -> Option<std::collections::BTreeMap<String, String>> {
let out = crate::review_ops::spawn_retrying_busy(&mut command)
.and_then(std::process::Child::wait_with_output)
.ok()?;
if !out.status.success() {
return None;
}
crate::config_sync::parse_remote_listing(&String::from_utf8_lossy(&out.stdout))
}
pub(super) fn push_config_files(
ssh: &SshControl,
resolution: &SyncResolution,
log: &mut dyn FnMut(String),
) {
let prefs = crate::config_layers::load_merged(None).prefs;
if crate::config_sync::host_excluded(&ssh.host, &prefs.config_sync_excluded_hosts) {
log(format!(
"Config sync: off for {} (config_sync_excluded_hosts)",
ssh.host
));
return;
}
let (files, skipped) = crate::config_sync::apply_exclusions(
crate::config_sync::local_files(),
&prefs.config_sync_excluded_files,
);
if !skipped.is_empty() {
log(format!(
"Config sync: not pushing {} (config_sync_excluded_files)",
skipped.join(", ")
));
}
if files.is_empty() {
return;
}
let mut mk = ssh.background_shell("mkdir -p ~/.config/croft");
if !matches!(mk.status(), Ok(st) if st.success()) {
log(String::from(
"Config sync: could not create ~/.config/croft on the remote; skipping",
));
return;
}
let Some(remote) = read_remote_hashes(ssh_socket_read(
&ssh.socket_path,
&ssh.host,
&crate::config_sync::remote_hash_script(),
)) else {
log(String::from(
"Config sync: could not read the remote's copies; pushing nothing rather than risk overwriting them",
));
return;
};
let state_path = crate::config_sync::SyncState::path();
let mut state = crate::config_sync::SyncState::load(&state_path);
let bulk = crate::remote_bulk::establish(&ssh.host, &ssh.socket_path, |_| {});
let mut pushed = Vec::new();
let mut failed = Vec::new();
let mut kept = Vec::new();
let mut conflicts = Vec::new();
for (syncable, local) in &files {
let Ok(bytes) = std::fs::read(local) else {
failed.push(syncable.name);
continue;
};
let local_hash = crate::config_sync::content_hash(&bytes);
let there = remote.get(syncable.name).map(String::as_str);
let chosen = |list: &[String]| list.iter().any(|n| n == syncable.name);
let plan = if chosen(&resolution.take_local) {
crate::config_sync::Plan::Push
} else if chosen(&resolution.keep_remote) && there.is_some_and(|r| r != local_hash) {
let entry = state.file_mut(&ssh.host, syncable.name);
entry.kept = there.map(|r| (r.to_string(), local_hash.clone()));
crate::config_sync::Plan::Kept
} else {
crate::config_sync::plan(&local_hash, there, state.file(&ssh.host, syncable.name))
};
match plan {
crate::config_sync::Plan::Push => {
let dest = crate::config_sync::remote_dest(&ssh.host, syncable.name);
let mut rsync = ship_file_rsync_command(&bulk.lane, &ssh.socket_path, local, &dest);
match rsync.status() {
Ok(st) if st.success() => {
let entry = state.file_mut(&ssh.host, syncable.name);
entry.pushed = Some(local_hash);
entry.kept = None;
pushed.push(syncable);
}
_ => failed.push(syncable.name),
}
}
crate::config_sync::Plan::UpToDate => {
let entry = state.file_mut(&ssh.host, syncable.name);
entry.pushed = Some(local_hash);
entry.kept = None;
}
crate::config_sync::Plan::Kept => kept.push(syncable.name),
crate::config_sync::Plan::Conflict => conflicts.push(syncable.name),
}
}
if let Err(e) = state.save(&state_path) {
log(format!(
"Config sync: could not record what was pushed ({e})"
));
}
if !kept.is_empty() {
log(format!(
"Config sync: keeping the remote's own {} (as you chose)",
kept.join(", ")
));
}
for name in &conflicts {
log(format!(
"Config sync: {name} was changed on {host} since croft last pushed it, so it was left alone. \
`croft sync-config {host} --diff {name}` compares the two; `--take-local {name}` pushes yours, \
`--keep-remote {name}` keeps theirs",
host = ssh.host
));
}
if !pushed.is_empty() {
let names: Vec<&str> = pushed.iter().map(|s| s.name).collect();
log(format!("Config sync: pushed {}", names.join(", ")));
log(format!(
"Config sync: {} applies on the remote within a few seconds",
names.join(", ")
));
}
if !failed.is_empty() {
log(format!(
"Config sync: could not push {} (the remote keeps its own copy)",
failed.join(", ")
));
}
}
#[derive(Debug, Default, Clone)]
pub struct SyncResolution {
pub take_local: Vec<String>,
pub keep_remote: Vec<String>,
}
pub fn sync_config_now(host: &str, resolution: &SyncResolution, diff: Option<&str>) -> Result<()> {
for name in resolution
.take_local
.iter()
.chain(&resolution.keep_remote)
.map(String::as_str)
.chain(diff)
{
if !crate::config_sync::SYNCABLE.iter().any(|s| s.name == name) {
let names: Vec<&str> = crate::config_sync::SYNCABLE
.iter()
.map(|s| s.name)
.collect();
anyhow::bail!("{name} is not a synced file ({})", names.join(", "));
}
}
let ssh = SshControl::start(host)?;
match diff {
Some(name) => print_config_diff(&ssh, name),
None => {
push_config_files(&ssh, resolution, &mut |msg| println!("{msg}"));
Ok(())
}
}
}
pub(super) fn read_remote_config(
socket_path: &Path,
host: &str,
name: &str,
) -> std::io::Result<Vec<u8>> {
let mut command = ssh_socket_read(
socket_path,
host,
&format!("cat ~/.config/croft/{name} 2>/dev/null"),
);
let out = crate::review_ops::spawn_retrying_busy(&mut command)
.and_then(std::process::Child::wait_with_output)?;
Ok(out.stdout)
}
pub(super) fn print_config_diff(ssh: &SshControl, name: &str) -> Result<()> {
let local = crate::paths::config_dir().join(name);
let remote = read_remote_config(&ssh.socket_path, &ssh.host, name)?;
let tmp = std::env::temp_dir().join(format!("croft-sync-{}-{name}", std::process::id()));
std::fs::write(&tmp, &remote)?;
let local_arg = if local.is_file() {
local
} else {
PathBuf::from("/dev/null")
};
let status = Command::new("diff")
.args(["-u", "--label"])
.arg(format!("{}:{name}", ssh.host))
.arg("--label")
.arg(format!("local:{name}"))
.arg(&tmp)
.arg(&local_arg)
.status();
let _ = std::fs::remove_file(&tmp);
let status = status?;
if status.code() == Some(0) {
println!("{name} is the same on {} and here", ssh.host);
}
Ok(())
}
impl SyncExclusions {
pub(super) fn load() -> Self {
let mut ex = SyncExclusions { known: None };
ex.update(crate::config_layers::load_merged(None));
ex
}
pub(super) fn current(&mut self) -> Option<(Vec<String>, Vec<String>)> {
self.update(crate::config_layers::load_merged(None));
self.known.clone()
}
pub(super) fn update(&mut self, merged: crate::config_layers::MergedConfig) {
if merged.warnings.is_empty() {
self.known = Some((
merged.prefs.config_sync_excluded_hosts,
merged.prefs.config_sync_excluded_files,
));
}
}
}
pub(super) fn config_sync_log() -> impl FnMut(String) {
let path = install_log_path().with_file_name("config-sync.log");
move |line: String| {
use std::io::Write as _;
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let _ = writeln!(f, "{secs} {line}");
}
}
}
pub(super) fn ship_file_rsync_command(
lane: &crate::remote_bulk::BulkLane,
interactive_socket: &Path,
local: &Path,
dest: &str,
) -> Command {
let mut rsync = Command::new("rsync");
rsync.args(["-az", "--checksum"]);
rsync.args(lane.rsync_throttle_args());
rsync.arg("-e").arg(lane.rsync_ssh_arg(interactive_socket));
rsync.arg(local).arg(dest);
rsync
}