envro 0.13.0

A crate to load environment variables from a .env file into the process environment variables
Documentation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
use std::collections::HashMap;
use std::io;
use std::{env, fs, path::Path};

pub mod coerce;
mod validate;

#[cfg(feature = "encryption")]
mod crypto;

pub use coerce::Value;
pub use validate::{load_dotenv_validated, validate, validate_env, Field, Schema, ValidationIssue};

#[cfg(feature = "encryption")]
pub use crypto::{decrypt_value, encrypt_value};

pub use envro_derive::Envro;

/// Typed config loaded from env vars via `#[derive(Envro)]`.
///
/// The derive encodes field **types** and validation **rules** only; values are
/// always read at runtime from a map, a `.env` file, or the process environment.
pub trait EnvroConfig: Sized {
    /// Schema generated from field types and `#[envro(...)]` attributes.
    fn schema() -> Schema;

    /// Validate and coerce from an in-memory map.
    fn from_vars(vars: &EnvroVars) -> Result<Self, EnvroError>;

    /// Load a `.env` file, then [`from_vars`](Self::from_vars).
    ///
    /// With feature `encryption`, `#[envro(secret)]` fields must be `Encrypted[AGE:b64:…]`
    /// in the file (checked before decrypt via [`load_dotenv_validated`]).
    fn from_dotenv(path: &Path) -> Result<Self, EnvroError> {
        let vars = load_dotenv_validated(path, &Self::schema())?;
        Self::from_vars(&vars)
    }

    /// Read schema keys from the process environment, then coerce.
    fn from_env() -> Result<Self, EnvroError>;
}

#[derive(Debug, thiserror::Error)]
pub enum EnvroError {
    #[error("FILE_ERROR unable to read env file {file:?}: {source:?}")]
    File {
        #[source]
        source: io::Error,
        file: String,
    },
    #[error("PARSE_ERROR line {line:?} is not valid: {reason}")]
    Parse { line: String, reason: String },
    #[error("VALIDATION_ERROR {}", validate::format_issues(errors))]
    Validation { errors: Vec<ValidationIssue> },
    #[error("DECRYPT_ERROR key {key}: {reason}")]
    Decrypt { key: String, reason: String },
}

pub type EnvroVars = HashMap<String, String>;
/// Does `s` end with an unescaped `"`?
///
/// A trailing `"` counts as closing only when preceded by an even number of
/// backslashes (0, 2, ...). One `\` before the quote is `\"` (escaped);
/// two are `\\"` (escaped backslash + real closing quote).
fn line_closes_quote(s: &str) -> bool {
    if !s.ends_with('"') {
        return false;
    }
    let bytes = s.as_bytes();
    // Count consecutive backslashes immediately before the final '"'.
    let mut count = 0usize;
    if bytes.len() >= 2 {
        let mut i = bytes.len() - 2;
        loop {
            if bytes[i] == b'\\' {
                count += 1;
                if i == 0 {
                    break;
                }
                i -= 1;
            } else {
                break;
            }
        }
    }
    count.is_multiple_of(2)
}

fn is_var_name_start(c: u8) -> bool {
    c.is_ascii_alphabetic() || c == b'_'
}

fn is_var_name_continue(c: u8) -> bool {
    c.is_ascii_alphanumeric() || c == b'_'
}

/// Collect `${NAME}` refs in `s`, ignoring `\${`.
fn var_refs_in(s: &str) -> Vec<&str> {
    let bytes = s.as_bytes();
    let mut refs = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\\' && i + 2 < bytes.len() && bytes[i + 1] == b'$' && bytes[i + 2] == b'{'
        {
            i += 3;
            continue;
        }
        if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'{' {
            let name_start = i + 2;
            let mut j = name_start;
            while j < bytes.len() && bytes[j] != b'}' {
                j += 1;
            }
            if j < bytes.len() {
                let name = &s[name_start..j];
                if !name.is_empty()
                    && is_var_name_start(name.as_bytes()[0])
                    && name.as_bytes()[1..]
                        .iter()
                        .copied()
                        .all(is_var_name_continue)
                {
                    refs.push(name);
                }
                i = j + 1;
                continue;
            }
        }
        i += 1;
    }
    refs
}

