summaryrefslogtreecommitdiff
path: root/support/texlab/crates/commands/src/build.rs
blob: 3d93601e39e130b744c47565956a2520c7238ae4 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::{
    io::{BufReader, Read},
    path::{Path, PathBuf},
    process::{ExitStatus, Stdio},
    thread::{self, JoinHandle},
};

use anyhow::Result;
use base_db::Workspace;
use bstr::io::BufReadExt;
use crossbeam_channel::Sender;
use thiserror::Error;
use url::Url;

use crate::placeholders::replace_placeholders;

#[derive(Debug, Error)]
pub enum BuildError {
    #[error("Document \"{0}\" was not found")]
    NotFound(Url),

    #[error("Document \"{0}\" does not exist on the local file system")]
    NotLocal(Url),

    #[error("Unable to run compiler: {0}")]
    Compile(#[from] std::io::Error),
}

#[derive(Debug)]
pub struct BuildCommand {
    program: String,
    args: Vec<String>,
    working_dir: PathBuf,
}

impl BuildCommand {
    pub fn new(workspace: &Workspace, uri: &Url) -> Result<Self, BuildError> {
        let Some(document) = workspace.lookup(uri) else {
            return Err(BuildError::NotFound(uri.clone()));
        };

        let document = workspace
            .parents(document)
            .into_iter()
            .next()
            .unwrap_or(document);

        let Some(path) = document.path.as_deref().and_then(Path::to_str) else {
            return Err(BuildError::NotLocal(document.uri.clone()));
        };

        let config = &workspace.config().build;
        let program = config.program.clone();
        let args = replace_placeholders(&config.args, &[('f', path)]);

        let Ok(working_dir) = workspace.current_dir(&document.dir).to_file_path() else {
            return Err(BuildError::NotLocal(document.uri.clone()));
        };

        Ok(Self {
            program,
            args,
            working_dir,
        })
    }

    pub fn run(self, sender: Sender<String>) -> Result<ExitStatus, BuildError> {
        log::debug!(
            "Spawning compiler {} {:#?} in directory {}",
            self.program,
            self.args,
            self.working_dir.display()
        );

        let mut process = std::process::Command::new(&self.program)
            .args(self.args)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .current_dir(&self.working_dir)
            .spawn()?;

        track_output(process.stderr.take().unwrap(), sender.clone());
        track_output(process.stdout.take().unwrap(), sender);

        let status = process.wait();
        Ok(status?)
    }
}

fn track_output(
    output: impl Read + Send + 'static,
    sender: Sender<String>,
) -> JoinHandle<std::io::Result<()>> {
    let mut reader = BufReader::new(output);
    thread::spawn(move || {
        reader.for_byte_line(|line| {
            let text = String::from_utf8_lossy(line).into_owned();
            let _ = sender.send(text);
            Ok(true)
        })
    })
}