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
//! Sets values loaded by [`adotenv`] in the current process environment.
//!
//! [`adotenv::load`] reads `.env` files into a [`LoadedEnvironment`] but never
//! changes the process environment. This crate adds that step: [`apply`]. It is
//! a separate crate because changing the environment is unsafe. The
//! environment is shared by every thread of the process, and on some platforms
//! reading it while another thread writes it is undefined behavior. The core
//! `adotenv` crate forbids unsafe code.
//!
//! ```toml
//! [dependencies]
//! adotenv = { version = "1", features = ["load"] }
//! adotenv-process = "1"
//! ```
//!
//! The crate has no features of its own and needs Rust 1.81 or later.
//!
//! # Prefer passing values explicitly
//!
//! Most programs do not need to change their own environment. Read values
//! with [`LoadedEnvironment::get`], deserialize them with the `serde` feature
//! of `adotenv`, or pass them to a child process:
//!
//! ```no_run
//! use std::process::Command;
//!
//! use adotenv::load::load_cascade;
//!
//! let loaded = load_cascade("/srv/my-app", "production")?;
//! let status = Command::new("my-server").envs(loaded.values()).status()?;
//! # let _ = status;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! Use [`apply`] only when code you do not control reads the process
//! environment, such as a library that calls [`std::env::var`].
//!
//! # Applying a loaded environment
//!
//! [`apply`] checks every key and value, then sets each loaded key. A loaded
//! key replaces a variable of the same name. Other variables are kept and
//! nothing is removed. Values are set as loaded: `${HOME}` is not expanded.
//! The changes cannot be rolled back.
//!
//! The caller must guarantee that no other thread reads or writes the process
//! environment while [`apply`] runs. In practice, call it at the start of
//! `main`, before starting threads or an async runtime.
//!
//! ```
//! use adotenv::load::load_cascade;
//!
//! # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-crate-{}", std::process::id()));
//! # std::fs::create_dir_all(&dir)?;
//! # std::fs::write(dir.join(".env"), "APP_PORT=3000\n")?;
//! # std::fs::write(dir.join(".env.production"), "APP_PORT=8080\n")?;
//! let loaded = load_cascade(&dir, "production")?;
//!
//! // SAFETY: called at startup, before any other thread exists.
//! unsafe { adotenv_process::apply(&loaded)? };
//! assert_eq!(std::env::var("APP_PORT")?, "8080");
//! # std::fs::remove_dir_all(&dir)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! [`validate`] runs the same checks without changing anything, and is safe
//! to call from any thread. Both return an [`ApplyError`] for the first key or
//! value that the process environment cannot hold.
//!
//! `apply` takes a [`LoadedEnvironment`]. To set resolved values, resolve them
//! with [`LoadedEnvironment::resolve_contextual`] and set them yourself.
use ;
use LoadedEnvironment;
/// A key or value that the process environment cannot hold.
///
/// Returned by [`validate`], and by [`apply`] before it changes anything. It
/// reports the first problem, in key order. These are the inputs for which
/// [`std::env::set_var`] may panic. The error names the key but never includes
/// the value.
///
/// # Examples
///
/// Python dotenv lets a quoted key contain `=`. With `'APP=PORT'=8080` in
/// `.env`:
///
/// ```
/// use adotenv::load::load_cascade_with;
/// use adotenv::Dialect;
/// use adotenv_process::{validate, ApplyError};
///
/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-ApplyError-{}", std::process::id()));
/// # std::fs::create_dir_all(&dir)?;
/// # std::fs::write(dir.join(".env"), "'APP=PORT'=8080\n")?;
/// let loaded = load_cascade_with(&dir, "", Dialect::PYTHON_DOTENV)?;
/// match validate(&loaded) {
/// Err(ApplyError::InvalidKey { key }) => assert_eq!(key, "APP=PORT"),
/// other => panic!("expected an invalid key, got {other:?}"),
/// }
/// # std::fs::remove_dir_all(&dir)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Checks that the process environment can hold every loaded key and value.
///
/// Runs the checks of [`apply`] without changing anything, so it is safe to
/// call from any thread, for example to report a bad `.env` file early. A key
/// must not be empty and must not contain NUL or `=`. A value must not contain
/// NUL. Keys are checked in sorted order.
///
/// # Errors
///
/// Returns the first problem found:
///
/// - [`ApplyError::EmptyKey`] if a key is empty.
/// - [`ApplyError::InvalidKey`] if a key contains NUL or `=`.
/// - [`ApplyError::InvalidValue`] if a value contains NUL.
///
/// # Examples
///
/// With `PORT=8080` and a `TOKEN` value that contains a NUL byte in `.env`:
///
/// ```
/// use adotenv::load::load_cascade;
/// use adotenv_process::{validate, ApplyError};
///
/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-validate-{}", std::process::id()));
/// # std::fs::create_dir_all(&dir)?;
/// # std::fs::write(dir.join(".env"), "PORT=8080\nTOKEN=abc\0def\n")?;
/// let loaded = load_cascade(&dir, "")?;
/// let error = validate(&loaded).unwrap_err();
/// assert_eq!(error, ApplyError::InvalidValue { key: "TOKEN".to_string() });
/// assert_eq!(error.to_string(), r#"environment value for "TOKEN" contains NUL"#);
/// # std::fs::remove_dir_all(&dir)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Sets every loaded key to its loaded value in the current process
/// environment.
///
/// First runs [`validate`], so an environment it rejects changes nothing. Then
/// sets each key with [`std::env::set_var`], in sorted order. A loaded key
/// replaces a variable of the same name. Other variables are kept and nothing
/// is removed. Values are set as loaded, without expanding references such as
/// `${HOME}`. The changes cannot be rolled back.
///
/// Prefer passing [`LoadedEnvironment::values`] to a child process, or reading
/// the values directly, unless code you do not control reads the process
/// environment. See the [crate documentation](crate).
///
/// # Errors
///
/// Returns the [`ApplyError`] from [`validate`], before changing anything.
///
/// # Safety
///
/// No other thread may read or write the process environment while `apply`
/// runs. That includes [`std::env::var`] and C functions such as `getenv` and
/// `setenv` called by libraries. On some platforms such concurrent access is
/// undefined behavior. In practice, call `apply` at the start of `main`, before
/// starting threads or an async runtime.
///
/// # Examples
///
/// With `APP_PORT=8080` and `APP_HOST=0.0.0.0` in `.env`:
///
/// ```
/// use adotenv::load::load_cascade;
/// use adotenv_process::apply;
///
/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-apply-{}", std::process::id()));
/// # std::fs::create_dir_all(&dir)?;
/// # std::fs::write(dir.join(".env"), "APP_PORT=8080\nAPP_HOST=0.0.0.0\n")?;
/// let loaded = load_cascade(&dir, "")?;
///
/// // SAFETY: called at startup, before any other thread exists.
/// unsafe { apply(&loaded)? };
/// assert_eq!(std::env::var("APP_PORT")?, "8080");
/// assert_eq!(std::env::var("APP_HOST")?, "0.0.0.0");
/// # std::fs::remove_dir_all(&dir)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub unsafe