flake-edit 0.3.6

Edit your flake inputs with ease.
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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
use crate::error::Error;
use crate::follows::{AttrPath, Segment};
use serde::{Deserialize, Deserializer};
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};

/// Errors that arise from parsing or walking `flake.lock`.
///
/// Each variant pinpoints a distinct shape failure: a missing field, a
/// follows cycle, or a node that the resolver cannot find. The variants
/// carry the smallest contextual data (segment path, node key) that lets
/// the caller reconstruct the failure without reparsing the message.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LockError {
    /// `flake.lock` did not parse as JSON.
    #[error("failed to parse flake.lock as json")]
    Parse(#[from] serde_json::Error),
    /// The lockfile has no `root` node referenced by `nodes`.
    #[error("flake.lock is missing the root node")]
    MissingRoot,
    /// The root node carries no `inputs`, so a path cannot be walked.
    #[error("flake.lock root has no inputs")]
    RootHasNoInputs,
    /// An intermediate input on the path has no sub-inputs.
    #[error("input '{path}' has no sub-inputs in flake.lock")]
    InputHasNoSubInputs { path: String },
    /// A path segment does not resolve to a declared input.
    #[error("input '{path}' not found in flake.lock")]
    InputNotFound { path: String },
    /// A `follows` declaration with an empty target was encountered while
    /// walking. Surfaced as a hard failure when the path needs a target.
    #[error("input '{path}' has no follows target")]
    FollowsTargetMissing { path: String },
    /// The node referenced by a path segment is absent from the `nodes` map.
    #[error("could not find lockfile node '{node}' referenced by input '{path}'")]
    NodeMissingForPath { node: String, path: String },
    /// The node looked up directly by name is absent.
    #[error("could not find lockfile node '{node}'")]
    NodeMissing { node: String },
    /// Recursion budget exhausted while resolving a follows path.
    #[error("cycle while resolving follows path")]
    FollowsCycle,
    /// A node has no `locked` block (so no `rev` can be retrieved).
    #[error("lockfile node has no locked information")]
    NodeNotLocked,
    /// A locked block has no `rev`.
    #[error("locked node has no rev")]
    LockedHasNoRev,
}

/// A nested input discovered in `flake.lock` with its existing follows
/// target, if any.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NestedInput {
    /// Dotted path to the nested input (e.g. `crane.nixpkgs`).
    pub path: AttrPath,
    /// Existing follows target, if the input is redirected.
    pub follows: Option<AttrPath>,
    /// Original flake URL for `Direct` references (e.g.
    /// `github:nixos/nixpkgs/nixos-unstable`). `None` for follows-only
    /// references.
    pub url: Option<String>,
}

impl NestedInput {
    /// Render as `path\tfollows_target` (or just `path` when the input has no
    /// follows target). The tab separator lets the UI style each side
    /// independently.
    pub fn to_display_string(&self) -> String {
        match &self.follows {
            Some(target) => format!("{}\t{}", self.path, target),
            None => self.path.to_string(),
        }
    }
}

/// Parsed `flake.lock`. Loaded with [`Self::from_default_path`],
/// [`Self::from_file`], or [`Self::read_from_str`].
#[derive(Debug, Deserialize)]
pub struct FlakeLock {
    nodes: HashMap<String, Node>,
    root: String,
}

/// A single entry in the lockfile's `nodes` map.
#[derive(Debug, Deserialize)]
pub(crate) struct Node {
    inputs: Option<HashMap<String, Input>>,
    locked: Option<Locked>,
    original: Option<Original>,
}

impl Node {
    fn rev(&self) -> Result<String, LockError> {
        self.locked.as_ref().ok_or(LockError::NodeNotLocked)?.rev()
    }
}

/// Reference from a node's `inputs` map.
///
/// Lockfile shape:
/// - `"name"` is a direct reference to another node, parsed as
///   [`Self::Direct`].
/// - `["a", "b", ...]` is a follows path with a target, parsed as
///   `Indirect(Some(path))`.
/// - `[]` is a follows declaration with no target (Nix emits this when an
///   upstream chain has overridden the input to nothing, e.g. a lockfile
///   whose source `flake.nix` carries
///   `nix.inputs.flake-compat.follows = "";`), parsed as `Indirect(None)`.
#[derive(Debug, Clone)]
pub enum Input {
    Direct(String),
    Indirect(Option<AttrPath>),
}

impl<'de> Deserialize<'de> for Input {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::{Error, SeqAccess, Visitor};
        use std::fmt;

        struct InputVisitor;

        impl<'de> Visitor<'de> for InputVisitor {
            type Value = Input;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str(
                    "a node name string, an empty array, or an array of \
                     non-empty segment names",
                )
            }

            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
                Ok(Input::Direct(v.to_string()))
            }

            fn visit_string<E: Error>(self, v: String) -> Result<Self::Value, E> {
                Ok(Input::Direct(v))
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                // Empty `[]` is a real lockfile shape: `inputs.X = []`
                // marks an input whose follows chain has been overridden
                // away. Surface it as `Indirect(None)` instead of an
                // error.
                let Some(first) = seq.next_element::<String>()? else {
                    return Ok(Input::Indirect(None));
                };
                let first_seg = Segment::from_unquoted(first).map_err(A::Error::custom)?;
                let mut path = AttrPath::new(first_seg);
                while let Some(raw) = seq.next_element::<String>()? {
                    let seg = Segment::from_unquoted(raw).map_err(A::Error::custom)?;
                    path.push(seg);
                }
                Ok(Input::Indirect(Some(path)))
            }
        }

        deserializer.deserialize_any(InputVisitor)
    }
}

/// Locked metadata for a node. Only [`Self::rev`] is consumed by the
/// crate; the other JSON coordinates (`owner`, `repo`, `type`, `narHash`,
/// ...) are ignored on parse.
#[derive(Debug, Deserialize, Clone)]
pub(crate) struct Locked {
    rev: Option<String>,
}