fn expand_value(raw_val: &str, known: &EnvroVars) -> String {
    if !raw_val.as_bytes().contains(&b'$') {
        raw_val.to_owned()
    } else {
        substitute_vars(raw_val, known)
    }
}

/// Expand `${VAR}` using `known` file vars, then process env.
///
/// - Bare `$` is always literal
/// - `\${` → literal `${` (skip replacement)
/// - Known key → its value; missing → `""`
/// - Name must match `[A-Za-z_][A-Za-z0-9_]*`
fn substitute_vars(input: &str, known: &EnvroVars) -> String {
    let bytes = input.as_bytes();
    let mut out = String::with_capacity(input.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\\' && i + 2 < bytes.len() && bytes[i + 1] == b'$' && bytes[i + 2] == b'{'
        {
            out.push_str("${");
            i += 3;
            continue;
        }

        if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'{' {
            let name_start = i + 2;
            let mut j = name_start;
            while j < bytes.len() && bytes[j] != b'}' {
                j += 1;
            }
            if j >= bytes.len() {
                out.push_str(&input[i..]);
                break;
            }
            let name = &input[name_start..j];
            let name_ok = !name.is_empty()
                && is_var_name_start(name.as_bytes()[0])
                && name.as_bytes()[1..]
                    .iter()
                    .copied()
                    .all(is_var_name_continue);
            if name_ok {
                if let Some(val) = known.get(name) {
                    out.push_str(val);
                } else if let Ok(val) = env::var(name) {
                    out.push_str(&val);
                }
                // else: unknown → empty
            }
            // Invalid / empty `${}` → empty (same as unknown).
            // Use `\${` to keep a literal `${`.
            i = j + 1;
        } else {
            // Bulk-copy UTF-8 until the next `$` or `\`.
            let start = i;
            i += 1;
            while i < bytes.len() && bytes[i] != b'$' && bytes[i] != b'\\' {
                i += 1;
            }
            out.push_str(&input[start..i]);
        }
    }
    out
}

/// Expand `${VAR}` refs across a map, order-independent.
///
/// Each value is substituted only once all of its in-map dependencies are
/// resolved (topological order). Refs that don't name a key in `raw` fall
/// back to the process environment; anything still missing — including
/// cycles — expands to `""`.
///
/// Used by [`load_dotenv`] after parsing, and by derive-generated
/// `from_env` implementations before validation.
pub fn expand_vars(raw: &EnvroVars) -> EnvroVars {
    let mut resolved = EnvroVars::with_capacity(raw.len());
    let mut indegree: HashMap<&str, usize> = HashMap::with_capacity(raw.len());
    let mut dependents: HashMap<&str, Vec<&str>> = HashMap::new();

    for (key, raw_val) in raw {
        let mut file_deps: Vec<&str> = var_refs_in(raw_val)
            .into_iter()
            .filter(|r| raw.contains_key(*r))
            .collect();
        file_deps.sort_unstable();
        file_deps.dedup();
        indegree.insert(key.as_str(), file_deps.len());
        for dep in file_deps {
            dependents.entry(dep).or_default().push(key.as_str());
        }
    }

    let mut queue: Vec<&str> = indegree
        .iter()
        .filter(|(_, deg)| **deg == 0)
        .map(|(k, _)| *k)
        .collect();

    while let Some(key) = queue.pop() {
        let raw_val = raw.get(key).expect("key from raw");
        resolved.insert(key.to_string(), expand_value(raw_val, &resolved));
        if let Some(deps) = dependents.get(key) {
            for &dep in deps {
                let deg = indegree.get_mut(dep).expect("indegree for dependent");
                *deg -= 1;
                if *deg == 0 {
                    queue.push(dep);
                }
            }
        }
    }

    if resolved.len() < raw.len() {
        // Cycles: expand against a snapshot that omits still-pending keys
        // so refs into the cycle become empty.
        let frozen = resolved.clone();
        for (key, raw_val) in raw {
            if !resolved.contains_key(key) {
                resolved.insert(key.clone(), expand_value(raw_val, &frozen));
            }
        }
    }

    resolved
}

/// Parse a `.env` file into a raw map (no decrypt, no `${VAR}` expand).
pub(crate) fn parse_dotenv(file_name: &Path) -> Result<EnvroVars, EnvroError> {
    let file_content = match fs::read_to_string(file_name) {
        Ok(c) => c,
        Err(err) => {
            return Err(EnvroError::File {
                source: err,
                file: String::from(file_name.to_str().unwrap_or("unknown file name")),
            })
        }
    };

    // Split on '\n' so we can advance the index across multi-line quoted values.
    let raw_lines: Vec<&str> = file_content.split('\n').collect();
    let mut vars = EnvroVars::with_capacity(raw_lines.len());
    let mut i = 0;
    while i < raw_lines.len() {
        // Strip a trailing '\r' so CRLF files parse identically to LF.
        let raw = raw_lines[i].strip_suffix('\r').unwrap_or(raw_lines[i]);
        let line = raw.trim();

        if line.is_empty() || line.starts_with('#') {
            i += 1;
        } else {
            let eq_idx = line.find('=').ok_or_else(|| EnvroError::Parse {
                line: String::from(line),
                reason: "missing value".to_string(),
            })?;

            let key = line[..eq_idx].trim_end();
            if key.is_empty() {
                return Err(EnvroError::Parse {
                    line: String::from(line),
                    reason: "missing variable name".to_string(),
                });
            }

            // env::set_var panics on NUL in the key.
            if key.contains('\0') {
                return Err(EnvroError::Parse {
                    line: String::from(line),
                    reason: "variable name contains NUL byte".to_string(),
                });
            }

            let after_eq = line[eq_idx + 1..].trim_start();
            let mut value = String::from(after_eq);
            let var = String::from(key);

            // Quoted values may span multiple lines. If the first line opens a
            // quote but does not close it, we accumulate subsequent lines with
            // '\n' between them until we find a line ending with the closing
            // quote. Single-line quoted values behave exactly as before.
            if value.starts_with('"') {
                let single_line_closed = value.len() >= 2 && line_closes_quote(&value);
                if single_line_closed {
                    let inner = &value[1..value.len() - 1];
                    value = if inner.contains("\\\"") {
                        inner.replace("\\\"", "\"")
                    } else {
                        inner.to_owned()
                    };
                } else {
                    let mut buf = String::from(&value[1..]);
                    let mut closed = false;
                    i += 1;
                    while i < raw_lines.len() {
                        let next = raw_lines[i].strip_suffix('\r').unwrap_or(raw_lines[i]);
                        buf.push('\n');
                        if line_closes_quote(next) {
                            buf.push_str(&next[..next.len() - 1]);
                            closed = true;
                            break;
                        }
                        buf.push_str(next);
                        i += 1;
                    }
                    if !closed {
                        return Err(EnvroError::Parse {
                            line: String::from(line),
                            reason: "missing closing quote".to_string(),
                        });
                    }
                    value = if buf.contains("\\\"") {
                        buf.replace("\\\"", "\"")
                    } else {
                        buf
                    };
                }
            }

            if value.contains('\0') {
                return Err(EnvroError::Parse {
                    line: String::from(line),
                    reason: "value contains NUL byte".to_string(),
                });
            }

            // Reject duplicate variable names in the same file.
            if vars.contains_key(&var) {
                return Err(EnvroError::Parse {
                    line: String::from(line),
                    reason: format!("duplicate variable name: {}", var),
                });
            }

            // Store raw values first; `${VAR}` is resolved after the whole file
            // is parsed so definition order does not matter.
            vars.insert(var, value);
            i += 1;
        }
    }

    Ok(vars)
}

/// Decrypt (feature `encryption`) or reject ciphertext, then expand `${VAR}`.
pub(crate) fn finalize_dotenv(vars: EnvroVars) -> Result<EnvroVars, EnvroError> {
    #[cfg(feature = "encryption")]
    let vars = crypto::decrypt_dotenv_vars(vars)?;
    #[cfg(not(feature = "encryption"))]
    {
        for (key, value) in &vars {
            if value.starts_with("Encrypted[AGE:b64:") && value.ends_with(']') {
                return Err(EnvroError::Decrypt {
                    key: key.clone(),
                    reason: "Encrypted[…] value requires envro feature `encryption`".into(),
                });
            }
        }
    }
    Ok(expand_vars(&vars))
}

/// load .env file into process.env var
///
/// # Examples
///
/// ```
/// use std::env;
/// use envro::*;
///
/// let env_file = env::current_dir().unwrap().join(".env-sample");
/// let env_vars = load_dotenv(&env_file).unwrap();
/// ```
pub fn load_dotenv(file_name: &Path) -> Result<EnvroVars, EnvroError> {
    finalize_dotenv(parse_dotenv(file_name)?)
}

/// Load vars from an env file into process environment variables.
///
/// When `override_existing` is `false`, existing non-empty process values are kept;
/// unset or empty values are filled from the file. When `true`, file values always win.
///
/// # Examples
///
/// ```
/// use std::env;
/// use envro::*;
///
/// let env_file = env::current_dir().unwrap().join(".env-sample");
/// load_dotenv_in_env_vars(&env_file, false).unwrap();
/// ```
pub fn load_dotenv_in_env_vars(
    file_name: &Path,
    override_existing: bool,
) -> Result<(), EnvroError> {
    let vars = load_dotenv(file_name)?;

    for (key, value) in vars {
        if !override_existing {
            if let Ok(current) = env::var(&key) {
                if !current.is_empty() {
                    continue;
                }
            }
        }

        env::set_var(key, value);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{env, fs, fs::File, io::Write};

    use super::*;
    use serial_test::serial;

    #[test]
    #[serial]
    fn should_load_a_simple_dotenv_file() {
        let file_name = env::temp_dir().join(".env-simple");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR=value").unwrap();
        env::remove_var("VAR");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR"), Ok("value".to_string()));
    }

    #[cfg(not(feature = "encryption"))]
    #[test]
    fn rejects_encrypted_marker_without_age_feature() {
        let dir = env::temp_dir().join(format!(
            "envro-no-age-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(".env");
        fs::write(&path, "SECRET=Encrypted[AGE:b64:dGVzdA==]\n").unwrap();
        let err = load_dotenv(&path).unwrap_err();
        assert!(
            matches!(err, EnvroError::Decrypt { .. }),
            "expected Decrypt, got {err}"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    #[serial]
    fn should_handle_error_on_non_existing_dotenv_file() {
        let r = load_dotenv(Path::new("none"));
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(
                r#"FILE_ERROR unable to read env file "none": Os { code: 2, kind: NotFound, message: "No such file or directory" }"#
            )
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    #[serial]
    fn should_handle_error_on_non_existing_dotenv_file_on_win() {
        let r = load_dotenv(Path::new("none"));
        let err = r.unwrap_err();

        assert!(err.to_string().starts_with(
            r#"FILE_ERROR unable to read env file "none": Os { code: 2, kind: NotFound"#
        ));
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    #[serial]
    fn should_handle_error_on_non_existing_dotenv_file_name_empty() {
        let r = load_dotenv(Path::new(""));
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(
                r#"FILE_ERROR unable to read env file "": Os { code: 2, kind: NotFound, message: "No such file or directory" }"#
            )
        );
    }

    #[test]
    #[serial]
    fn should_handle_error_on_invalid_dotenv_line() {
        let file_name = env::temp_dir().join(".env-invalid-line");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR value").unwrap();

        let r = load_dotenv(file_name.as_path());
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(r#"PARSE_ERROR line "VAR value" is not valid: missing value"#)
        );
    }

    #[test]
    #[serial]
    fn should_handle_error_on_invalid_dotenv_var() {
        let file_name = env::temp_dir().join(".env-invalid-var");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"=value").unwrap();

        let r = load_dotenv(file_name.as_path());
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(r#"PARSE_ERROR line "=value" is not valid: missing variable name"#)
        );
    }

    #[test]
    #[serial]
    fn should_handle_empty_values() {
        let file_name = env::temp_dir().join(".env-empty-value");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR=\nVAR2=\"\"\nVAR3=value").unwrap();
        env::remove_var("VAR");
        env::remove_var("VAR2");
        env::remove_var("VAR3");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR"), Ok("".to_string()));
        assert_eq!(env::var("VAR2"), Ok("".to_string()));
        assert_eq!(env::var("VAR3"), Ok("value".to_string()));
    }

    #[test]
    #[serial]
    fn should_handle_empty_lines() {
        let file_name = env::temp_dir().join(".env-empty-lines");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"\nVAR=1\nVAR1=asd").unwrap();
        env::remove_var("VAR");
        env::remove_var("VAR1");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR"), Ok("1".to_string()));
        assert_eq!(env::var("VAR1"), Ok("asd".to_string()));
    }

    #[test]
    #[serial]
    fn should_handle_comment_lines() {
        let file_name = env::temp_dir().join(".env-empty-lines");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"\nVAR=1\n#VAR1=asd").unwrap();
        env::remove_var("VAR");
        env::remove_var("VAR1");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR"), Ok("1".to_string()));
        assert_eq!(env::var("VAR1"), Err(env::VarError::NotPresent));
    }

    #[test]
    #[serial]
    fn should_handle_quoted_values() {
        let file_name = env::temp_dir().join(".env-quoted");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(
            b"\nVAR1=\"1\"\nVAR2=\"Lorem ipsum \"ciao!\" \"\nVAR3=\"say \\\"hello\\\"\"",
        )
        .unwrap();
        env::remove_var("VAR1");
        env::remove_var("VAR2");
        env::remove_var("VAR3");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR1"), Ok("1".to_string()));
        assert_eq!(env::var("VAR2"), Ok("Lorem ipsum \"ciao!\" ".to_string()));
        assert_eq!(env::var("VAR3"), Ok("say \"hello\"".to_string()));
    }

    #[test]
    #[serial]
    fn should_handle_quoted_values_containg_equals() {
        let file_name = env::temp_dir().join(".env-quoted-equals");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(
            b"\nVAR1=\"1\"\nVAR2=\"host=localhost user=admin password=secret dbname=mydb\"",
        )
        .unwrap();
        env::remove_var("VAR1");
        env::remove_var("VAR2");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR1"), Ok("1".to_string()));
        assert_eq!(
            env::var("VAR2"),
            Ok("host=localhost user=admin password=secret dbname=mydb".to_string())
        );
    }

    #[test]
    #[serial]
    fn should_handle_invalid_quoted_values() {
        let file_name = env::temp_dir().join(".env-invalid-quoted");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(
            b"\nVAR1=\"1\"\nVAR2=\"host=localhost user=admin password=secret dbname=mydb",
        )
        .unwrap();
        env::remove_var("VAR1");
        env::remove_var("VAR2");

        let r = load_dotenv(file_name.as_path());
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(
                r#"PARSE_ERROR line "VAR2=\"host=localhost user=admin password=secret dbname=mydb" is not valid: missing closing quote"#
            )
        );
    }

    #[test]
    #[serial]
    fn should_not_ovveride_env_vars() {
        env::remove_var("VAR1");
        env::remove_var("VAR2");
        env::remove_var("VAR3");

        let file_name = env::temp_dir().join(".env-not-override");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"\nVAR1=\"value1\"\nVAR2=2\nVAR3=3")
            .unwrap();

        env::set_var("VAR1", "current-value");

        load_dotenv_in_env_vars(file_name.as_path(), false).unwrap();

        assert_eq!(env::var("VAR1"), Ok("current-value".to_string()));
        assert_eq!(env::var("VAR2"), Ok("2".to_string()));
        assert_eq!(env::var("VAR3"), Ok("3".to_string()));
    }

    #[test]
    #[serial]
    fn should_detect_duplicate_variable_names() {
        let file_name = env::temp_dir().join(".env-duplicate");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR1=value1\nVAR2=value2\nVAR1=value3")
            .unwrap();

        let r = load_dotenv(file_name.as_path());
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(
                r#"PARSE_ERROR line "VAR1=value3" is not valid: duplicate variable name: VAR1"#
            )
        );
    }

    #[test]
    #[serial]
    fn should_override_env_vars_when_enabled() {
        env::remove_var("VAR1");
        env::remove_var("VAR2");

        let file_name = env::temp_dir().join(".env-override");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR1=from-file\nVAR2=2").unwrap();

        env::set_var("VAR1", "current-value");

        load_dotenv_in_env_vars(file_name.as_path(), true).unwrap();

        assert_eq!(env::var("VAR1"), Ok("from-file".to_string()));
        assert_eq!(env::var("VAR2"), Ok("2".to_string()));
    }

    #[test]
    #[serial]
    fn should_substitute_braced_vars_from_file_and_env() {
        env::remove_var("ENVRO_TEST_FROM_ENV");
        env::set_var("ENVRO_TEST_FROM_ENV", "from-env");

        let file_name = env::temp_dir().join(".env-dollar-sub");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(
            b"HOST=example.com\n\
BARE=$HOST\n\
BRACE=${HOST}\n\
MIXED=prefix-${HOST}-suffix\n\
QUOTED=\"url://${HOST}/path\"\n\
FROM_ENV=${ENVRO_TEST_FROM_ENV}\n\
ESCAPED=\\${HOST}\n\
UNKNOWN=${DOES_NOT_EXIST}",
        )
        .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        // Bare $HOST is never expanded — `$` is a normal character.
        assert_eq!(vars.get("BARE").map(String::as_str), Some("$HOST"));
        assert_eq!(vars.get("BRACE").map(String::as_str), Some("example.com"));
        assert_eq!(
            vars.get("MIXED").map(String::as_str),
            Some("prefix-example.com-suffix")
        );
        assert_eq!(
            vars.get("QUOTED").map(String::as_str),
            Some("url://example.com/path")
        );
        assert_eq!(vars.get("FROM_ENV").map(String::as_str), Some("from-env"));
        // `\${HOST}` skips replacement → literal `${HOST}`
        assert_eq!(vars.get("ESCAPED").map(String::as_str), Some("${HOST}"));
        // Unknown `${VAR}` → empty string
        assert_eq!(vars.get("UNKNOWN").map(String::as_str), Some(""));

        env::remove_var("ENVRO_TEST_FROM_ENV");
    }

    #[test]
    #[serial]
    fn should_treat_empty_braces_as_empty_unless_escaped() {
        let file_name = env::temp_dir().join(".env-dollar-empty-braces");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(
            b"EMPTY=${}\n\
AROUND=pre${}post\n\
ESCAPED=\\${}\n\
ESCAPED_AROUND=pre\\${}post\n\
INVALID=${123}\n\
INVALID_NAME=${bad-name}",
        )
        .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        // `${}` → empty
        assert_eq!(vars.get("EMPTY").map(String::as_str), Some(""));
        assert_eq!(vars.get("AROUND").map(String::as_str), Some("prepost"));
        // `\${}` → no replace
        assert_eq!(vars.get("ESCAPED").map(String::as_str), Some("${}"));
        assert_eq!(
            vars.get("ESCAPED_AROUND").map(String::as_str),
            Some("pre${}post")
        );
        // invalid braces also → empty
        assert_eq!(vars.get("INVALID").map(String::as_str), Some(""));
        assert_eq!(vars.get("INVALID_NAME").map(String::as_str), Some(""));
    }

    #[test]
    #[serial]
    fn should_keep_unclosed_brace_ref_literal() {
        let file_name = env::temp_dir().join(".env-dollar-unclosed");
        let mut file = File::create(&file_name).unwrap();
        // No closing `}` — the `${HOST` tail is kept literal.
        file.write_all(b"A=pre${HOST\nB=ok").unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(vars.get("A").map(String::as_str), Some("pre${HOST"));
        assert_eq!(vars.get("B").map(String::as_str), Some("ok"));
    }

    #[test]
    #[serial]
    fn should_keep_bare_dollar_signs_literal() {
        let file_name = env::temp_dir().join(".env-dollar-literal");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(
            b"HOST=example.com\n\
PASSWORD_HASH=$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy\n\
REF=$HOST\n\
QUOTED=\"cost=$2a$10$abc\"\n\
DOLLAR_ONLY=$\n\
DIGIT=$1",
        )
        .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(
            vars.get("PASSWORD_HASH").map(String::as_str),
            Some("$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy")
        );
        assert_eq!(vars.get("REF").map(String::as_str), Some("$HOST"));
        assert_eq!(
            vars.get("QUOTED").map(String::as_str),
            Some("cost=$2a$10$abc")
        );
        assert_eq!(vars.get("DOLLAR_ONLY").map(String::as_str), Some("$"));
        assert_eq!(vars.get("DIGIT").map(String::as_str), Some("$1"));
    }

    #[test]
    #[serial]
    fn should_resolve_vars_regardless_of_order() {
        let file_name = env::temp_dir().join(".env-dollar-order");
        let mut file = File::create(&file_name).unwrap();
        // A references B before B is defined — must still expand.
        file.write_all(b"A=abc${B}\nB=123").unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(vars.get("A").map(String::as_str), Some("abc123"));
        assert_eq!(vars.get("B").map(String::as_str), Some("123"));
    }

    #[test]
    #[serial]
    fn should_resolve_forward_and_chained_references() {
        let file_name = env::temp_dir().join(".env-dollar-chain");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"A=${B}${C}\nB=${C}\nC=x").unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(vars.get("A").map(String::as_str), Some("xx"));
        assert_eq!(vars.get("B").map(String::as_str), Some("x"));
        assert_eq!(vars.get("C").map(String::as_str), Some("x"));
    }

    #[test]
    #[serial]
    fn should_resolve_cycles_to_empty() {
        let file_name = env::temp_dir().join(".env-dollar-cycle");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"A=${B}\nB=${A}").unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(vars.get("A").map(String::as_str), Some(""));
        assert_eq!(vars.get("B").map(String::as_str), Some(""));
    }

    #[test]
    #[serial]
    fn should_reject_lone_opening_quote_without_panic() {
        let file_name = env::temp_dir().join(".env-lone-quote");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR=\"").unwrap();

        let err = load_dotenv(file_name.as_path()).unwrap_err();
        assert!(
            err.to_string().contains("missing closing quote"),
            "got: {err}"
        );
    }

    #[test]
    #[serial]
    fn should_reject_nul_in_value() {
        let file_name = env::temp_dir().join(".env-nul-value");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VAR=a\0b").unwrap();

        let err = load_dotenv(file_name.as_path()).unwrap_err();
        assert!(
            err.to_string().contains("value contains NUL byte"),
            "got: {err}"
        );
    }

    #[test]
    #[serial]
    fn should_reject_nul_in_key() {
        let file_name = env::temp_dir().join(".env-nul-key");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"VA\0R=ok").unwrap();

        let err = load_dotenv(file_name.as_path()).unwrap_err();
        assert!(
            err.to_string().contains("variable name contains NUL byte"),
            "got: {err}"
        );
    }
    #[test]
    #[serial]
    fn should_load_multiline_quoted_value() {
        let file_name = env::temp_dir().join(".env-multiline");
        let mut file = File::create(&file_name).unwrap();
        // KEY spans three physical lines; newlines are preserved in the value.
        file.write_all(
            b"BEFORE=before\n\
KEY=\"line1\n\
line2\n\
line3\"\n\
AFTER=after",
        )
        .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(vars.get("BEFORE").map(String::as_str), Some("before"));
        assert_eq!(
            vars.get("KEY").map(String::as_str),
            Some("line1\nline2\nline3")
        );
        assert_eq!(vars.get("AFTER").map(String::as_str), Some("after"));
    }

    #[test]
    #[serial]
    fn should_preserve_blank_and_special_lines_inside_multiline_quote() {
        let file_name = env::temp_dir().join(".env-multiline-mixed");
        let mut file = File::create(&file_name).unwrap();
        // Blank lines and lines starting with `#` inside the quotes are part
        // of the value, not comments/skips.
        file.write_all(
            b"BLOB=\"line1\n\
\n\
# not a comment\n\
line=with=equals\n\
line4\"",
        )
        .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(
            vars.get("BLOB").map(String::as_str),
            Some("line1\n\n# not a comment\nline=with=equals\nline4")
        );
    }

    #[test]
    fn should_close_multiline_quote_when_closing_line_is_only_backslashes() {
        let dir = env::temp_dir().join(format!(
            "envro-bs-close-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(".env");
        // Closing line is `\\"` (two backslashes + quote) — hits i==0 in line_closes_quote.
        fs::write(&path, "MSG=\"hi\n\\\\\"").unwrap();
        let vars = load_dotenv(&path).unwrap();
        assert_eq!(vars.get("MSG").map(String::as_str), Some("hi\n\\\\"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    #[serial]
    fn should_support_escaped_quote_inside_multiline_value() {
        let file_name = env::temp_dir().join(".env-multiline-escape");
        let mut file = File::create(&file_name).unwrap();
        // \" escapes an inner quote, even across lines.
        file.write_all(
            b"MSG=\"first\n\
second \\\"hello\\\"\n\
third\"",
        )
        .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(
            vars.get("MSG").map(String::as_str),
            Some("first\nsecond \"hello\"\nthird")
        );
    }

    #[test]
    #[serial]
    fn should_reject_unclosed_multiline_quote() {
        let file_name = env::temp_dir().join(".env-multiline-unclosed");
        let mut file = File::create(&file_name).unwrap();
        // Opens on VAR2, never closes.
        file.write_all(b"VAR1=1\nVAR2=\"start\nmiddle\nno close")
            .unwrap();

        let r = load_dotenv(file_name.as_path());
        let err = r.unwrap_err();

        assert_eq!(
            err.to_string(),
            String::from(r#"PARSE_ERROR line "VAR2=\"start" is not valid: missing closing quote"#)
        );
    }

    #[test]
    #[serial]
    fn should_handle_crlf_line_endings_including_multiline() {
        let file_name = env::temp_dir().join(".env-crlf-multiline");
        let mut file = File::create(&file_name).unwrap();
        file.write_all(b"A=1\r\nB=\"one\r\ntwo\"\r\nC=3\r\n")
            .unwrap();

        let vars = load_dotenv(file_name.as_path()).unwrap();

        assert_eq!(vars.get("A").map(String::as_str), Some("1"));
        assert_eq!(vars.get("B").map(String::as_str), Some("one\ntwo"));
        assert_eq!(vars.get("C").map(String::as_str), Some("3"));
    }
}