tarn 0.11.4

CLI-first API testing tool
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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
use crate::config::NamedEnvironmentConfig;
use crate::error::TarnError;
use crate::model::Location;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use yaml_rust2::parser::{Event, MarkedEventReceiver, Parser};
use yaml_rust2::scanner::Marker;

/// Origin of a resolved environment variable. Mirrors the layers applied in
/// [`resolve_env_with_profiles`] so editors and LSP clients can surface
/// *where* a value came from in hover tooltips.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnvSource {
    /// From the inline `env:` block in the test file itself.
    InlineEnvBlock,
    /// From the default `tarn.env.yaml` (or a caller-configured equivalent).
    DefaultEnvFile {
        /// Display path of the env file that supplied the value.
        path: String,
    },
    /// From the `tarn.env.{name}.yaml` file for a named environment.
    NamedEnvFile {
        /// Display path of the env file that supplied the value.
        path: String,
        /// Name of the active environment (e.g. "staging").
        env_name: String,
    },
    /// From a `NamedEnvironmentConfig.vars` entry declared in `tarn.config.yaml`.
    NamedProfileVars {
        /// Name of the active environment profile.
        env_name: String,
    },
    /// From the `tarn.env.local.yaml` file (gitignored, secrets).
    LocalEnvFile {
        /// Display path of the local env file that supplied the value.
        path: String,
    },
    /// From a `--var KEY=VALUE` CLI override.
    CliVar,
}

impl EnvSource {
    /// Short human-readable label for this source. Stable — do not rename
    /// without bumping the LSP hover tests.
    pub fn label(&self) -> &str {
        match self {
            EnvSource::InlineEnvBlock => "inline env: block",
            EnvSource::DefaultEnvFile { .. } => "default env file",
            EnvSource::NamedEnvFile { .. } => "named env file",
            EnvSource::NamedProfileVars { .. } => "named profile vars",
            EnvSource::LocalEnvFile { .. } => "local env file",
            EnvSource::CliVar => "CLI --var",
        }
    }

    /// Display path of the file that supplied the value, if any. Returns
    /// `None` for sources that are not backed by a file on disk (inline,
    /// CLI overrides).
    pub fn source_file(&self) -> Option<&str> {
        match self {
            EnvSource::DefaultEnvFile { path }
            | EnvSource::NamedEnvFile { path, .. }
            | EnvSource::LocalEnvFile { path } => Some(path.as_str()),
            _ => None,
        }
    }
}

/// One resolved environment variable plus the layer that supplied it.
/// Returned by [`resolve_env_with_sources`] so LSP hovers can show the
/// effective value *and* where it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvEntry {
    /// Final effective value after shell-variable expansion.
    pub value: String,
    /// The winning layer for this key.
    pub source: EnvSource,
    /// Best-effort source location of the key that supplied this value,
    /// if the layer is backed by a YAML file we could scan (inline env
    /// block, default env file, named env file, local env file). `None`
    /// for CLI `--var`, shell expansion, and named profile vars — those
    /// layers do not live in a YAML file we can point an LSP jump at.
    ///
    /// Added in NAZ-297 so `textDocument/definition` can return the
    /// declaration site of an env key. Existing callers (hover, etc.)
    /// ignore this field, so it is optional and populated best-effort.
    pub declaration_range: Option<Location>,
}

/// Resolve environment variables with the priority chain:
/// CLI --var > shell env ${VAR} > tarn.env.local.yaml > tarn.env.{name}.yaml > tarn.env.yaml > inline env: block
pub fn resolve_env(
    inline_env: &HashMap<String, String>,
    env_name: Option<&str>,
    cli_vars: &[(String, String)],
    base_dir: &Path,
) -> Result<HashMap<String, String>, TarnError> {
    resolve_env_with_profiles(
        inline_env,
        env_name,
        cli_vars,
        base_dir,
        "tarn.env.yaml",
        &HashMap::new(),
    )
}

/// Resolve environment variables using a configurable env file name.
pub fn resolve_env_with_file(
    inline_env: &HashMap<String, String>,
    env_name: Option<&str>,
    cli_vars: &[(String, String)],
    base_dir: &Path,
    env_file_name: &str,
) -> Result<HashMap<String, String>, TarnError> {
    resolve_env_with_profiles(
        inline_env,
        env_name,
        cli_vars,
        base_dir,
        env_file_name,
        &HashMap::new(),
    )
}

