loga/
entry.rs

1use console::Style as TextStyle;
2use std::{
3    collections::{
4        HashMap,
5        HashSet,
6    },
7    io::Write,
8    process::exit,
9};
10use crate::types::{
11    log,
12    Error,
13    Error_,
14};
15
16/// Create a new error. If you want to inherit attributes from a logging context,
17/// see `Log::err`.
18pub fn err(message: impl ToString) -> Error {
19    return Error(Box::new(Error_ {
20        message: message.to_string(),
21        attrs: HashMap::new(),
22        context: vec![],
23        causes: vec![],
24        incidental: vec![],
25    }));
26}
27
28/// Create a new error and attach attributes. If you want to inherit attributes
29/// from a logging context, see `Log::err`.
30pub fn err_with(message: impl ToString, attrs: impl Fn(&mut HashMap<&'static str, String>) -> ()) -> Error {
31    let mut new_attrs = HashMap::new();
32    attrs(&mut new_attrs);
33    return Error(Box::new(Error_ {
34        message: message.to_string(),
35        attrs: new_attrs,
36        context: vec![],
37        causes: vec![],
38        incidental: vec![],
39    }));
40}
41
42/// Create an error from multiple errors
43pub fn agg_err(message: impl ToString, errs: Vec<Error>) -> Error {
44    return Error(Box::new(Error_ {
45        message: message.to_string(),
46        attrs: HashMap::new(),
47        context: vec![],
48        causes: errs,
49        incidental: vec![],
50    }));
51}
52
53/// Create an error from multiple errors, attaching attributes
54pub fn agg_err_with(
55    message: impl ToString,
56    errs: Vec<Error>,
57    attrs: impl Fn(&mut HashMap<&'static str, String>) -> (),
58) -> Error {
59    let mut new_attrs = HashMap::new();
60    attrs(&mut new_attrs);
61    return Error(Box::new(Error_ {
62        message: message.to_string(),
63        attrs: new_attrs,
64        context: vec![],
65        causes: errs,
66        incidental: vec![],
67    }));
68}
69
70/// Log a fatal error and terminate the program.
71pub fn fatal(e: Error) -> ! {
72    let body_color = TextStyle::new().for_stderr().red();
73    let level_color = TextStyle::new().for_stderr().red().bold();
74    let mut node = e.build_render_nodes(&HashSet::new());
75    node.title = format!("Exiting due to error: {}", node.title).into();
76    log(body_color, level_color, "FATAL", node);
77    _ = std::io::stderr().flush();
78    exit(1)
79}