pistonite-cu 0.9.1

Battery-included common utils to speed up development of rust tools
Documentation
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use std::process::Stdio;
use std::sync::{Arc, LazyLock};

use regex::Regex;
use tokio::io::AsyncBufReadExt as _;
use tokio::process::{Child as TokioChild, ChildStderr, ChildStdout, Command as TokioCommand};

use crate::BoxedFuture;
use crate::cli::{ProgressBar, ProgressBarBuilder};
use crate::lv::Lv;
use crate::process::{Command, Preset, pio};

/// Display progress of cargo task with a progress bar, and emitting
/// status messages and diagnostic messages using this crate's printing utilities.
///
/// `json` feature is required to enable parsing cargo's output messages.
///
/// ```rust,no_run
/// # use pistonite_cu as cu;
/// use cu::pre::*;
///
/// # fn main() -> cu::Result<()> {
/// cu::which("cargo")?.command()
///     .args(["build", "--release"])
///     .preset(cu::pio::cargo("building my crate"))
///     .spawn()?.0
///     .wait_nz()?;
/// # Ok(()) }
/// ```
///
/// # Behavior
/// - Added args: `--message-format json-diagnostic-rendered-ansi`
/// - All IO will be configured. You should avoid configuring IO by yourself
///   before or after applying this preset. This may become enforced in the future
///   through generics.
///
/// The progress is displayed on the progress bar, showing the current
/// crates being built in one line (similar to the build progress bar shown
/// by cargo).
///
/// You can customize the spawned progress bar with
///
/// # Message levels
/// Errors, warnings and status messages (like `Compiling foobar v0.1.0`)
/// can be configured with the [`error`](Cargo::error), [`warning`](Cargo::warning),
/// or [`other`](Cargo::other) functions that take a message level.
///
/// ```rust,no_run
/// # use pistonite_cu as cu;
/// use cu::pre::*;
///
/// cu::pio::cargo("cargo build")
///     // configure message levels; levels shown here are the default
///     .error(cu::lv::E)
///     .warning(cu::lv::W)
///     .other(cu::lv::D);
/// ```
///
/// # Diagnostic hooks
/// To process diagnostic messages from cargo, you can provide a diagnostic hook,
/// which is a function `(is_warning: bool, message: &str) -> ()`.
/// If a diagnostic hook is provided, then the hook is responsible for displaying
/// the message. The `error` and `warning` levels will have no effect.
///
/// ```rust,no_run
/// # use pistonite_cu as cu;
/// use cu::pre::*;
///
/// cu::pio::cargo("cargo build")
///     // configure message levels; levels shown here are the default
///     .on_diagnostic(|is_warning, message| {
///         // this implementation will be identical to the default behavior
///         if is_warning {
///             cu::warn!("{message}")
///         } else {
///             cu::error!("{message}")
///         }
///     });
/// ```
///
/// # Output
/// The handle to the progress bar is emitted to the stdout slot.
/// Be sure to manually call `.done()` on it. See [Progress Bars](fn@crate::progress)
/// for more details
///
#[inline(always)]
pub fn cargo(progress_message: impl Into<String>) -> Cargo {
    Cargo {
        error_lv: Lv::Error,
        warning_lv: Lv::Warn,
        other_lv: Lv::Debug,
        diagnostic_hook: None,
        progress_builder: crate::progress(progress_message),
    }
}
pub struct Cargo {
    error_lv: Lv,
    warning_lv: Lv,
    other_lv: Lv,
    diagnostic_hook: Option<DianogsticHook>,
    progress_builder: ProgressBarBuilder,
}

impl Cargo {
    /// Set the level for printing error messages from cargo
    pub fn error(mut self, lv: Lv) -> Self {
        self.error_lv = lv;
        self
    }
    /// Set the level for printing warning messages from cargo
    pub fn warning(mut self, lv: Lv) -> Self {
        self.warning_lv = lv;
        self
    }
    /// Set the level for printing other messages from cargo
    pub fn other(mut self, lv: Lv) -> Self {
        self.other_lv = lv;
        self
    }
    /// Set a diagnostic hook, used to inspect compiler diagnostics from cargo
    ///
    /// The parameters are `(is_warning, message)`. The message is ansi-rendered.
    ///
    /// The hook should take care of printing the message
    pub fn on_diagnostic<F: Fn(bool, &str) + Send + 'static>(mut self, f: F) -> Self {
        self.diagnostic_hook = Some(Box::new(f));
        self
    }

    /// Configure the progress bar that will be spawned
    #[inline(always)]
    pub fn configure_spinner<F: FnOnce(ProgressBarBuilder) -> ProgressBarBuilder>(
        mut self,
        f: F,
    ) -> Self {
        self.progress_builder = f(self.progress_builder);
        self
    }
}

impl Preset for Cargo {
    type Output = Command<Cargo, CargoStubStdErr, pio::Null>;