impl Locked {
    fn rev(&self) -> Result<String, LockError> {
        self.rev.clone().ok_or(LockError::LockedHasNoRev)
    }
}

/// Original (pre-lock) reference for a node, as written in the source
/// flake. One variant per flakeref shape Nix produces in `flake.lock`.
#[derive(Debug)]
pub(crate) enum Original {
    Github {
        owner: String,
        repo: String,
        ref_field: Option<String>,
    },
    Gitlab {
        owner: String,
        repo: String,
        ref_field: Option<String>,
    },
    Sourcehut {
        owner: String,
        repo: String,
        ref_field: Option<String>,
    },
    Git {
        url: String,
        ref_field: Option<String>,
    },
    Hg {
        url: String,
        ref_field: Option<String>,
    },
    Tarball {
        url: String,
    },
    File {
        url: String,
    },
    Path {
        path: String,
    },
    Indirect {
        id: String,
        ref_field: Option<String>,
    },
    /// Flakeref `type` not recognized by this crate. Tolerated because
    /// Nix adds new schemes occasionally; lockfiles that mention one
    /// should still parse so the rest of the inputs stay usable.
    /// Malformed payloads of recognized types surface as `D::Error`,
    /// not here.
    Unknown {
        node_type: String,
    },
}

impl<'de> Deserialize<'de> for Original {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        #[derive(Deserialize)]
        struct ForgePayload {
            owner: String,
            repo: String,
            #[serde(rename = "ref")]
            ref_field: Option<String>,
        }
        #[derive(Deserialize)]
        struct VcsPayload {
            url: String,
            #[serde(rename = "ref")]
            ref_field: Option<String>,
        }
        #[derive(Deserialize)]
        struct UrlPayload {
            url: String,
        }
        #[derive(Deserialize)]
        struct PathPayload {
            path: String,
        }
        #[derive(Deserialize)]
        struct IndirectPayload {
            id: String,
            #[serde(rename = "ref")]
            ref_field: Option<String>,
        }

        let value = serde_json::Value::deserialize(deserializer)?;
        let node_type = value
            .get("type")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| D::Error::missing_field("type"))?
            .to_string();

        fn payload<T: for<'a> Deserialize<'a>, E: Error>(value: serde_json::Value) -> Result<T, E> {
            serde_json::from_value(value).map_err(E::custom)
        }

        Ok(match node_type.as_str() {
            "github" => {
                let ForgePayload {
                    owner,
                    repo,
                    ref_field,
                } = payload(value)?;
                Original::Github {
                    owner,
                    repo,
                    ref_field,
                }
            }
            "gitlab" => {
                let ForgePayload {
                    owner,
                    repo,
                    ref_field,
                } = payload(value)?;
                Original::Gitlab {
                    owner,
                    repo,
                    ref_field,
                }
            }
            "sourcehut" => {
                let ForgePayload {
                    owner,
                    repo,
                    ref_field,
                } = payload(value)?;
                Original::Sourcehut {
                    owner,
                    repo,
                    ref_field,
                }
            }
            "git" => {
                let VcsPayload { url, ref_field } = payload(value)?;
                Original::Git { url, ref_field }
            }
            "hg" => {
                let VcsPayload { url, ref_field } = payload(value)?;
                Original::Hg { url, ref_field }
            }
            "tarball" => {
                let UrlPayload { url } = payload(value)?;
                Original::Tarball { url }
            }
            "file" => {
                let UrlPayload { url } = payload(value)?;
                Original::File { url }
            }
            "path" => {
                let PathPayload { path } = payload(value)?;
                Original::Path { path }
            }
            "indirect" => {
                let IndirectPayload { id, ref_field } = payload(value)?;
                Original::Indirect { id, ref_field }
            }
            _ => Original::Unknown { node_type },
        })
    }
}

impl Original {
    /// Reconstruct a flake URL from the original reference. Returns
    /// `None` for [`Original::Unknown`], which also logs a
    /// `tracing::warn!` naming the unrecognized type.
    fn to_flake_url(&self) -> Option<String> {
        match self {
            Original::Github {
                owner,
                repo,
                ref_field,
            } => Some(forge_flake_url("github", owner, repo, ref_field.as_deref())),
            Original::Gitlab {
                owner,
                repo,
                ref_field,
            } => Some(forge_flake_url("gitlab", owner, repo, ref_field.as_deref())),
            Original::Sourcehut {
                owner,
                repo,
                ref_field,
            } => Some(forge_flake_url(
                "sourcehut",
                owner,
                repo,
                ref_field.as_deref(),
            )),
            Original::Git { url, ref_field } => {
                Some(prefixed_vcs_url("git+", url, ref_field.as_deref()))
            }
            Original::Hg { url, ref_field } => {
                Some(prefixed_vcs_url("hg+", url, ref_field.as_deref()))
            }
            Original::Tarball { url } | Original::File { url } => Some(url.clone()),
            Original::Path { path } => Some(format!("path:{path}")),
            Original::Indirect { id, ref_field } => {
                Some(indirect_flake_url(id, ref_field.as_deref()))
            }
            Original::Unknown { node_type } => {
                tracing::warn!(
                    "Unknown flake.lock node type '{node_type}'; cannot reconstruct flake URL"
                );
                None
            }
        }
    }
}

/// Build a `<scheme>:<owner>/<repo>[/<ref>]` URL, the shape shared by
/// `github`, `gitlab`, and `sourcehut` flakerefs.
fn forge_flake_url(scheme: &str, owner: &str, repo: &str, ref_field: Option<&str>) -> String {
    let mut url = format!("{scheme}:{owner}/{repo}");
    if let Some(r) = ref_field {
        url.push('/');
        url.push_str(r);
    }
    url
}

