use crate::source::Stop;
use crate::version;
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
use tessera_frontend::tasks::Error;
use tessera_frontend::tasks::task::{Argv, Field, Json, Role, Run, Shown, Sink, Task, Usage};
const SSH: [&str; 4] = ["-o", "ConnectTimeout=15", "-o", "BatchMode=yes"];
const ROOT: &str = "$HOME/.cache/tessera/bin";
const SCHEMES: [&str; 6] = [
"hf:",
"kindling:",
"catalog:",
"git+",
"http://",
"https://",
];
pub const PLATFORMS: [(&str, &str, &str); 3] = [
("Darwin arm64", "aarch64-macos", "tesserax-darwin-arm64"),
("Linux aarch64", "aarch64-linux", "tesserax-linux-arm64"),
("Linux x86_64", "x86_64-linux", "tesserax-linux-x64"),
];
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Mode {
Copy(Vec<String>),
Run { host: String, command: Vec<String> },
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Args {
pub(crate) from: Option<PathBuf>,
pub(crate) root: String,
pub(crate) mode: Mode,
}
struct Host {
platform: &'static str,
asset: &'static str,
root: String,
dest: String,
}
enum Build {
File(PathBuf),
Url(String),
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum PathArg {
Keep(String),
Local {
prefix: String,
path: PathBuf,
suffix: String,
},
}
enum StagedKind {
Missing,
File { sha: String },
Dir,
}
struct Staged {
local: PathBuf,
slot_dir: String,
remote: String,
name: String,
kind: StagedKind,
}
pub(crate) fn parse(rest: &[String]) -> Result<Args, Stop> {
let mut from = None;
let mut root = ROOT.to_string();
let mut host: Option<String> = None;
let mut hosts = Vec::new();
let mut command = Vec::new();
let mut i = 0;
while i < rest.len() {
let arg = &rest[i];
match arg.as_str() {
"--from" => {
from = Some(rest.get(i + 1).ok_or(Stop::Usage)?.into());
i += 2;
}
"--root" => {
root = rest.get(i + 1).ok_or(Stop::Usage)?.clone();
i += 2;
}
"--host" if host.is_none() && hosts.is_empty() => {
host = Some(rest.get(i + 1).ok_or(Stop::Usage)?.clone());
i += 2;
}
"--" if host.is_some() => {
command = rest[i + 1..].to_vec();
break;
}
_ if host.is_some() => {
command = rest[i..].to_vec();
break;
}
_ if arg.starts_with('-') => return Err(Stop::Usage),
_ => {
hosts.push(arg.clone());
i += 1;
}
}
}
let mode = match host {
Some(host) if !command.is_empty() => Mode::Run { host, command },
None if !hosts.is_empty() => Mode::Copy(hosts),
_ => return Err(Stop::Usage),
};
Ok(Args { from, root, mode })
}
#[cfg(feature = "tern")]
pub(crate) fn runs_remote(rest: &[String]) -> bool {
matches!(
parse(rest),
Ok(Args {
mode: Mode::Run { .. },
..
})
)
}
pub fn quote(text: &str) -> String {
format!("'{}'", text.replace('\'', r"'\''"))
}
fn shell(host: &str, script: &str) -> Result<String, String> {
let mut cmd = Command::new(if host == "local" { "sh" } else { "ssh" });
if host == "local" {
cmd.arg("-c").arg(script);
} else {
cmd.args(SSH)
.arg(host)
.arg(format!("sh -c {}", quote(script)));
}
let out = cmd.output().map_err(|e| format!("{host}: {e}"))?;
if out.status.success() {
return Ok(String::from_utf8_lossy(&out.stdout).trim().to_string());
}
let err = String::from_utf8_lossy(&out.stderr);
let last = err.trim().lines().last().unwrap_or("failed").to_string();
Err(format!("{host}: {last}"))
}
fn hash(host: &str, path: &str) -> Result<String, String> {
let f = quote(path);
let sum = format!("(sha256sum {f} 2>/dev/null || shasum -a 256 {f} 2>/dev/null)");
shell(host, &format!("{sum} | cut -c1-64"))
}
pub fn platform(uname: &str) -> Option<(&'static str, &'static str)> {
let found = PLATFORMS.iter().find(|p| p.0 == uname.trim())?;
Some((found.1, found.2))
}
fn probe(host: &str, root: &str) -> Result<Host, String> {
let out = shell(host, &format!("uname -sm; echo \"{root}\""))?;
let (uname, root) = out.split_once('\n').ok_or(format!("{host}: no uname"))?;
let (platform, asset) = platform(uname).ok_or(format!("{host}: no build for {uname}"))?;
let root = root.trim().to_string();
let dest = format!("{}/{}/tesserax", root, version::id());
Ok(Host {
platform,
asset,
root,
dest,
})
}
fn release(asset: &str) -> Result<(Build, String), String> {
let tag = format!("v{}", env!("CARGO_PKG_VERSION"));
let base = format!("{}/releases/download/{tag}", env!("CARGO_PKG_REPOSITORY"));
let sums = Command::new("curl")
.args(["-fsSL", "--max-time", "60", &format!("{base}/SHA256SUMS")])
.output()
.map_err(|e| e.to_string())?;
for line in String::from_utf8_lossy(&sums.stdout).lines() {
if let [sum, name] = line.split_whitespace().collect::<Vec<_>>()[..]
&& name == asset
{
return Ok((Build::Url(format!("{base}/{asset}")), sum.to_string()));
}
}
Err(format!("no {asset} in release {tag}: pass --from <dir>"))
}
fn binary(platform: &str, asset: &str, from: Option<&Path>) -> Result<(Build, String), String> {
let path = if platform == version::platform() {
std::env::current_exe().map_err(|e| e.to_string())?
} else {
match from.map(|d| d.join(asset)).filter(|p| p.is_file()) {
Some(path) => path,
None => return release(asset),
}
};
let sum = hash("local", &path.to_string_lossy())?;
Ok((Build::File(path), sum))
}
fn put_file(host: &str, local: &Path, remote: &str) -> Result<(), String> {
if host == "local" {
fs::copy(local, remote).map_err(|e| format!("{host}: {e}"))?;
return Ok(());
}
let file = File::open(local).map_err(|e| format!("{}: {e}", local.display()))?;
let status = Command::new("ssh")
.args(SSH)
.arg(host)
.arg(format!("cat > {}", quote(remote)))
.stdin(Stdio::from(file))
.status()
.map_err(|e| format!("{host}: {e}"))?;
if !status.success() {
return Err(format!("{host}: copy failed"));
}
Ok(())
}
fn upload(host: &str, build: &Build, part: &str) -> Result<(), String> {
match build {
Build::Url(url) => {
let get = format!(
"curl -fsSL --max-time 900 -o {} {}",
quote(part),
quote(url)
);
shell(host, &get).map(drop)
}
Build::File(local) => put_file(host, local, part),
}
}
fn place(host: &str, build: &Build, dest: &str, want: &str) -> Result<&'static str, String> {
if hash(host, dest)? == want {
return Ok("present");
}
let part = format!("{dest}.part");
let (d, p) = (quote(dest), quote(&part));
shell(host, &format!("mkdir -p \"$(dirname {d})\" && rm -f {p}"))?;
upload(host, build, &part)?;
if hash(host, &part)? != want {
return Err(format!("{host}: sha256 differs after copy"));
}
shell(host, &format!("chmod 755 {p} && mv -f {p} {d}"))?;
Ok("copied")
}
struct Sent {
platform: &'static str,
state: &'static str,
dest: String,
version: String,
}
fn send(name: &str, host: &Host, build: &Build, want: &str) -> Result<Sent, String> {
let state = place(name, build, &host.dest, want)?;
let line = shell(name, &format!("{} --version", quote(&host.dest)))?;
if version::COMMIT.is_some_and(|c| !line.contains(c)) {
return Err(format!("{name}: commit differs: {line}"));
}
Ok(Sent {
platform: host.platform,
state,
dest: host.dest.clone(),
version: line,
})
}
fn each<I: Sync, T: Send>(items: &[I], f: impl Fn(&I) -> T + Sync) -> Vec<T> {
std::thread::scope(|s| {
let jobs: Vec<_> = items.iter().map(|i| s.spawn(|| f(i))).collect();
let done = jobs.into_iter().map(|j| j.join());
done.map(|r| r.expect("teleport thread")).collect()
})
}
fn expand_home(raw: &str) -> String {
let Some(home) = tessera_frontend::frontend_settings::home_dir() else {
return raw.to_string();
};
let home = home.to_string_lossy();
if raw == "~" {
home.into_owned()
} else if let Some(tail) = raw.strip_prefix("~/") {
format!("{home}/{tail}")
} else {
raw.to_string()
}
}
fn split_existing(raw: &str) -> Option<(PathBuf, String)> {
let expanded = expand_home(raw);
if Path::new(&expanded).exists() {
return Some((PathBuf::from(expanded), String::new()));
}
for (at, _) in expanded.rmatch_indices(':') {
let head = &expanded[..at];
if !head.is_empty() && Path::new(head).exists() {
return Some((PathBuf::from(head), expanded[at..].to_string()));
}
}
None
}
pub(crate) fn classify_arg(arg: &str) -> Result<PathArg, String> {
let (prefix, val) = if arg.starts_with('-') {
match arg.split_once('=') {
Some((k, v)) => (format!("{k}="), v),
None => return Ok(PathArg::Keep(arg.to_string())),
}
} else {
(String::new(), arg)
};
if let Some(rest) = val.strip_prefix("remote:") {
if rest.is_empty() {
return Err("empty remote: path".into());
}
return Ok(PathArg::Keep(format!("{prefix}{rest}")));
}
if let Some(spec) = val.strip_prefix("local:") {
if spec.is_empty() {
return Err("empty local: path".into());
}
let (path, suffix) = split_existing(spec)
.unwrap_or_else(|| (PathBuf::from(expand_home(spec)), String::new()));
return Ok(PathArg::Local {
prefix,
path,
suffix,
});
}
if SCHEMES.iter().any(|s| val.starts_with(s)) {
return Ok(PathArg::Keep(arg.to_string()));
}
let rel = val.starts_with("./") || val.starts_with("../") || val.starts_with("~/");
if rel && let Some((path, suffix)) = split_existing(val) {
return Ok(PathArg::Local {
prefix,
path,
suffix,
});
}
Ok(PathArg::Keep(arg.to_string()))
}
fn slot_name(path: &Path) -> String {
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.or_else(|| {
path.canonicalize()
.ok()
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
})
.filter(|n| !n.is_empty() && n != "." && n != "..")
.unwrap_or_else(|| "item".into())
}
fn ensure_parent(path: &Path) -> Result<(), String> {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
Ok(())
}
fn get_file(host: &str, remote: &str, local: &Path) -> Result<(), String> {
ensure_parent(local)?;
let mut part = local.as_os_str().to_os_string();
part.push(".teleport.part");
let part = PathBuf::from(part);
if host == "local" {
fs::copy(remote, &part).map_err(|e| format!("{}: {e}", local.display()))?;
} else {
let out = File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?;
let status = Command::new("ssh")
.args(SSH)
.arg(host)
.arg(format!("cat {}", quote(remote)))
.stdout(Stdio::from(out))
.status()
.map_err(|e| format!("{host}: {e}"))?;
if !status.success() {
let _ = fs::remove_file(&part);
return Err(format!("{host}: fetch failed for {remote}"));
}
}
fs::rename(&part, local).map_err(|e| format!("{}: {e}", local.display()))
}
fn copy_tree(from: &Path, to: &Path) -> Result<(), String> {
fs::create_dir_all(to).map_err(|e| format!("{}: {e}", to.display()))?;
let entries = fs::read_dir(from).map_err(|e| format!("{}: {e}", from.display()))?;
for entry in entries {
let entry = entry.map_err(|e| format!("{}: {e}", from.display()))?;
let src = entry.path();
let dst = to.join(entry.file_name());
if src.is_dir() {
copy_tree(&src, &dst)?;
} else if src.is_file() {
fs::copy(&src, &dst).map_err(|e| format!("{}: {e}", dst.display()))?;
}
}
Ok(())
}
fn get_dir(host: &str, remote: &str, local: &Path) -> Result<(), String> {
if host == "local" {
return copy_tree(Path::new(remote), local);
}
fs::create_dir_all(local).map_err(|e| format!("{}: {e}", local.display()))?;
let mut ssh = Command::new("ssh")
.args(SSH)
.arg(host)
.arg(format!("tar -C {} -cf - .", quote(remote)))
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("{host}: {e}"))?;
let pipe = ssh.stdout.take().ok_or("missing ssh stdout")?;
let tar = Command::new("tar")
.arg("-C")
.arg(local)
.args(["-xf", "-"])
.stdin(Stdio::from(pipe))
.status()
.map_err(|e| format!("tar: {e}"))?;
let ssh_ok = ssh.wait().map_err(|e| format!("{host}: {e}"))?.success();
if !ssh_ok || !tar.success() {
return Err(format!("{host}: dir fetch failed for {remote}"));
}
Ok(())
}
fn cache_file(host: &str, files_root: &str, local: &Path) -> Result<(String, String), String> {
let sha = hash("local", &local.to_string_lossy())?;
if sha.is_empty() {
return Err(format!("{}: could not hash file", local.display()));
}
let name = slot_name(local);
let cached = format!("{files_root}/{sha}/{name}");
if hash(host, &cached)? != sha {
let part = format!("{cached}.part");
let (d, p, c) = (
quote(&format!("{files_root}/{sha}")),
quote(&part),
quote(&cached),
);
shell(host, &format!("mkdir -p {d} && rm -f {p}"))?;
put_file(host, local, &part)?;
if hash(host, &part)? != sha {
return Err(format!("{host}: sha256 differs after upload"));
}
shell(host, &format!("mv -f {p} {c}"))?;
}
Ok((cached, sha))
}
fn walk_files(root: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) -> Result<(), String> {
let entries = fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
let path = entry.path();
let kind = entry
.file_type()
.map_err(|e| format!("{}: {e}", path.display()))?;
if kind.is_dir() {
walk_files(root, &path, out)?;
} else if path.is_file() {
let rel = path
.strip_prefix(root)
.map_err(|e| e.to_string())?
.to_string_lossy()
.into_owned();
out.push((rel, path));
}
}
Ok(())
}
fn stage_dir(host: &str, files_root: &str, local: &Path, remote: &str) -> Result<(), String> {
let mut files = Vec::new();
walk_files(local, local, &mut files)?;
let mut dirs = BTreeSet::new();
dirs.insert(remote.to_string());
let mut links = Vec::with_capacity(files.len());
for (rel, path) in &files {
let (cached, _) = cache_file(host, files_root, path)?;
let dst = format!("{remote}/{rel}");
if let Some((parent, _)) = dst.rsplit_once('/') {
dirs.insert(parent.to_string());
}
links.push((cached, dst));
}
let mut script = String::new();
for dir in dirs {
script.push_str(&format!("mkdir -p {}\n", quote(&dir)));
}
for (src, dst) in links {
script.push_str(&format!("ln -sf {} {}\n", quote(&src), quote(&dst)));
}
shell(host, &script).map(drop)
}
fn stage_arg(
host: &str,
files_root: &str,
run_dir: &str,
idx: usize,
arg: PathArg,
staged: &mut Vec<Staged>,
) -> Result<String, String> {
let PathArg::Local {
prefix,
path,
suffix,
} = arg
else {
let PathArg::Keep(lit) = arg else {
unreachable!()
};
return Ok(lit);
};
let slot_dir = format!("{run_dir}/{idx}");
let name = slot_name(&path);
let remote = format!("{slot_dir}/{name}");
let kind = if path.is_file() {
let (cached, sha) = cache_file(host, files_root, &path)?;
let (sd, c, r) = (quote(&slot_dir), quote(&cached), quote(&remote));
shell(
host,
&format!("mkdir -p {sd} && (cp --reflink=auto {c} {r} 2>/dev/null || cp {c} {r})"),
)?;
StagedKind::File { sha }
} else if path.is_dir() {
stage_dir(host, files_root, &path, &remote)?;
StagedKind::Dir
} else {
shell(host, &format!("mkdir -p {}", quote(&slot_dir)))?;
StagedKind::Missing
};
staged.push(Staged {
local: path,
slot_dir,
remote: remote.clone(),
name,
kind,
});
Ok(format!("{prefix}{remote}{suffix}"))
}
fn sync_siblings(host: &str, s: &Staged, skip: Option<&str>) -> Result<(), String> {
let sd = quote(&s.slot_dir);
let list = shell(host, &format!("ls -1A {sd} 2>/dev/null || true"))?;
let base = s.local.parent().unwrap_or_else(|| Path::new(""));
for entry in list.lines().filter(|l| !l.is_empty()) {
if skip == Some(entry) {
continue;
}
let remote = format!("{}/{entry}", s.slot_dir);
let is_file = shell(
host,
&format!("test -f {} && echo y || true", quote(&remote)),
)?;
if is_file == "y" {
let local = if base.as_os_str().is_empty() {
PathBuf::from(entry)
} else {
base.join(entry)
};
get_file(host, &remote, &local)?;
}
}
Ok(())
}
fn sync_slot(host: &str, marker: &str, s: &Staged) -> Result<(), String> {
match &s.kind {
StagedKind::Missing => {
let r = quote(&s.remote);
let kind = shell(
host,
&format!("if [ -f {r} ]; then echo f; elif [ -d {r} ]; then echo d; fi"),
)?;
match kind.as_str() {
"f" => get_file(host, &s.remote, &s.local),
"d" => get_dir(host, &s.remote, &s.local),
_ => sync_siblings(host, s, None),
}
}
StagedKind::File { sha } => {
let now = hash(host, &s.remote)?;
if !now.is_empty() && now != *sha {
get_file(host, &s.remote, &s.local)?;
}
sync_siblings(host, s, Some(&s.name))
}
StagedKind::Dir => {
let found = shell(
host,
&format!(
"find {} -type f -newer {} 2>/dev/null || true",
quote(&s.remote),
quote(marker)
),
)?;
let prefix = format!("{}/", s.remote);
for path in found.lines().filter(|l| !l.is_empty()) {
if let Some(rel) = path.strip_prefix(&prefix) {
get_file(host, path, &s.local.join(rel))?;
}
}
Ok(())
}
}
}
fn exec_remote(host: &str, bin: &str, args: &[String], sink: &mut dyn Sink) -> Result<u8, String> {
let mut cmd = if host == "local" {
let mut c = Command::new(bin);
c.args(args);
c
} else {
let mut parts = Vec::with_capacity(1 + args.len());
parts.push(quote(bin));
for arg in args {
parts.push(quote(arg));
}
let line = parts.join(" ");
let mut c = Command::new("ssh");
c.args(SSH);
if sink.passthrough() && std::io::stdin().is_terminal() && std::io::stdout().is_terminal() {
c.arg("-t");
}
c.arg(host).arg(format!("sh -c {}", quote(&line)));
c
};
if sink.passthrough() {
let status = cmd.status().map_err(|e| format!("{host}: {e}"))?;
return Ok(status.code().unwrap_or(1) as u8);
}
let out = cmd.output().map_err(|e| format!("{host}: {e}"))?;
let stdout = String::from_utf8_lossy(&out.stdout);
if !stdout.is_empty() {
sink.text(&stdout);
}
let stderr = String::from_utf8_lossy(&out.stderr);
if !stderr.trim().is_empty() {
sink.note(stderr.trim());
}
Ok(out.status.code().unwrap_or(1) as u8)
}
fn run_id() -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
format!("{}-{nanos}", std::process::id())
}
pub(crate) fn run_with_sink(
host: &str,
root: &str,
bin: &str,
command: &[String],
sink: &mut dyn Sink,
) -> Result<(), Stop> {
let classified: Vec<PathArg> = command
.iter()
.map(|a| classify_arg(a))
.collect::<Result<_, _>>()
.map_err(Stop::Failed)?;
let has_local = classified
.iter()
.any(|a| matches!(a, PathArg::Local { .. }));
if !has_local {
let args: Vec<String> = classified
.into_iter()
.map(|a| match a {
PathArg::Keep(s) => s,
PathArg::Local { .. } => unreachable!(),
})
.collect();
let code = exec_remote(host, bin, &args, sink).map_err(Stop::Failed)?;
return if code == 0 {
Ok(())
} else {
Err(Stop::Code(code))
};
}
let files_root = format!("{root}/teleport/files");
let run_dir = format!("{root}/teleport/runs/{}", run_id());
let marker = format!("{run_dir}/.start");
let mut staged = Vec::new();
let mut rewritten = Vec::with_capacity(classified.len());
for (idx, arg) in classified.into_iter().enumerate() {
match stage_arg(host, &files_root, &run_dir, idx, arg, &mut staged) {
Ok(a) => rewritten.push(a),
Err(e) => {
let _ = shell(host, &format!("rm -rf {}", quote(&run_dir)));
return Err(Stop::Failed(e));
}
}
}
if staged.iter().any(|s| matches!(s.kind, StagedKind::Dir))
&& let Err(e) = shell(host, &format!("touch {}", quote(&marker)))
{
let _ = shell(host, &format!("rm -rf {}", quote(&run_dir)));
return Err(Stop::Failed(e));
}
let exec_res = exec_remote(host, bin, &rewritten, sink);
let mut sync_err = None;
for slot in &staged {
if let Err(e) = sync_slot(host, &marker, slot) {
sync_err = Some(e);
break;
}
}
let _ = shell(host, &format!("rm -rf {}", quote(&run_dir)));
let code = exec_res.map_err(Stop::Failed)?;
if let Some(e) = sync_err {
return Err(Stop::Failed(e));
}
if code == 0 {
Ok(())
} else {
Err(Stop::Code(code))
}
}
fn run_host(
host: &str,
root: &str,
from: Option<&Path>,
command: &[String],
sink: &mut dyn Sink,
) -> Result<(), Stop> {
let probed = probe(host, root).map_err(Stop::Failed)?;
let (build, want) = binary(probed.platform, probed.asset, from).map_err(Stop::Failed)?;
let sent = send(host, &probed, &build, &want).map_err(Stop::Failed)?;
if sent.state == "copied" {
sink.note(&format!(
"teleport: copied {} to {}:{}",
sent.platform, host, sent.dest
));
}
run_with_sink(host, &probed.root, &sent.dest, command, sink)
}
fn copy_hosts(
hosts: &[String],
root: &str,
from: Option<&Path>,
sink: &mut dyn Sink,
) -> Result<(), Stop> {
let probes = each(hosts, |h| probe(h, root));
let mut builds = BTreeMap::new();
for host in probes.iter().flatten() {
if !builds.contains_key(host.asset) {
let found = binary(host.platform, host.asset, from);
builds.insert(host.asset, found);
}
}
let pairs: Vec<_> = hosts.iter().zip(&probes).collect();
let lines = each(&pairs, |(name, probed)| {
let host = probed.as_ref().map_err(String::clone)?;
let (build, want) = builds[host.asset].as_ref().map_err(String::clone)?;
send(name, host, build, want)
});
let mut rows: Vec<Value> = Vec::new();
let mut failed = 0;
for (name, line) in hosts.iter().zip(lines.iter()) {
match line {
Ok(sent) => {
rows.push(json!({
"host": name,
"platform": sent.platform,
"state": sent.state,
"path": sent.dest,
"version": sent.version,
}));
}
Err(e) => {
failed += 1;
rows.push(json!({"host": name, "error": e}));
}
}
}
if !sink.passthrough() {
sink.record(json!({"hosts": rows}));
} else if !sink.show(Shown::Hosts(&rows)) {
for (name, line) in hosts.iter().zip(lines.iter()) {
match line {
Ok(sent) => sink.text(&format!(
"{} {} {} {} {}\n",
name, sent.platform, sent.state, sent.dest, sent.version
)),
Err(e) => sink.text(&format!("error {e}\n")),
}
}
}
if failed > 0 {
let total = hosts.len();
return Err(Stop::Failed(format!("{failed} of {total} hosts failed")));
}
Ok(())
}
pub(crate) struct Teleport(Args);
const fn field(
key: &'static str,
flag: &'static str,
value: &'static str,
about: &'static str,
kind: &'static str,
items: Option<&'static str>,
) -> Field {
Field {
key,
flag,
value,
about,
kind,
items,
role: Role::Flag,
takes: true,
tool: true,
min: None,
max: None,
example: None,
}
}
const TELEPORT_FIELDS: &[Field] = &[
field(
"from",
"--from",
"<dir>",
"Local directory with binaries.",
"string",
None,
),
field(
"root",
"--root",
"<dir>",
"Remote install directory.",
"string",
None,
),
field(
"host",
"--host",
"<host>",
"Remote host to run on.",
"string",
None,
),
field(
"hosts",
"--hosts",
"<host>",
"Hosts to copy build to.",
"array",
Some("string"),
),
field(
"command",
"--command",
"<arg>",
"Remote command arguments.",
"array",
Some("string"),
),
];
impl Task for Teleport {
const NAME: &'static str = "teleport";
const KIND: Option<&'static str> = None;
const ABOUT: &'static str = "Copy this build to other machines or run remotely.";
const EXAMPLE: Option<&'static str> = None;
const FIELDS: &'static [Field] = TELEPORT_FIELDS;
fn parse(args: &[String], _: &dyn Fn(&str) -> Option<bool>) -> Result<Self, Usage> {
parse(args).map(Teleport).map_err(|_| {
Usage("want [--from <dir>] [--root <dir>] <hosts...> or --host <h> <cmd...>".into())
})
}
fn from_json(value: &Value) -> Result<Self, Usage> {
let json = Json::new(value, Self::FIELDS)?;
let from: Option<PathBuf> = json.take("from")?;
let root: Option<String> = json.take("root")?;
let host: Option<String> = json.take("host")?;
let hosts: Vec<String> = json.take("hosts")?;
let command: Vec<String> = json.take("command")?;
let mode = match host {
Some(host) if !command.is_empty() && hosts.is_empty() => Mode::Run { host, command },
None if !hosts.is_empty() && command.is_empty() => Mode::Copy(hosts),
_ => {
return Err(Usage("give either hosts, or host with command".into()));
}
};
Ok(Teleport(Args {
from,
root: root.unwrap_or_else(|| ROOT.to_string()),
mode,
}))
}
fn push(&self, out: &mut Argv) {
let mut argv = Vec::new();
if let Some(from) = &self.0.from {
argv.extend(["--from".into(), from.display().to_string()]);
}
if self.0.root != ROOT {
argv.extend(["--root".into(), self.0.root.clone()]);
}
match &self.0.mode {
Mode::Copy(hosts) => argv.extend(hosts.iter().cloned()),
Mode::Run { host, command } => {
argv.extend(["--host".into(), host.clone(), "--".into()]);
argv.extend(command.iter().cloned());
}
}
out.extra(&argv);
}
fn usage(_: &str) -> String {
"teleport [--from <dir>] [--root <dir>] [--host <user@host | local>] <user@host | local | command>..."
.into()
}
}
impl Run<()> for Teleport {
fn run(self, _: (), sink: &mut dyn Sink) -> Result<(), Error> {
let args = self.0;
match args.mode {
Mode::Copy(hosts) => Ok(copy_hosts(&hosts, &args.root, args.from.as_deref(), sink)?),
Mode::Run { host, command } => Ok(run_host(
&host,
&args.root,
args.from.as_deref(),
&command,
sink,
)?),
}
}
}
crate::task::register!(Teleport, crate::task::OnMachine, "", false);
pub fn run(rest: &[String], sink: &mut dyn Sink) -> Result<(), Stop> {
let args = parse(rest)?;
match args.mode {
Mode::Copy(hosts) => copy_hosts(&hosts, &args.root, args.from.as_deref(), sink),
Mode::Run { host, command } => {
run_host(&host, &args.root, args.from.as_deref(), &command, sink)
}
}
}