summaryrefslogtreecommitdiff
path: root/support/texlab/crates/commands/src/clean.rs
blob: d4ec6b24f4cde05e0eaf82ba9ffc96a41fb61ea9 (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
use std::process::Stdio;

use anyhow::Result;
use base_db::{deps::ProjectRoot, Document, Workspace};

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
pub enum CleanTarget {
    Auxiliary,
    Artifacts,
}

#[derive(Debug)]
pub struct CleanCommand {
    executable: String,
    args: Vec<String>,
}

impl CleanCommand {
    pub fn new(workspace: &Workspace, document: &Document, target: CleanTarget) -> Result<Self> {
        let Some(path) = document.path.as_deref() else {
            anyhow::bail!("document '{}' is not a local file", document.uri)
        };

        let root = ProjectRoot::walk_and_find(workspace, &document.dir);

        let flag = match target {
            CleanTarget::Auxiliary => "-c",
            CleanTarget::Artifacts => "-C",
        };

        let out_dir = match target {
            CleanTarget::Auxiliary => root.aux_dir,
            CleanTarget::Artifacts => root.pdf_dir,
        };

        let out_dir_path = out_dir.to_file_path().unwrap();

        let executable = String::from("latexmk");
        let args = vec![
            format!("-outdir={}", out_dir_path.display()),
            String::from(flag),
            path.display().to_string(),
        ];

        Ok(Self { executable, args })
    }

    pub fn run(self) -> Result<()> {
        log::debug!("Cleaning output files: {} {:?}", self.executable, self.args);
        let result = std::process::Command::new(self.executable)
            .args(self.args)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();

        if let Err(why) = result {
            anyhow::bail!("failed to spawn process: {why}")
        }

        Ok(())
    }
}