/// Prepend `git+` / `hg+` to a VCS transport URL and append `?ref=<r>`.
///
/// Nix keeps unrecognized query parameters (e.g. `?dir=subdir`) inside
/// the lockfile's `url` field, so the input may already carry a `?`.
/// Append with `&` in that case to avoid producing a flakeref with two
/// `?`, which Nix's URL parser rejects.
fn prefixed_vcs_url(scheme_prefix: &str, url: &str, ref_field: Option<&str>) -> String {
    let Some(r) = ref_field else {
        return format!("{scheme_prefix}{url}");
    };
    let separator = if url.contains('?') { '&' } else { '?' };
    format!("{scheme_prefix}{url}{separator}ref={r}")
}

/// Indirect refs encode `ref` as a path component (`flake:<id>/<ref>`),
/// not a query parameter. Other VCS schemes use `?ref=`; the indirect
/// scheme is the odd one out and easy to get wrong.
fn indirect_flake_url(id: &str, ref_field: Option<&str>) -> String {
    match ref_field {
        Some(r) => format!("flake:{id}/{r}"),
        None => format!("flake:{id}"),
    }
}

// Per-thread `nested_inputs` call counter. A `follow` invocation must walk
// the immutable lockfile once and thread the result through every consumer;
// tests reset this and assert the walk count. Thread-local so parallel test
// threads do not contend.
#[cfg(test)]
thread_local! {
    pub(crate) static NESTED_INPUTS_CALLS: std::cell::Cell<usize> =
        const { std::cell::Cell::new(0) };
}

impl FlakeLock {
    const LOCK: &'static str = "flake.lock";

    /// Load `flake.lock` from the current directory.
    pub fn from_default_path() -> Result<Self, Error> {
        let path = PathBuf::from(Self::LOCK);
        Self::from_file(path)
    }

    /// Load and parse a lockfile from `path`.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let path = path.as_ref();
        let mut file = File::open(path).map_err(|source| Error::Read {
            path: path.to_path_buf(),
            source,
        })?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .map_err(|source| Error::Read {
                path: path.to_path_buf(),
                source,
            })?;
        Self::read_from_str(&contents)
    }

    /// Parse lockfile JSON from `str`.
    pub fn read_from_str(str: &str) -> Result<Self, Error> {
        serde_json::from_str(str).map_err(|e| Error::Lock(LockError::Parse(e)))
    }

    /// Name of the root node.
    pub fn root(&self) -> &str {
        &self.root
    }

    /// Resolve an [`AttrPath`] to the node key it ultimately points at,
    /// walking the lock tree from `root`.
    ///
    /// [`Input::Indirect`] entries are `follows` paths of input *names*
    /// rooted at the lock root, not node keys, so encountering one restarts
    /// the walk from root with that path plus any remaining segments.
    fn resolve_input_path(&self, path: &AttrPath) -> Result<String, LockError> {
        // Bound recursion: a valid lock file has no follows cycles, but we
        // still guard against malformed input.
        const MAX_HOPS: usize = 64;
        self.resolve_input_path_inner(path.segments(), MAX_HOPS)
    }

    /// `segments` is non-empty by construction: callers either forward an
    /// [`AttrPath`]'s segments or prepend an [`Input::Indirect`] follows
    /// path, both of which are non-empty.
    fn resolve_input_path_inner(
        &self,
        segments: &[Segment],
        budget: usize,
    ) -> Result<String, LockError> {
        if budget == 0 {
            return Err(LockError::FollowsCycle);
        }

        let mut current_key = self.root.clone();
        let mut current_node = self.nodes.get(self.root()).ok_or(LockError::MissingRoot)?;

        for (i, segment) in segments.iter().enumerate() {
            let inputs = current_node.inputs.as_ref().ok_or_else(|| {
                if i == 0 {
                    LockError::RootHasNoInputs
                } else {
                    let prefix: Vec<_> = segments[..i].iter().map(|s| s.as_str()).collect();
                    LockError::InputHasNoSubInputs {
                        path: prefix.join("."),
                    }
                }
            })?;

            let resolved = inputs.get(segment.as_str()).ok_or_else(|| {
                let prefix: Vec<_> = segments[..=i].iter().map(|s| s.as_str()).collect();
                LockError::InputNotFound {
                    path: prefix.join("."),
                }
            })?;

            match resolved {
                Input::Direct(node_key) => {
                    current_key = node_key.clone();
                }
                Input::Indirect(Some(follows_path)) => {
                    let mut new_path: Vec<Segment> = follows_path.segments().to_vec();
                    new_path.extend(segments[i + 1..].iter().cloned());
                    return self.resolve_input_path_inner(&new_path, budget - 1);
                }
                Input::Indirect(None) => {
                    let prefix: Vec<_> = segments[..=i].iter().map(|s| s.as_str()).collect();
                    return Err(LockError::FollowsTargetMissing {
                        path: prefix.join("."),
                    });
                }
            }

            if i + 1 < segments.len() {
                current_node = self.nodes.get(&current_key).ok_or_else(|| {
                    let prefix: Vec<_> = segments[..=i].iter().map(|s| s.as_str()).collect();
                    LockError::NodeMissingForPath {
                        node: current_key.clone(),
                        path: prefix.join("."),
                    }
                })?;
            }
        }

        Ok(current_key)
    }

    /// Resolve `path` to its locked revision.
    ///
    /// # Errors
    ///
    /// Returns a [`Error::Lock`] wrapping the underlying
    /// [`LockError`] if any segment is missing in the lock graph, the
    /// resolved node is not present, or it carries no `rev`.
    pub fn rev_for(&self, path: &AttrPath) -> Result<String, Error> {
        let node_name = self.resolve_input_path(path)?;
        let node = self
            .nodes
            .get(&node_name)
            .ok_or_else(|| LockError::NodeMissing {
                node: node_name.clone(),
            })?;
        Ok(node.rev()?)
    }

    /// All nested inputs reachable from the root, with their existing
    /// follows targets.
    ///
    /// Walks `flake.lock` recursively from the root, emitting one entry per
    /// `inputs.X` on any descendant node and building the path
    /// segment-by-segment. Capped at [`NESTED_INPUTS_MAX_DEPTH`]. Cycles in
    /// the node graph are broken by a visited set keyed on node name.
    ///
    /// Output is sorted by path for stable emission order.
    pub fn nested_inputs(&self) -> Vec<NestedInput> {
        #[cfg(test)]
        NESTED_INPUTS_CALLS.with(|c| c.set(c.get() + 1));

        let mut inputs = Vec::new();
        let Some(root_node) = self.nodes.get(&self.root) else {
            return inputs;
        };
        let Some(root_inputs) = &root_node.inputs else {
            return inputs;
        };

        for (top_level_name, top_level_ref) in root_inputs {
            let node_name = match top_level_ref {
                Input::Direct(name) => name.clone(),
                // Indirect top-level inputs have no sub-inputs to descend
                // into. Their follows edges still appear via the recursive
                // walker on the `Direct` siblings that own them.
                Input::Indirect(_) => continue,
            };
            let Ok(parent_seg) = Segment::from_unquoted(top_level_name.clone()) else {
                continue;
            };
            let path = AttrPath::new(parent_seg);
            let mut visited: HashMap<String, ()> = HashMap::new();
            visited.insert(node_name.clone(), ());
            self.collect_nested_inputs_recursive(&node_name, &path, 1, &mut visited, &mut inputs);
        }

        inputs.sort_by(|a, b| a.path.cmp(&b.path));
        inputs
    }

    /// Descend through `node_name`, emitting one [`NestedInput`] per declared
    /// sub-input up to [`NESTED_INPUTS_MAX_DEPTH`].
    fn collect_nested_inputs_recursive(
        &self,
        node_name: &str,
        parent_path: &AttrPath,
        depth: usize,
        visited: &mut HashMap<String, ()>,
        out: &mut Vec<NestedInput>,
    ) {
        if depth >= NESTED_INPUTS_MAX_DEPTH {
            return;
        }
        let Some(node) = self.nodes.get(node_name) else {
            return;
        };
        let Some(node_inputs) = &node.inputs else {
            return;
        };

        // Iterate sub-inputs in lex order so emission is deterministic.
        let mut keys: Vec<&String> = node_inputs.keys().collect();
        keys.sort();
        for nested_name in keys {
            let nested_ref = node_inputs.get(nested_name).unwrap();
            let Ok(nested_seg) = Segment::from_unquoted(nested_name.clone()) else {
                continue;
            };
            let mut path = parent_path.clone();
            path.push(nested_seg);

            let (follows, url, descend_into) = match nested_ref {
                Input::Indirect(Some(target)) => (Some(target.clone()), None, None),
                // Empty `[]` declarations have no follows target. Emit
                // the input with `follows: None` so the path is still
                // visible to the UI.
                Input::Indirect(None) => (None, None, None),
                Input::Direct(child_node_name) => {
                    let url = self
                        .nodes
                        .get(child_node_name.as_str())
                        .and_then(|n| n.original.as_ref())
                        .and_then(|o| o.to_flake_url());
                    (None, url, Some(child_node_name.clone()))
                }
            };

            out.push(NestedInput {
                path: path.clone(),
                follows,
                url,
            });

            if let Some(child) = descend_into {
                if visited.contains_key(&child) {
                    continue;
                }
                visited.insert(child.clone(), ());
                self.collect_nested_inputs_recursive(&child, &path, depth + 1, visited, out);
                visited.remove(&child);
            }
        }
    }
}

