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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
#![deny(missing_docs)]

/*!
This crate parses the output of `cargo check --message-format json` into transparent data structures.

The main entrypoint for running cargo and parsing output is the [`Analyzer`](struct.Analyzer.html) struct.
*/

use std::{
    collections::VecDeque,
    error,
    fmt::{self, Debug, Display, Formatter},
    fs,
    io::{self, Read, Write},
    path::PathBuf,
    process::{Child, Command, Stdio},
    result,
};

use colored::Colorize;
use pad::{Alignment, PadStr};
use serde_derive::{Deserialize, Serialize};

/// Error type used by coral
#[derive(Debug)]
pub enum Error {
    /// An error running cargo
    Cargo,
    /// An IO error
    IO(io::Error),
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        use Error::*;
        match self {
            Cargo => write!(f, "Unable to run cargo"),
            IO(e) => write!(f, "{}", e),
        }
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        Error::IO(e)
    }
}

impl error::Error for Error {}

/// Result type used by coral
pub type Result<T> = result::Result<T, Error>;

/// Get the width of the terminal
pub fn terminal_width() -> usize {
    terminal_size::terminal_size()
        .map(|(w, _)| w.0 as usize)
        .unwrap_or(100)
}

const LEVEL_COLUMN_WIDTH: usize = 7;
const FILE_COLUMN_WIDTH: usize = 18;
const LINE_COLUMN_WIDTH: usize = 8;
const ELIPSES_COLUMN_WIDTH: usize = 3;

fn message_column_width(terminal_width: usize) -> usize {
    terminal_width - LEVEL_COLUMN_WIDTH - FILE_COLUMN_WIDTH - LINE_COLUMN_WIDTH - 6
}

fn ensure_color() {
    #[cfg(windows)]
    colored::control::set_virtual_terminal(true).unwrap();
}

/// A way of checking a project
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum Checker {
    /// Check with `cargo check`
    Check,
    /// Check with `cargo clippy`
    Clippy,
    /// "Check" with `cargo build`
    Build,
}

impl Default for Checker {
    fn default() -> Self {
        Checker::Check
    }
}

/// The main entrypoint for running cargo and parsing output
pub struct Analyzer {
    child: Child,
    buffer: VecDeque<u8>,
    debug: bool,
    color: bool,
}

impl Analyzer {
    /// Create a new `Analyzer` that uses `cargo check`
    pub fn new() -> Result<Analyzer> {
        Analyzer::with_args(Checker::Check, &[])
    }
    /// Create a new `Analyzer` that uses `cargo clippy`
    pub fn clippy() -> Result<Analyzer> {
        Analyzer::with_args(Checker::Clippy, &[])
    }
    /// Create a new `Analyzer` that uses the given checker and argments
    pub fn with_args(checker: Checker, args: &[String]) -> Result<Analyzer> {
        ensure_color();
        Ok(Analyzer {
            child: Command::new("cargo")
                .args(&[
                    &format!("{:?}", checker).to_lowercase(),
                    "--message-format",
                    "json",
                ])
                .args(args)
                .stdin(Stdio::null())
                .stderr(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()
                .map_err(|_| Error::Cargo)?,
            buffer: VecDeque::new(),
            debug: false,
            color: true,
        })
    }
    /// Set whether to enable debug mode. Default is `false`
    pub fn debug(self, debug: bool) -> Self {
        if debug {
            let _ = fs::write("coral.json", &[]);
        }
        Analyzer { debug, ..self }
    }
    /// Set whether to enable console coloring. Default is `true`
    pub fn color(self, color: bool) -> Self {
        Analyzer { color, ..self }
    }
    fn add_to_buffer(&mut self) {
        const BUFFER_LEN: usize = 100;
        let mut buffer = [0u8; BUFFER_LEN];
        while !self.buffer.contains(&b'\n') {
            if let Ok(len) = self.child.stdout.as_mut().unwrap().read(&mut buffer) {
                if len == 0 {
                    break;
                } else {
                    self.buffer.extend(&buffer[..len]);
                }
            } else {
                break;
            }
        }
    }
}

impl Iterator for Analyzer {
    type Item = Entry;
    fn next(&mut self) -> Option<Self::Item> {
        colored::control::set_override(true);
        self.add_to_buffer();
        let mut entry_buffer = Vec::new();
        while let Some(byte) = self.buffer.pop_front().filter(|&b| b != b'\n') {
            entry_buffer.push(byte);
        }
        let res = if entry_buffer.is_empty() {
            None
        } else {
            if self.debug {
                println!("\t{}\n", String::from_utf8_lossy(&entry_buffer));
                let mut file = fs::OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open("coral.json")
                    .unwrap();
                let _ = file.write(&entry_buffer).unwrap();
                writeln!(file).unwrap();
            }
            let mut entry: Entry = serde_json::from_slice(&entry_buffer).unwrap();
            entry.color = self.color;
            Some(entry)
        };
        if res.is_none() {
            self.child.wait().unwrap();
        }
        res
    }
}

impl Debug for Analyzer {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Analyzer")
    }
}

