summaryrefslogtreecommitdiff
path: root/support/texlab/crates/tex/src/compile.rs
blob: eeb7db9e4ed401e14210c371f9bb1e50b097cf49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use futures::future::TryFutureExt;
use std::io;
use std::process::Stdio;
use std::time::Duration;
use tempfile::{tempdir, TempDir};
use tokio::fs;
use tokio::future::FutureExt;
use tokio_net::process::Command;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Format {
    Latex,
    Pdflatex,
    Xelatex,
    Lualatex,
}

impl Format {
    pub fn executable(self) -> &'static str {
        match self {
            Self::Latex => "latex",
            Self::Pdflatex => "pdflatex",
            Self::Xelatex => "xelatex",
            Self::Lualatex => "lualatex",
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum OutputKind {
    Dvi,
    Pdf,
}

#[derive(Debug)]
pub struct CompileResult {
    pub log: String,
    pub directory: TempDir,
}

#[derive(Debug)]
pub enum CompileError {
    IO(io::Error),
    NotInstalled,
    Timeout,
}

impl From<io::Error> for CompileError {
    fn from(error: io::Error) -> Self {
        Self::IO(error)
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct CompileParams<'a> {
    pub file_name: &'a str,
    pub code: &'a str,
    pub format: Format,
    pub timeout: Duration,
}

pub async fn compile<'a>(
    executable: &'a str,
    args: &'a [&'a str],
    params: CompileParams<'a>,
) -> Result<CompileResult, CompileError> {
    let directory = tempdir()?;
    let code_file = directory.path().join(params.file_name);
    fs::write(code_file.clone(), params.code).await?;

    Command::new(executable)
        .args(args)
        .current_dir(&directory)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map_err(|_| CompileError::NotInstalled)
        .timeout(params.timeout)
        .map_err(|_| CompileError::Timeout)
        .await?
        .map_err(|_| CompileError::NotInstalled)?;

    let log_file = code_file.with_extension("log");
    let log_bytes = fs::read(log_file).await?;
    let log = String::from_utf8_lossy(&log_bytes).into_owned();
    Ok(CompileResult { log, directory })
}