]> git.proxmox.com Git - rustc.git/blob - vendor/codespan-reporting/src/term/mod.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / vendor / codespan-reporting / src / term / mod.rs
1 //! Terminal back-end for emitting diagnostics.
2
3 use codespan::Files;
4 use std::io;
5 use std::str::FromStr;
6 use termcolor::{ColorChoice, WriteColor};
7
8 use crate::diagnostic::Diagnostic;
9
10 mod config;
11 mod views;
12
13 pub use termcolor;
14
15 pub use self::config::{Chars, Config, DisplayStyle, Styles};
16
17 /// Emit a diagnostic using the given writer, context, config, and files.
18 pub fn emit(
19 writer: &mut impl WriteColor,
20 config: &Config,
21 files: &Files,
22 diagnostic: &Diagnostic,
23 ) -> io::Result<()> {
24 use self::views::{RichDiagnostic, ShortDiagnostic};
25
26 match config.display_style {
27 DisplayStyle::Rich => RichDiagnostic::new(files, diagnostic).emit(writer, config),
28 DisplayStyle::Short => ShortDiagnostic::new(files, diagnostic).emit(writer, config),
29 }
30 }
31
32 /// A command line argument that configures the coloring of the output.
33 ///
34 /// This can be used with command line argument parsers like `clap` or `structopt`.
35 ///
36 /// # Example
37 ///
38 /// ```rust
39 /// use structopt::StructOpt;
40 /// use codespan_reporting::term::termcolor::StandardStream;
41 /// use codespan_reporting::term::ColorArg;
42 ///
43 /// #[derive(Debug, StructOpt)]
44 /// #[structopt(name = "groovey-app")]
45 /// pub struct Opts {
46 /// /// Configure coloring of output
47 /// #[structopt(
48 /// long = "color",
49 /// parse(try_from_str),
50 /// default_value = "auto",
51 /// raw(possible_values = "ColorArg::VARIANTS", case_insensitive = "true")
52 /// )]
53 /// pub color: ColorArg,
54 /// }
55 ///
56 /// fn main() {
57 /// let opts = Opts::from_args();
58 /// let writer = StandardStream::stderr(opts.color.into());
59 /// }
60 /// ```
61 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
62 pub struct ColorArg(pub ColorChoice);
63
64 impl ColorArg {
65 /// Allowed values the argument.
66 ///
67 /// This is useful for generating documentation via `clap` or `structopt`'s
68 /// `possible_values` configuration.
69 pub const VARIANTS: &'static [&'static str] = &["auto", "always", "ansi", "never"];
70 }
71
72 impl FromStr for ColorArg {
73 type Err = &'static str;
74
75 fn from_str(src: &str) -> Result<ColorArg, &'static str> {
76 match src {
77 _ if src.eq_ignore_ascii_case("auto") => Ok(ColorArg(ColorChoice::Auto)),
78 _ if src.eq_ignore_ascii_case("always") => Ok(ColorArg(ColorChoice::Always)),
79 _ if src.eq_ignore_ascii_case("ansi") => Ok(ColorArg(ColorChoice::AlwaysAnsi)),
80 _ if src.eq_ignore_ascii_case("never") => Ok(ColorArg(ColorChoice::Never)),
81 _ => Err("valid values: auto, always, ansi, never"),
82 }
83 }
84 }
85
86 impl Into<ColorChoice> for ColorArg {
87 fn into(self) -> ColorChoice {
88 self.0
89 }
90 }