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
//! [`Segment`] and [`AttrPath`]: typed attribute paths.
//!
//! [`Segment`] is a single attribute name. [`AttrPath`] is a non-empty
//! sequence of them. Both store values unquoted. The `"..."` quotes Nix
//! requires for names containing dots or leading digits live on the rendering
//! boundary ([`fmt::Display`] / [`Segment::render`]).

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use smallvec::{SmallVec, smallvec};

/// Strip a single outer pair of `"..."` from CST source text.
///
/// Returns the input unchanged when it is not bracketed by quotes.
pub fn strip_outer_quotes(s: &str) -> &str {
    s.strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .unwrap_or(s)
}

/// Sentinel segment used when CST text cannot form a valid [`Segment`].
pub(crate) const INVALID_SEGMENT_SENTINEL: &str = "__invalid__";

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Segment(String);

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SegmentError {
    #[error("segment must not be empty")]
    Empty,
    #[error("segment must not contain an embedded double quote")]
    ContainsQuote,
    #[error("segment must not contain control characters")]
    ContainsControl,
}

impl Segment {
    /// Construct from already-unquoted text.
    ///
    /// Rejects empty input, embedded `"`, and ASCII control characters.
    /// Everything else (`.`, `+`, `/`, leading digits, hyphens, single quotes)
    /// is accepted. [`Self::render`] decides whether to wrap in `"..."`.
    pub fn from_unquoted(s: impl Into<String>) -> Result<Self, SegmentError> {
        let s = s.into();
        if s.is_empty() {
            return Err(SegmentError::Empty);
        }
        if s.contains('"') {
            return Err(SegmentError::ContainsQuote);
        }
        if s.chars().any(|c| c.is_control()) {
            return Err(SegmentError::ContainsControl);
        }
        Ok(Segment(s))
    }

    /// Parse source-form text. Strips a single surrounding pair of `"..."`,
    /// otherwise behaves like [`Self::from_unquoted`].
    pub fn from_source(s: &str) -> Result<Self, SegmentError> {
        let body = if s.len() >= 2 && s.starts_with('"') && s.ends_with('"') {
            &s[1..s.len() - 1]
        } else {
            s
        };
        Segment::from_unquoted(body.to_string())
    }

    /// Build a [`Segment`] from a CST node's source text.
    pub fn from_syntax(node: &rnix::SyntaxNode) -> Result<Self, SegmentError> {
        Segment::from_source(&node.to_string())
    }

    /// Infallible [`Self::from_syntax`]: substitutes [`INVALID_SEGMENT_SENTINEL`]
    /// when the node text would be rejected by [`Self::from_unquoted`], emitting
    /// `tracing::warn!` on the fall-through.
    pub(crate) fn from_syntax_or_sentinel(node: &rnix::SyntaxNode) -> Self {
        Segment::from_syntax(node).unwrap_or_else(|err| {
            let raw = node.to_string();
            tracing::warn!(
                "follows::path::Segment: invalid attribute segment {raw:?} ({err}); using \
                 sentinel {INVALID_SEGMENT_SENTINEL:?}"
            );
            Segment::from_unquoted(INVALID_SEGMENT_SENTINEL)
                .expect("sentinel segment is non-empty and quote-free")
        })
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the segment, returning the unquoted text.
    pub fn into_string(self) -> String {
        self.0
    }

    /// Whether this segment requires source-level `"..."` quoting.
    ///
    /// Bare Nix identifiers match `[a-zA-Z_][a-zA-Z0-9_'-]*`. Anything else
    /// (leading digit, embedded `.`, leading `-`) needs quoting.
    pub fn needs_quoting(&self) -> bool {
        let mut chars = self.0.chars();
        let Some(first) = chars.next() else {
            return true;
        };
        if !(first.is_ascii_alphabetic() || first == '_') {
            return true;
        }
        for c in chars {
            if !(c.is_ascii_alphanumeric() || c == '_' || c == '\'' || c == '-') {
                return true;
            }
        }
        false
    }

    /// Render to source form, wrapping in `"..."` only when needed.
    pub fn render(&self) -> String {
        if self.needs_quoting() {
            format!("\"{}\"", self.0)
        } else {
            self.0.clone()
        }
    }
}

impl fmt::Display for Segment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.render())
    }
}

impl FromStr for Segment {
    type Err = SegmentError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Segment::from_source(s)
    }
}