    fn configure<O, E, I>(self, command: crate::Command<O, E, I>) -> Self::Output {
        command
            .args(["--message-format=json-diagnostic-rendered-ansi"])
            .stderr(CargoStubStdErr)
            .stdout(self)
            .stdin_null()
    }
}

pub struct CargoTask {
    error_lv: Lv,
    warning_lv: Lv,
    other_lv: Lv,
    bar: Arc<ProgressBar>,
    out: ChildStdout,
    err: ChildStderr,
    diagnostic_hook: Option<DianogsticHook>,
}

impl pio::ChildOutConfig for Cargo {
    type Task = CargoTask;
    type __Null = super::__OCNonNull;
    fn configure_stdout(&mut self, command: &mut TokioCommand) {
        command.stdout(Stdio::piped());
    }
    fn configure_stderr(&mut self, _: &mut TokioCommand) {}
    fn take(self, child: &mut TokioChild, _: Option<&str>, _: bool) -> crate::Result<Self::Task> {
        let stdout = super::take_child_stdout(child)?;
        let stderr = super::take_child_stderr(child)?;
        let bar = self.progress_builder.spawn();
        Ok(CargoTask {
            error_lv: self.error_lv,
            warning_lv: self.warning_lv,
            other_lv: self.other_lv,
            bar,
            out: stdout,
            err: stderr,
            diagnostic_hook: self.diagnostic_hook,
        })
    }
}
pub struct CargoStubStdErr;
impl pio::ChildOutConfig for CargoStubStdErr {
    type Task = ();
    type __Null = super::__OCNull;
    fn configure_stdout(&mut self, _: &mut TokioCommand) {}
    fn configure_stderr(&mut self, command: &mut TokioCommand) {
        command.stderr(Stdio::piped());
    }
    fn take(self, _: &mut TokioChild, _: Option<&str>, _: bool) -> crate::Result<Self::Task> {
        Ok(())
    }
}

impl pio::ChildOutTask for CargoTask {
    type Output = Arc<ProgressBar>;

    fn run(self) -> (Option<BoxedFuture<()>>, Self::Output) {
        let bar = Arc::clone(&self.bar);
        (Some(Box::pin(self.main())), bar)
    }
}

impl CargoTask {
    async fn main(self) {
        let read_out = tokio::io::BufReader::new(self.out);
        let mut out_lines = Some(read_out.lines());
        let read_err = tokio::io::BufReader::new(self.err);
        let mut err_lines = Some(read_err.lines());

        let bar = self.bar;

        crate::progress!(bar, "preparing");

        let mut state = PrintState::new(
            self.error_lv,
            self.warning_lv,
            self.other_lv,
            bar,
            self.diagnostic_hook,
        );

        loop {
            let read_res = match (&mut out_lines, &mut err_lines) {
                (None, None) => break,
                (Some(out), None) => Ok(out.next_line().await),
                (None, Some(err)) => Err(err.next_line().await),
                (Some(out), Some(err)) => {
                    tokio::select! {
                        x = out.next_line() => Ok(x),
                        x = err.next_line() => Err(x)
                    }
                }
            };
            let line: Result<String, String> = match read_res {
                Ok(x) => match x {
                    Ok(Some(x)) => Ok(x),
                    _ => {
                        out_lines = None;
                        continue;
                    }
                },
                Err(x) => match x {
                    Ok(Some(x)) => Err(x),
                    _ => {
                        err_lines = None;
                        continue;
                    }
                },
            };
            match line {
                Ok(line) => state.handle_stdout(&line),
                Err(line) => state.handle_stderr(&line),
            }
        }
    }
}

struct PrintState {
    error_lv: Lv,
    warning_lv: Lv,
    other_lv: Lv,
    bar: Arc<ProgressBar>,
    done_count: usize,
    in_progress: Vec<String>, // using a vec to preserve order
    buf: String,
    diagnostic_hook: Option<DianogsticHook>,
    stderr_printing_message_lv: Option<Lv>,
}

