adotenv 0.9.7

A tooling-grade .env parser: literal values (no variable expansion), exact byte spans, and edits that leave the rest of the file untouched.
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
//! Opt-in filesystem loading of `.env` cascades.
//!
//! This module is compiled only with the `load` feature. It reads and validates
//! every participating file before returning any values, and performs no
//! process-environment mutation, expansion or command execution.
//!
//! The default cascade is `.env`, `.env.local`, `.env.{mode}` and
//! `.env.{mode}.local`, in that order. Later files override earlier files by
//! effective key.

use std::{
    collections::{BTreeMap, HashMap},
    fmt, fs, io,
    ops::Range,
    path::{Path, PathBuf},
    string::String,
    vec::Vec,
};

use crate::{
    encode_value, parse_strict, parse_strict_with, parse_with, Diagnostic, Dialect, ExpandOptions,
    ExpandScope, ResolveError, Severity,
};

/// A file, source span and one-based line identifying a loaded value.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct LoadOrigin {
    /// File path used for the load.
    pub path: PathBuf,
    /// Original value span in that file.
    pub span: Range<usize>,
    /// One-based source line.
    pub line: usize,
}

/// One effective declaration observed during a load.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadedEntry {
    /// Declaration key.
    pub key: String,
    /// Decoded literal value.
    pub value: String,
    /// Where the declaration came from.
    pub origin: LoadOrigin,
}

/// A later file overriding an earlier effective key.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadOverride {
    /// Overridden key.
    pub key: String,
    /// Earlier active value.
    pub previous: LoadOrigin,
    /// Later active value.
    pub replacement: LoadOrigin,
}

/// Duplicate declarations for one key within a single file.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadRepeated {
    /// Repeated key.
    pub key: String,
    /// All occurrences in source order.
    pub origins: Vec<LoadOrigin>,
}

/// Why a declaration was not loaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SkipReason {
    /// A key-only declaration has no literal value.
    Bare,
    /// The selected dialect excludes this declaration from lookup.
    NonParticipating,
    /// The declaration key is empty.
    EmptyKey,
}

/// A declaration that was retained in the report but not loaded.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadSkipped {
    /// Key, if one was available.
    pub key: Option<String>,
    /// File and position.
    pub origin: LoadOrigin,
    /// Why it was skipped.
    pub reason: SkipReason,
}

/// Fully validated result of a file load.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadedEnvironment {
    values: BTreeMap<String, String>,
    origins: BTreeMap<String, LoadOrigin>,
    raw_entries: BTreeMap<String, (usize, String, String)>,
    dialect: Dialect,
    entries: Vec<LoadedEntry>,
    overrides: Vec<LoadOverride>,
    repeated: Vec<LoadRepeated>,
    skipped: Vec<LoadSkipped>,
    raw_tokens: bool,
}

/// Retention policy for the full loader.
///
/// The default retains every report and the raw winning tokens required by
/// [`LoadedEnvironment::resolve_contextual`]. Applications that only need
/// values, or that never need contextual resolution, can opt out of the
/// corresponding allocations. Origins are always retained by this loader; use
/// [`crate::load::load_values`] when no origins are needed at all. Disabling
/// reports leaves [`LoadedEnvironment::entries`], [`LoadedEnvironment::overrides`],
/// [`LoadedEnvironment::repeated`] and [`LoadedEnvironment::skipped`] empty.
/// Disabling raw tokens makes [`LoadedEnvironment::resolve_contextual`] return an
/// error; decoded-value resolution remains available.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadOptions {
    /// Dialect used to parse every file.
    pub dialect: Dialect,
    /// Retain raw winning key/value tokens for contextual resolution.
    pub retain_raw_tokens: bool,
    /// Retain loaded-entry, override, repeat and skipped reports.
    pub retain_reports: bool,
}

impl Default for LoadOptions {
    fn default() -> Self {
        Self::new(Dialect::PORTABLE)
    }
}

