use std::{num::NonZeroU32, path::Path, process::Command};
use base64::Engine as _;
use rho_protocol::{
methods::{HostPath, HostStreamEnd, HostStreamId, HostStreamReadParams},
Caller, ClientInfo, ConnectionId,
};
use super::{machine::Machine, machine_fs::canonical};
pub(super) fn caller() -> Caller {
Caller::new(
ConnectionId::new(1),
ClientInfo {
name: "test".to_owned(),
version: "0".to_owned(),
},
)
}
pub(super) fn machine() -> Machine {
Machine::without_login(Path::new("/nonexistent/.rho"))
}
pub(super) fn machine_in(variables: &[(&str, &str)]) -> Machine {
let environment = variables
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
.collect();
Machine::with_environment(Path::new("/nonexistent/.rho"), environment)
}
pub(super) fn host(path: &Path) -> HostPath {
HostPath::new(path.to_str().unwrap())
}
pub(super) fn real(path: &Path) -> HostPath {
host(&canonical(path).unwrap())
}
pub(super) fn git(dir: &Path, args: &[&str]) -> String {
let output = git_command(dir, args).output().unwrap();
assert!(
output.status.success(),
"git {args:?} failed in {}: {}",
dir.display(),
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout).unwrap().trim().to_owned()
}
pub(super) fn git_command(dir: &Path, args: &[&str]) -> Command {
let mut command = Command::new("git");
for name in crate::git::LOCATION_ENV {
command.env_remove(name);
}
command
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_NOSYSTEM", "1")
.args([
"-c",
"user.name=rho",
"-c",
"user.email=rho@example.com",
"-c",
"commit.gpgsign=false",
])
.args(args)
.current_dir(dir);
command
}
pub(super) fn repository(dir: &Path, files: &[(&str, &str)]) {
std::fs::create_dir_all(dir).unwrap();
git(dir, &["init", "-q"]);
git(dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
for (path, contents) in files {
let path = dir.join(path);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, contents).unwrap();
}
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "-m", "files"]);
}
pub(super) async fn read_out(caller: &Caller, stream: HostStreamId) -> (Vec<u8>, HostStreamEnd) {
let mut bytes = Vec::new();
loop {
let read = caller
.read_stream(HostStreamReadParams::new(
stream.clone(),
bytes.len() as u64,
NonZeroU32::new(1 << 20).unwrap(),
))
.await
.unwrap();
bytes.extend(
base64::engine::general_purpose::STANDARD
.decode(read.data)
.unwrap(),
);
if let Some(end) = read.end {
return (bytes, end);
}
}
}