nu_protocol/config/
helper.rs

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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use super::error::ConfigErrors;
use crate::{Record, ShellError, Span, Type, Value};
use std::{
    borrow::Borrow,
    collections::HashMap,
    fmt::{self, Display},
    hash::Hash,
    ops::{Deref, DerefMut},
    str::FromStr,
};

pub(super) struct ConfigPath<'a> {
    components: Vec<&'a str>,
}

impl<'a> ConfigPath<'a> {
    pub fn new() -> Self {
        Self {
            components: vec!["$env.config"],
        }
    }

    pub fn push(&mut self, key: &'a str) -> ConfigPathScope<'_, 'a> {
        self.components.push(key);
        ConfigPathScope { inner: self }
    }
}

impl Display for ConfigPath<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.components.join("."))
    }
}

pub(super) struct ConfigPathScope<'whole, 'part> {
    inner: &'whole mut ConfigPath<'part>,
}

impl Drop for ConfigPathScope<'_, '_> {
    fn drop(&mut self) {
        self.inner.components.pop();
    }
}

impl<'a> Deref for ConfigPathScope<'_, 'a> {
    type Target = ConfigPath<'a>;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}

impl DerefMut for ConfigPathScope<'_, '_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.inner
    }
}

pub(super) trait UpdateFromValue: Sized {
    fn update<'a>(
        &mut self,
        value: &'a Value,
        path: &mut ConfigPath<'a>,
        errors: &mut ConfigErrors,
    );
}

impl UpdateFromValue for Value {
    fn update(&mut self, value: &Value, _path: &mut ConfigPath, _errors: &mut ConfigErrors) {
        *self = value.clone();
    }
}

impl UpdateFromValue for bool {
    fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
        if let Ok(val) = value.as_bool() {
            *self = val;
        } else {
            errors.type_mismatch(path, Type::Bool, value);
        }
    }
}

impl UpdateFromValue for i64 {
    fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
        if let Ok(val) = value.as_int() {
            *self = val;
        } else {
            errors.type_mismatch(path, Type::Int, value);
        }
    }
}

impl UpdateFromValue for usize {
    fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
        if let Ok(val) = value.as_int() {
            if let Ok(val) = val.try_into() {
                *self = val;
            } else {
                errors.invalid_value(path, "a non-negative integer", value);
            }
        } else {
            errors.type_mismatch(path, Type::Int, value);
        }
    }
}

impl UpdateFromValue for String {
    fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
        if let Ok(val) = value.as_str() {
            *self = val.into();
        } else {
            errors.type_mismatch(path, Type::String, value);
        }
    }
}

impl<K, V> UpdateFromValue for HashMap<K, V>
where
    K: Borrow<str> + for<'a> From<&'a str> + Eq + Hash,
    V: Default + UpdateFromValue,
{
    fn update<'a>(
        &mut self,
        value: &'a Value,
        path: &mut ConfigPath<'a>,
        errors: &mut ConfigErrors,
    ) {
        if let Ok(record) = value.as_record() {
            *self = record
                .iter()
                .map(|(key, val)| {
                    let mut old = self.remove(key).unwrap_or_default();
                    old.update(val, &mut path.push(key), errors);
                    (key.as_str().into(), old)
                })
                .collect();
        } else {
            errors.type_mismatch(path, Type::record(), value);
        }
    }
}

pub(super) fn config_update_string_enum<T>(
    choice: &mut T,
    value: &Value,
    path: &mut ConfigPath,
    errors: &mut ConfigErrors,
) where
    T: FromStr,
    T::Err: Display,
{
    if let Ok(str) = value.as_str() {
        match str.parse() {
            Ok(val) => *choice = val,
            Err(err) => errors.invalid_value(path, err.to_string(), value),
        }
    } else {
        errors.type_mismatch(path, Type::String, value);
    }
}

pub fn extract_value<'record>(
    column: &'static str,
    record: &'record Record,
    span: Span,
) -> Result<&'record Value, ShellError> {
    record
        .get(column)
        .ok_or_else(|| ShellError::MissingRequiredColumn { column, span })
}