impl Serialize for Segment {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Segment {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Segment::from_unquoted(s).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AttrPath(SmallVec<[Segment; 2]>);

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AttrPathParseError {
    #[error("attribute path must not be empty")]
    Empty,
    #[error("attribute path has an empty segment")]
    EmptySegment,
    #[error("invalid segment: {0}")]
    SegmentInvalid(#[from] SegmentError),
}

impl AttrPath {
    pub fn new(first: Segment) -> Self {
        AttrPath(smallvec![first])
    }

    /// Parse a dotted path, respecting `"..."` quoting on individual segments.
    ///
    /// Examples:
    /// - `nixpkgs` → 1 segment.
    /// - `crane.nixpkgs` → 2 segments.
    /// - `"hls-1.10".nixpkgs` → 2 segments, the first stored unquoted.
    /// - `a."b.c".d` → 3 segments.
    pub fn parse(s: &str) -> Result<Self, AttrPathParseError> {
        if s.is_empty() {
            return Err(AttrPathParseError::Empty);
        }
        let mut segments: SmallVec<[Segment; 2]> = SmallVec::new();
        let bytes = s.as_bytes();
        let mut start = 0;
        let mut i = 0;
        while i < bytes.len() {
            if bytes[i] == b'"' {
                // Skip until matching closing quote.
                i += 1;
                while i < bytes.len() && bytes[i] != b'"' {
                    i += 1;
                }
                if i < bytes.len() {
                    i += 1; // skip closing quote
                }
            } else if bytes[i] == b'.' {
                let raw = &s[start..i];
                if raw.is_empty() {
                    return Err(AttrPathParseError::EmptySegment);
                }
                segments.push(Segment::from_source(raw)?);
                i += 1;
                start = i;
            } else {
                i += 1;
            }
        }
        let last = &s[start..];
        if last.is_empty() {
            return Err(AttrPathParseError::EmptySegment);
        }
        segments.push(Segment::from_source(last)?);
        Ok(AttrPath(segments))
    }

    pub fn first(&self) -> &Segment {
        &self.0[0]
    }

    pub fn last(&self) -> &Segment {
        self.0.last().expect("AttrPath is non-empty by invariant")
    }

    #[expect(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn segments(&self) -> &[Segment] {
        &self.0
    }

    /// All segments except the last, or `None` for a length-1 path.
    pub fn parent(&self) -> Option<AttrPath> {
        if self.0.len() <= 1 {
            return None;
        }
        let parent_segments: SmallVec<[Segment; 2]> =
            self.0[..self.0.len() - 1].iter().cloned().collect();
        Some(AttrPath(parent_segments))
    }

    /// The second segment, or `None` for length-1 paths.
    pub fn child(&self) -> Option<&Segment> {
        if self.0.len() >= 2 {
            self.0.get(1)
        } else {
            None
        }
    }

    pub fn push(&mut self, seg: Segment) {
        self.0.push(seg);
    }

    /// Whether `self` is a structural prefix of `other`. A path is its own
    /// prefix.
    pub(crate) fn is_prefix_of(&self, other: &AttrPath) -> bool {
        if self.0.len() > other.0.len() {
            return false;
        }
        self.0.iter().zip(other.0.iter()).all(|(a, b)| a == b)
    }

    /// Parse the right-hand side of a `follows = "..."` binding into a typed
    /// target.
    ///
    /// Empty input produces `None`. Non-empty input is split on `/`, the only
    /// separator Nix recognises in a follows target ,  a `.` inside a segment
    /// is part of the identifier (`"hls-1.10/nixpkgs"` is two segments, not
    /// three). Each segment passes through [`Segment::from_unquoted`]; if the
    /// body is malformed the result falls back to a single-segment path
    /// built from `fallback` so the caller never loses an entry.
    pub(crate) fn parse_follows_target(text: &str, fallback: &Segment) -> Option<AttrPath> {
        if text.is_empty() {
            return None;
        }
        let body = strip_outer_quotes(text);
        if body.is_empty() {
            return None;
        }
        let mut segs = body
            .split('/')
            .filter(|s| !s.is_empty())
            .filter_map(|s| Segment::from_unquoted(s.to_string()).ok());
        let Some(first) = segs.next() else {
            return Some(AttrPath::new(fallback.clone()));
        };
        let mut path = AttrPath::new(first);
        for seg in segs {
            path.push(seg);
        }
        Some(path)
    }

    /// Render for the RHS of `follows = "..."`. `Display` emits the
    /// LHS attribute-path form and injects per-segment quoting that
    /// is invalid in this string-value position.
    pub fn to_flake_follows_string(&self) -> String {
        self.0
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join("/")
    }
}

/// Idents for the `inputs.<S0>.inputs.<S1>...inputs.<SN>.follows` attrpath shape.
pub(crate) fn follows_idents_prefixed(segments: &[Segment]) -> Vec<&str> {
    let mut out: Vec<&str> = Vec::with_capacity(segments.len() * 2 + 1);
    for seg in segments {
        out.push("inputs");
        out.push(seg.as_str());
    }
    out.push("follows");
    out
}

/// Idents for the `<S0>.inputs.<S1>...inputs.<SN>.follows` attrpath shape, with
/// no leading `inputs.` qualifier.
pub(crate) fn follows_idents_bare(segments: &[Segment]) -> Vec<&str> {
    let mut out: Vec<&str> = Vec::with_capacity(segments.len() * 2);
    for (i, seg) in segments.iter().enumerate() {
        if i > 0 {
            out.push("inputs");
        }
        out.push(seg.as_str());
    }
    out.push("follows");
    out
}

impl fmt::Display for AttrPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for seg in &self.0 {
            if !first {
                f.write_str(".")?;
            }
            first = false;
            f.write_str(&seg.render())?;
        }
        Ok(())
    }
}

