aether/
builders.rs

1use crate::{
2    endpoint::{EndpointExt, EndpointHash},
3    logger::{setup_logger, KeepAlive},
4    EndpointSuper, LogEntry,
5};
6use std::{
7    collections::HashMap,
8    marker::PhantomData,
9    path::{Path, PathBuf},
10};
11
12/// Builder for an endpoint.
13pub struct EndpointBuilder {
14    pub(crate) path: Option<PathBuf>,
15    pub(crate) silent: bool,
16    pub(crate) disabled: bool,
17}
18
19impl EndpointBuilder {
20    /// Disables file output. This is the default.
21    pub fn no_path(mut self) -> Self {
22        self.path = None;
23        self
24    }
25
26    /// Enables file output.
27    pub fn path(mut self, path: impl AsRef<Path>) -> Self {
28        self.path = Some(path.as_ref().into());
29        self
30    }
31
32    /// Don't log to console.
33    pub fn silent(mut self) -> Self {
34        self.silent = true;
35        self
36    }
37
38    /// Ignore this endpoint.
39    pub fn disable(mut self) -> Self {
40        self.disabled = true;
41        self
42    }
43}
44
45/// Builder for the logger type.
46pub struct LoggerBuilder<EP: EndpointSuper> {
47    pub(crate) base_path: Option<PathBuf>,
48    pub(crate) fmt: fn(LogEntry<EP>) -> String,
49    pub(crate) endpoints: HashMap<EndpointHash, EndpointBuilder>,
50}
51
52impl<EP: EndpointSuper + std::hash::Hash> LoggerBuilder<EP> {
53    /// Sets the format for all log entries.
54    pub fn format(mut self, fmt: fn(LogEntry<EP>) -> String) -> Self {
55        self.fmt = fmt;
56        self
57    }
58
59    /// Specifies the base path for files and archives.
60    pub fn base_path(mut self, path: impl AsRef<Path>) -> Self {
61        self.base_path = Some(path.as_ref().into());
62        self
63    }
64
65    /// Setup an endpoint.
66    pub fn setup(mut self, endpoint: EP, setup: fn(EndpointBuilder) -> EndpointBuilder) -> Self {
67        self.endpoints.insert(
68            endpoint.endpoint_hash(),
69            setup(EndpointBuilder {
70                path: None,
71                silent: false,
72                disabled: false,
73            }),
74        );
75        self
76    }
77
78    /// Construct the logger. See [`KeepAlive`] for more details.
79    pub fn build(self) -> KeepAlive {
80        setup_logger(self);
81        KeepAlive(PhantomData)
82    }
83}