use super::*;
pub(super) fn remote_source_dir_prep(source: &Path) -> String {
let keeps: String = std::iter::once("target")
.chain(
SOURCE_STAMP_INPUTS
.iter()
.copied()
.filter(|name| source.join(name).exists()),
)
.map(|name| format!("! -name '{name}' "))
.collect();
format!(
"mkdir -p \"$HOME/.cache/croft/source\" && \
find \"$HOME/.cache/croft/source/.\" -mindepth 1 -maxdepth 1 \
{keeps}-exec rm -rf {{}} +"
)
}
pub(super) fn source_sync_filter_args() -> Vec<String> {
let mut args: Vec<String> = Vec::new();
for name in SOURCE_SKIP_NAMES {
args.push(format!("--exclude={name}"));
}
for name in SOURCE_STAMP_INPUTS {
args.push(format!("--include=/{name}"));
args.push(format!("--include=/{name}/***"));
}
args.push(String::from("--exclude=*"));
args
}
pub(super) fn source_sync_tar_members(source: &Path) -> Vec<&'static str> {
SOURCE_STAMP_INPUTS
.iter()
.copied()
.filter(|name| source.join(name).exists())
.collect()
}
pub(super) fn source_sync_rsync_command(
lane: &crate::remote_bulk::BulkLane,
interactive_socket: &Path,
source_arg: &std::ffi::OsStr,
dest: &str,
) -> Command {
let mut rsync = Command::new("rsync");
rsync.args(["-a", "-z", "--delete"]);
rsync.args(source_sync_filter_args());
rsync.args(lane.rsync_throttle_args());
rsync.arg("-e").arg(lane.rsync_ssh_arg(interactive_socket));
rsync.arg(source_arg).arg(dest);
rsync
}
pub(super) fn sync_local_source_to_remote(ssh: &SshControl) -> Result<()> {
match sync_via_rsync(ssh) {
Ok(()) => Ok(()),
Err(e) => {
eprintln!("rsync sync failed ({e}); falling back to tar pipe");
sync_via_tar(ssh)
}
}
}
pub(super) fn sync_via_rsync(ssh: &SshControl) -> Result<()> {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mkdir_status = ssh
.command()
.arg(&ssh.host)
.arg(remote_source_dir_prep(&source))
.status()
.context("creating remote source dir")?;
if !mkdir_status.success() {
anyhow::bail!("remote mkdir exited with {mkdir_status}");
}
let ssh_e = format!(
"ssh -S {} -o ControlMaster=no",
shell_quote_for_e_arg(&ssh.socket_path),
);
let mut source_arg: std::ffi::OsString = source.clone().into_os_string();
source_arg.push("/");
let dest = format!("{}:.cache/croft/source/", ssh.host);
let status = Command::new("rsync")
.args(["-a", "-z", "--delete"])
.args(source_sync_filter_args())
.arg("-e")
.arg(&ssh_e)
.arg(&source_arg)
.arg(&dest)
.status()
.context("running rsync to remote")?;
if !status.success() {
anyhow::bail!("rsync exited with {status}");
}
Ok(())
}
pub(super) fn sync_via_tar(ssh: &SshControl) -> Result<()> {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mut tar = Command::new("tar")
.env("COPYFILE_DISABLE", "1")
.args(["-czf", "-"])
.args(
SOURCE_SKIP_NAMES
.iter()
.map(|name| format!("--exclude={name}")),
)
.arg("-C")
.arg(&source)
.args(source_sync_tar_members(&source))
.stdout(Stdio::piped())
.spawn()
.with_context(|| format!("packing {}", source.display()))?;
let tar_stdout = tar.stdout.take().context("opening tar stdout")?;
let mut remote = ssh
.command()
.arg(&ssh.host)
.arg(format!(
"{} && tar -xzf - -C \"$HOME/.cache/croft/source\"",
remote_source_dir_prep(&source)
))
.stdin(Stdio::from(tar_stdout))
.spawn()
.context("copying croft source to remote")?;
let ssh_status = remote.wait().context("waiting for remote source copy")?;
let tar_status = tar.wait().context("waiting for local source archive")?;
if !tar_status.success() {
anyhow::bail!("local source archive failed with {tar_status}");
}
if !ssh_status.success() {
anyhow::bail!("remote source copy failed with {ssh_status}");
}
Ok(())
}
pub(crate) fn shell_quote_for_e_arg(p: &std::path::Path) -> String {
let s = p.to_string_lossy();
if s.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-'))
{
s.into_owned()
} else {
format!("'{}'", s.replace('\'', r"'\''"))
}
}
pub(super) fn local_source_stamp() -> Result<String> {
build_stamp_for(
&PathBuf::from(env!("CARGO_MANIFEST_DIR")),
env!("CARGO_PKG_VERSION"),
)
}
pub(super) fn build_stamp_for(root: &PathBuf, version: &str) -> Result<String> {
if !root.exists() {
return Ok(format!("release-v{version}"));
}
source_stamp_for(root)
}
pub(super) fn source_snapshot_warning() -> Option<String> {
let dir = env!("CARGO_MANIFEST_DIR");
source_dir_is_snapshot(dir).then(|| {
format!(
"WARNING: this croft was installed from an immutable snapshot ({dir}); remote installs can never ship local changes. Reinstall with `cargo install --path <your repo>` to make installs track your tree."
)
})
}
pub(super) fn source_dir_is_snapshot(dir: &str) -> bool {
dir.contains("/registry/src/") || dir.contains("/git/checkouts/")
}
pub(super) const SOURCE_SKIP_NAMES: &[&str] = &[".git", "target", ".DS_Store"];
pub(super) const SOURCE_STAMP_INPUTS: &[&str] = &[
"Cargo.toml",
"Cargo.lock",
"build.rs",
"rust-toolchain.toml",
"src",
"assets",
"vendor",
];
pub(super) fn source_stamp_for(root: &PathBuf) -> Result<String> {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
for name in SOURCE_STAMP_INPUTS {
let path = root.join(name);
let Ok(meta) = std::fs::metadata(&path) else {
continue;
};
hasher.write(name.as_bytes());
if meta.is_dir() {
hash_source_dir(root, &path, &mut hasher)?;
} else {
hasher.write_u64(meta.len());
hasher.write(
&std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
);
}
}
Ok(format!("{:016x}", hasher.finish()))
}
pub(super) fn hash_source_dir(
root: &PathBuf,
dir: &PathBuf,
hasher: &mut impl Hasher,
) -> Result<()> {
let mut entries = std::fs::read_dir(dir)
.with_context(|| format!("reading {}", dir.display()))?
.collect::<std::result::Result<Vec<_>, _>>()
.with_context(|| format!("reading entries in {}", dir.display()))?;
entries.sort_by_key(|entry| entry.path());
for entry in entries {
let path = entry.path();
let name = entry.file_name();
let name = name.to_string_lossy();
if SOURCE_SKIP_NAMES.contains(&name.as_ref()) {
continue;
}
let meta = entry
.metadata()
.with_context(|| format!("reading metadata for {}", path.display()))?;
let rel = path.strip_prefix(root).unwrap_or(&path);
hasher.write(rel.to_string_lossy().as_bytes());
if meta.is_dir() {
hasher.write_u8(b'/');
hash_source_dir(root, &path, hasher)?;
} else if meta.is_file() {
hasher.write_u64(meta.len());
hasher.write(
&std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
);
}
}
Ok(())
}