impl PrintState {
    fn new(
        error_lv: Lv,
        warning_lv: Lv,
        other_lv: Lv,
        bar: Arc<ProgressBar>,
        diagnostic_hook: Option<DianogsticHook>,
    ) -> Self {
        Self {
            error_lv,
            warning_lv,
            other_lv,
            bar,
            done_count: 0,
            in_progress: Default::default(),
            buf: Default::default(),
            diagnostic_hook,
            stderr_printing_message_lv: None,
        }
    }
    fn handle_stdout(&mut self, line: &str) {
        // only handle json output from stdout
        if !line.starts_with('{') {
            crate::trace!("{line}");
            return;
        }

        let payload = match crate::json::parse::<Payload>(line) {
            Ok(x) => x,
            Err(e) => {
                crate::trace!("failed to parse cargo json output: {e:?}");
                return;
            }
        };
        match payload.reason {
            "compiler-artifact" => {
                let Some(target) = payload.target else {
                    return;
                };
                if target.name == "build-script-build" {
                    // skip processing build script builds
                    return;
                }
                self.done_count += 1;
                self.in_progress.retain(|x| x != target.name);
                self.update_bar();
            }
            "compiler-message" => {
                let Some(message) = payload.message else {
                    return;
                };
                let Some(rendered) = message.rendered else {
                    return;
                };
                match message.level {
                    Some("warning") => match &self.diagnostic_hook {
                        None => {
                            crate::cli::__print_with_level(
                                self.warning_lv,
                                format_args!("{rendered}"),
                            );
                        }
                        Some(hook) => hook(true, &rendered),
                    },
                    Some("error") => match &self.diagnostic_hook {
                        None => {
                            crate::cli::__print_with_level(
                                self.error_lv,
                                format_args!("{rendered}"),
                            );
                        }
                        Some(hook) => hook(false, &rendered),
                    },
                    _ => {
                        crate::cli::__print_with_level(self.other_lv, format_args!("{rendered}"));
                    }
                }
            }
            "build-finished" => match payload.success {
                Some(true) => {
                    self.bar.done_by_ref();
                    crate::trace!("cargo build successful");
                }
                _ => {
                    crate::trace!("cargo build failed");
                }
            },
            "build-script-executed" => {}
            _ => {
                crate::trace!("unhandled cargo message reason: {}", payload.reason);
            }
        }
    }

    fn handle_stderr(&mut self, line: &str) {
        static STATUS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new("^((\x1b[^m]*m)|\\s)*(Compiling|Checking)((\x1b[^m]*m)|\\s)*").unwrap()
        });
        static OTHER_STATUS_REGEX: LazyLock<Regex> = LazyLock::new(|| {
            Regex::new("^((\x1b[^m]*m)|\\s)*(Downloading|Downloaded)((\x1b[^m]*m)|\\s)*").unwrap()
        });
        static ERROR_REGEX: LazyLock<Regex> =
            LazyLock::new(|| Regex::new("^((\x1b[^m]*m)|\\s)*error").unwrap());
        static WARNING_REGEX: LazyLock<Regex> =
            LazyLock::new(|| Regex::new("^((\x1b[^m]*m)|\\s)*warning").unwrap());
        let Some(m) = STATUS_REGEX.find(line) else {
            if OTHER_STATUS_REGEX.is_match(line) {
                crate::cli::__print_with_level(self.other_lv, format_args!("{line}"));
                self.stderr_printing_message_lv = None;
                return;
            }
            // some error/warning messages aren't emited to stdout,
            // so we use a regex to match and print them
            if let Some(lv) = self.stderr_printing_message_lv {
                // since the message might be multi-line, we
                // keep printing until a status message is matched
                crate::cli::__print_with_level(lv, format_args!("{line}"));
                return;
            }
            // check if the message matches error/warning
            if ERROR_REGEX.is_match(line) {
                crate::cli::__print_with_level(self.error_lv, format_args!("{line}"));
                self.stderr_printing_message_lv = Some(self.error_lv);
                return;
            }
            if WARNING_REGEX.is_match(line) {
                crate::cli::__print_with_level(self.warning_lv, format_args!("{line}"));
                self.stderr_printing_message_lv = Some(self.warning_lv);
                return;
            }
            // print as other message
            crate::cli::__print_with_level(self.other_lv, format_args!("{line}"));
            return;
        };
        // print the status message as other, and clear the error/warning message state
        crate::cli::__print_with_level(self.other_lv, format_args!("{line}"));
        self.stderr_printing_message_lv = None;

        // process the status message
        let line = &line[m.end()..].trim();
        // crate name can't have space (right?)
        let crate_name = match line.find(' ') {
            None => line,
            Some(i) => &line[..i],
        };
        self.in_progress.push(crate_name.replace('-', "_"));
        self.update_bar();
    }

    fn update_bar(&mut self) {
        let count = self.done_count;
        let bar = &self.bar;

        self.buf.clear();
        let mut iter = self.in_progress.iter();
        if let Some(x) = iter.next() {
            self.buf.push_str(x);
            for c in iter {
                self.buf.push_str(", ");
                self.buf.push_str(c);
            }
            crate::progress!(bar, "{count} done, compiling: {}", self.buf);
        } else if count != 0 {
            crate::progress!(bar, "{count} done");
        }
    }
}

// (is_warning, message) -> Break = don't print, Continue = print original or overriden message
type DianogsticHook = Box<dyn Fn(bool, &str) + Send>;

#[derive(serde::Deserialize)]
struct Payload<'a> {
    reason: &'a str,
    target: Option<PayloadTarget<'a>>,
    message: Option<PayloadMessage<'a>>,
    success: Option<bool>,
}

#[derive(serde::Deserialize)]
struct PayloadTarget<'a> {
    name: &'a str,
}

#[derive(serde::Deserialize)]
struct PayloadMessage<'a> {
    level: Option<&'a str>,
    // for some reason, this can't be deserialize as borrowed
    rendered: Option<String>,
}