/// Resolve environment variables using a configurable env file name and named profiles.
pub fn resolve_env_with_profiles(
    inline_env: &HashMap<String, String>,
    env_name: Option<&str>,
    cli_vars: &[(String, String)],
    base_dir: &Path,
    env_file_name: &str,
    profiles: &HashMap<String, NamedEnvironmentConfig>,
) -> Result<HashMap<String, String>, TarnError> {
    let mut env = HashMap::new();

    // Layer 1 (lowest): inline env: block from test file
    for (k, v) in inline_env {
        env.insert(k.clone(), v.clone());
    }

    // Layer 2: tarn.env.yaml (default env file)
    let default_env_file = base_dir.join(env_file_name);
    if default_env_file.exists() {
        let file_env = load_env_file(&default_env_file)?;
        for (k, v) in file_env {
            env.insert(k, v);
        }
    }

    // Layer 3: tarn.env.{name}.yaml (environment-specific)
    if let Some(name) = env_name {
        let named_env_file = profiles
            .get(name)
            .and_then(|profile| profile.env_file.as_ref().map(|path| base_dir.join(path)))
            .unwrap_or_else(|| base_dir.join(env_variant_filename(env_file_name, name)));
        if named_env_file.exists() {
            let file_env = load_env_file(&named_env_file)?;
            for (k, v) in file_env {
                env.insert(k, v);
            }
        }
        if let Some(profile) = profiles.get(name) {
            for (k, v) in &profile.vars {
                env.insert(k.clone(), v.clone());
            }
        }
    }

    // Layer 4: tarn.env.local.yaml (gitignored, secrets)
    let local_env_file = base_dir.join(env_variant_filename(env_file_name, "local"));
    if local_env_file.exists() {
        let file_env = load_env_file(&local_env_file)?;
        for (k, v) in file_env {
            env.insert(k, v);
        }
    }

    // Layer 5: shell environment variables (resolve ${VAR} references)
    let resolved: HashMap<String, String> = env
        .into_iter()
        .map(|(k, v)| {
            let resolved_v = resolve_shell_vars(&v);
            (k, resolved_v)
        })
        .collect();
    env = resolved;

    // Layer 6 (highest): CLI --var overrides
    for (k, v) in cli_vars {
        env.insert(k.clone(), v.clone());
    }

    Ok(env)
}

/// Resolve environment variables while preserving per-key provenance.
///
/// This is the LSP-facing counterpart to [`resolve_env_with_profiles`]: it
/// applies the exact same priority chain and shell-variable expansion, but
/// returns a map from key to [`EnvEntry`] so callers can report *which*
/// layer supplied each final value. The natural consumer is `tarn-lsp`'s
/// hover provider, which shows the effective value together with the file
/// path it came from.
///
/// The priority chain (lowest to highest — later layers overwrite earlier
/// ones) is identical to [`resolve_env_with_profiles`]:
///
///   1. inline `env:` block from the test file
///   2. `tarn.env.yaml` (or the caller-configured equivalent)
///   3. `tarn.env.{name}.yaml` for a named environment (if configured)
///   4. `NamedEnvironmentConfig.vars` from `tarn.config.yaml`
///   5. `tarn.env.local.yaml` (gitignored, secrets)
///   6. CLI `--var KEY=VALUE`
///
/// Between layers 5 and 6 every value is passed through
/// [`resolve_shell_vars`] so `${VAR}` placeholders in env-file values
/// expand to their shell values.
pub fn resolve_env_with_sources(
    inline_env: &HashMap<String, String>,
    env_name: Option<&str>,
    cli_vars: &[(String, String)],
    base_dir: &Path,
    env_file_name: &str,
    profiles: &HashMap<String, NamedEnvironmentConfig>,
) -> Result<BTreeMap<String, EnvEntry>, TarnError> {
    let mut env: BTreeMap<String, EnvEntry> = BTreeMap::new();

    // Layer 1: inline env block from the test file. No file path is known
    // at this layer — the inline map came from `TestFile::env` which
    // `serde_yaml` produced from somewhere the caller knows about. LSP
    // consumers enrich `declaration_range` after this call using
    // `inline_env_locations_from_source` against the test file's own YAML.
    for (k, v) in inline_env {
        env.insert(
            k.clone(),
            EnvEntry {
                value: v.clone(),
                source: EnvSource::InlineEnvBlock,
                declaration_range: None,
            },
        );
    }

    // Layer 2: default env file (tarn.env.yaml).
    let default_env_file = base_dir.join(env_file_name);
    if default_env_file.exists() {
        let loaded = load_env_file_with_locations(&default_env_file)?;
        let display = default_env_file.display().to_string();
        for (k, v) in loaded.values {
            let declaration_range = loaded.locations.get(&k).cloned();
            env.insert(
                k,
                EnvEntry {
                    value: v,
                    source: EnvSource::DefaultEnvFile {
                        path: display.clone(),
                    },
                    declaration_range,
                },
            );
        }
    }

    // Layer 3: named env file (tarn.env.{name}.yaml or profile override).
    if let Some(name) = env_name {
        let named_env_file = profiles
            .get(name)
            .and_then(|profile| profile.env_file.as_ref().map(|path| base_dir.join(path)))
            .unwrap_or_else(|| base_dir.join(env_variant_filename(env_file_name, name)));
        if named_env_file.exists() {
            let loaded = load_env_file_with_locations(&named_env_file)?;
            let display = named_env_file.display().to_string();
            for (k, v) in loaded.values {
                let declaration_range = loaded.locations.get(&k).cloned();
                env.insert(
                    k,
                    EnvEntry {
                        value: v,
                        source: EnvSource::NamedEnvFile {
                            path: display.clone(),
                            env_name: name.to_owned(),
                        },
                        declaration_range,
                    },
                );
            }
        }
        if let Some(profile) = profiles.get(name) {
            for (k, v) in &profile.vars {
                env.insert(
                    k.clone(),
                    EnvEntry {
                        value: v.clone(),
                        source: EnvSource::NamedProfileVars {
                            env_name: name.to_owned(),
                        },
                        declaration_range: None,
                    },
                );
            }
        }
    }

    // Layer 4: tarn.env.local.yaml (gitignored, secrets).
    let local_env_file = base_dir.join(env_variant_filename(env_file_name, "local"));
    if local_env_file.exists() {
        let loaded = load_env_file_with_locations(&local_env_file)?;
        let display = local_env_file.display().to_string();
        for (k, v) in loaded.values {
            let declaration_range = loaded.locations.get(&k).cloned();
            env.insert(
                k,
                EnvEntry {
                    value: v,
                    source: EnvSource::LocalEnvFile {
                        path: display.clone(),
                    },
                    declaration_range,
                },
            );
        }
    }

    // Layer 5: shell variable expansion of ${VAR} placeholders in each
    // already-resolved value. The *source* of the entry does not change —
    // shell expansion is a post-processing step, not a new layer.
    for entry in env.values_mut() {
        entry.value = resolve_shell_vars(&entry.value);
    }

    // Layer 6 (highest): CLI --var overrides.
    for (k, v) in cli_vars {
        env.insert(
            k.clone(),
            EnvEntry {
                value: v.clone(),
                source: EnvSource::CliVar,
                declaration_range: None,
            },
        );
    }

    Ok(env)
}

