summaryrefslogtreecommitdiff
path: root/support/texlab/crates/commands/src/build.rs
blob: 34d39f26e48e40837ea76ca26b663859e790f47c (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::{
    io::{BufReader, Read},
    path::{Path, PathBuf},
    process::{Child, Stdio},
    thread::{self, JoinHandle},
};

use anyhow::Result;
use base_db::{
    deps::{self, ProjectRoot},
    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 = deps::parents(workspace, 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 root = ProjectRoot::walk_and_find(workspace, &document.dir);

        let Ok(working_dir) = root.compile_dir.to_file_path() else {
            return Err(BuildError::NotLocal(document.uri.clone()));
        };

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

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

        let mut process = self.spawn_internal()?;
        track_output(process.stderr.take().unwrap(), sender.clone());
        track_output(process.stdout.take().unwrap(), sender);
        Ok(process)
    }

    #[cfg(windows)]
    fn spawn_internal(&self) -> Result<Child, BuildError> {
        std::process::Command::new(&self.program)
            .args(self.args.clone())
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .current_dir(&self.working_dir)
            .spawn()
            .map_err(Into::into)
    }

    #[cfg(unix)]
    fn spawn_internal(&self) -> Result<Child, BuildError> {
        use std::os::unix::process::CommandExt;
        std::process::Command::new(&self.program)
            .args(self.args.clone())
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .current_dir(&self.working_dir)
            .process_group(0)
            .spawn()
            .map_err(Into::into)
    }

    #[cfg(windows)]
    pub fn cancel(pid: u32) -> std::io::Result<bool> {
        Ok(std::process::Command::new("taskkill")
            .arg("/PID")
            .arg(pid.to_string())
            .arg("/F")
            .arg("/T")
            .status()?
            .success())
    }

    #[cfg(not(windows))]
    pub fn cancel(pid: u32) -> Result<bool> {
        unsafe {
            libc::killpg(pid as libc::pid_t, libc::SIGTERM);
        }

        Ok(true)
    }
}

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)
        })
    })
}