Add rust code to invoke the shim

This commit is contained in:
Tom Alexander 2020-04-04 19:40:53 -04:00
parent 26a752baea
commit d3b58c9a0e
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
2 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,7 @@
//! This module contains a rust implementation of LinkedIn Dust
mod node_invoker;
pub use node_invoker::run_node_dust;
pub use node_invoker::NodeError;
pub use node_invoker::Result;

View File

@ -0,0 +1,61 @@
use std::error;
use std::fmt;
use std::io::Write;
use std::process::Output;
use std::process::{Command, Stdio};
pub type Result<T> = std::result::Result<T, NodeError>;
#[derive(Clone)]
pub struct NodeError {
output: Output,
}
impl fmt::Display for NodeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Error from node: {}",
String::from_utf8_lossy(&self.output.stderr)
)
}
}
impl fmt::Debug for NodeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Error from node: {}",
String::from_utf8_lossy(&self.output.stderr)
)
}
}
impl error::Error for NodeError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
None
}
}
/// Invokes Node to run the authentic LinkedIn Dust
pub fn run_node_dust(template_path: &str, context: &str) -> Result<String> {
let mut proc = Command::new("node")
.arg("./src/js/dustjs_shim.js")
.arg(template_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("failed to execute process");
proc.stdin
.take()
.unwrap()
.write_all(context.as_bytes())
.expect("Failed to write to stdin of node process");
let output = proc.wait_with_output().expect("Failed to wait on node");
if output.status.success() {
Ok(String::from_utf8(output.stdout).expect("Invalid UTF-8 from node process"))
} else {
Err(NodeError { output: output })
}
}