fn env_variant_filename(env_file_name: &str, suffix: &str) -> PathBuf {
    let path = Path::new(env_file_name);
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(env_file_name);

    match path.extension().and_then(|ext| ext.to_str()) {
        Some(ext) => PathBuf::from(format!("{stem}.{suffix}.{ext}")),
        None => PathBuf::from(format!("{stem}.{suffix}")),
    }
}

/// Load an env file (YAML key-value pairs).
fn load_env_file(path: &Path) -> Result<HashMap<String, String>, TarnError> {
    let content = std::fs::read_to_string(path).map_err(|e| {
        TarnError::Config(format!("Failed to read env file {}: {}", path.display(), e))
    })?;

    let map: HashMap<String, serde_yaml::Value> = serde_yaml::from_str(&content).map_err(|e| {
        TarnError::Config(format!(
            "Failed to parse env file {}: {}",
            path.display(),
            e
        ))
    })?;

    Ok(map
        .into_iter()
        .map(|(k, v)| {
            let s = match v {
                serde_yaml::Value::String(s) => s,
                serde_yaml::Value::Number(n) => n.to_string(),
                serde_yaml::Value::Bool(b) => b.to_string(),
                serde_yaml::Value::Null => String::new(),
                other => format!("{:?}", other),
            };
            (k, s)
        })
        .collect())
}

/// Loaded env file values plus the per-key source location metadata we
/// use to populate [`EnvEntry::declaration_range`]. Split out as a
/// named struct so the clippy `type_complexity` lint is happy and so
/// callers can pattern-match by field.
struct LoadedEnvFile {
    values: HashMap<String, String>,
    locations: HashMap<String, Location>,
}

/// Sibling of [`load_env_file`] that also returns the 1-based [`Location`]
/// of each top-level key's scalar in the YAML document.
///
/// Locations are produced with a second pass using `yaml-rust2` so the
/// LSP can resolve `textDocument/definition` jumps from `{{ env.x }}` to
/// the declaring file. The location points at the value scalar when the
/// key has a scalar value, otherwise at the key itself — either way the
/// jump lands on the right line.
///
/// Missing or non-mapping YAML is *not* an error: the function returns
/// an empty location map in that case. The accompanying value map is
/// always produced from the same `load_env_file` code path, so the LSP
/// only loses the jump target, never the value.
fn load_env_file_with_locations(path: &Path) -> Result<LoadedEnvFile, TarnError> {
    let values = load_env_file(path)?;
    let content = std::fs::read_to_string(path).map_err(|e| {
        TarnError::Config(format!("Failed to read env file {}: {}", path.display(), e))
    })?;
    let locations = scan_top_level_key_locations(&content, &path.display().to_string());
    Ok(LoadedEnvFile { values, locations })
}