impl FromStr for AttrPath {
    type Err = AttrPathParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        AttrPath::parse(s)
    }
}

impl From<Segment> for AttrPath {
    fn from(value: Segment) -> Self {
        AttrPath::new(value)
    }
}

impl Serialize for AttrPath {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for AttrPath {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        AttrPath::parse(&s).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn segment_from_unquoted_rejects_empty() {
        assert_eq!(Segment::from_unquoted(""), Err(SegmentError::Empty));
    }

    #[test]
    fn segment_from_unquoted_rejects_embedded_quote() {
        assert_eq!(
            Segment::from_unquoted("a\"b"),
            Err(SegmentError::ContainsQuote)
        );
    }

    #[test]
    fn segment_from_unquoted_rejects_control() {
        assert_eq!(
            Segment::from_unquoted("a\nb"),
            Err(SegmentError::ContainsControl)
        );
    }

    #[test]
    fn segment_from_unquoted_accepts_dotted() {
        let s = Segment::from_unquoted("hls-1.10").unwrap();
        assert_eq!(s.as_str(), "hls-1.10");
    }

    #[test]
    fn segment_from_source_strips_quotes() {
        let s = Segment::from_source("\"hls-1.10\"").unwrap();
        assert_eq!(s.as_str(), "hls-1.10");
    }

    #[test]
    fn segment_from_source_unquoted_passthrough() {
        let s = Segment::from_source("nixpkgs").unwrap();
        assert_eq!(s.as_str(), "nixpkgs");
    }

    #[test]
    fn segment_from_syntax_via_rnix() {
        // Build a tiny CST and route the first NODE_STRING through
        // `from_syntax` to verify the round-trip.
        let src = r#"{ inputs."hls-1.10".url = "x"; }"#;
        let parsed = rnix::Root::parse(src);
        let syntax = parsed.syntax();
        fn find_string(node: rnix::SyntaxNode) -> Option<rnix::SyntaxNode> {
            if node.kind() == rnix::SyntaxKind::NODE_STRING {
                return Some(node);
            }
            for c in node.children() {
                if let Some(s) = find_string(c) {
                    return Some(s);
                }
            }
            None
        }
        let string_node = find_string(syntax).expect("has a string node");
        let seg = Segment::from_syntax(&string_node).unwrap();
        // The first NODE_STRING in source order is "hls-1.10".
        assert_eq!(seg.as_str(), "hls-1.10");
    }

    #[test]
    fn segment_needs_quoting_boundaries() {
        for bare in ["nixpkgs", "_x", "foo'bar"] {
            assert!(
                !Segment::from_unquoted(bare).unwrap().needs_quoting(),
                "{bare} should be a bare ident",
            );
        }
        for quoted in ["hls-1.10", "24.11", "-x"] {
            assert!(
                Segment::from_unquoted(quoted).unwrap().needs_quoting(),
                "{quoted} should require quoting",
            );
        }
    }

    #[test]
    fn segment_render_unquoted() {
        let s = Segment::from_unquoted("nixpkgs").unwrap();
        assert_eq!(s.render(), "nixpkgs");
    }

    #[test]
    fn segment_render_quoted() {
        let s = Segment::from_unquoted("hls-1.10").unwrap();
        assert_eq!(s.render(), "\"hls-1.10\"");
    }

