config_tools/macros.rs
1#[macro_export]
2/// Generate a `Config` object with sections and default values.
3/// Variables are supported in section, key, and value fields, but must be strings.
4/// # Syntax
5/// ```rust
6/// # use config_tools::{sectioned_defaults, Config};
7/// let server_section = "Server"; // Variables are supported
8/// let default_host = "127.0.0.1"; // across all fields.
9/// let secure = "true"; // Value must be a string!
10///
11/// let mut config: Config = sectioned_defaults! {
12/// // Optional general section (no section title)
13/// // must be the first section if included
14/// {
15/// "console" => "true",
16/// }
17///
18/// // Section titles are enclosed in square brackets
19/// [server_section] {
20/// "host" => default_host,
21/// "port" => "8080",
22/// }
23///
24/// ["Window"] {
25/// "width" => "720",
26/// "height" => "480",
27/// }
28/// };
29/// ```
30macro_rules! sectioned_defaults {
31 (
32 {
33 $($general_key:expr => $general_value:expr),* $(,)?
34 }
35 $(
36 [$section:expr] {
37 $($key:expr => $value:expr),* $(,)?
38 }
39 )*) => {
40 config_tools::Config::builder()
41 $(.set($general_key, $general_value))*
42 $(
43 .section($section)
44 $(.set($key, $value))*
45 )*
46 .build();
47 };
48 ($(
49 [$section:expr] {
50 $($key:expr => $value:expr),* $(,)?
51 }
52 )*) => {
53 config_tools::Config::builder()
54 $(
55 .section($section)
56 $(.set($key, $value))*
57 )*
58 .build();
59 }
60}
61
62#[macro_export]
63/// Generate a `Config` object with default values in a section entitled "DEFAULT".
64/// Variables are supported in key and value fields, but must be strings.
65/// # Syntax
66/// ```rust
67/// # use config_tools::{general_defaults, Config};
68/// let logging = "logging"; // Variables are supported across all fields.
69/// let use_logging = "true"; // Value must be a string!
70/// let mut config: Config = general_defaults! {
71/// "console" => "true",
72/// logging => use_logging,
73/// };
74/// ```
75macro_rules! general_defaults {
76 ($($key:expr => $value:expr),* $(,)?) => {
77 config_tools::Config::builder()
78 $(.set($key, $value))*
79 .build();
80 }
81}