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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Environment variables for deser.
//!
//! ```rust
//! use deser::Deserialize;
//!
//! #[derive(Debug, Deserialize)]
//! struct Config {
//! name: String,
//! debug: bool,
//! server: Server,
//! }
//!
//! #[derive(Debug, Deserialize)]
//! struct Server {
//! port: u16,
//! max_connections: Option<u32>,
//! }
//!
//! // `deser_env::from_env::<Config>("APP_")` reads the environment of the
//! // process, `from_vars` reads the given variables
//! let config: Config = deser_env::from_vars("APP_", [
//! ("APP_NAME", "shop"),
//! ("APP_DEBUG", "yes"),
//! ("APP_SERVER__PORT", "8080"),
//! ("PATH", "/usr/bin"),
//! ])
//! .unwrap();
//! assert_eq!(config.name, "shop");
//! assert!(config.debug);
//! assert_eq!(config.server.port, 8080);
//! assert_eq!(config.server.max_connections, None);
//! ```
//!
//! # Data Model
//!
//! The variables with names that start with a prefix (like `APP_`) are a
//! map. The prefix is removed and the rest of the name is split at the
//! separator (`__` by default, see [`DeserializerConfig::set_separator`]) into
//! nested keys which are lowercased (see [`Case`]):
//!
//! | variables | deser |
//! |-----------------------------------------|-------------------------------------------|
//! | `APP_PORT=80` | `{"port": "80"}` |
//! | `APP_MAX_CONNECTIONS=5` | `{"max_connections": "5"}` |
//! | `APP_SERVER__PORT=80` | `{"server": {"port": "80"}}` |
//! | `APP_HOSTS__0=a` `APP_HOSTS__1=b` | `{"hosts": ["a", "b"]}` |
//! | `APP_HOSTS__1=a` `APP_HOSTS__3=b` | `{"hosts": {"1": "a", "3": "b"}}` |
//! | `APP_FEATURES__NEW_UI=on` | `{"features": {"new_ui": "on"}}` |
//!
//! A single `_` separates words in names, which is why nested keys are
//! separated with two. Indexes that start at `0` and have no gaps are
//! sequences, other indexes are map keys. Names that start or end with the
//! separator or contain it twice in a row are taken as they are. A name
//! that has a value and nested names (`APP_DB=x` and `APP_DB__POOL=4`) is an
//! error. The order of the environment is arbitrary, the variables are
//! sorted by name.
//!
//! Everything in the environment is text, the type of a value is only known
//! to the type it's deserialized into. Keys and values are therefore passed
//! on as [lexical atoms](deser_core::Atom::Lexical) which are parsed by the
//! types they are delivered to: numbers parse them, strings take them as
//! they are. Booleans accept `true`, `yes`, `on` and `1` and `false`, `no`,
//! `off` and `0`. Lexical atoms are retained when values are buffered, so
//! flattened structs and internally tagged and untagged enums work as well.
//!
//! ## Empty Values
//!
//! A variable that is set to the empty string is the empty value, like
//! `?page=` in a query string: it's `None` for optionals of types that do
//! not accept it (`APP_PORT=` is `None` for an `Option<u16>`) and
//! `Some("")` for an `Option<String>`. Variables that switch something on
//! by being set (like `APP_VERBOSE=`) use the
//! [`Flag`](deser_core::adapters::Flag) adapter which treats the empty
//! value as `true`:
//!
//! ```rust
//! use deser::adapters::Flag;
//!
//! #[derive(deser::Deserialize)]
//! struct Options {
//! #[deser(as = Flag)]
//! verbose: bool,
//! port: Option<u16>,
//! }
//!
//! let options: Options =
//! deser_env::from_vars("APP_", [("APP_VERBOSE", ""), ("APP_PORT", "")])
//! .unwrap();
//! assert!(options.verbose);
//! assert_eq!(options.port, None);
//! ```
//!
//! ## Lists
//!
//! Sequences can be given with indexes (`APP_HOSTS__0`) without changes to
//! the types. A single variable (`APP_HOSTS=a`) is a list of one value and
//! a list without variables is empty (the maps of the environment are
//! [multimaps](deser_core::ContainerShape::set_multimap), like query
//! strings). Lists in a single variable (`APP_HOSTS=a,b,c`) use the
//! [`Separated`](deser_core::adapters::Separated) adapter, with
//! [`TrimWhitespace`](deser_core::adapters::TrimWhitespace) to allow spaces
//! (`a, b, c`). Both work with all formats, a configuration file can still
//! give an array:
//!
//! ```rust
//! use deser::adapters::{Separated, TrimWhitespace};
//!
//! #[derive(deser::Deserialize)]
//! struct Config {
//! #[deser(as = Separated<',', TrimWhitespace>)]
//! hosts: Vec<String>,
//! ports: Vec<u16>,
//! tags: Vec<String>,
//! }
//!
//! let config: Config = deser_env::from_vars("APP_", [
//! ("APP_HOSTS", "a, b"),
//! ("APP_PORTS__0", "80"),
//! ("APP_PORTS__1", "443"),
//! ])
//! .unwrap();
//! assert_eq!(config.hosts, ["a", "b"]);
//! assert_eq!(config.ports, [80, 443]);
//! assert!(config.tags.is_empty());
//! ```
//!
//! # Errors
//!
//! Errors carry the name of the variable they refer to (see [`EnvVar`]).
//! This is also the case for unknown fields that are collected as warnings
//! (see [`UnknownFields`](deser_core::de::UnknownFields)) and for values
//! which are buffered:
//!
//! ```rust
//! use deser_env::EnvVar;
//!
//! #[derive(Debug, deser::Deserialize)]
//! struct Config {
//! port: u16,
//! }
//!
//! let vars = [("APP_PORT", "http")];
//! let err = deser_env::from_vars::<Config, _, _, _>("APP_", vars)
//! .unwrap_err();
//! assert_eq!(err.attachment::<EnvVar>().unwrap().name(), "APP_PORT");
//! assert_eq!(
//! err.to_string(),
//! "InvalidValue: invalid value \"http\", expected u16 \
//! (environment variable APP_PORT)"
//! );
//! ```
//!
//! # Layering
//!
//! Environment variables typically override a configuration file. With
//! [`update`](deser_core::de::Deserializer::update) the variables that are
//! set are applied to an existing value, nested structs are merged:
//!
//! ```rust
//! use deser::de::Deserializer as _;
//!
//! #[derive(Debug, deser::Deserialize)]
//! struct Config {
//! server: Server,
//! }
//!
//! #[derive(Debug, deser::Deserialize)]
//! struct Server {
//! host: String,
//! port: u16,
//! }
//!
//! let mut config = Config {
//! server: Server { host: "localhost".into(), port: 80 },
//! };
//! deser_env::Deserializer::from_vars("APP_", [("APP_SERVER__PORT", "8080")])
//! .update(&mut config)
//! .unwrap();
//! assert_eq!(config.server.host, "localhost");
//! assert_eq!(config.server.port, 8080);
//! ```
//!
//! # Platforms
//!
//! On Unix values which are not valid unicode are passed on as
//! [bytes](deser_core::adapters#bytes) (which `Vec<u8>` and `PathBuf`
//! accept), on other platforms they are an error. Names that are not valid
//! unicode are skipped unless they start with the prefix. On Windows names
//! are not case sensitive, the prefix is matched ignoring ASCII case.
//!
//! Setting environment variables of the running process is `unsafe` (see
//! [`std::env::set_var`]), [`from_vars`] is a better fit for tests.
//!
//! # Serialization
//!
//! Values are serialized into name-value pairs (see [`to_vars`] and
//! [`SerializerConfig`]), for instance to pass a configuration to a child
//! process with [`Command::envs`](std::process::Command::envs).
//!
//! # Features
//!
//! * `speedups` (enabled by default): has no effect yet, it exists so
//! that all formats have it.
use Cow;
use fmt;
use Arc;
use Text;
use ;
use ;
pub use ;
pub use ;
/// How the case of names maps onto keys.
///
/// ```
/// use std::collections::BTreeMap;
/// use deser_env::{Case, DeserializerConfig, SerializerConfig};
///
/// let vars = [("APP_Server__Port", "80")];
/// let value: BTreeMap<String, BTreeMap<String, u16>> =
/// deser_env::from_vars("APP_", vars).unwrap();
/// assert_eq!(value["server"]["port"], 80);
///
/// let preserve = DeserializerConfig::builder().case(Case::Preserve).build();
/// let value: BTreeMap<String, BTreeMap<String, u16>> =
/// preserve.from_vars("APP_", vars).unwrap();
/// assert_eq!(value["Server"]["Port"], 80);
///
/// let vars = deser_env::to_vars("APP_", &value).unwrap();
/// assert_eq!(vars, [("APP_SERVER__PORT".to_string(), "80".to_string())]);
/// ```
/// The environment variable an error refers to.
///
/// Errors of values and keys that come from environment variables carry
/// this [attachment](deser_core::ErrorAttachment). For keys that more than
/// one variable share (like `server` in `APP_SERVER__HOST` and
/// `APP_SERVER__PORT`) it's the name up to the key (`APP_SERVER`). Errors
/// that do not come from a single variable (like missing fields) have none.
///
/// ```
/// use deser_env::EnvVar;
///
/// #[derive(Debug, deser::Deserialize)]
/// struct Config {
/// server: Server,
/// }
///
/// #[derive(Debug, deser::Deserialize)]
/// #[deser(deny_unknown_fields)]
/// struct Server {
/// port: u16,
/// }
///
/// let err = deser_env::from_vars::<Config, _, _, _>(
/// "APP_",
/// [("APP_SERVER__PROT", "80")],
/// )
/// .unwrap_err();
/// assert_eq!(err.message(), "unknown field `prot`, expected `port`");
/// assert_eq!(
/// err.attachment::<EnvVar>().unwrap().name(),
/// "APP_SERVER__PROT"
/// );
/// ```
/// Deserializes a value from the environment variables with a prefix.
///
/// This reads the environment of the process with the default
/// [`DeserializerConfig`], see the [crate documentation](crate) for how
/// variables map onto deser. Without a prefix (`""`) all variables are
/// read. Then `PATH`, `HOME` and the like are keys too which fails for
/// types that deny unknown fields.
///
/// ```no_run
/// #[derive(deser::Deserialize)]
/// struct Config {
/// port: u16,
/// }
///
/// // reads `APP_PORT`
/// let config: Config = deser_env::from_env("APP_").unwrap();
/// ```
/// Deserializes a value from the given variables with a prefix.
///
/// The variables are name-value pairs, for instance from
/// [`std::env::vars`] or a file, which are deserialized as if they were the
/// environment (see [`from_env`]). Values that are given borrowed are
/// passed on borrowed.
///
/// ```
/// use std::collections::BTreeMap;
///
/// let value: BTreeMap<String, Vec<u32>> =
/// deser_env::from_vars("", [("A__0", "1"), ("A__1", "2"), ("B", "3")])
/// .unwrap();
/// assert_eq!(value["a"], [1, 2]);
/// assert_eq!(value["b"], [3]);
/// ```
/// Deserializes the value of a single environment variable.
///
/// The value is parsed like the values of [`from_env`] (numbers and
/// booleans parse, the empty value is `None` for optionals of types that do
/// not accept it). Collections (like `Vec<T>`) are a collection of the
/// value, like the fields of structs. If the variable is not set, types
/// that can be missing (like `Option<T>`) use their missing value and
/// collections are empty, other types fail. Errors carry the name of the
/// variable (see [`EnvVar`]).
///
/// ```no_run
/// let port: u16 = deser_env::var("PORT").unwrap();
/// let workers: Option<usize> = deser_env::var("WORKERS").unwrap();
/// ```