impl LoadOptions {
    /// Full retention using the selected dialect.
    #[must_use]
    pub const fn new(dialect: Dialect) -> Self {
        Self {
            dialect,
            retain_raw_tokens: true,
            retain_reports: true,
        }
    }
    /// Select a different dialect.
    #[must_use]
    pub const fn with_dialect(mut self, dialect: Dialect) -> Self {
        self.dialect = dialect;
        self
    }
    /// Control retention of raw winning tokens.
    #[must_use]
    pub const fn with_raw_tokens(mut self, retain: bool) -> Self {
        self.retain_raw_tokens = retain;
        self
    }
    /// Control retention of report vectors.
    #[must_use]
    pub const fn with_reports(mut self, retain: bool) -> Self {
        self.retain_reports = retain;
        self
    }
}

impl LoadedEnvironment {
    /// Final effective literal values.
    #[must_use]
    pub fn values(&self) -> &BTreeMap<String, String> {
        &self.values
    }
    /// Whether raw winning tokens were retained for contextual resolution.
    #[must_use]
    pub const fn retains_raw_tokens(&self) -> bool {
        self.raw_tokens
    }
    /// Final value for one key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.values.get(key).map(String::as_str)
    }
    /// Final origin for one effective key.
    #[must_use]
    pub fn origin(&self, key: &str) -> Option<&LoadOrigin> {
        self.origins.get(key)
    }
    /// Every loaded declaration, including later-overridden entries.
    ///
    /// Empty when loaded with [`LoadOptions::with_reports`] set to `false`.
    #[must_use]
    pub fn entries(&self) -> &[LoadedEntry] {
        &self.entries
    }
    /// Cross-file overrides in load order.
    ///
    /// Empty when loaded with [`LoadOptions::with_reports`] set to `false`.
    #[must_use]
    pub fn overrides(&self) -> &[LoadOverride] {
        &self.overrides
    }
    /// Duplicate declarations within individual files.
    ///
    /// Empty when loaded with [`LoadOptions::with_reports`] set to `false`.
    #[must_use]
    pub fn repeated(&self) -> &[LoadRepeated] {
        &self.repeated
    }
    /// Declarations that were inspected but not loaded.
    ///
    /// Empty when loaded with [`LoadOptions::with_reports`] set to `false`.
    #[must_use]
    pub fn skipped(&self) -> &[LoadSkipped] {
        &self.skipped
    }
    /// Number of effective values.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }
    /// Whether no effective values were loaded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
}

/// A compact values-only result of loading one or more files.
///
/// This drops origins, raw winning tokens, skipped/repeated reports and
/// cross-file override reports. Use [`LoadedEnvironment`] when that provenance
/// or contextual resolution is required.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LoadedValues {
    values: BTreeMap<String, String>,
}

impl LoadedValues {
    /// Final effective literal values.
    #[must_use]
    pub fn values(&self) -> &BTreeMap<String, String> {
        &self.values
    }
    /// Final value for one key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.values.get(key).map(String::as_str)
    }
    /// Number of effective values.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }
    /// Whether no effective values were loaded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
    /// Consume the result and return its map.
    #[must_use]
    pub fn into_values(self) -> BTreeMap<String, String> {
        self.values
    }
}

impl LoadedEnvironment {
    /// Drop provenance and reports, retaining only final effective values.
    #[must_use]
    pub fn into_values(self) -> LoadedValues {
        LoadedValues {
            values: self.values,
        }
    }
}

/// A resolved decoded loaded environment.
///
/// Values have been processed by [`LoadedEnvironment::resolve_contextual`] or
/// [`LoadedEnvironment::resolve_decoded`]. Origins identify the winning
/// declaration that supplied the original value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedEnvironment {
    values: BTreeMap<String, String>,
    origins: BTreeMap<String, LoadOrigin>,
}

