warpgate_api/
host_funcs.rsuse crate::virtual_path::VirtualPath;
use crate::{api_struct, api_unit_enum, AnyResult};
use rustc_hash::FxHashMap;
use serde::de::DeserializeOwned;
api_unit_enum!(
pub enum HostLogTarget {
Stderr,
Stdout,
#[default]
Tracing,
}
);
api_struct!(
pub struct HostLogInput {
#[serde(default)]
pub data: FxHashMap<String, serde_json::Value>,
pub message: String,
#[serde(default)]
pub target: HostLogTarget,
}
);
impl HostLogInput {
pub fn new(message: impl AsRef<str>) -> Self {
Self {
message: message.as_ref().to_owned(),
..Default::default()
}
}
}
impl From<&str> for HostLogInput {
fn from(message: &str) -> Self {
HostLogInput::new(message)
}
}
impl From<String> for HostLogInput {
fn from(message: String) -> Self {
HostLogInput::new(message)
}
}
api_struct!(
pub struct ExecCommandInput {
pub command: String,
pub args: Vec<String>,
#[serde(default)]
pub env: FxHashMap<String, String>,
#[doc(hidden)]
pub set_executable: bool,
#[serde(default)]
pub stream: bool,
#[serde(default)]
pub working_dir: Option<VirtualPath>,
}
);
impl ExecCommandInput {
pub fn pipe<C, I, V>(command: C, args: I) -> ExecCommandInput
where
C: AsRef<str>,
I: IntoIterator<Item = V>,
V: AsRef<str>,
{
ExecCommandInput {
command: command.as_ref().to_string(),
args: args.into_iter().map(|a| a.as_ref().to_owned()).collect(),
..ExecCommandInput::default()
}
}
pub fn inherit<C, I, V>(command: C, args: I) -> ExecCommandInput
where
C: AsRef<str>,
I: IntoIterator<Item = V>,
V: AsRef<str>,
{
let mut input = Self::pipe(command, args);
input.stream = true;
input
}
}
api_struct!(
#[serde(default)]
pub struct ExecCommandOutput {
pub command: String,
pub exit_code: i32,
pub stderr: String,
pub stdout: String,
}
);
impl ExecCommandOutput {
pub fn get_output(&self) -> String {
let mut out = String::new();
out.push_str(self.stdout.trim());
if !self.stderr.is_empty() {
if !out.is_empty() {
out.push(' ');
}
out.push_str(self.stderr.trim());
}
out
}
}
api_struct!(
pub struct SendRequestInput {
pub url: String,
}
);
impl SendRequestInput {
pub fn new(url: impl AsRef<str>) -> Self {
Self {
url: url.as_ref().to_owned(),
}
}
}
impl From<&str> for SendRequestInput {
fn from(url: &str) -> Self {
SendRequestInput::new(url)
}
}
impl From<String> for SendRequestInput {
fn from(url: String) -> Self {
SendRequestInput::new(url)
}
}
api_struct!(
pub struct SendRequestOutput {
pub body: Vec<u8>,
pub body_length: u64,
pub body_offset: u64,
pub status: u16,
}
);
impl SendRequestOutput {
pub fn json<T: DeserializeOwned>(self) -> AnyResult<T> {
Ok(serde_json::from_slice(&self.body)?)
}
pub fn text(self) -> AnyResult<String> {
Ok(String::from_utf8(self.body)?)
}
}