fn default_color_setting() -> bool {
    true
}

/// A top-level entry output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Entry {
    pub reason: Reason,
    pub package_id: String,
    pub target: Option<Target>,
    pub message: Option<Message>,
    pub profile: Option<Profile>,
    pub features: Option<Vec<String>>,
    pub filenames: Option<Vec<PathBuf>>,
    pub executable: Option<PathBuf>,
    pub fresh: Option<bool>,
    #[serde(default = "default_color_setting")]
    pub color: bool,
}

impl Entry {
    /// Check if the `Entry` is a compiler message
    pub fn is_message(&self) -> bool {
        self.reason == Reason::CompilerMessage
    }
    /// Check if the `Entry` is a compiler artifact
    pub fn is_artifact(&self) -> bool {
        self.reason == Reason::CompilerArtifact
    }
    /// Check if a level exists and is a warning
    pub fn is_warning(&self) -> bool {
        self.message
            .as_ref()
            .map(Message::is_warning)
            .unwrap_or(false)
    }
    /// Check if a level exists and is an error
    pub fn is_error(&self) -> bool {
        self.message
            .as_ref()
            .map(Message::is_error)
            .unwrap_or(false)
    }
    /// Check if a level exists and is a note
    pub fn is_note(&self) -> bool {
        self.message.as_ref().map(Message::is_note).unwrap_or(false)
    }
    /// Check if a level exists and is a help
    pub fn is_help(&self) -> bool {
        self.message.as_ref().map(Message::is_help).unwrap_or(false)
    }
    /// Get an error, warning, or info report from the `Entry`
    pub fn report(&self) -> Option<String> {
        self.report_width(terminal_width())
    }
    /// Same as [`Entry::report`](struct.Entry.html#method.report) but uses a custom terminal width
    pub fn report_width(&self, terminal_width: usize) -> Option<String> {
        self.message
            .as_ref()
            .and_then(|m| m.report(self.color, terminal_width))
    }
    /// Get the `Entry`'s render if it had one
    pub fn rendered(&self) -> Option<&str> {
        self.message
            .as_ref()
            .and_then(|m| m.rendered.as_ref().map(String::as_str))
    }
}

/// A reason output by cargo
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum Reason {
    CompilerArtifact,
    CompilerMessage,
    BuildScriptExecuted,
}

/// Target information output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Target {
    pub kind: Vec<TargetKind>,
    pub crate_types: Vec<CrateType>,
    pub name: String,
    pub src_path: PathBuf,
    pub edition: String,
}

/// The kind of a `Target` output by cargo
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum TargetKind {
    Lib,
    Bin,
    Rlib,
    CustomBuild,
    ProcMacro,
}

/// A message output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Message {
    pub message: String,
    pub code: Option<Code>,
    pub level: Level,
    pub spans: Option<Vec<Span>>,
    pub children: Option<Vec<Message>>,
    pub rendered: Option<String>,
}

impl Message {
    /// Check if the level is a warning
    pub fn is_warning(&self) -> bool {
        self.level.is_warning()
    }
    /// Check if the level is an error
    pub fn is_error(&self) -> bool {
        self.level.is_error()
    }
    /// Check if the level is a note
    pub fn is_note(&self) -> bool {
        self.level.is_note()
    }
    /// Check if the level is a help
    pub fn is_help(&self) -> bool {
        self.level.is_help()
    }
    /// Get a string containing the column headers for reports
    pub fn report_headers(color: bool) -> String {
        ensure_color();
        colored::control::set_override(color);
        let level = "Level"
            .pad_to_width_with_alignment(LEVEL_COLUMN_WIDTH, Alignment::Right)
            .bright_white();
        let file = "File"
            .pad_to_width_with_alignment(FILE_COLUMN_WIDTH, Alignment::Right)
            .bright_white();
        let line = "Line"
            .pad_to_width_with_alignment(LINE_COLUMN_WIDTH, Alignment::Left)
            .bright_white();
        let message = "Message".bright_white();
        let res = format!("{} {}    {} {}", level, file, line, message);
        colored::control::unset_override();
        res
    }
    /// Get the message as a compact report
    pub fn report(&self, color: bool, terminal_width: usize) -> Option<String> {
        if self.message.contains("aborting") {
            None
        } else if self.level.is_some() {
            let span = self.spans.as_ref().and_then(|v| v.last());
            colored::control::set_override(color);
            let level = self.level.format();
            let file = span
                .as_ref()
                .map(|span| span.file_name_string())
                .unwrap_or_else(String::new);
            let file = if file.len() <= FILE_COLUMN_WIDTH {
                file
            } else {
                format!("...{}", &file[(file.len() - FILE_COLUMN_WIDTH + 3)..])
            }
            .pad_to_width_with_alignment(FILE_COLUMN_WIDTH, Alignment::Right)
            .bright_cyan();
            let line = if let Some(ref span) = span {
                let (line, column) = span.line();
                format!("{}:{}", line, column)
            } else {
                String::new()
            }
            .pad_to_width_with_alignment(LINE_COLUMN_WIDTH, Alignment::Left)
            .bright_cyan();
            let message_column_width = message_column_width(terminal_width);
            let mut message = self.message.clone();
            message.retain(|c| c != '\n');
            let message = if message.len() <= message_column_width {
                message[..(message_column_width.min(message.len()))].to_string()
            } else {
                format!(
                    "{}...",
                    &message[..((message_column_width - ELIPSES_COLUMN_WIDTH).min(message.len()))]
                )
            }
            .pad_to_width_with_alignment(message_column_width, Alignment::Left)
            .white();
            let res = Some(format!(
                "{} {} {} {} {}",
                level,
                file,
                if span.is_some() { "at" } else { "  " },
                line,
                message
            ));
            colored::control::unset_override();
            res
        } else {
            None
        }
    }
    /// Find a `Span` that contains a suggested replacement
    pub fn replacement_span(&self) -> Option<&Span> {
        self.spans
            .as_ref()
            .and_then(|spans| {
                spans
                    .iter()
                    .find(|span| span.suggested_replacement.is_some())
            })
            .or_else(|| {
                self.children
                    .as_ref()
                    .and_then(|children| children.iter().find_map(Message::replacement_span))
            })
    }
    /// Get an iterator over this message and it's children
    pub fn unroll(&self) -> impl Iterator<Item = &Message> {
        let mut messages = Vec::new();
        messages.push(self);
        if let Some(ref children) = self.children {
            for child in children {
                messages.extend(child.unroll());
            }
        }
        messages.into_iter()
    }
}