impl ResolvedEnvironment {
    /// Final resolved values.
    #[must_use]
    pub fn values(&self) -> &BTreeMap<String, String> {
        &self.values
    }
    /// One resolved value.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.values.get(key).map(String::as_str)
    }
    /// Origin of the winning declaration for one key.
    #[must_use]
    pub fn origin(&self, key: &str) -> Option<&LoadOrigin> {
        self.origins.get(key)
    }
    /// Number of resolved values.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }
    /// Whether no values remain.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
}

/// Failure from loaded-environment resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadedResolveError {
    key: Option<String>,
    origin: Option<LoadOrigin>,
    message: String,
}

impl LoadedResolveError {
    fn new(key: Option<String>, origin: Option<LoadOrigin>, message: impl Into<String>) -> Self {
        Self {
            key,
            origin,
            message: message.into(),
        }
    }
    /// Key being resolved when available.
    #[must_use]
    pub fn key(&self) -> Option<&str> {
        self.key.as_deref()
    }
    /// Origin of the winning declaration when available.
    #[must_use]
    pub fn origin(&self) -> Option<&LoadOrigin> {
        self.origin.as_ref()
    }
    /// Human-readable failure message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for LoadedResolveError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(origin) = &self.origin {
            write!(formatter, "{}:{}: ", origin.path.display(), origin.line)?;
        }
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for LoadedResolveError {}

impl LoadedEnvironment {
    /// Resolve variable references in the final decoded values.
    ///
    /// This is the explicit **decoded-value** policy: loaded values are treated
    /// as unquoted decoded text. Original quote, escape and source-line context
    /// is not retained by [`LoadedEnvironment`]; use [`crate::Document::resolve`]
    /// when context-aware resolution is required.
    ///
    /// Only [`ExpandScope::WholeFile`] is accepted. The synthetic resolution
    /// order is lexicographic by key, but whole-file bindings do not depend on
    /// order. Command substitutions remain literal unless the caller supplies a
    /// context-aware document callback.
    ///
    /// # Errors
    /// Returns [`LoadedResolveError`] for unsupported sequential scope, values
    /// that cannot be encoded, or resolution failures. The error retains the
    /// winning declaration origin when available.
    pub fn resolve_decoded<F>(
        &self,
        lookup: F,
        options: &ExpandOptions,
    ) -> Result<ResolvedEnvironment, LoadedResolveError>
    where
        F: Fn(&str) -> Option<String>,
    {
        if options.scope != ExpandScope::WholeFile {
            return Err(LoadedResolveError::new(
                None,
                None,
                "loaded environments require whole-file resolution scope",
            ));
        }
        let mut source = String::new();
        for (key, value) in &self.values {
            let token = encode_value(value).ok_or_else(|| {
                LoadedResolveError::new(
                    Some(key.clone()),
                    self.origin(key).cloned(),
                    "value cannot be represented exactly",
                )
            })?;
            source.push_str(key);
            source.push('=');
            source.push_str(&token);
            source.push('\n');
        }
        let document = parse_strict(&source).map_err(|error| {
            LoadedResolveError::new(None, None, format!("cannot prepare resolution: {error}"))
        })?;
        let mut options = *options;
        // The synthetic document must treat decoded text as unquoted text. Any
        // quoting introduced by the exact encoder must not change eligibility.
        options.rules.single_quotes = true;
        options.rules.backtick_quotes = true;
        options.rules.escaped_dollar = true;
        let resolved = document.resolve(lookup, &options).map_err(|error| {
            let key = resolve_error_key(&error).to_string();
            let origin = self.origin(&key).cloned();
            LoadedResolveError::new(Some(key), origin, error.to_string())
        })?;
        let mut values = BTreeMap::new();
        for entry in resolved.entries() {
            values.insert(entry.key.clone(), entry.value.clone().unwrap_or_default());
        }
        Ok(ResolvedEnvironment {
            values,
            origins: self.origins.clone(),
        })
    }