/// Scan the top-level keys of a YAML mapping and return a map from key
/// name to 1-based [`Location`] of the key (or its value scalar when
/// available).
///
/// Public so `tarn-lsp` can enrich inline `env:` block entries with the
/// declaration range of the key inside the currently-open test file. The
/// inline env path is not otherwise accessible to the env loader — it
/// arrives as a pre-parsed `HashMap` — so callers that want a jump
/// target call this helper separately against the test file's raw text.
///
/// `display_path` is stored in every returned [`Location::file`]. Pass
/// the absolute or display path of the source file so downstream
/// consumers can anchor on the same string they already use elsewhere.
pub fn scan_top_level_key_locations(
    content: &str,
    display_path: &str,
) -> HashMap<String, Location> {
    let mut out = HashMap::new();
    let mut sink = LocationSink { events: Vec::new() };
    let mut parser = Parser::new_from_str(content);
    if parser.load(&mut sink, true).is_err() {
        return out;
    }

    // Walk the event stream: StreamStart, DocumentStart, MappingStart,
    // then alternating (key, value) pairs until MappingEnd.
    let events = &sink.events;
    let mut i = 0usize;
    // Skip the StreamStart/DocumentStart header.
    while i < events.len() {
        if matches!(events[i].0, Event::MappingStart(_, _)) {
            i += 1;
            break;
        }
        i += 1;
    }
    // At this point we are just past the root MappingStart.
    while i < events.len() {
        match &events[i].0 {
            Event::MappingEnd => break,
            Event::Scalar(key, _, _, _) => {
                let key = key.clone();
                let key_marker = events[i].1;
                i += 1;
                // Consume the value node, recording its location if it
                // is a scalar. Otherwise fall back to the key marker.
                if i < events.len() {
                    let (value_event, value_marker) = &events[i];
                    let (loc_line, loc_col) = match value_event {
                        Event::Scalar(_, _, _, _) => (value_marker.line(), value_marker.col() + 1),
                        _ => (key_marker.line(), key_marker.col() + 1),
                    };
                    out.insert(
                        key,
                        Location {
                            file: display_path.to_owned(),
                            line: loc_line,
                            column: loc_col,
                        },
                    );
                    // Skip the value node in a balanced way. For a bare
                    // scalar that is one event; for nested structures we
                    // consume up to the matching close event.
                    i = skip_node(events, i);
                } else {
                    break;
                }
            }
            _ => {
                // Unexpected event while looking for a key; try to
                // recover by scanning forward.
                i += 1;
            }
        }
    }
    out
}

/// Scan the inline `env:` block at the top level of a Tarn test file and
/// return a map from key name to its declaration [`Location`].
///
/// Wraps [`scan_top_level_key_locations`] with the extra step of
/// descending from the root mapping into the `env:` sub-mapping. Returns
/// an empty map when the file has no `env:` block, when the block is not
/// a mapping, or when the YAML cannot be scanned at all.
pub fn inline_env_locations_from_source(
    content: &str,
    display_path: &str,
) -> HashMap<String, Location> {
    let mut out = HashMap::new();
    let mut sink = LocationSink { events: Vec::new() };
    let mut parser = Parser::new_from_str(content);
    if parser.load(&mut sink, true).is_err() {
        return out;
    }
    let events = &sink.events;

    // Locate the root mapping.
    let mut i = 0usize;
    while i < events.len() {
        if matches!(events[i].0, Event::MappingStart(_, _)) {
            i += 1;
            break;
        }
        i += 1;
    }

    // Walk keys at the root looking for `env`. Everything else is
    // balanced-skipped so nested mappings cannot leak their own keys
    // into our output.
    while i < events.len() {
        match &events[i].0 {
            Event::MappingEnd => break,
            Event::Scalar(key, _, _, _) => {
                let key = key.clone();
                i += 1;
                if key == "env" {
                    // Expect a mapping value. Descend into it and emit
                    // every inner scalar key's location.
                    if i < events.len() {
                        if matches!(events[i].0, Event::MappingStart(_, _)) {
                            i += 1;
                            while i < events.len() {
                                match &events[i].0 {
                                    Event::MappingEnd => {
                                        break;
                                    }
                                    Event::Scalar(inner_key, _, _, _) => {
                                        let inner_key = inner_key.clone();
                                        let key_marker = events[i].1;
                                        i += 1;
                                        let (loc_line, loc_col) =
                                            if let Some((val_event, val_marker)) = events.get(i) {
                                                match val_event {
                                                    Event::Scalar(_, _, _, _) => {
                                                        (val_marker.line(), val_marker.col() + 1)
                                                    }
                                                    _ => (key_marker.line(), key_marker.col() + 1),
                                                }
                                            } else {
                                                (key_marker.line(), key_marker.col() + 1)
                                            };
                                        out.insert(
                                            inner_key,
                                            Location {
                                                file: display_path.to_owned(),
                                                line: loc_line,
                                                column: loc_col,
                                            },
                                        );
                                        i = skip_node(events, i);
                                    }
                                    _ => {
                                        i = skip_node(events, i);
                                    }
                                }
                            }
                            return out;
                        } else {
                            // `env:` without a mapping value — nothing to jump to.
                            return out;
                        }
                    }
                } else {
                    // Non-env key at the root — skip its value balanced.
                    i = skip_node(events, i);
                }
            }
            _ => {
                i += 1;
            }
        }
    }

    out
}

