aboutsummaryrefslogtreecommitdiffstats
path: root/crates/config/src/option.rs
blob: b361d38527cbb2e28bc0fc9a7d55db9d74eaa80a (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//! The options a program takes, each described once: the command line, the keys of
//! configuration files and the reading of text values all go by them.

use anyhow::{Result, anyhow, bail};
use serde_json::Value as JsonValue;

/// How an option's value is written as text (command line, text imports).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// `true`/`false`; on the command line, present or not.
    Flag,
    Text,
    Integer,
    /// Seconds, or with units: `500ms`, `30s`, `1h30m` (`units::parse_duration`).
    Duration,
    /// Bytes, or with a unit: `64KiB` (`units::parse_size`).
    Size,
    /// Comma- or line-separated; repeatable on the command line.
    List,
}

#[derive(Debug)]
pub struct OptionSpec {
    pub name: &'static str,
    pub kind: Kind,
    pub value_name: &'static str,
    /// For `--help` only; the effective defaults are in [`Settings`].
    pub default: Option<&'static str>,
    pub help: &'static str,
    pub hidden: bool,
    /// Its value is never shown (logs, `--print-config`, `GET /admin/config`), however
    /// it was given.
    pub secret: bool,
}

impl OptionSpec {
    pub const fn secret(self) -> Self {
        Self {
            secret: true,
            ..self
        }
    }
}

pub const fn option(
    name: &'static str,
    kind: Kind,
    value_name: &'static str,
    default: Option<&'static str>,
    help: &'static str,
) -> OptionSpec {
    OptionSpec {
        name,
        kind,
        value_name,
        default,
        help,
        hidden: false,
        secret: false,
    }
}

/// Options that can't be combined: those of one side with those of the other.
pub type Conflict = (&'static [&'static str], &'static [&'static str]);

/// What a program's configuration is read by: its options, and what it says of them.
#[derive(Debug, Clone, Copy)]
pub struct Schema {
    /// Every option. Names are the long option names and the configuration file keys.
    pub options: &'static [OptionSpec],
    /// Options that can't be combined. A source that sets one side drops the other
    /// side's values from earlier sources (lower precedence), so one on the command line
    /// overrides the other from a file.
    pub conflicts: &'static [Conflict],
    /// Options of earlier releases that are gone, each with what to do instead: a program
    /// given one, in a configuration file or on its command line, says so and stops,
    /// where "unknown option" would leave its operator guessing.
    pub gone: &'static [(&'static str, &'static str)],
}

impl Schema {
    /// A schema of `options` alone: none conflicting, none gone.
    pub const fn of(options: &'static [OptionSpec]) -> Schema {
        Schema {
            options,
            conflicts: &[],
            gone: &[],
        }
    }

    /// The option named `name`.
    pub fn spec(&self, name: &str) -> Option<&'static OptionSpec> {
        self.options.iter().find(|spec| spec.name == name)
    }

    /// Why `name` is no option any more, where it was one.
    pub fn gone(&self, name: &str) -> Option<&'static str> {
        self.gone
            .iter()
            .find(|(gone, _)| *gone == name)
            .map(|(_, why)| *why)
    }

    /// Whether the option named `name` is never shown.
    pub fn secret(&self, name: &str) -> bool {
        self.spec(name).is_some_and(|spec| spec.secret)
    }

    /// The options `name` can't be combined with.
    pub fn conflicting<'a>(&self, name: &'a str) -> impl Iterator<Item = &'static str> + 'a {
        self.conflicts.iter().flat_map(move |(a, b)| {
            let other: &'static [&'static str] = if a.contains(&name) {
                b
            } else if b.contains(&name) {
                a
            } else {
                &[]
            };
            other.iter().copied()
        })
    }
}

/// The value of a text, by the option's kind.
pub fn from_text(kind: Kind, text: &str) -> Result<JsonValue> {
    Ok(match kind {
        Kind::Text => JsonValue::String(text.to_owned()),
        Kind::Integer => {
            let number: u64 = text
                .trim()
                .parse()
                .map_err(|_| anyhow!("{text:?} is not a non-negative integer"))?;
            JsonValue::from(number)
        }
        Kind::Duration => {
            crate::units::parse_duration(text).map_err(|reason| anyhow!(reason))?;
            JsonValue::String(text.trim().to_owned())
        }
        Kind::Size => {
            crate::units::parse_size(text).map_err(|reason| anyhow!(reason))?;
            JsonValue::String(text.trim().to_owned())
        }
        Kind::Flag => match text.trim() {
            "true" | "yes" | "1" => JsonValue::Bool(true),
            "false" | "no" | "0" => JsonValue::Bool(false),
            _ => bail!("{text:?} is not true or false"),
        },
        Kind::List => JsonValue::Array(
            text.split([',', '\n'])
                .map(str::trim)
                .filter(|item| !item.is_empty())
                .map(|item| JsonValue::String(item.to_owned()))
                .collect(),
        ),
    })
}