| 1 | //!colored_json crate to output colored serde json with ANSI terminal escape codes |
| 2 | //! |
| 3 | //!# Examples |
| 4 | //! |
| 5 | //!For everything, which implements `AsRef<str>` |
| 6 | //! |
| 7 | //!```rust |
| 8 | //! use colored_json::prelude::*; |
| 9 | //! |
| 10 | //! # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 11 | //! println!( |
| 12 | //! "{}", |
| 13 | //! r#"{ |
| 14 | //! "array": [ |
| 15 | //! "ele1", |
| 16 | //! "ele2" |
| 17 | //! ], |
| 18 | //! "float": 3.1415926, |
| 19 | //! "integer": 4398798674962568, |
| 20 | //! "string": "string" |
| 21 | //! } |
| 22 | //! "#.to_colored_json_auto()? |
| 23 | //! ); |
| 24 | //! # Ok(()) |
| 25 | //! # } |
| 26 | //!``` |
| 27 | //! |
| 28 | //!or for serde_json::Value |
| 29 | //! |
| 30 | //!```rust |
| 31 | //! use serde_json::{json, Value}; |
| 32 | //! use colored_json::to_colored_json_auto; |
| 33 | //! |
| 34 | //! # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 35 | //! let val : Value = json!({ |
| 36 | //! "name": "John Doe", |
| 37 | //! "age": 43, |
| 38 | //! "phones": [ |
| 39 | //! "+44 1234567", |
| 40 | //! "+44 2345678" |
| 41 | //! ] |
| 42 | //! }); |
| 43 | //! let s = to_colored_json_auto(&val)?; |
| 44 | //! println!("{}", s); |
| 45 | //! # Ok(()) |
| 46 | //! # } |
| 47 | //!``` |
| 48 | //! |
| 49 | //!With a custom color style: |
| 50 | //! |
| 51 | //!```rust |
| 52 | //! use colored_json::prelude::*; |
| 53 | //! use colored_json::{Color, Style, Styler}; |
| 54 | //! |
| 55 | //! # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 56 | //! println!( |
| 57 | //! "{}", |
| 58 | //! r#"{ |
| 59 | //! "array": [ |
| 60 | //! "ele1", |
| 61 | //! "ele2" |
| 62 | //! ], |
| 63 | //! "float": 3.1415926, |
| 64 | //! "integer": 4398798674962568, |
| 65 | //! "string": "string" |
| 66 | //! } |
| 67 | //! "#.to_colored_json_with_styler( |
| 68 | //! ColorMode::default().eval(), |
| 69 | //! Styler { |
| 70 | //! key: Color::Green.foreground(), |
| 71 | //! string_value: Color::Blue.bold(), |
| 72 | //! integer_value: Color::Magenta.bold(), |
| 73 | //! float_value: Color::Magenta.italic(), |
| 74 | //! object_brackets: Color::Yellow.bold(), |
| 75 | //! array_brackets: Color::Cyan.bold(), |
| 76 | //! ..Default::default() |
| 77 | //! })? |
| 78 | //! ); |
| 79 | //! Ok(()) |
| 80 | //! # } |
| 81 | //!``` |
| 82 | //! |
| 83 | //! |
| 84 | //!```rust |
| 85 | //! use serde_json::json; |
| 86 | //! |
| 87 | //! use colored_json::{ColoredFormatter, CompactFormatter, Color, Styler, Style}; |
| 88 | //! |
| 89 | //! # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 90 | //! let f = ColoredFormatter::with_styler( |
| 91 | //! CompactFormatter {}, |
| 92 | //! Styler { |
| 93 | //! key: Color::Green.foreground(), |
| 94 | //! string_value: Color::Blue.bold(), |
| 95 | //! ..Default::default() |
| 96 | //! }, |
| 97 | //! ); |
| 98 | //! |
| 99 | //! println!( |
| 100 | //! "{}", |
| 101 | //! f.clone().to_colored_json_auto(&json!({ |
| 102 | //! "name": "John Doe", |
| 103 | //! "age": 43, |
| 104 | //! "phones": [ |
| 105 | //! "+44 1234567", |
| 106 | //! "+44 2345678" |
| 107 | //! ] |
| 108 | //! }))? |
| 109 | //! ); |
| 110 | //! |
| 111 | //! println!( |
| 112 | //! "{}", |
| 113 | //! f.to_colored_json_auto(&json!({ |
| 114 | //! "name":"John", "age":31, "city":"New York" |
| 115 | //! }))? |
| 116 | //! ); |
| 117 | //! # Ok(()) |
| 118 | //! # } |
| 119 | //!``` |
| 120 | |
| 121 | use serde::Serialize; |
| 122 | use serde_json::ser::Formatter; |
| 123 | use serde_json::value::Value; |
| 124 | use std::env::var_os; |
| 125 | use std::io::{self, IsTerminal}; |
| 126 | |
| 127 | pub use serde_json::ser::{CompactFormatter, PrettyFormatter}; |
| 128 | pub use yansi::{Color, Paint, Style}; |
| 129 | |
| 130 | pub mod prelude { |
| 131 | pub use crate::ColorMode; |
| 132 | pub use crate::ToColoredJson; |
| 133 | } |
| 134 | |
| 135 | /// Styler lets you define the look of the colored json output |
| 136 | #[derive(Clone, Copy)] |
| 137 | pub struct Styler { |
| 138 | /// style of object brackets |
| 139 | pub object_brackets: Style, |
| 140 | /// style of object colons |
| 141 | pub object_colon: Style, |
| 142 | /// style of array brackets |
| 143 | pub array_brackets: Style, |
| 144 | /// style of object |
| 145 | pub key: Style, |
| 146 | /// style of string values |
| 147 | pub string_value: Style, |
| 148 | /// style of integer values |
| 149 | pub integer_value: Style, |
| 150 | /// style of float values |
| 151 | pub float_value: Style, |
| 152 | /// style of bool values |
| 153 | pub bool_value: Style, |
| 154 | /// style of the `nil` value |
| 155 | pub nil_value: Style, |
| 156 | /// should the quotation get the style of the inner string/key? |
| 157 | pub string_include_quotation: bool, |
| 158 | } |
| 159 | |
| 160 | /// Default style resembling the `jq` style |
| 161 | impl Default for Styler { |
| 162 | fn default() -> Styler { |
| 163 | Styler { |
| 164 | object_brackets: Style::new().bold(), |
| 165 | object_colon: Style::new(), |
| 166 | array_brackets: Style::new().bold(), |
| 167 | key: Color::Blue.bold(), |
| 168 | string_value: Color::Green.foreground(), |
| 169 | integer_value: Style::new(), |
| 170 | float_value: Style::new(), |
| 171 | bool_value: Style::new(), |
| 172 | nil_value: Style::new().bright_black().bold(), |
| 173 | string_include_quotation: true, |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// `ColoredFormatter` decorates a `Formatter` with color defined in `Styler` |
| 179 | #[derive(Clone)] |
| 180 | pub struct ColoredFormatter<F> |
| 181 | where |
| 182 | F: Formatter, |
| 183 | { |
| 184 | formatter: F, |
| 185 | styler: Styler, |
| 186 | in_object_key: bool, |
| 187 | } |
| 188 | |
| 189 | impl<F> ColoredFormatter<F> |
| 190 | where |
| 191 | F: Formatter, |
| 192 | { |
| 193 | pub fn new(formatter: F) -> Self { |
| 194 | ColoredFormatter { |
| 195 | formatter, |
| 196 | styler: Styler::default(), |
| 197 | in_object_key: false, |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | pub fn with_styler(formatter: F, styler: Styler) -> Self { |
| 202 | ColoredFormatter { |
| 203 | formatter, |
| 204 | styler, |
| 205 | in_object_key: false, |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | #[allow(clippy::wrong_self_convention)] |
| 210 | pub fn to_colored_json_auto<T>(self, value: &T) -> serde_json::Result<String> |
| 211 | where |
| 212 | T: Serialize, |
| 213 | { |
| 214 | self.to_colored_json(value, ColorMode::Auto(Output::StdOut)) |
| 215 | } |
| 216 | |
| 217 | #[allow(clippy::wrong_self_convention)] |
| 218 | pub fn to_colored_json<T>(self, value: &T, mode: ColorMode) -> serde_json::Result<String> |
| 219 | where |
| 220 | T: Serialize, |
| 221 | { |
| 222 | let mut writer: Vec<u8> = Vec::with_capacity(128); |
| 223 | |
| 224 | self.write_colored_json(value, &mut writer, mode)?; |
| 225 | |
| 226 | Ok(String::from_utf8_lossy(&writer).to_string()) |
| 227 | } |
| 228 | |
| 229 | pub fn write_colored_json<W, T>( |
| 230 | self, |
| 231 | value: &T, |
| 232 | writer: &mut W, |
| 233 | mode: ColorMode, |
| 234 | ) -> Result<(), serde_json::Error> |
| 235 | where |
| 236 | W: io::Write, |
| 237 | T: Serialize, |
| 238 | { |
| 239 | if mode.use_color() { |
| 240 | let mut serializer = serde_json::Serializer::with_formatter(writer, self); |
| 241 | value.serialize(&mut serializer) |
| 242 | } else { |
| 243 | let mut serializer = serde_json::Serializer::with_formatter(writer, self.formatter); |
| 244 | value.serialize(&mut serializer) |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | fn colored<W: ?Sized, H>(writer: &mut W, style: Style, mut handler: H) -> io::Result<()> |
| 250 | where |
| 251 | W: io::Write, |
| 252 | H: FnMut(&mut Vec<u8>) -> io::Result<()>, |
| 253 | { |
| 254 | let mut w: Vec<u8> = Vec::with_capacity(128); |
| 255 | handler(&mut w)?; |
| 256 | |
| 257 | if !w.is_empty() { |
| 258 | let s = String::from_utf8_lossy(&w); |
| 259 | writer.write_all(s.paint(style).to_string().as_bytes())?; |
| 260 | } |
| 261 | |
| 262 | Ok(()) |
| 263 | } |
| 264 | |
| 265 | impl<F> Formatter for ColoredFormatter<F> |
| 266 | where |
| 267 | F: Formatter, |
| 268 | { |
| 269 | fn write_null<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 270 | where |
| 271 | W: io::Write, |
| 272 | { |
| 273 | colored(writer, self.styler.nil_value, |w| { |
| 274 | self.formatter.write_null(w) |
| 275 | }) |
| 276 | } |
| 277 | |
| 278 | fn write_bool<W: ?Sized>(&mut self, writer: &mut W, value: bool) -> io::Result<()> |
| 279 | where |
| 280 | W: io::Write, |
| 281 | { |
| 282 | colored(writer, self.styler.bool_value, |w| { |
| 283 | self.formatter.write_bool(w, value) |
| 284 | }) |
| 285 | } |
| 286 | |
| 287 | fn write_i8<W: ?Sized>(&mut self, writer: &mut W, value: i8) -> io::Result<()> |
| 288 | where |
| 289 | W: io::Write, |
| 290 | { |
| 291 | colored(writer, self.styler.integer_value, |w| { |
| 292 | self.formatter.write_i8(w, value) |
| 293 | }) |
| 294 | } |
| 295 | |
| 296 | fn write_i16<W: ?Sized>(&mut self, writer: &mut W, value: i16) -> io::Result<()> |
| 297 | where |
| 298 | W: io::Write, |
| 299 | { |
| 300 | colored(writer, self.styler.integer_value, |w| { |
| 301 | self.formatter.write_i16(w, value) |
| 302 | }) |
| 303 | } |
| 304 | |
| 305 | fn write_i32<W: ?Sized>(&mut self, writer: &mut W, value: i32) -> io::Result<()> |
| 306 | where |
| 307 | W: io::Write, |
| 308 | { |
| 309 | colored(writer, self.styler.integer_value, |w| { |
| 310 | self.formatter.write_i32(w, value) |
| 311 | }) |
| 312 | } |
| 313 | |
| 314 | fn write_i64<W: ?Sized>(&mut self, writer: &mut W, value: i64) -> io::Result<()> |
| 315 | where |
| 316 | W: io::Write, |
| 317 | { |
| 318 | colored(writer, self.styler.integer_value, |w| { |
| 319 | self.formatter.write_i64(w, value) |
| 320 | }) |
| 321 | } |
| 322 | |
| 323 | fn write_u8<W: ?Sized>(&mut self, writer: &mut W, value: u8) -> io::Result<()> |
| 324 | where |
| 325 | W: io::Write, |
| 326 | { |
| 327 | colored(writer, self.styler.integer_value, |w| { |
| 328 | self.formatter.write_u8(w, value) |
| 329 | }) |
| 330 | } |
| 331 | |
| 332 | fn write_u16<W: ?Sized>(&mut self, writer: &mut W, value: u16) -> io::Result<()> |
| 333 | where |
| 334 | W: io::Write, |
| 335 | { |
| 336 | colored(writer, self.styler.integer_value, |w| { |
| 337 | self.formatter.write_u16(w, value) |
| 338 | }) |
| 339 | } |
| 340 | |
| 341 | fn write_u32<W: ?Sized>(&mut self, writer: &mut W, value: u32) -> io::Result<()> |
| 342 | where |
| 343 | W: io::Write, |
| 344 | { |
| 345 | colored(writer, self.styler.integer_value, |w| { |
| 346 | self.formatter.write_u32(w, value) |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | fn write_u64<W: ?Sized>(&mut self, writer: &mut W, value: u64) -> io::Result<()> |
| 351 | where |
| 352 | W: io::Write, |
| 353 | { |
| 354 | colored(writer, self.styler.integer_value, |w| { |
| 355 | self.formatter.write_u64(w, value) |
| 356 | }) |
| 357 | } |
| 358 | |
| 359 | fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()> |
| 360 | where |
| 361 | W: io::Write, |
| 362 | { |
| 363 | colored(writer, self.styler.float_value, |w| { |
| 364 | self.formatter.write_f32(w, value) |
| 365 | }) |
| 366 | } |
| 367 | |
| 368 | fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()> |
| 369 | where |
| 370 | W: io::Write, |
| 371 | { |
| 372 | colored(writer, self.styler.float_value, |w| { |
| 373 | self.formatter.write_f64(w, value) |
| 374 | }) |
| 375 | } |
| 376 | |
| 377 | fn write_number_str<W: ?Sized>(&mut self, writer: &mut W, value: &str) -> io::Result<()> |
| 378 | where |
| 379 | W: io::Write, |
| 380 | { |
| 381 | colored(writer, self.styler.integer_value, |w| { |
| 382 | self.formatter.write_number_str(w, value) |
| 383 | }) |
| 384 | // self.formatter.write_number_str(writer, value) |
| 385 | } |
| 386 | |
| 387 | fn begin_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 388 | where |
| 389 | W: io::Write, |
| 390 | { |
| 391 | if self.styler.string_include_quotation { |
| 392 | let style = if self.in_object_key { |
| 393 | self.styler.key |
| 394 | } else { |
| 395 | self.styler.string_value |
| 396 | }; |
| 397 | colored(writer, style, |w| self.formatter.begin_string(w)) |
| 398 | } else { |
| 399 | self.formatter.begin_string(writer) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | fn end_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 404 | where |
| 405 | W: io::Write, |
| 406 | { |
| 407 | if self.styler.string_include_quotation { |
| 408 | let style = if self.in_object_key { |
| 409 | self.styler.key |
| 410 | } else { |
| 411 | self.styler.string_value |
| 412 | }; |
| 413 | colored(writer, style, |w| self.formatter.end_string(w)) |
| 414 | } else { |
| 415 | self.formatter.end_string(writer) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | fn write_string_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> |
| 420 | where |
| 421 | W: io::Write, |
| 422 | { |
| 423 | let style = if self.in_object_key { |
| 424 | self.styler.key |
| 425 | } else { |
| 426 | self.styler.string_value |
| 427 | }; |
| 428 | colored(writer, style, |w| { |
| 429 | self.formatter.write_string_fragment(w, fragment) |
| 430 | }) |
| 431 | } |
| 432 | |
| 433 | fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 434 | where |
| 435 | W: io::Write, |
| 436 | { |
| 437 | colored(writer, self.styler.array_brackets, |w| { |
| 438 | self.formatter.begin_array(w) |
| 439 | }) |
| 440 | } |
| 441 | |
| 442 | fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 443 | where |
| 444 | W: io::Write, |
| 445 | { |
| 446 | colored(writer, self.styler.array_brackets, |w| { |
| 447 | self.formatter.end_array(w) |
| 448 | }) |
| 449 | } |
| 450 | |
| 451 | fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> |
| 452 | where |
| 453 | W: io::Write, |
| 454 | { |
| 455 | self.formatter.begin_array_value(writer, first) |
| 456 | } |
| 457 | |
| 458 | fn end_array_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 459 | where |
| 460 | W: io::Write, |
| 461 | { |
| 462 | self.formatter.end_array_value(writer) |
| 463 | } |
| 464 | |
| 465 | fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 466 | where |
| 467 | W: io::Write, |
| 468 | { |
| 469 | colored(writer, self.styler.object_brackets, |w| { |
| 470 | self.formatter.begin_object(w) |
| 471 | }) |
| 472 | } |
| 473 | |
| 474 | fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 475 | where |
| 476 | W: io::Write, |
| 477 | { |
| 478 | colored(writer, self.styler.object_brackets, |w| { |
| 479 | self.formatter.end_object(w) |
| 480 | }) |
| 481 | } |
| 482 | |
| 483 | fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> |
| 484 | where |
| 485 | W: io::Write, |
| 486 | { |
| 487 | self.in_object_key = true; |
| 488 | self.formatter.begin_object_key(writer, first) |
| 489 | } |
| 490 | |
| 491 | fn end_object_key<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 492 | where |
| 493 | W: io::Write, |
| 494 | { |
| 495 | self.in_object_key = false; |
| 496 | colored(writer, self.styler.object_colon, |w| { |
| 497 | self.formatter.end_object_key(w) |
| 498 | }) |
| 499 | } |
| 500 | |
| 501 | fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 502 | where |
| 503 | W: io::Write, |
| 504 | { |
| 505 | self.in_object_key = false; |
| 506 | colored(writer, self.styler.object_colon, |w| { |
| 507 | self.formatter.begin_object_value(w) |
| 508 | }) |
| 509 | } |
| 510 | |
| 511 | fn end_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> |
| 512 | where |
| 513 | W: io::Write, |
| 514 | { |
| 515 | self.in_object_key = false; |
| 516 | self.formatter.end_object_value(writer)?; |
| 517 | Ok(()) |
| 518 | } |
| 519 | |
| 520 | fn write_raw_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> |
| 521 | where |
| 522 | W: io::Write, |
| 523 | { |
| 524 | self.formatter.write_raw_fragment(writer, fragment) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | /// Trait to add json coloring for all `AsRef<str>` like `String` and `&str` |
| 529 | pub trait ToColoredJson { |
| 530 | fn to_colored_json_auto(&self) -> serde_json::Result<String>; |
| 531 | fn to_colored_json(&self, mode: ColorMode) -> serde_json::Result<String>; |
| 532 | fn to_colored_json_with_styler( |
| 533 | &self, |
| 534 | mode: ColorMode, |
| 535 | styler: Styler, |
| 536 | ) -> serde_json::Result<String>; |
| 537 | fn write_colored_json<W>(&self, writer: &mut W) -> serde_json::Result<()> |
| 538 | where |
| 539 | W: io::Write; |
| 540 | fn write_colored_json_with_mode<W>( |
| 541 | &self, |
| 542 | writer: &mut W, |
| 543 | mode: ColorMode, |
| 544 | ) -> serde_json::Result<()> |
| 545 | where |
| 546 | W: io::Write; |
| 547 | fn write_colored_json_with_styler<W>( |
| 548 | &self, |
| 549 | writer: &mut W, |
| 550 | mode: ColorMode, |
| 551 | styler: Styler, |
| 552 | ) -> serde_json::Result<()> |
| 553 | where |
| 554 | W: io::Write; |
| 555 | } |
| 556 | |
| 557 | impl<S> ToColoredJson for S |
| 558 | where |
| 559 | S: ?Sized + AsRef<str>, |
| 560 | { |
| 561 | /// Serialize the given data structure as a pretty-color-printed String of JSON. |
| 562 | /// |
| 563 | /// # Errors |
| 564 | /// |
| 565 | /// Serialization can fail if `T`'s implementation of `Serialize` decides to |
| 566 | /// fail, or if `T` contains a map with non-string keys. |
| 567 | fn to_colored_json_auto(&self) -> serde_json::Result<String> { |
| 568 | let v: Value = serde_json::from_str(self.as_ref())?; |
| 569 | to_colored_json(&v, ColorMode::Auto(Output::StdOut)) |
| 570 | } |
| 571 | |
| 572 | /// Serialize the given data structure as a pretty-color-printed String of JSON. |
| 573 | /// |
| 574 | /// # Errors |
| 575 | /// |
| 576 | /// Serialization can fail if `T`'s implementation of `Serialize` decides to |
| 577 | /// fail, or if `T` contains a map with non-string keys. |
| 578 | fn to_colored_json(&self, mode: ColorMode) -> serde_json::Result<String> { |
| 579 | let v: Value = serde_json::from_str(self.as_ref())?; |
| 580 | to_colored_json(&v, mode) |
| 581 | } |
| 582 | |
| 583 | /// Serialize the given data structure as a pretty-color-printed String of JSON. |
| 584 | /// |
| 585 | /// # Errors |
| 586 | /// |
| 587 | /// Serialization can fail if `T`'s implementation of `Serialize` decides to |
| 588 | /// fail, or if `T` contains a map with non-string keys. |
| 589 | fn to_colored_json_with_styler( |
| 590 | &self, |
| 591 | mode: ColorMode, |
| 592 | styler: Styler, |
| 593 | ) -> serde_json::Result<String> { |
| 594 | let f = ColoredFormatter::with_styler(PrettyFormatter::new(), styler); |
| 595 | let v: Value = serde_json::from_str(self.as_ref())?; |
| 596 | f.to_colored_json(&v, mode) |
| 597 | } |
| 598 | |
| 599 | /// Serialize the given data structure as pretty-color-printed JSON into the IO |
| 600 | /// stream. |
| 601 | /// |
| 602 | /// # Errors |
| 603 | /// |
| 604 | /// Serialization can fail if `T`'s implementation of `Serialize` decides to |
| 605 | /// fail, or if `T` contains a map with non-string keys. |
| 606 | fn write_colored_json<W>(&self, writer: &mut W) -> serde_json::Result<()> |
| 607 | where |
| 608 | W: io::Write, |
| 609 | { |
| 610 | let value: Value = serde_json::from_str(self.as_ref())?; |
| 611 | write_colored_json_with_mode(&value, writer, ColorMode::Auto(Output::StdOut)) |
| 612 | } |
| 613 | |
| 614 | fn write_colored_json_with_mode<W>( |
| 615 | &self, |
| 616 | writer: &mut W, |
| 617 | mode: ColorMode, |
| 618 | ) -> serde_json::Result<()> |
| 619 | where |
| 620 | W: io::Write, |
| 621 | { |
| 622 | let value: Value = serde_json::from_str(self.as_ref())?; |
| 623 | write_colored_json_with_mode(&value, writer, mode) |
| 624 | } |
| 625 | |
| 626 | fn write_colored_json_with_styler<W>( |
| 627 | &self, |
| 628 | writer: &mut W, |
| 629 | mode: ColorMode, |
| 630 | styler: Styler, |
| 631 | ) -> serde_json::Result<()> |
| 632 | where |
| 633 | W: io::Write, |
| 634 | { |
| 635 | let value: Value = serde_json::from_str(self.as_ref())?; |
| 636 | let f = ColoredFormatter::with_styler(PrettyFormatter::new(), styler); |
| 637 | f.write_colored_json(&value, writer, mode) |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | /// Serialize the given data structure as a pretty-color-printed String of JSON. |
| 642 | /// |
| 643 | /// # Errors |
| 644 | /// |
| 645 | /// Serialization can fail if `T`'s implementation of `Serialize` decides to |
| 646 | /// fail, or if `T` contains a map with non-string keys. |
| 647 | pub fn to_colored_json_auto<T>(value: &T) -> serde_json::Result<String> |
| 648 | where |
| 649 | T: Serialize, |
| 650 | { |
| 651 | to_colored_json(value, ColorMode::Auto(Output::StdOut)) |
| 652 | } |
| 653 | |
| 654 | pub fn to_colored_json<T>(value: &T, mode: ColorMode) -> serde_json::Result<String> |
| 655 | where |
| 656 | T: Serialize, |
| 657 | { |
| 658 | let mut writer: Vec<u8> = Vec::with_capacity(128); |
| 659 | |
| 660 | write_colored_json_with_mode(value, &mut writer, mode)?; |
| 661 | |
| 662 | Ok(String::from_utf8_lossy(&writer).to_string()) |
| 663 | } |
| 664 | |
| 665 | /// Serialize the given data structure as pretty-color-printed JSON into the IO |
| 666 | /// stream. |
| 667 | /// |
| 668 | /// # Errors |
| 669 | /// |
| 670 | /// Serialization can fail if `T`'s implementation of `Serialize` decides to |
| 671 | /// fail, or if `T` contains a map with non-string keys. |
| 672 | pub fn write_colored_json<W, T>(value: &T, writer: &mut W) -> serde_json::Result<()> |
| 673 | where |
| 674 | W: io::Write, |
| 675 | T: Serialize, |
| 676 | { |
| 677 | write_colored_json_with_mode(value, writer, ColorMode::Auto(Output::StdOut)) |
| 678 | } |
| 679 | |
| 680 | pub fn write_colored_json_with_mode<W, T>( |
| 681 | value: &T, |
| 682 | writer: &mut W, |
| 683 | mode: ColorMode, |
| 684 | ) -> serde_json::Result<()> |
| 685 | where |
| 686 | W: io::Write, |
| 687 | T: Serialize, |
| 688 | { |
| 689 | if mode.use_color() { |
| 690 | let formatter = ColoredFormatter::new(PrettyFormatter::new()); |
| 691 | let mut serializer = serde_json::Serializer::with_formatter(writer, formatter); |
| 692 | value.serialize(&mut serializer) |
| 693 | } else { |
| 694 | let formatter = PrettyFormatter::new(); |
| 695 | let mut serializer = serde_json::Serializer::with_formatter(writer, formatter); |
| 696 | value.serialize(&mut serializer) |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | /// ColorMode is a switch to enforce color mode, turn it off or auto-detect, if it should be used |
| 701 | #[derive(Clone, Copy, PartialEq)] |
| 702 | pub enum ColorMode { |
| 703 | On, |
| 704 | Off, |
| 705 | Auto(Output), |
| 706 | } |
| 707 | |
| 708 | /// Specify the output sink, which should be used for the auto detection |
| 709 | #[derive(Clone, Copy, PartialEq)] |
| 710 | pub enum Output { |
| 711 | StdOut, |
| 712 | StdErr, |
| 713 | } |
| 714 | |
| 715 | /// With `ColorMode` you can implement command line options like `--color=auto|on|off` easily. |
| 716 | /// |
| 717 | /// # Example: |
| 718 | /// |
| 719 | /// ```rust |
| 720 | /// # use colored_json::{ColorMode, Output}; |
| 721 | /// |
| 722 | /// let option = "--color=auto"; |
| 723 | /// |
| 724 | /// let color_mode = match option { |
| 725 | /// "--color=on" => ColorMode::Off, |
| 726 | /// "--color=off" => ColorMode::On, |
| 727 | /// _ => ColorMode::default().eval(), |
| 728 | /// }; |
| 729 | /// |
| 730 | /// assert!(match color_mode { |
| 731 | /// ColorMode::On | ColorMode::Off => true, |
| 732 | /// _ => false |
| 733 | /// }); |
| 734 | /// ``` |
| 735 | impl ColorMode { |
| 736 | fn is_tty(output: Output) -> bool { |
| 737 | match output { |
| 738 | Output::StdOut => io::stdout().is_terminal(), |
| 739 | Output::StdErr => io::stderr().is_terminal(), |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | /// indicates, if the `output` is capable of displaying colors and if `NO_COLOR` is not active. |
| 744 | pub fn should_colorize(output: Output) -> bool { |
| 745 | // check if `NO_COLOR` is present and not empty |
| 746 | if var_os("NO_COLOR") |
| 747 | .filter(|value| !value.is_empty()) |
| 748 | .is_some() |
| 749 | { |
| 750 | // color is requested to be off |
| 751 | return false; |
| 752 | } |
| 753 | |
| 754 | Self::is_tty(output) |
| 755 | } |
| 756 | |
| 757 | /// Returns ColorMode::On or ColorMode::Off |
| 758 | /// |
| 759 | /// # Example: |
| 760 | /// |
| 761 | /// ```rust |
| 762 | /// # use colored_json::{ColorMode, Output}; |
| 763 | /// let on_off = ColorMode::default().eval(); |
| 764 | /// |
| 765 | /// assert!(match on_off { |
| 766 | /// ColorMode::On | ColorMode::Off => true, |
| 767 | /// _ => false |
| 768 | /// }); |
| 769 | /// ``` |
| 770 | pub fn eval(self) -> Self { |
| 771 | if self.use_color() { |
| 772 | ColorMode::On |
| 773 | } else { |
| 774 | ColorMode::Off |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | /// Indicates if color should be used |
| 779 | // |
| 780 | /// # Example: |
| 781 | // |
| 782 | /// ```rust |
| 783 | /// # use colored_json::{ColorMode, Output}; |
| 784 | // |
| 785 | /// if ColorMode::default().use_color() { |
| 786 | /// println!("We can use color! :-)"); |
| 787 | /// } else { |
| 788 | /// println!("No color for you! :-("); |
| 789 | /// } |
| 790 | // |
| 791 | /// if ColorMode::Auto(Output::StdErr).use_color() { |
| 792 | /// println!("We can use color on stderr! :-)"); |
| 793 | /// } else { |
| 794 | /// println!("No color for you on stderr! :-("); |
| 795 | /// } |
| 796 | // |
| 797 | /// assert_eq!(ColorMode::On.use_color(), true); |
| 798 | /// assert_eq!(ColorMode::Off.use_color(), false); |
| 799 | /// ``` |
| 800 | pub fn use_color(self) -> bool { |
| 801 | match self { |
| 802 | ColorMode::On => true, |
| 803 | ColorMode::Off => false, |
| 804 | ColorMode::Auto(output) => Self::should_colorize(output), |
| 805 | } |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | impl Default for ColorMode { |
| 810 | /// returns `ColorMode::Auto(Output::StdOut)` |
| 811 | fn default() -> Self { |
| 812 | ColorMode::Auto(Output::StdOut) |
| 813 | } |
| 814 | } |