/// Advance past a balanced YAML node (scalar, sequence, or mapping),
/// returning the index of the first event *after* the node's closing
/// event. Used by the location scanners above so they can hop over
/// non-scalar values without losing their place in the stream.
fn skip_node(events: &[(Event, Marker)], mut i: usize) -> usize {
    if i >= events.len() {
        return i;
    }
    let start = &events[i].0;
    match start {
        Event::Scalar(_, _, _, _) | Event::Alias(_) => i + 1,
        Event::SequenceStart(_, _) => {
            i += 1;
            let mut depth = 1i32;
            while i < events.len() && depth > 0 {
                match &events[i].0 {
                    Event::SequenceStart(_, _) | Event::MappingStart(_, _) => depth += 1,
                    Event::SequenceEnd | Event::MappingEnd => depth -= 1,
                    _ => {}
                }
                i += 1;
            }
            i
        }
        Event::MappingStart(_, _) => {
            i += 1;
            let mut depth = 1i32;
            while i < events.len() && depth > 0 {
                match &events[i].0 {
                    Event::MappingStart(_, _) | Event::SequenceStart(_, _) => depth += 1,
                    Event::MappingEnd | Event::SequenceEnd => depth -= 1,
                    _ => {}
                }
                i += 1;
            }
            i
        }
        _ => i + 1,
    }
}

struct LocationSink {
    events: Vec<(Event, Marker)>,
}

impl MarkedEventReceiver for LocationSink {
    fn on_event(&mut self, ev: Event, mark: Marker) {
        self.events.push((ev, mark));
    }
}

/// Resolve ${VAR_NAME} references in a string using shell environment variables.
fn resolve_shell_vars(value: &str) -> String {
    let mut result = value.to_string();
    // Find all ${VAR} patterns
    while let Some(start) = result.find("${") {
        if let Some(end) = result[start..].find('}') {
            let var_name = &result[start + 2..start + end];
            let replacement = std::env::var(var_name).unwrap_or_default();
            result = format!(
                "{}{}{}",
                &result[..start],
                replacement,
                &result[start + end + 1..]
            );
        } else {
            break;
        }
    }
    result
}