    #[test]
    fn segment_display_matches_render() {
        let s = Segment::from_unquoted("hls-1.10").unwrap();
        assert_eq!(format!("{s}"), s.render());
    }

    #[test]
    fn segment_from_str_uses_from_source() {
        let s: Segment = "\"hls-1.10\"".parse().unwrap();
        assert_eq!(s.as_str(), "hls-1.10");
    }

    #[test]
    fn segment_serde_roundtrip_bare() {
        let s = Segment::from_unquoted("nixpkgs").unwrap();
        let j = serde_json::to_string(&s).unwrap();
        assert_eq!(j, "\"nixpkgs\"");
        let back: Segment = serde_json::from_str(&j).unwrap();
        assert_eq!(s, back);
    }

    #[test]
    fn segment_serde_roundtrip_dotted() {
        let s = Segment::from_unquoted("hls-1.10").unwrap();
        let j = serde_json::to_string(&s).unwrap();
        // Wire form has no embedded backslash-quote.
        assert_eq!(j, "\"hls-1.10\"");
        let back: Segment = serde_json::from_str(&j).unwrap();
        assert_eq!(s, back);
    }

    #[test]
    fn attr_path_parse_single_segment() {
        let p = AttrPath::parse("nixpkgs").unwrap();
        assert_eq!(p.len(), 1);
        assert_eq!(p.first().as_str(), "nixpkgs");
    }

    #[test]
    fn attr_path_parse_two_segments() {
        let p = AttrPath::parse("crane.nixpkgs").unwrap();
        assert_eq!(p.len(), 2);
        assert_eq!(p.first().as_str(), "crane");
        assert_eq!(p.last().as_str(), "nixpkgs");
    }

    #[test]
    fn attr_path_parse_quoted_first() {
        let p = AttrPath::parse("\"hls-1.10\".nixpkgs").unwrap();
        assert_eq!(p.len(), 2);
        assert_eq!(p.first().as_str(), "hls-1.10");
        assert_eq!(p.last().as_str(), "nixpkgs");
    }

    #[test]
    fn attr_path_parse_three_segments_middle_quoted() {
        let p = AttrPath::parse("a.\"b.c\".d").unwrap();
        assert_eq!(p.len(), 3);
        assert_eq!(p.segments()[0].as_str(), "a");
        assert_eq!(p.segments()[1].as_str(), "b.c");
        assert_eq!(p.segments()[2].as_str(), "d");
    }

    #[test]
    fn attr_path_parse_empty_rejected() {
        assert_eq!(AttrPath::parse(""), Err(AttrPathParseError::Empty));
    }

    #[test]
    fn attr_path_parse_double_dot_rejected() {
        assert_eq!(
            AttrPath::parse("a..b"),
            Err(AttrPathParseError::EmptySegment)
        );
    }

    #[test]
    fn attr_path_display_roundtrip() {
        for s in ["crane.nixpkgs", "\"hls-1.10\".nixpkgs"] {
            let p = AttrPath::parse(s).unwrap();
            assert_eq!(format!("{p}"), s);
        }
    }

    #[test]
    fn attr_path_parent_none_for_single() {
        let p = AttrPath::parse("nixpkgs").unwrap();
        assert!(p.parent().is_none());
    }

    #[test]
    fn attr_path_parent_some_for_two() {
        let p = AttrPath::parse("crane.nixpkgs").unwrap();
        let parent = p.parent().unwrap();
        assert_eq!(parent.len(), 1);
        assert_eq!(parent.first().as_str(), "crane");
    }

    #[test]
    fn attr_path_child_returns_second_segment() {
        let p = AttrPath::parse("crane.nixpkgs").unwrap();
        assert_eq!(p.child().unwrap().as_str(), "nixpkgs");
    }

    #[test]
    fn attr_path_child_none_for_single() {
        let p = AttrPath::parse("crane").unwrap();
        assert!(p.child().is_none());
    }

    #[test]
    fn attr_path_push_extends() {
        let mut p = AttrPath::parse("a").unwrap();
        p.push(Segment::from_unquoted("b").unwrap());
        assert_eq!(format!("{p}"), "a.b");
    }

    #[test]
    fn attr_path_is_prefix_self() {
        let p = AttrPath::parse("a.b").unwrap();
        assert!(p.is_prefix_of(&p));
    }

    #[test]
    fn attr_path_is_prefix_strict() {
        let a = AttrPath::parse("a").unwrap();
        let ab = AttrPath::parse("a.b").unwrap();
        assert!(a.is_prefix_of(&ab));
        assert!(!ab.is_prefix_of(&a));
    }