    /// Resolve references in final values using each winning declaration's
    /// original literal context.
    ///
    /// The winning key/value tokens are reconstructed in cascade order and
    /// parsed with the dialect used at load time. Quote, escape and bare-key
    /// context therefore match the source that won the cascade. The synthetic
    /// source has no original file offsets; errors retain the winning
    /// declaration's [`LoadOrigin`], key and message. It returns an error when
    /// the environment was loaded with raw-token retention disabled; use
    /// [`Self::resolve_decoded`] in that case.
    ///
    /// # Errors
    /// Returns [`LoadedResolveError`] if raw tokens were not retained, if the
    /// reconstructed source cannot be parsed, or if resolution fails.
    pub fn resolve_contextual<F>(
        &self,
        lookup: F,
        options: &ExpandOptions,
    ) -> Result<ResolvedEnvironment, LoadedResolveError>
    where
        F: Fn(&str) -> Option<String>,
    {
        if !self.raw_tokens {
            return Err(LoadedResolveError::new(
                None,
                None,
                "raw token context was not retained; load with raw tokens or use resolve_decoded",
            ));
        }
        let mut entries: Vec<_> = self.raw_entries.iter().collect();
        entries.sort_unstable_by_key(|(_, (order, _, _))| *order);
        let mut source = String::new();
        for (_, (_, raw_key, raw_value)) in entries {
            source.push_str(raw_key);
            source.push('=');
            source.push_str(raw_value);
            source.push('\n');
        }
        let document = parse_strict_with(&source, self.dialect).map_err(|error| {
            LoadedResolveError::new(None, None, format!("cannot prepare resolution: {error}"))
        })?;
        let resolved = document.resolve(lookup, options).map_err(|error| {
            let key = resolve_error_key(&error).to_string();
            let origin = self.origin(&key).cloned();
            LoadedResolveError::new(Some(key), origin, error.to_string())
        })?;
        let mut values = BTreeMap::new();
        for entry in resolved.entries() {
            values.insert(entry.key.clone(), entry.value.clone().unwrap_or_default());
        }
        Ok(ResolvedEnvironment {
            values,
            origins: self.origins.clone(),
        })
    }
}

fn resolve_error_key(error: &ResolveError) -> &str {
    match error {
        ResolveError::Unresolved { key, .. }
        | ResolveError::Required { key, .. }
        | ResolveError::Cycle { key, .. }
        | ResolveError::DepthExceeded { key, .. }
        | ResolveError::ValueTooLarge { key, .. }
        | ResolveError::Command { key, .. } => key,
    }
}

/// File loading failure.
#[derive(Debug)]
#[non_exhaustive]
pub enum LoadError {
    /// A file could not be read.
    Io {
        /// Path that failed.
        path: PathBuf,
        /// OS error.
        source: io::Error,
    },
    /// A file was not valid UTF-8.
    InvalidUtf8 {
        /// Path that failed.
        path: PathBuf,
    },
    /// A file contained a syntax or policy error.
    Invalid {
        /// Path that failed.
        path: PathBuf,
        /// First error in source order.
        diagnostic: Diagnostic,
    },
    /// A mode name could escape the cascade or is otherwise invalid.
    InvalidMode,
}

impl fmt::Display for LoadError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => {
                write!(formatter, "failed to read {}: {source}", path.display())
            }
            Self::InvalidUtf8 { path } => {
                write!(formatter, "{} is not valid UTF-8", path.display())
            }
            Self::Invalid { path, diagnostic } => {
                write!(formatter, "{}: {diagnostic}", path.display())
            }
            Self::InvalidMode => formatter.write_str("mode must not contain path separators"),
        }
    }
}

impl std::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// Load the standard `.env` cascade from `directory` using Portable syntax.
///
/// Missing cascade files are skipped. A file that exists but cannot be read,
/// decoded, or parsed invalidates the complete load.
///
/// # Errors
/// Returns [`LoadError`] for invalid mode names, I/O errors, invalid UTF-8 or
/// syntax/policy errors.
pub fn load_cascade<P: AsRef<Path>>(
    directory: P,
    mode: &str,
) -> Result<LoadedEnvironment, LoadError> {
    load_cascade_with(directory, mode, Dialect::PORTABLE)
}

