use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command as Process, ExitStatus, Output as ProcessOutput, Stdio};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use crate::args::{split_stdout, stderr_error};
use crate::binary::find_binary;
use crate::error::{Error, Failure, Result};
use crate::report::Report;
#[derive(Debug, Clone, Default)]
pub struct Postext {
binary: Option<PathBuf>,
found: OnceLock<PathBuf>,
cwd: Option<PathBuf>,
env: Vec<(OsString, OsString)>,
timeout: Option<Duration>,
pub(crate) offline: bool,
pub(crate) font_dirs: Vec<OsString>,
}
impl Postext {
pub fn new() -> Self {
Self::default()
}
pub fn with_binary(path: impl AsRef<Path>) -> Self {
Postext { binary: Some(path.as_ref().to_owned()), ..Self::default() }
}
pub fn cwd(mut self, dir: impl AsRef<Path>) -> Self {
self.cwd = Some(dir.as_ref().to_owned());
self
}
pub fn env(mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self {
self.env.push((key.as_ref().to_owned(), value.as_ref().to_owned()));
self
}
pub fn timeout(mut self, limit: Duration) -> Self {
self.timeout = Some(limit);
self
}
pub fn offline(mut self, offline: bool) -> Self {
self.offline = offline;
self
}
pub fn font_dir(mut self, dir: impl AsRef<OsStr>) -> Self {
self.font_dirs.push(dir.as_ref().to_owned());
self
}
pub fn executable(&self) -> Result<PathBuf> {
if let Some(path) = &self.binary {
return Ok(path.clone());
}
if let Some(path) = self.found.get() {
return Ok(path.clone());
}
let path = find_binary()?;
Ok(self.found.get_or_init(|| path).clone())
}
pub fn version(&self) -> Result<String> {
let out = self.run(["--version"])?;
Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
fn process<I, S>(&self, args: I) -> Result<Process>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut cmd = Process::new(self.executable()?);
cmd.args(args).stdin(Stdio::null());
if let Some(dir) = &self.cwd {
cmd.current_dir(dir);
}
for (k, v) in &self.env {
cmd.env(k, v);
}
Ok(cmd)
}
pub fn run<I, S>(&self, args: I) -> Result<ProcessOutput>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut cmd = self.process(args)?;
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let Some(limit) = self.timeout else {
return Ok(cmd.output()?);
};
let mut child = cmd.spawn()?;
let read = |pipe: Option<Box<dyn Read + Send>>| {
std::thread::spawn(move || {
let mut buf = Vec::new();
if let Some(mut p) = pipe { p.read_to_end(&mut buf).map(|_| buf) } else { Ok(buf) }
})
};
let stdout = read(child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>));
let stderr = read(child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>));
let deadline = Instant::now() + limit;
let status = loop {
if let Some(status) = child.try_wait()? {
break status;
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return Err(Error::Timeout(limit));
}
std::thread::sleep(Duration::from_millis(20));
};
let join = |h: std::thread::JoinHandle<std::io::Result<Vec<u8>>>| h.join().unwrap_or_else(|_| Ok(Vec::new()));
Ok(ProcessOutput { status, stdout: join(stdout)?, stderr: join(stderr)? })
}
pub fn run_inherit<I, S>(&self, args: I) -> Result<ExitStatus>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
Ok(self.process(args)?.stdout(Stdio::inherit()).stderr(Stdio::inherit()).status()?)
}
pub(crate) fn execute(
&self,
command: &str,
args: Vec<OsString>,
content: bool,
allow_problems: bool,
) -> Result<Report> {
let mut all: Vec<OsString> = Vec::with_capacity(args.len() + 3);
all.push(command.into());
all.extend(args);
all.push("--json".into());
all.push("--no-color".into());
let out = self.run(&all)?;
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
let (data, payload) = split_stdout(&out.stdout, content);
let report = data.map(|d| Report::from_json(d, payload, stderr.clone()));
let code = out.status.code().unwrap_or(-1);
if code == 0 {
return report.ok_or_else(|| {
Error::Failed(Failure {
message: format!("postext {command} printed no report"),
exit_code: 0,
report: None,
stderr,
})
});
}
let message = report.as_ref().and_then(|r| r.error.clone()).unwrap_or_else(|| stderr_error(&stderr));
let failure = |message: String, report: Option<Report>| Failure {
message,
exit_code: code,
report: report.map(Box::new),
stderr: stderr.clone(),
};
match (code, report) {
(2, report) => Err(Error::Usage(failure(message, report))),
(3, Some(report)) => {
if allow_problems {
return Ok(report);
}
let found: Vec<String> = report.warnings.iter().take(3).map(ToString::to_string).collect();
let found = if found.is_empty() { message } else { found.join(", ") };
Err(Error::ProblemsFound(failure(format!("postext {command}: {found}"), Some(report))))
}
(_, report) => Err(Error::Failed(failure(message, report))),
}
}
}