/// Maximum recursion depth for [`FlakeLock::nested_inputs`]. Backstops
/// pathological cycles in malformed lockfiles.
pub const NESTED_INPUTS_MAX_DEPTH: usize = 64;
#[cfg(test)]
mod tests {
    use super::*;

    fn minimal_lock() -> &'static str {
        r#"
    {
  "nodes": {
    "nixpkgs": {
      "locked": {
        "lastModified": 1718714799,
        "narHash": "sha256-FUZpz9rg3gL8NVPKbqU8ei1VkPLsTIfAJ2fdAf5qjak=",
        "owner": "nixos",
        "repo": "nixpkgs",
        "rev": "c00d587b1a1afbf200b1d8f0b0e4ba9deb1c7f0e",
        "type": "github"
      },
      "original": {
        "owner": "nixos",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "root": {
      "inputs": {
        "nixpkgs": "nixpkgs"
      }
    }
  },
  "root": "root",
  "version": 7
}
    "#
    }
    fn minimal_independent_lock_no_overrides() -> &'static str {
        r#"
    {
  "nodes": {
    "nixpkgs": {
      "locked": {
        "lastModified": 1721138476,
        "narHash": "sha256-+W5eZOhhemLQxelojLxETfbFbc19NWawsXBlapYpqIA=",
        "owner": "nixos",
        "repo": "nixpkgs",
        "rev": "ad0b5eed1b6031efaed382844806550c3dcb4206",
        "type": "github"
      },
      "original": {
        "owner": "nixos",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "nixpkgs_2": {
      "locked": {
        "lastModified": 1719690277,
        "narHash": "sha256-0xSej1g7eP2kaUF+JQp8jdyNmpmCJKRpO12mKl/36Kc=",
        "owner": "nixos",
        "repo": "nixpkgs",
        "rev": "2741b4b489b55df32afac57bc4bfd220e8bf617e",
        "type": "github"
      },
      "original": {
        "owner": "nixos",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "root": {
      "inputs": {
        "nixpkgs": "nixpkgs",
        "treefmt-nix": "treefmt-nix"
      }
    },
    "treefmt-nix": {
      "inputs": {
        "nixpkgs": "nixpkgs_2"
      },
      "locked": {
        "lastModified": 1721382922,
        "narHash": "sha256-GYpibTC0YYKRpFR9aftym9jjRdUk67ejw1IWiaQkaiU=",
        "owner": "numtide",
        "repo": "treefmt-nix",
        "rev": "50104496fb55c9140501ea80d183f3223d13ff65",
        "type": "github"
      },
      "original": {
        "owner": "numtide",
        "repo": "treefmt-nix",
        "type": "github"
      }
    }
  },
  "root": "root",
  "version": 7
}
    "#
    }

    fn minimal_independent_lock_nixpkgs_overridden() -> &'static str {
        r#"
    {
  "nodes": {
    "nixpkgs": {
      "locked": {
        "lastModified": 1721138476,
        "narHash": "sha256-+W5eZOhhemLQxelojLxETfbFbc19NWawsXBlapYpqIA=",
        "owner": "nixos",
        "repo": "nixpkgs",
        "rev": "ad0b5eed1b6031efaed382844806550c3dcb4206",
        "type": "github"
      },
      "original": {
        "owner": "nixos",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    },
    "root": {
      "inputs": {
        "nixpkgs": "nixpkgs",
        "treefmt-nix": "treefmt-nix"
      }
    },
    "treefmt-nix": {
      "inputs": {
        "nixpkgs": [
          "nixpkgs"
        ]
      },
      "locked": {
        "lastModified": 1721382922,
        "narHash": "sha256-GYpibTC0YYKRpFR9aftym9jjRdUk67ejw1IWiaQkaiU=",
        "owner": "numtide",
        "repo": "treefmt-nix",
        "rev": "50104496fb55c9140501ea80d183f3223d13ff65",
        "type": "github"
      },
      "original": {
        "owner": "numtide",
        "repo": "treefmt-nix",
        "type": "github"
      }
    }
  },
  "root": "root",
  "version": 7
}
    "#
    }

    #[test]
    fn parse_minimal() {
        let minimal_lock = minimal_lock();
        FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
    }
    /// The lockfile's top-level `"version"` field is not validated. A
    /// wildly unsupported version (e.g. `99`) must still parse cleanly
    /// so this crate can read whatever shape Nix produces.
    #[test]
    fn parse_ignores_unknown_version() {
        let lock = r#"{
  "nodes": { "root": { "inputs": {} } },
  "root": "root",
  "version": 99
}"#;
        FlakeLock::read_from_str(lock).expect("unknown version must still parse");
    }
    #[test]
    fn parse_minimal_root() {
        let minimal_lock = minimal_lock();
        let parsed_lock =
            FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
        assert_eq!("root", parsed_lock.root);
    }
    #[test]
    fn minimal_ref() {
        let minimal_lock = minimal_lock();
        let parsed_lock =
            FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
        assert_eq!(
            "c00d587b1a1afbf200b1d8f0b0e4ba9deb1c7f0e",
            parsed_lock
                .rev_for(&"nixpkgs".parse().unwrap())
                .expect("Id: nixpkgs is in the lockfile.")
        );
    }
    #[test]
    fn parse_minimal_independent_lock_no_overrides() {
        let minimal_lock = minimal_independent_lock_no_overrides();
        FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
    }
    #[test]
    fn minimal_independent_lock_no_overrides_ref() {
        let minimal_lock = minimal_independent_lock_no_overrides();
        let parsed_lock =
            FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
        assert_eq!(
            "ad0b5eed1b6031efaed382844806550c3dcb4206",
            parsed_lock
                .rev_for(&"nixpkgs".parse().unwrap())
                .expect("Id: nixpkgs is in the lockfile.")
        );
    }
    #[test]
    fn parse_minimal_independent_lock_nixpkgs_overridden() {
        let minimal_lock = minimal_independent_lock_nixpkgs_overridden();
        FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
    }

    #[test]
    fn rev_for_sub_input_path_missing_parent_returns_error() {
        let minimal_lock = minimal_lock();
        let parsed_lock =
            FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
        assert!(
            parsed_lock
                .rev_for(&"browseros.nixpkgs".parse().unwrap())
                .is_err()
        );
    }

    #[test]
    fn rev_for_sub_input_path_resolves() {
        let lock = minimal_independent_lock_no_overrides();
        let parsed = FlakeLock::read_from_str(lock).expect("Should be parsed correctly.");
        assert_eq!(
            "2741b4b489b55df32afac57bc4bfd220e8bf617e",
            parsed
                .rev_for(&"treefmt-nix.nixpkgs".parse().unwrap())
                .expect("Should resolve sub-input path")
        );
    }

    #[test]
    fn rev_for_sub_input_follows_resolves() {
        let lock = minimal_independent_lock_nixpkgs_overridden();
        let parsed = FlakeLock::read_from_str(lock).expect("Should be parsed correctly.");
        assert_eq!(
            parsed.rev_for(&"nixpkgs".parse().unwrap()).unwrap(),
            parsed
                .rev_for(&"treefmt-nix.nixpkgs".parse().unwrap())
                .expect("Should resolve followed sub-input")
        );
    }

    #[test]
    fn rev_for_quoted_id() {
        // Quoted attribute names like `"nixpkgs-24.11"` from `list --format simple`
        // should be stripped before lock lookup.
        let minimal_lock = minimal_lock();
        let parsed_lock =
            FlakeLock::read_from_str(minimal_lock).expect("Should be parsed correctly.");
        assert_eq!(
            parsed_lock.rev_for(&"nixpkgs".parse().unwrap()).unwrap(),
            parsed_lock
                .rev_for(&"\"nixpkgs\"".parse().unwrap())
                .unwrap(),
        );
    }

    #[test]
    fn rev_for_node_without_locked_returns_error() {
        let lock = r#"{
  "nodes": {
    "root": {
      "inputs": { "bare": "bare" }
    },
    "bare": {
      "original": { "owner": "o", "repo": "r", "type": "github" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        assert!(parsed.rev_for(&"bare".parse().unwrap()).is_err());
    }

    #[test]
    fn rev_for_node_without_rev_returns_error() {
        // `path` is set only so the `original` block deserializes; this
        // test is about missing `locked.rev`.
        let lock = r#"{
  "nodes": {
    "root": {
      "inputs": { "norev": "norev" }
    },
    "norev": {
      "locked": { "lastModified": 1, "narHash": "", "type": "path" },
      "original": { "type": "path", "path": "/tmp/norev" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        assert!(parsed.rev_for(&"norev".parse().unwrap()).is_err());
    }

    #[test]
    fn nested_input_path_quotes_dots() {
        let lock = r#"{
  "nodes": {
    "hls-1.10": {
      "inputs": { "nixpkgs": "nixpkgs_2" },
      "flake": false,
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "abc", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixpkgs": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "abc", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixpkgs_2": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "def", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": {
      "inputs": { "hls-1.10": "hls-1.10", "nixpkgs": "nixpkgs" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        let nested = parsed.nested_inputs();
        assert_eq!(nested.len(), 1);
        assert_eq!(nested[0].path.to_string(), "\"hls-1.10\".nixpkgs");
    }

    #[test]
    fn nested_inputs_recurses_to_grandchild() {
        // The walker descends through `Direct` children, so a depth-2
        // nested input (root → neovim → nixvim → flake-parts) must be
        // emitted with a 3-segment path. This exercises the recursive
        // path-stack code in `collect_nested_inputs_recursive`.
        let lock = r#"{
  "nodes": {
    "flake-parts": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "a", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "flake-parts_2": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "b", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "neovim": {
      "inputs": { "nixvim": "nixvim" },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "c", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixvim": {
      "inputs": { "flake-parts": "flake-parts_2" },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "d", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": {
      "inputs": { "flake-parts": "flake-parts", "neovim": "neovim" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        let nested = parsed.nested_inputs();
        let paths: Vec<String> = nested.iter().map(|n| n.path.to_string()).collect();
        assert!(
            paths.contains(&"neovim.nixvim".to_string()),
            "depth-1 path missing, got: {paths:?}"
        );
        assert!(
            paths.contains(&"neovim.nixvim.flake-parts".to_string()),
            "depth-2 path missing, got: {paths:?}"
        );
    }

    #[test]
    fn nested_inputs_terminates_on_cyclic_lockfile() {
        // A pathological lock graph where node A's input recurses back
        // into A itself must not loop forever. The visited-set in
        // `collect_nested_inputs_recursive` short-circuits the cycle.
        let lock = r#"{
  "nodes": {
    "a": {
      "inputs": { "b": "b" },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "a", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "b": {
      "inputs": { "a": "a" },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "b", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": { "inputs": { "a": "a" } }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        let nested = parsed.nested_inputs();
        assert!(!nested.is_empty());
        assert!(
            nested
                .iter()
                .all(|n| n.path.len() <= NESTED_INPUTS_MAX_DEPTH)
        );
    }

    #[test]
    fn rev_for_quoted_sub_input_path() {
        let lock = r#"{
  "nodes": {
    "hls-1.10": {
      "inputs": { "nixpkgs": "nixpkgs_2" },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "abc", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixpkgs": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "abc", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixpkgs_2": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "def", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": {
      "inputs": { "hls-1.10": "hls-1.10", "nixpkgs": "nixpkgs" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        assert_eq!(
            "def",
            parsed
                .rev_for(&"\"hls-1.10\".nixpkgs".parse().unwrap())
                .expect("Should resolve quoted sub-input path")
        );
    }

    /// An `Indirect` follows path names *inputs* from the lock root, not node
    /// keys. Resolution must go through `root.inputs`, which may map e.g.
    /// `nixpkgs` to a node keyed `nixpkgs_2`.
    #[test]
    fn rev_for_indirect_resolves_via_root_inputs() {
        let lock = r#"{
  "nodes": {
    "nixpkgs_2": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "treefmt-nix": {
      "inputs": { "nixpkgs": ["nixpkgs"] },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": {
      "inputs": { "nixpkgs": "nixpkgs_2", "treefmt-nix": "treefmt-nix" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        // treefmt-nix.nixpkgs follows ["nixpkgs"], i.e. root.inputs.nixpkgs,
        // which is node "nixpkgs_2". There is no node literally named "nixpkgs".
        assert_eq!(
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            parsed
                .rev_for(&"treefmt-nix.nixpkgs".parse().unwrap())
                .expect("indirect follows must resolve through root.inputs, not by node name")
        );
    }

    /// A multi-segment follows path like `["crane", "nixpkgs"]` must be walked
    /// segment-by-segment from root, since each hop can map to a renamed node key.
    #[test]
    fn rev_for_indirect_multi_segment_path() {
        let lock = r#"{
  "nodes": {
    "nixpkgs": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "1111111111111111111111111111111111111111", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixpkgs_2": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "2222222222222222222222222222222222222222", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "crane": {
      "inputs": { "nixpkgs": "nixpkgs_2" },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "cccccccccccccccccccccccccccccccccccccccc", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "devshell": {
      "inputs": { "nixpkgs": ["crane", "nixpkgs"] },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "dddddddddddddddddddddddddddddddddddddddd", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": {
      "inputs": { "nixpkgs": "nixpkgs", "crane": "crane", "devshell": "devshell" }
    }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).unwrap();
        // devshell.nixpkgs follows ["crane","nixpkgs"] -> node "nixpkgs_2" (rev 222...),
        // NOT root's "nixpkgs" node (rev 111...).
        assert_eq!(
            "2222222222222222222222222222222222222222",
            parsed
                .rev_for(&"devshell.nixpkgs".parse().unwrap())
                .expect("multi-segment indirect follows must be walked from root")
        );
    }

    /// Walk every `inputs` map and collect each `Indirect` follows target as
    /// a vector of segment strings. Used by the fixture parse tests below.
    fn collect_indirect_targets(lock: &FlakeLock) -> Vec<(String, String, Vec<String>)> {
        let mut out: Vec<(String, String, Vec<String>)> = Vec::new();
        for (node_name, node) in &lock.nodes {
            let Some(inputs) = node.inputs.as_ref() else {
                continue;
            };
            for (input_name, input_ref) in inputs {
                if let Input::Indirect(Some(path)) = input_ref {
                    let segs: Vec<String> = path
                        .segments()
                        .iter()
                        .map(|s| s.as_str().to_string())
                        .collect();
                    out.push((node_name.clone(), input_name.clone(), segs));
                }
            }
        }
        out.sort();
        out
    }

    /// `depth_upstream_redundant_depth3.flake.lock` has three `Indirect`
    /// entries forming the upstream-propagation chain: `omnibus.nixpkgs`
    /// follows `["nixpkgs"]`, the depth-2 follows `["omnibus", "nixpkgs"]`,
    /// and the depth-3 follows `["omnibus", "flops", "nixpkgs"]`.
    #[test]
    fn fixture_depth_upstream_redundant_depth3_parses_indirects() {
        let lock_text =
            std::fs::read_to_string("tests/fixtures/depth_upstream_redundant_depth3.flake.lock")
                .expect("fixture present");
        let lock = FlakeLock::read_from_str(&lock_text).expect("fixture parses");
        let mut segs_only: Vec<Vec<String>> = collect_indirect_targets(&lock)
            .into_iter()
            .map(|(_, _, segs)| segs)
            .collect();
        segs_only.sort();
        assert_eq!(
            segs_only,
            vec![
                vec!["nixpkgs".to_string()],
                vec![
                    "omnibus".to_string(),
                    "flops".to_string(),
                    "nixpkgs".to_string()
                ],
                vec!["omnibus".to_string(), "nixpkgs".to_string()],
            ],
            "Indirect entries must be decoded with their full structural depth",
        );
    }

    /// `depth_upstream_partial.flake.lock` covers a deeper mix of Indirect
    /// shapes; verify each one is decoded into a non-empty `AttrPath` whose
    /// segments are valid Nix names (no embedded quotes / control chars).
    #[test]
    fn fixture_depth_upstream_partial_parses_indirects() {
        let lock_text = std::fs::read_to_string("tests/fixtures/depth_upstream_partial.flake.lock")
            .expect("fixture present");
        let lock = FlakeLock::read_from_str(&lock_text).expect("fixture parses");
        let entries = collect_indirect_targets(&lock);
        assert!(
            entries.len() >= 3,
            "fixture has at least three Indirect arrays, got {}",
            entries.len()
        );
        for (node, input, segs) in &entries {
            assert!(
                !segs.is_empty(),
                "{node}.{input}: Indirect path must be non-empty",
            );
            for seg in segs {
                assert!(
                    !seg.is_empty() && !seg.contains('"'),
                    "{node}.{input}: segment `{seg}` must be a valid Nix name",
                );
            }
        }
    }

    /// `dot_ancestor_cycle.flake.lock` exercises the dotted-segment case:
    /// the lockfile node `hls-1.10` is reachable through the typed
    /// `AttrPath`, even though a literal dot in the segment forces source-
    /// form quoting at the `flake.nix` boundary.
    #[test]
    fn fixture_dot_ancestor_cycle_parses_indirects_with_dotted_node() {
        let lock_text = std::fs::read_to_string("tests/fixtures/dot_ancestor_cycle.flake.lock")
            .expect("fixture present");
        let lock = FlakeLock::read_from_str(&lock_text).expect("fixture parses");
        // Direct walk: the dotted node `hls-1.10` exists and its
        // `Indirect` `["helper"]` entry is decoded as a one-segment path.
        let hls = lock.nodes.get("hls-1.10").expect("hls-1.10 node");
        let inputs = hls.inputs.as_ref().expect("hls-1.10 has inputs");
        match inputs.get("helper").expect("helper input present") {
            Input::Indirect(Some(path)) => {
                let segs: Vec<&str> = path.segments().iter().map(|s| s.as_str()).collect();
                assert_eq!(segs, vec!["helper"]);
            }
            Input::Indirect(None) => panic!("expected Indirect(Some), got Indirect(None)"),
            Input::Direct(name) => panic!("expected Indirect, got Direct({name})"),
        }
    }

    /// Empty `[]` follows arrays mark an input whose follows chain has
    /// been overridden away (e.g. a lockfile entry `inputs.flake-compat
    /// = []`). The deserializer must accept them and store them as
    /// `Indirect(None)`.
    #[test]
    fn indirect_empty_array_is_accepted_as_none() {
        let lock = r#"{
  "nodes": {
    "child": {
      "inputs": { "disabled": [] },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "x", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": { "inputs": { "child": "child" } }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).expect("empty Indirect must parse");
        let child = parsed.nodes.get("child").expect("child node");
        let inputs = child.inputs.as_ref().expect("child has inputs");
        match inputs.get("disabled").expect("disabled input present") {
            Input::Indirect(None) => {}
            other => panic!("expected Indirect(None), got {other:?}"),
        }
    }

    /// A top-level input (`nix`) whose nested inputs map mixes
    /// [`Input::Direct`] references, non-empty
    /// [`Input::Indirect`] arrays (`["nixpkgs"]`), and empty `[]`
    /// declarations must parse cleanly. [`FlakeLock::nested_inputs`]
    /// emits one entry per declaration; entries built from `[]` carry
    /// `follows: None`.
    #[test]
    fn nested_inputs_handles_mixed_direct_indirect_and_empty() {
        let lock = r#"{
  "nodes": {
    "flake-parts": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "fp", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nix": {
      "inputs": {
        "flake-compat": [],
        "flake-parts": "flake-parts",
        "nixpkgs": ["nixpkgs"]
      },
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "n", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "nixpkgs": {
      "locked": { "lastModified": 1, "narHash": "", "owner": "o", "repo": "r", "rev": "np", "type": "github" },
      "original": { "owner": "o", "repo": "r", "type": "github" }
    },
    "root": { "inputs": { "nix": "nix", "nixpkgs": "nixpkgs" } }
  },
  "root": "root",
  "version": 7
}"#;
        let parsed = FlakeLock::read_from_str(lock).expect("mixed-shape lock parses");
        let nested = parsed.nested_inputs();
        let by_path: std::collections::HashMap<String, &NestedInput> =
            nested.iter().map(|n| (n.path.to_string(), n)).collect();

        let disabled = by_path
            .get("nix.flake-compat")
            .expect("empty Indirect emitted as nested input");
        assert!(
            disabled.follows.is_none(),
            "empty `[]` must surface as follows: None, got {:?}",
            disabled.follows
        );

        let resolved = by_path
            .get("nix.nixpkgs")
            .expect("non-empty Indirect emitted as nested input");
        assert_eq!(
            resolved.follows.as_ref().map(|p| p.to_string()),
            Some("nixpkgs".to_string()),
            "non-empty Indirect must surface its follows target",
        );
    }

    /// A bare `https://...` parses as a `tarball` flakeref, not a
    /// `git` repo, so the missing `git+` prefix is a silent corruption
    /// rather than a parse error.
    #[test]
    fn to_flake_url_git_type_prepends_scheme() {
        let o = Original::Git {
            url: "https://git.clan.lol/clan/munix".to_string(),
            ref_field: None,
        };
        assert_eq!(
            o.to_flake_url().as_deref(),
            Some("git+https://git.clan.lol/clan/munix"),
        );
    }

    /// Loss of `ref` would unpin the reconstructed URL from the branch
    /// the lock captured.
    #[test]
    fn to_flake_url_git_with_ref_appends_query() {
        let o = Original::Git {
            url: "https://git.example.com/repo".to_string(),
            ref_field: Some("main".to_string()),
        };
        assert_eq!(
            o.to_flake_url().as_deref(),
            Some("git+https://git.example.com/repo?ref=main"),
        );
    }

    /// The lockfile type is `"hg"` (not `"mercurial"`); the previous
    /// spelling silently matched no input and dropped every hg
    /// promotion.
    #[test]
    fn to_flake_url_hg_type_prepends_scheme() {
        let o = Original::Hg {
            url: "https://hg.example.com/repo".to_string(),
            ref_field: None,
        };
        assert_eq!(
            o.to_flake_url().as_deref(),
            Some("hg+https://hg.example.com/repo"),
        );
    }

    /// `original.url` may already carry a `?` (Nix only strips
    /// recognized params like `ref` / `shallow`; the rest stay
    /// in-band). Appending `?ref=` would produce two `?`, which Nix
    /// rejects.
    #[test]
    fn to_flake_url_git_with_existing_query_appends_with_ampersand() {
        let o = Original::Git {
            url: "https://git.example.com/repo?dir=subdir".to_string(),
            ref_field: Some("main".to_string()),
        };
        assert_eq!(
            o.to_flake_url().as_deref(),
            Some("git+https://git.example.com/repo?dir=subdir&ref=main"),
        );
    }

    #[test]
    fn to_flake_url_tarball_returns_url_unchanged() {
        let o = Original::Tarball {
            url: "https://channels.nixos.org/nixos-25.05/nixexprs.tar.xz".to_string(),
        };
        assert_eq!(
            o.to_flake_url().as_deref(),
            Some("https://channels.nixos.org/nixos-25.05/nixexprs.tar.xz"),
        );
    }

    #[test]
    fn to_flake_url_path_uses_path_field() {
        let o = Original::Path {
            path: "/etc/nixos".to_string(),
        };
        assert_eq!(o.to_flake_url().as_deref(), Some("path:/etc/nixos"));
    }

    #[test]
    fn to_flake_url_indirect_uses_id_field() {
        let o = Original::Indirect {
            id: "nixpkgs".to_string(),
            ref_field: None,
        };
        assert_eq!(o.to_flake_url().as_deref(), Some("flake:nixpkgs"));
    }

    /// Indirect refs use a path component (`flake:<id>/<ref>`) rather
    /// than the `?ref=` query the VCS schemes use; pin the test on
    /// that asymmetry.
    #[test]
    fn to_flake_url_indirect_with_ref_appends_path_component() {
        let o = Original::Indirect {
            id: "nixpkgs".to_string(),
            ref_field: Some("nixos-25.05".to_string()),
        };
        assert_eq!(
            o.to_flake_url().as_deref(),
            Some("flake:nixpkgs/nixos-25.05"),
        );
    }

    /// Unrecognized `type` strings deserialize to [`Original::Unknown`]
    /// and [`Original::to_flake_url`] returns `None`.
    #[test]
    fn to_flake_url_unknown_type_returns_none() {
        let o: Original = serde_json::from_str(r#"{"type": "future-type"}"#).unwrap();
        assert!(matches!(&o, Original::Unknown { node_type } if node_type == "future-type"));
        assert_eq!(o.to_flake_url(), None);
    }

    /// Malformed payload of a recognized type must be a parse error, not
    /// a silent fall-through to [`Original::Unknown`]. The error message
    /// must name the missing field so the failure is actionable.
    #[test]
    fn malformed_known_type_is_a_parse_error() {
        let err = serde_json::from_str::<Original>(r#"{"type": "github"}"#).unwrap_err();
        assert!(
            err.to_string().contains("owner"),
            "error must name the missing field, got: {err}",
        );
    }

    /// A node with `original.type` absent is malformed at the protocol
    /// level. Surface it as a parse error rather than coercing to
    /// `Unknown { node_type: "" }`.
    #[test]
    fn missing_type_is_a_parse_error() {
        let err = serde_json::from_str::<Original>(r#"{}"#).unwrap_err();
        assert!(
            err.to_string().contains("type"),
            "error must name the missing field, got: {err}",
        );
    }
}