hippo_shared/
preprocessor.rs

1//
2// Hippo
3// (C) 2021 Brave Monday
4//
5
6use std::env;
7use std::io::Result;
8use std::path::PathBuf;
9use std::process::{Command, Output};
10
11use serde::Deserialize;
12
13use super::OutputFormat;
14
15/// An agent responsible for preprocessor orchestration.
16#[derive(Deserialize)]
17pub struct Preprocessor {
18	/// The command associated with the preprocessor.
19	pub command: String,
20
21	/// The collection of program options that will influence the command behavior.
22	#[serde(default)]
23	pub flags: Vec<String>,
24
25	/// The path to the prepended to any input argument.
26	pub prefix: Option<String>,
27
28	/// The output format of the preprocessor. Defaults to bytes.
29	#[serde(default)]
30	pub format: OutputFormat
31}
32
33impl Preprocessor {
34	/// Construct a preprocessor.
35	pub fn new(command: &str) -> Self {
36		Preprocessor {
37			command: command.to_owned(),
38			flags:   vec![],
39
40			prefix: None,
41
42			format: OutputFormat::Bytes
43		}
44	}
45
46	/// Rewrite input arguments into absolute paths.
47	pub fn rewrite_arguments(&self, args: &Vec<String>) -> Vec<String> {
48		args.iter().map(|p| {
49			let mut buf = PathBuf::new();
50
51			if let Some(root) = env::var("CARGO_MANIFEST_DIR").ok() {
52				buf.push(root);
53			}
54
55			if let Some(prefix) = &self.prefix {
56				buf.push(prefix);
57			}
58
59			buf.push(p);
60
61			buf.to_string_lossy().to_string()
62		})
63		.collect::<Vec<String>>()
64	}
65
66	/// Execute the preprocessor with input arguments.
67	pub fn execute(&self, args: &Vec<String>) -> Result<Output> {
68		Command::new(&self.command)
69			.args(&self.flags)
70			.args(args)
71			.output()
72	}
73}