summaryrefslogtreecommitdiffstats
path: root/src/package/script.rs
blob: a0f1527433528a76867e9d97ddab2698afcea32c (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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use std::process::ExitStatus;

use anyhow::anyhow;
use anyhow::Context as AnyhowContext;
use anyhow::Error;
use anyhow::Result;
use handlebars::{
    Context, Handlebars, Helper, HelperDef, HelperResult, JsonRender, Output, PathAndJson,
    RenderContext, RenderError,
};
use log::trace;
use serde::Deserialize;
use serde::Serialize;
use syntect::easy::HighlightLines;
use syntect::highlighting::{Style, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};
use tokio::process::Command;

use crate::package::Package;
use crate::package::Phase;
use crate::package::PhaseName;

#[derive(parse_display::Display, Serialize, Deserialize, Clone, Debug)]
#[serde(transparent)]
#[display("{0}")]
pub struct Script(String);

impl From<String> for Script {
    fn from(s: String) -> Script {
        Script(s)
    }
}

#[derive(Clone, Debug)]
pub struct Shebang(String);

impl Script {
    pub fn highlighted<'a>(&'a self, script_theme: &'a str) -> HighlightedScript<'a> {
        HighlightedScript::new(self, script_theme)
    }

    pub fn lines_numbered(&self) -> impl Iterator<Item = (usize, &str)> {
        self.0.lines().enumerate().map(|(n, l)| (n + 1, l))
    }

    pub async fn lint(&self, mut cmd: Command) -> Result<(ExitStatus, String, String)> {
        use tokio::io::AsyncWriteExt;
        use tokio::io::BufWriter;

        let mut child = cmd
            .stderr(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stdin(std::process::Stdio::piped())
            .spawn()
            .context("Spawning subprocess for linting package script")?;

        trace!("Child = {:?}", child);

        {
            let stdin = child.stdin.take().ok_or_else(|| anyhow!("No stdin"))?;
            let mut writer = BufWriter::new(stdin);
            let _ = writer
                .write_all(self.0.as_bytes())
                .await
                .context("Writing package script to STDIN of subprocess")?;

            let _ = writer
                .flush()
                .await
                .context("Flushing STDIN of subprocess")?;
            trace!("Script written");
        }

        trace!("Waiting for child...");
        let out = child
            .wait_with_output()
            .await
            .context("Waiting for subprocess")?;

        Ok((
            out.status,
            String::from_utf8(out.stdout)?,
            String::from_utf8(out.stderr)?,
        ))
    }
}

#[derive(Debug)]
pub struct HighlightedScript<'a> {
    script: &'a Script,
    script_theme: &'a str,

    ps: SyntaxSet,
    ts: ThemeSet,
}

impl<'a> HighlightedScript<'a> {
    fn new(script: &'a Script, script_theme: &'a str) -> Self {
        HighlightedScript {
            script,
            script_theme,

            ps: SyntaxSet::load_defaults_newlines(),
            ts: ThemeSet::load_defaults(),
        }
    }

    pub fn lines(&'a self) -> Result<impl Iterator<Item = String> + 'a> {
        let syntax = self
            .ps
            .find_syntax_by_first_line(&self.script.0)
            .ok_or_else(|| anyhow!("Failed to load syntax for highlighting script"))?;

        let theme = self
            .ts
            .themes
            .get(self.script_theme)
            .ok_or_else(|| anyhow!("Theme not available: {}", self.script_theme))?;

        let mut h = HighlightLines::new(syntax, &theme);

        Ok({
            LinesWithEndings::from(&self.script.0).map(move |line| {
                let ranges: Vec<(Style, &str)> = h.highlight(line, &self.ps);
                as_24_bit_terminal_escaped(&ranges[..], true)
            })
        })
    }

    pub fn lines_numbered(&'a self) -> Result<impl Iterator<Item = (usize, String)> + 'a> {
        self.lines().map(|iter| iter.enumerate().map(|(n, l)| (n + 1, l)))
    }
}

impl From<String> for Shebang {
    fn from(s: String) -> Self {
        Shebang(s)
    }
}

impl AsRef<str> for Script {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

pub struct ScriptBuilder<'a> {
    shebang: &'a Shebang,
}

impl<'a> ScriptBuilder<'a> {
    pub fn new(shebang: &'a Shebang) -> Self {
        ScriptBuilder { shebang }
    }

    pub fn build(
        self,
        package: &Package,
        phaseorder: &[PhaseName],
        strict_mode: bool,
    ) -> Result<Script> {
        let mut script = format!("{shebang}\n", shebang = self.shebang.0);

        for name in phaseorder {
            match package.phases().get(name) {
                Some(Phase::Text(text)) => {
                    use unindent::Unindent;

                    script.push_str(&indoc::formatdoc!(
                        r#"
                        ### phase {}
                        {}
                        ### / {} phase
                    "#,
                        name.as_str(),
                        // whack hack: insert empty line on top because unindent ignores the
                        // indentation of the first line, see commit message for more info
                        format!("\n{}", text).unindent(),
                        name.as_str(),
                    ));

                    script.push('\n');
                }

                // TODO: Support path embedding
                // (requires possibility to have stuff in Script type that gets copied to
                // container)
                Some(Phase::Path(pb)) => {
                    script.push_str(&format!(
                        r#"
                        # Phase (from file {path}): {name}
                        # NOT SUPPORTED YET
                        exit 1
                    "#,
                        path = pb.display(),
                        name = name.as_str()
                    ));
                    script.push('\n');
                }

                None => {
                    script.push_str(&format!(
                        "# No script for phase: {name}",
                        name = name.as_str()
                    ));
                    script.push('\n');
                }
            }
        }

        Self::interpolate_package(script, package, strict_mode).map(Script)
    }

    fn interpolate_package(script: String, package: &Package, strict_mode: bool) -> Result<String> {
        let mut hb = Handlebars::new();
        hb.register_escape_fn(handlebars::no_escape);
        hb.register_template_string("script", script)?;
        hb.register_helper("phase", Box::new(PhaseHelper));
        hb.register_helper("state", Box::new(StateHelper));
        hb.register_helper("progress", Box::new(ProgressHelper));
        hb.register_helper("join", Box::new(JoinHelper));
        hb.register_helper("joinwith", Box::new(JoinWithHelper));
        hb.set_strict_mode(strict_mode);

        #[cfg(debug_assertions)]
        {
            trace!("Rendering Package: {:?}", package.debug_details());
        }

        hb.render("script", package)
            .with_context(|| anyhow!("Rendering script for package {} {} failed", package.name(), package.version()))
            .map_err(Error::from)
    }
}

#[derive(Clone, Copy)]