/// Load the standard cascade with an explicit dialect.
///
/// # Errors
/// Returns [`LoadError`] for invalid mode names, I/O errors, invalid UTF-8 or
/// syntax/policy errors.
pub fn load_cascade_with<P: AsRef<Path>>(
    directory: P,
    mode: &str,
    dialect: Dialect,
) -> Result<LoadedEnvironment, LoadError> {
    load_cascade_with_options(directory, mode, LoadOptions::new(dialect))
}

/// Load the standard cascade with explicit retention options.
///
/// # Errors
/// Returns [`LoadError`] for invalid mode names, I/O errors, invalid UTF-8 or
/// syntax/policy errors.
pub fn load_cascade_with_options<P: AsRef<Path>>(
    directory: P,
    mode: &str,
    options: LoadOptions,
) -> Result<LoadedEnvironment, LoadError> {
    if !valid_mode(mode) {
        return Err(LoadError::InvalidMode);
    }
    let directory = directory.as_ref();
    let mut paths = vec![directory.join(".env"), directory.join(".env.local")];
    if !mode.is_empty() {
        paths.push(directory.join(format!(".env.{mode}")));
        paths.push(directory.join(format!(".env.{mode}.local")));
    }
    load_paths(paths, options, true)
}

/// Load an explicit ordered list of files, with later files overriding earlier
/// files by key.
///
/// Every listed file must exist. Use [`load_cascade`] for optional standard
/// filenames.
///
/// # Errors
/// Returns [`LoadError`] for I/O errors, invalid UTF-8 or syntax/policy errors.
pub fn load_files<I, P>(paths: I, dialect: Dialect) -> Result<LoadedEnvironment, LoadError>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    load_files_with_options(paths, LoadOptions::new(dialect))
}

/// Load an explicit ordered file list with explicit retention options.
///
/// # Errors
/// Returns [`LoadError`] for I/O errors, invalid UTF-8 or syntax/policy errors.
pub fn load_files_with_options<I, P>(
    paths: I,
    options: LoadOptions,
) -> Result<LoadedEnvironment, LoadError>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    load_paths(paths, options, false)
}

/// Load the standard cascade while retaining only final effective values.
///
/// This is the compact application-loading path. It applies the same strict
/// read/validate and override semantics as [`load_cascade`], then drops
/// origins, raw winning tokens and reports. Missing cascade files are skipped.
///
/// # Errors
/// Returns [`LoadError`] for invalid mode names, I/O errors, invalid UTF-8 or
/// syntax/policy errors.
pub fn load_cascade_values<P: AsRef<Path>>(
    directory: P,
    mode: &str,
) -> Result<LoadedValues, LoadError> {
    load_cascade_values_with(directory, mode, Dialect::PORTABLE)
}

/// Load the standard cascade with an explicit dialect, retaining only values.
///
/// # Errors
/// Returns [`LoadError`] for invalid mode names, I/O errors, invalid UTF-8 or
/// syntax/policy errors.
pub fn load_cascade_values_with<P: AsRef<Path>>(
    directory: P,
    mode: &str,
    dialect: Dialect,
) -> Result<LoadedValues, LoadError> {
    if !valid_mode(mode) {
        return Err(LoadError::InvalidMode);
    }
    let directory = directory.as_ref();
    let mut paths = vec![directory.join(".env"), directory.join(".env.local")];
    if !mode.is_empty() {
        paths.push(directory.join(format!(".env.{mode}")));
        paths.push(directory.join(format!(".env.{mode}.local")));
    }
    load_value_paths(paths, dialect, true)
}

/// Load an explicit ordered file list while retaining only final effective
/// values.
///
/// Every listed file must exist, and later files override earlier files by
/// key. Use [`load_cascade_values`] for optional standard filenames.
///
/// # Errors
/// Returns [`LoadError`] for I/O errors, invalid UTF-8 or syntax/policy errors.
pub fn load_values<I, P>(paths: I, dialect: Dialect) -> Result<LoadedValues, LoadError>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    load_value_paths(paths, dialect, false)
}

