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
use serde_derive::{Deserialize, Serialize};

/// A metric represents a Mackerel metric schema.
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub struct Metric {
    pub name: String,
    pub label: String,
    pub stacked: bool,
    #[serde(skip_serializing)]
    pub diff: bool,
}

/// Builds a new [`Metric`].
///
/// ```rust
/// use mackerel_plugin::metric;
///
/// let metric = metric! {
///     name: "foo",
///     label: "Foo metric",
/// };
/// ```
///
/// You can also specify `stacked` and `diff` options.
///
/// ```rust
/// use mackerel_plugin::metric;
///
/// let metric = metric! {
///     name: "foo",
///     label: "Foo metric",
///     stacked: true,
///     diff: true,
/// };
/// ```
#[macro_export]
macro_rules! metric {
    (
        name: $name:expr,
        label: $label:expr
        $( , $field:ident: $value:expr )* $(,)?
    ) => {{
        assert!(
            !$name.is_empty()
                && (str::chars($name).all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_'))
                    || matches!($name, "*" | "#"))
        );
        $crate::Metric {
            $( $field: $value, )*
            ..$crate::Metric {
                name: $name.into(),
                label: $label.into(),
                stacked: false,
                diff: false,
            }
        }
    }};

    ($($_:tt)*) => {
        compile_error!("name and label are required");
    };
}