use std::path::{Path, PathBuf};
use tokio::process::Command;
use crate::{CrocChild, Result};
pub struct CrocReceive {
inner: Command,
overwrite: bool,
out: Option<PathBuf>,
}
impl CrocReceive {
pub(crate) fn new(inner: Command) -> Self {
Self {
inner,
overwrite: false,
out: None,
}
}
pub fn overwrite(mut self, value: bool) -> Self {
self.overwrite = value;
self
}
pub fn out<P: AsRef<Path>>(mut self, path: P) -> Self {
let path = path.as_ref();
if path.is_dir() {
self.out = Some(path.to_owned());
} else {
self.out = path.parent().map(ToOwned::to_owned);
}
self
}
pub fn spawn<C: AsRef<str>>(mut self, code: C) -> Result<CrocChild> {
self.parse_options();
self.set_receive_code(code.as_ref());
self.inner.spawn().map(CrocChild::new).map_err(Into::into)
}
fn parse_options(&mut self) {
if self.overwrite {
self.inner.arg("--overwrite");
}
if let Some(ref path) = self.out {
self.inner.arg(format!("--out={}", path.display()));
}
}
fn set_receive_code(&mut self, code: &str) {
#[cfg(target_os = "windows")]
self.inner.arg(code.trim());
#[cfg(not(target_os = "windows"))]
self.inner.env("CROC_SECRET", code.trim());
}
}
impl std::fmt::Debug for CrocReceive {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}