fn load_value_paths<I, P>(
    paths: I,
    dialect: Dialect,
    skip_missing: bool,
) -> Result<LoadedValues, LoadError>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let mut values = BTreeMap::new();
    for path in paths {
        let path = path.as_ref();
        let bytes = match fs::read(path) {
            Ok(bytes) => bytes,
            Err(error) if skip_missing && error.kind() == io::ErrorKind::NotFound => continue,
            Err(source) => {
                return Err(LoadError::Io {
                    path: path.to_path_buf(),
                    source,
                });
            }
        };
        let text = String::from_utf8(bytes).map_err(|_| LoadError::InvalidUtf8 {
            path: path.to_path_buf(),
        })?;
        let (document, diagnostics) = parse_with(&text, dialect);
        if let Some(diagnostic) = diagnostics
            .into_iter()
            .find(|diagnostic| diagnostic.severity() == Severity::Error)
        {
            return Err(LoadError::Invalid {
                path: path.to_path_buf(),
                diagnostic,
            });
        }
        for entry in document.effective_entries() {
            values.insert(entry.key().to_string(), entry.value().to_string());
        }
    }
    Ok(LoadedValues { values })
}

fn valid_mode(mode: &str) -> bool {
    !mode.contains(['/', '\\', '\0']) && mode != "." && mode != ".."
}

fn load_paths<I, P>(
    paths: I,
    options: LoadOptions,
    skip_missing: bool,
) -> Result<LoadedEnvironment, LoadError>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    let mut loaded = LoadedEnvironment {
        values: BTreeMap::new(),
        origins: BTreeMap::new(),
        raw_entries: BTreeMap::new(),
        dialect: options.dialect,
        entries: Vec::new(),
        overrides: Vec::new(),
        repeated: Vec::new(),
        skipped: Vec::new(),
        raw_tokens: options.retain_raw_tokens,
    };
    let mut next_order = 0;
    for path in paths {
        let path = path.as_ref();
        let bytes = match fs::read(path) {
            Ok(bytes) => bytes,
            Err(error) if skip_missing && error.kind() == io::ErrorKind::NotFound => continue,
            Err(source) => {
                return Err(LoadError::Io {
                    path: path.to_path_buf(),
                    source,
                });
            }
        };
        let text = String::from_utf8(bytes).map_err(|_| LoadError::InvalidUtf8 {
            path: path.to_path_buf(),
        })?;
        let (document, diagnostics) = parse_with(&text, options.dialect);
        if let Some(diagnostic) = diagnostics
            .into_iter()
            .find(|diagnostic| diagnostic.severity() == Severity::Error)
        {
            return Err(LoadError::Invalid {
                path: path.to_path_buf(),
                diagnostic,
            });
        }
        merge_document(&mut loaded, path, &document, options, &mut next_order);
    }
    Ok(loaded)
}

struct MergeState<'a> {
    loaded: &'a mut LoadedEnvironment,
    path: &'a Path,
    options: LoadOptions,
    next_order: usize,
}

fn merge_document(
    loaded: &mut LoadedEnvironment,
    path: &Path,
    document: &crate::Document<'_>,
    options: LoadOptions,
    next_order: &mut usize,
) {
    let mut state = MergeState {
        loaded,
        path,
        options,
        next_order: *next_order,
    };
    if options.retain_reports {
        merge_reported(&mut state, document);
    } else {
        merge_effective_entries(&mut state, document);
    }
    *next_order = state.next_order;
}

fn merge_effective_entries(state: &mut MergeState<'_>, document: &crate::Document<'_>) {
    for effective in document.effective_entries() {
        merge_effective(
            state,
            document,
            effective.key().to_string(),
            effective.value().to_string(),
            effective.entry(),
        );
    }
}

