summaryrefslogtreecommitdiff
path: root/support/texlab/src/features/build.rs
blob: c6a670528f49885659cd91551c6fed99b58556ba (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
use std::{
    io::{self, BufRead, BufReader, Read},
    path::Path,
    process::{Command, Stdio},
    thread,
};

use cancellation::CancellationToken;
use crossbeam_channel::Sender;
use encoding_rs_io::DecodeReaderBytesBuilder;
use lsp_types::TextDocumentIdentifier;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

use crate::Options;

use super::FeatureRequest;

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildParams {
    pub text_document: TextDocumentIdentifier,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize_repr, Deserialize_repr)]
#[repr(i32)]
pub enum BuildStatus {
    Success = 0,
    Error = 1,
    Failure = 2,
    Cancelled = 3,
}

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BuildResult {
    pub status: BuildStatus,
}

pub fn build_document(
    request: FeatureRequest<BuildParams>,
    _cancellation_token: &CancellationToken,
    log_sender: Sender<String>,
) -> BuildResult {
    let document = request
        .subset
        .documents
        .iter()
        .find(|document| {
            if let Some(data) = document.data.as_latex() {
                data.extras.has_document_environment
            } else {
                false
            }
        })
        .map(|document| document.as_ref())
        .unwrap_or_else(|| request.main_document());

    if document.uri.scheme() != "file" {
        return BuildResult {
            status: BuildStatus::Failure,
        };
    }
    log::info!("Building document {}", document.uri.as_str());

    let options = { request.context.options.read().unwrap().clone() };

    let status = match build_internal(&document.uri.to_file_path().unwrap(), &options, log_sender) {
        Ok(true) => BuildStatus::Success,
        Ok(false) => BuildStatus::Error,
        Err(why) => {
            log::error!("Failed to execute textDocument/build: {}", why);
            BuildStatus::Failure
        }
    };
    BuildResult { status }
}

fn build_internal(path: &Path, options: &Options, log_sender: Sender<String>) -> io::Result<bool> {
    let build_dir = options
        .root_directory
        .as_ref()
        .map(AsRef::as_ref)
        .or_else(|| path.parent())
        .unwrap();

    let args: Vec<_> = options
        .build
        .args()
        .into_iter()
        .map(|arg| replace_placeholder(arg, path))
        .collect();

    let mut process = Command::new(options.build.executable())
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .current_dir(build_dir)
        .spawn()?;

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

    if !options.build.is_continuous {
        process.wait().map(|status| status.success())
    } else {
        Ok(true)
    }
}

fn replace_placeholder(arg: String, file: &Path) -> String {
    if arg.starts_with('"') || arg.ends_with('"') {
        arg
    } else {
        arg.replace("%f", &file.to_string_lossy())
    }
}

fn track_output(output: impl Read + Send + 'static, sender: Sender<String>) {
    let reader = BufReader::new(
        DecodeReaderBytesBuilder::new()
            .encoding(Some(encoding_rs::UTF_8))
            .utf8_passthru(true)
            .strip_bom(true)
            .build(output),
    );
    thread::spawn(move || {
        for line in reader.lines() {
            sender.send(line.unwrap()).unwrap();
        }
    });
}