/// A code output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Code {
    pub code: String,
    pub explanation: Option<String>,
}

/// A message severity level output by cargo
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum Level {
    #[serde(rename = "")]
    None,
    Note,
    Help,
    Warning,
    Error,
}

impl Level {
    /// Check if the level is a warning
    pub fn is_warning(self) -> bool {
        self == Level::Warning
    }
    /// Check if the level is an error
    pub fn is_error(self) -> bool {
        self == Level::Error
    }
    /// Check if the level is a note
    pub fn is_note(self) -> bool {
        self == Level::Note
    }
    /// Check if the level is a help
    pub fn is_help(self) -> bool {
        self == Level::Help
    }
    /// Check if the level is not `Level::None`
    pub fn is_some(self) -> bool {
        !self.is_none()
    }
    /// Check if the level is `Level::None`
    pub fn is_none(self) -> bool {
        self == Level::None
    }
    fn format(self) -> String {
        let pad = |s: &str| s.pad_to_width_with_alignment(LEVEL_COLUMN_WIDTH, Alignment::Right);
        match self {
            Level::None => String::new(),
            Level::Note => format!("{}", pad("note").bright_cyan()),
            Level::Help => format!("{}", pad("help").bright_green()),
            Level::Warning => format!("{}", pad("warning").bright_yellow()),
            Level::Error => format!("{}", pad("error").bright_red()),
        }
    }
}

/// A span output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Span {
    pub file_name: PathBuf,
    pub byte_start: usize,
    pub byte_end: usize,
    pub line_start: usize,
    pub line_end: usize,
    pub column_start: usize,
    pub column_end: usize,
    pub is_primary: bool,
    pub text: Vec<Text>,
    pub label: Option<String>,
    pub suggested_replacement: Option<String>,
    pub suggestion_applicability: Option<String>,
    pub expansion: Option<Box<Expansion>>,
}

impl Span {
    /// Get the `Span`'s line and column
    pub fn line(&self) -> (usize, usize) {
        (self.line_start, self.column_start)
    }
    /// Get the `Span`'s file name as a `String`
    pub fn file_name_string(&self) -> String {
        self.file_name.to_string_lossy().into_owned()
    }
    /// Get the byte length of the `Span`
    pub fn len(&self) -> usize {
        self.byte_end - self.byte_start
    }
    /// Check if the `Span` is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Modify the source file, replacing
    /// the span with its suggested replacement
    ///
    /// This function consumes the `Span` because it is
    /// invalidated once the file is modified.
    pub fn replace_in_file(self) -> Result<()> {
        if let Some(replacement) = self.suggested_replacement {
            let mut buffer = fs::read(&self.file_name)?;
            let mut end = buffer.split_off(self.byte_end);
            buffer.truncate(self.byte_start);
            buffer.extend_from_slice(replacement.as_bytes());
            buffer.append(&mut end);
            fs::write(&self.file_name, buffer)?;
        }
        Ok(())
    }
}

/// A piece of text output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Text {
    pub text: String,
    pub highlight_start: usize,
    pub highlight_end: usize,
}

/// A macro expansion output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Expansion {
    pub span: Span,
    pub macro_decl_name: String,
    pub def_site_span: Option<Span>,
}

/// A crate type output by cargo
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
#[allow(missing_docs)]
pub enum CrateType {
    Lib,
    Bin,
    Rlib,
    ProcMacro,
}

/// A profile output by cargo
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[allow(missing_docs)]
pub struct Profile {
    pub opt_level: String,
    pub debuginfo: u8,
    pub debug_assertions: bool,
    pub overflow_checks: bool,
    pub test: bool,
}