    #[test]
    fn attr_path_is_prefix_diverging() {
        let a = AttrPath::parse("a.x").unwrap();
        let b = AttrPath::parse("a.y").unwrap();
        assert!(!a.is_prefix_of(&b));
    }

    #[test]
    fn attr_path_from_segment() {
        let s = Segment::from_unquoted("nixpkgs").unwrap();
        let p: AttrPath = s.clone().into();
        assert_eq!(p.len(), 1);
        assert_eq!(p.first(), &s);
    }

    #[test]
    fn attr_path_from_str_parses() {
        let p: AttrPath = "crane.nixpkgs".parse().unwrap();
        assert_eq!(p.len(), 2);
    }

    #[test]
    fn attr_path_serde_roundtrip() {
        let p = AttrPath::parse("\"hls-1.10\".nixpkgs").unwrap();
        let j = serde_json::to_string(&p).unwrap();
        // Wire form is the canonical Display output (quoted as needed).
        assert_eq!(j, "\"\\\"hls-1.10\\\".nixpkgs\"");
        let back: AttrPath = serde_json::from_str(&j).unwrap();
        assert_eq!(p, back);
    }

    #[test]
    fn attr_path_to_flake_follows_string_simple() {
        let p = AttrPath::parse("nixpkgs").unwrap();
        assert_eq!(p.to_flake_follows_string(), "nixpkgs");
    }

    #[test]
    fn attr_path_to_flake_follows_string_two_segments() {
        let p = AttrPath::parse("crane.nixpkgs").unwrap();
        assert_eq!(p.to_flake_follows_string(), "crane/nixpkgs");
    }

    #[test]
    fn attr_path_to_flake_follows_string_dotted_segment_preserved() {
        let p = AttrPath::parse("\"hls-1.10\".nixpkgs").unwrap();
        // Dot inside a segment must NOT become a slash.
        assert_eq!(p.to_flake_follows_string(), "hls-1.10/nixpkgs");
    }

    #[test]
    fn parse_follows_target_accepts_slash_form() {
        let fallback = Segment::from_unquoted("fallback").unwrap();
        let parsed = AttrPath::parse_follows_target("hyprland/hyprlang", &fallback)
            .expect("non-empty input must parse to Some");
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed.first().as_str(), "hyprland");
        assert_eq!(parsed.last().as_str(), "hyprlang");
    }

    #[test]
    fn parse_follows_target_dot_inside_segment_is_not_a_separator() {
        let fallback = Segment::from_unquoted("fallback").unwrap();

        let single = AttrPath::parse_follows_target("hls-1.10", &fallback).unwrap();
        assert_eq!(single.len(), 1);
        assert_eq!(single.first().as_str(), "hls-1.10");

        let two = AttrPath::parse_follows_target("hls-1.10/nixpkgs", &fallback).unwrap();
        assert_eq!(two.len(), 2);
        assert_eq!(two.first().as_str(), "hls-1.10");
        assert_eq!(two.last().as_str(), "nixpkgs");
    }

    #[test]
    fn segment_from_syntax_or_sentinel_falls_back_on_empty_string() {
        use rnix::SyntaxKind;

        let src = r#"{ inputs."" = {}; }"#;
        let parsed = rnix::Root::parse(src);
        fn find_first_string(node: rnix::SyntaxNode) -> Option<rnix::SyntaxNode> {
            if node.kind() == SyntaxKind::NODE_STRING {
                return Some(node);
            }
            for c in node.children() {
                if let Some(s) = find_first_string(c) {
                    return Some(s);
                }
            }
            None
        }
        let empty_string = find_first_string(parsed.syntax()).expect("CST has an empty string");
        let seg = Segment::from_syntax_or_sentinel(&empty_string);
        assert_eq!(seg.as_str(), super::INVALID_SEGMENT_SENTINEL);
    }

    #[test]
    fn follows_idents_prefixed_interleaves_inputs() {
        let p = AttrPath::parse("crane.nixpkgs").unwrap();
        assert_eq!(
            follows_idents_prefixed(p.segments()),
            vec!["inputs", "crane", "inputs", "nixpkgs", "follows"],
        );
    }

    #[test]
    fn follows_idents_bare_omits_leading_inputs() {
        let p = AttrPath::parse("crane.nixpkgs").unwrap();
        assert_eq!(
            follows_idents_bare(p.segments()),
            vec!["crane", "inputs", "nixpkgs", "follows"],
        );
    }
}