fn merge_reported(state: &mut MergeState<'_>, document: &crate::Document<'_>) {
    let mut first: HashMap<&str, crate::Entry<'_>> = HashMap::new();
    let mut duplicates: HashMap<&str, Vec<crate::Entry<'_>>> = HashMap::new();
    let mut keys = Vec::new();
    for entry in document.entries() {
        let key = entry.key();
        if let Some(previous) = first.get(key).copied() {
            duplicates
                .entry(key)
                .or_insert_with(|| vec![previous])
                .push(entry);
        } else {
            keys.push(key);
            first.insert(key, entry);
        }
    }

    for key in keys {
        let all: &[crate::Entry<'_>] = if let Some(all) = duplicates.get(key) {
            all
        } else {
            std::slice::from_ref(
                first
                    .get(key)
                    .expect("every key in the occurrence order map has an entry"),
            )
        };
        merge_reported_key(state, document, key, all);
    }
}

fn merge_reported_key(
    state: &mut MergeState<'_>,
    document: &crate::Document<'_>,
    key: &str,
    all: &[crate::Entry<'_>],
) {
    if key.is_empty() {
        for entry in all {
            state.loaded.skipped.push(LoadSkipped {
                key: None,
                origin: origin(state.path, *entry),
                reason: SkipReason::EmptyKey,
            });
        }
        return;
    }
    let mut first_participating = None;
    let mut last_participating = None;
    let mut participating_count = 0;
    for entry in all {
        if entry.participates_in_lookup() {
            if first_participating.is_none() {
                first_participating = Some(*entry);
            }
            last_participating = Some(*entry);
            participating_count += 1;
        }
    }
    if participating_count > 1 {
        state.loaded.repeated.push(LoadRepeated {
            key: key.to_string(),
            origins: all
                .iter()
                .filter(|entry| entry.participates_in_lookup())
                .map(|entry| origin(state.path, *entry))
                .collect(),
        });
    }
    let effective = match document.dialect().duplicates {
        crate::Duplicates::First => first_participating,
        crate::Duplicates::Last => last_participating,
    };
    let Some(effective) = effective else {
        state.loaded.skipped.push(LoadSkipped {
            key: Some(key.to_string()),
            origin: origin(state.path, all[0]),
            reason: SkipReason::NonParticipating,
        });
        return;
    };
    let value = if let Some(value) = effective.value() {
        value.to_string()
    } else if document.dialect().bare_keys == crate::BareKeys::Empty {
        String::new()
    } else {
        state.loaded.skipped.push(LoadSkipped {
            key: Some(key.to_string()),
            origin: origin(state.path, effective),
            reason: SkipReason::Bare,
        });
        return;
    };
    merge_effective(state, document, key.to_string(), value, effective);
}

fn merge_effective(
    state: &mut MergeState<'_>,
    document: &crate::Document<'_>,
    key: String,
    value: String,
    effective: crate::Entry<'_>,
) {
    let entry_origin = origin(state.path, effective);
    let order = state.next_order;
    state.next_order += 1;
    if state.options.retain_raw_tokens {
        let raw_key = &document.source()[effective.tokens().key.clone()];
        let raw_value = effective.raw_value().unwrap_or_default();
        state.loaded.raw_entries.insert(
            key.clone(),
            (order, raw_key.to_string(), raw_value.to_string()),
        );
    }
    let previous = state
        .loaded
        .origins
        .insert(key.clone(), entry_origin.clone());
    if state.options.retain_reports {
        state.loaded.entries.push(LoadedEntry {
            key: key.clone(),
            value: value.clone(),
            origin: entry_origin.clone(),
        });
        if let Some(previous) = previous {
            state.loaded.overrides.push(LoadOverride {
                key: key.clone(),
                previous,
                replacement: entry_origin,
            });
        }
    }
    state.loaded.values.insert(key, value);
}

fn origin(path: &Path, entry: crate::Entry<'_>) -> LoadOrigin {
    LoadOrigin {
        path: path.to_path_buf(),
        span: entry.value_span().unwrap_or_else(|| entry.key_span()),
        line: entry.line(),
    }
}