/// Parse CLI --var arguments from "key=value" format.
pub fn parse_cli_vars(vars: &[String]) -> Result<Vec<(String, String)>, TarnError> {
    vars.iter()
        .map(|s| {
            let parts: Vec<&str> = s.splitn(2, '=').collect();
            if parts.len() != 2 {
                Err(TarnError::Config(format!(
                    "Invalid --var format '{}': expected key=value",
                    s
                )))
            } else {
                Ok((parts[0].to_string(), parts[1].to_string()))
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    fn setup_env_files(dir: &TempDir, files: &[(&str, &str)]) {
        for (name, content) in files {
            let path = dir.path().join(name);
            let mut f = std::fs::File::create(&path).unwrap();
            f.write_all(content.as_bytes()).unwrap();
        }
    }

    // --- Priority chain ---

    #[test]
    fn inline_env_is_base_layer() {
        let dir = TempDir::new().unwrap();
        let mut inline = HashMap::new();
        inline.insert("base_url".into(), "http://localhost:3000".into());

        let env = resolve_env(&inline, None, &[], dir.path()).unwrap();
        assert_eq!(env.get("base_url").unwrap(), "http://localhost:3000");
    }

    #[test]
    fn env_file_overrides_inline() {
        let dir = TempDir::new().unwrap();
        setup_env_files(&dir, &[("tarn.env.yaml", "base_url: http://from-file")]);

        let mut inline = HashMap::new();
        inline.insert("base_url".into(), "http://inline".into());

        let env = resolve_env(&inline, None, &[], dir.path()).unwrap();
        assert_eq!(env.get("base_url").unwrap(), "http://from-file");
    }

    #[test]
    fn named_env_overrides_default() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default"),
                ("tarn.env.staging.yaml", "base_url: http://staging"),
            ],
        );

        let env = resolve_env(&HashMap::new(), Some("staging"), &[], dir.path()).unwrap();
        assert_eq!(env.get("base_url").unwrap(), "http://staging");
    }

    #[test]
    fn named_profile_uses_custom_env_file_and_vars() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default\nregion: local"),
                ("env.staging.yaml", "base_url: http://from-profile-file"),
            ],
        );

        let mut profiles = HashMap::new();
        profiles.insert(
            "staging".into(),
            NamedEnvironmentConfig {
                env_file: Some("env.staging.yaml".into()),
                vars: HashMap::from([("region".into(), "eu-west-1".into())]),
            },
        );

        let env = resolve_env_with_profiles(
            &HashMap::new(),
            Some("staging"),
            &[],
            dir.path(),
            "tarn.env.yaml",
            &profiles,
        )
        .unwrap();
        assert_eq!(env.get("base_url").unwrap(), "http://from-profile-file");
        assert_eq!(env.get("region").unwrap(), "eu-west-1");
    }

    #[test]
    fn local_env_overrides_named() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default"),
                ("tarn.env.staging.yaml", "base_url: http://staging"),
                ("tarn.env.local.yaml", "base_url: http://local"),
            ],
        );

        let env = resolve_env(&HashMap::new(), Some("staging"), &[], dir.path()).unwrap();
        assert_eq!(env.get("base_url").unwrap(), "http://local");
    }

    #[test]
    fn cli_var_overrides_all() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default"),
                ("tarn.env.local.yaml", "base_url: http://local"),
            ],
        );

        let mut inline = HashMap::new();
        inline.insert("base_url".into(), "http://inline".into());

        let cli_vars = vec![("base_url".into(), "http://cli".into())];
        let env = resolve_env(&inline, None, &cli_vars, dir.path()).unwrap();
        assert_eq!(env.get("base_url").unwrap(), "http://cli");
    }

    // --- Shell variable resolution ---

    #[test]
    fn resolve_shell_variable() {
        std::env::set_var("TARN_TEST_SECRET", "s3cret");
        let result = resolve_shell_vars("password is ${TARN_TEST_SECRET}");
        assert_eq!(result, "password is s3cret");
        std::env::remove_var("TARN_TEST_SECRET");
    }

    #[test]
    fn resolve_missing_shell_variable_becomes_empty() {
        let result = resolve_shell_vars("${TARN_NONEXISTENT_VAR}");
        assert_eq!(result, "");
    }

    #[test]
    fn resolve_multiple_shell_variables() {
        std::env::set_var("TARN_TEST_A", "alpha");
        std::env::set_var("TARN_TEST_B", "beta");
        let result = resolve_shell_vars("${TARN_TEST_A} and ${TARN_TEST_B}");
        assert_eq!(result, "alpha and beta");
        std::env::remove_var("TARN_TEST_A");
        std::env::remove_var("TARN_TEST_B");
    }

    #[test]
    fn no_shell_vars_unchanged() {
        let result = resolve_shell_vars("no variables here");
        assert_eq!(result, "no variables here");
    }

    // --- Env file parsing ---

    #[test]
    fn load_env_file_with_various_types() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[(
                "test.yaml",
                "string_val: hello\nnumber_val: 42\nbool_val: true\nnull_val: null",
            )],
        );

        let env = load_env_file(&dir.path().join("test.yaml")).unwrap();
        assert_eq!(env.get("string_val").unwrap(), "hello");
        assert_eq!(env.get("number_val").unwrap(), "42");
        assert_eq!(env.get("bool_val").unwrap(), "true");
        assert_eq!(env.get("null_val").unwrap(), "");
    }

    #[test]
    fn load_env_file_missing() {
        let result = load_env_file(Path::new("/nonexistent/file.yaml"));
        assert!(result.is_err());
    }

    #[test]
    fn load_env_file_invalid_yaml() {
        let dir = TempDir::new().unwrap();
        setup_env_files(&dir, &[("bad.yaml", "not: [valid: yaml")]);
        let result = load_env_file(&dir.path().join("bad.yaml"));
        assert!(result.is_err());
    }

    // --- CLI var parsing ---

    #[test]
    fn parse_cli_vars_valid() {
        let vars = vec!["key=value".into(), "another=with=equals".into()];
        let result = parse_cli_vars(&vars).unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], ("key".into(), "value".into()));
        assert_eq!(result[1], ("another".into(), "with=equals".into()));
    }

    #[test]
    fn parse_cli_vars_invalid() {
        let vars = vec!["no_equals_sign".into()];
        let result = parse_cli_vars(&vars);
        assert!(result.is_err());
    }

    #[test]
    fn parse_cli_vars_empty() {
        let vars: Vec<String> = vec![];
        let result = parse_cli_vars(&vars).unwrap();
        assert!(result.is_empty());
    }

    // --- Merging ---

    #[test]
    fn variables_from_different_layers_merge() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[("tarn.env.yaml", "file_only: from_file\nbase_url: from_file")],
        );

        let mut inline = HashMap::new();
        inline.insert("inline_only".into(), "from_inline".into());
        inline.insert("base_url".into(), "from_inline".into());

        let env = resolve_env(&inline, None, &[], dir.path()).unwrap();
        assert_eq!(env.get("inline_only").unwrap(), "from_inline");
        assert_eq!(env.get("file_only").unwrap(), "from_file");
        assert_eq!(env.get("base_url").unwrap(), "from_file"); // file overrides inline
    }

    #[test]
    fn missing_named_env_file_is_ok() {
        let dir = TempDir::new().unwrap();
        // No tarn.env.staging.yaml exists
        let env = resolve_env(&HashMap::new(), Some("staging"), &[], dir.path()).unwrap();
        assert!(env.is_empty());
    }

    #[test]
    fn custom_env_file_supports_named_and_local_variants() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("custom.env.yaml", "base_url: http://default"),
                ("custom.env.staging.yaml", "base_url: http://staging"),
                ("custom.env.local.yaml", "token: secret"),
            ],
        );

        let env = resolve_env_with_file(
            &HashMap::new(),
            Some("staging"),
            &[],
            dir.path(),
            "custom.env.yaml",
        )
        .unwrap();

        assert_eq!(env.get("base_url").unwrap(), "http://staging");
        assert_eq!(env.get("token").unwrap(), "secret");
    }

    #[test]
    fn env_variant_filename_inserts_suffix_before_extension() {
        assert_eq!(
            env_variant_filename("tarn.env.yaml", "local"),
            PathBuf::from("tarn.env.local.yaml")
        );
        assert_eq!(
            env_variant_filename("custom.env.yaml", "staging"),
            PathBuf::from("custom.env.staging.yaml")
        );
    }

    // --- resolve_env_with_sources ---

    #[test]
    fn resolve_env_with_sources_tags_inline_entries() {
        let dir = TempDir::new().unwrap();
        let mut inline = HashMap::new();
        inline.insert("base_url".into(), "http://localhost:3000".into());

        let env = resolve_env_with_sources(
            &inline,
            None,
            &[],
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        let entry = env.get("base_url").unwrap();
        assert_eq!(entry.value, "http://localhost:3000");
        assert!(matches!(entry.source, EnvSource::InlineEnvBlock));
    }

    #[test]
    fn resolve_env_with_sources_reports_default_env_file_path() {
        let dir = TempDir::new().unwrap();
        setup_env_files(&dir, &[("tarn.env.yaml", "base_url: http://from-file")]);

        let env = resolve_env_with_sources(
            &HashMap::new(),
            None,
            &[],
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        let entry = env.get("base_url").unwrap();
        assert_eq!(entry.value, "http://from-file");
        match &entry.source {
            EnvSource::DefaultEnvFile { path } => {
                assert!(path.ends_with("tarn.env.yaml"), "got path: {}", path);
            }
            other => panic!("expected DefaultEnvFile source, got {:?}", other),
        }
    }

    #[test]
    fn resolve_env_with_sources_named_env_file_wins_over_default() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default"),
                ("tarn.env.staging.yaml", "base_url: http://staging"),
            ],
        );

        let env = resolve_env_with_sources(
            &HashMap::new(),
            Some("staging"),
            &[],
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        let entry = env.get("base_url").unwrap();
        assert_eq!(entry.value, "http://staging");
        match &entry.source {
            EnvSource::NamedEnvFile { env_name, path } => {
                assert_eq!(env_name, "staging");
                assert!(path.ends_with("tarn.env.staging.yaml"));
            }
            other => panic!("expected NamedEnvFile source, got {:?}", other),
        }
    }

    #[test]
    fn resolve_env_with_sources_cli_var_has_highest_priority() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default"),
                ("tarn.env.local.yaml", "base_url: http://local"),
            ],
        );

        let cli_vars = vec![("base_url".into(), "http://cli".into())];
        let env = resolve_env_with_sources(
            &HashMap::new(),
            None,
            &cli_vars,
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        let entry = env.get("base_url").unwrap();
        assert_eq!(entry.value, "http://cli");
        assert!(matches!(entry.source, EnvSource::CliVar));
    }

    #[test]
    fn resolve_env_with_sources_local_env_file_overrides_named() {
        let dir = TempDir::new().unwrap();
        setup_env_files(
            &dir,
            &[
                ("tarn.env.yaml", "base_url: http://default"),
                ("tarn.env.staging.yaml", "base_url: http://staging"),
                ("tarn.env.local.yaml", "base_url: http://local"),
            ],
        );

        let env = resolve_env_with_sources(
            &HashMap::new(),
            Some("staging"),
            &[],
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        let entry = env.get("base_url").unwrap();
        assert_eq!(entry.value, "http://local");
        assert!(matches!(entry.source, EnvSource::LocalEnvFile { .. }));
    }

    #[test]
    fn resolve_env_with_sources_populates_file_declaration_range() {
        let dir = TempDir::new().unwrap();
        setup_env_files(&dir, &[("tarn.env.yaml", "base_url: http://from-file\n")]);

        let env = resolve_env_with_sources(
            &HashMap::new(),
            None,
            &[],
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        let entry = env.get("base_url").unwrap();
        let range = entry
            .declaration_range
            .as_ref()
            .expect("env files must populate declaration_range");
        assert_eq!(range.line, 1, "single-line env file -> line 1");
        assert!(range.column >= 1);
        assert!(range.file.ends_with("tarn.env.yaml"));
    }

    #[test]
    fn resolve_env_with_sources_cli_var_has_no_declaration_range() {
        let dir = TempDir::new().unwrap();
        let cli_vars = vec![("token".into(), "abc".into())];
        let env = resolve_env_with_sources(
            &HashMap::new(),
            None,
            &cli_vars,
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        assert!(env.get("token").unwrap().declaration_range.is_none());
    }

    #[test]
    fn resolve_env_with_sources_inline_entries_start_with_no_declaration_range() {
        let dir = TempDir::new().unwrap();
        let mut inline = HashMap::new();
        inline.insert("base_url".into(), "http://inline".into());
        let env = resolve_env_with_sources(
            &inline,
            None,
            &[],
            dir.path(),
            "tarn.env.yaml",
            &HashMap::new(),
        )
        .unwrap();
        assert!(env.get("base_url").unwrap().declaration_range.is_none());
    }

    #[test]
    fn scan_top_level_key_locations_for_bare_env_file_points_at_value_scalar() {
        let yaml = "base_url: http://localhost\ntoken: secret\n";
        let out = scan_top_level_key_locations(yaml, "/tmp/tarn.env.yaml");
        let base = out.get("base_url").expect("base_url present");
        assert_eq!(base.line, 1);
        // Value `http://localhost` starts at column 11 (after `base_url: `).
        assert!(base.column >= 10);
        let token = out.get("token").expect("token present");
        assert_eq!(token.line, 2);
    }

    #[test]
    fn inline_env_locations_from_source_finds_keys_inside_env_block() {
        let yaml = "\
name: Sample
env:
  base_url: http://localhost
  token: secret
steps:
  - name: step1
    request:
      method: GET
      url: http://localhost
";
        let out = inline_env_locations_from_source(yaml, "/tmp/t.tarn.yaml");
        let base = out.get("base_url").expect("base_url present");
        assert_eq!(base.line, 3);
        let token = out.get("token").expect("token present");
        assert_eq!(token.line, 4);
        // Must not leak step-name keys into the output.
        assert!(!out.contains_key("name"));
    }

    #[test]
    fn inline_env_locations_returns_empty_when_no_env_block() {
        let yaml = "name: No env\nsteps:\n  - name: a\n    request: {method: GET, url: http://x}\n";
        let out = inline_env_locations_from_source(yaml, "/tmp/t.tarn.yaml");
        assert!(out.is_empty());
    }

    #[test]
    fn env_source_label_and_source_file_accessors_are_stable() {
        assert_eq!(EnvSource::InlineEnvBlock.label(), "inline env: block");
        assert_eq!(EnvSource::CliVar.label(), "CLI --var");
        assert_eq!(EnvSource::InlineEnvBlock.source_file(), None);
        assert_eq!(EnvSource::CliVar.source_file(), None);
        assert_eq!(
            EnvSource::DefaultEnvFile {
                path: "/tmp/tarn.env.yaml".into()
            }
            .source_file(),
            Some("/tmp/tarn.env.yaml")
        );
    }
}