Skip to main content

flake_edit/
input.rs

1use rnix::TextRange;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Clone, PartialEq, Hash, Eq, Deserialize, Serialize, PartialOrd, Ord)]
5pub struct Input {
6    pub(crate) id: String,
7    pub(crate) flake: bool,
8    pub(crate) url: String,
9    pub(crate) follows: Vec<Follows>,
10    pub range: Range,
11}
12
13#[derive(Debug, Default, Clone, PartialEq, Hash, Eq, Deserialize, Serialize, PartialOrd, Ord)]
14pub struct Range {
15    pub start: usize,
16    pub end: usize,
17}
18
19impl Range {
20    pub fn from_text_range(text_range: TextRange) -> Self {
21        Self {
22            start: text_range.start().into(),
23            end: text_range.end().into(),
24        }
25    }
26}
27
28#[derive(Debug, Clone, PartialEq, Hash, Eq, Deserialize, Serialize, PartialOrd, Ord)]
29pub enum Follows {
30    // From , To
31    Indirect(String, String),
32    // From , To
33    Direct(String, Input),
34}
35
36impl Default for Input {
37    fn default() -> Self {
38        Self {
39            id: String::new(),
40            flake: true,
41            url: String::new(),
42            follows: vec![],
43            range: Range::default(),
44        }
45    }
46}
47
48impl Input {
49    pub(crate) fn new(name: String) -> Self {
50        Self {
51            id: name,
52            ..Self::default()
53        }
54    }
55
56    /// Create an Input with id, url, and range set from a TextRange.
57    pub(crate) fn with_url(id: String, url: String, text_range: TextRange) -> Self {
58        Self {
59            id,
60            url,
61            range: Range::from_text_range(text_range),
62            ..Self::default()
63        }
64    }
65
66    pub fn id(&self) -> &str {
67        self.id.as_ref()
68    }
69    /// Return the id with surrounding double-quotes stripped.
70    ///
71    /// AST-extracted identifiers preserve Nix quoting (e.g. `"nixpkgs-24.11"`),
72    /// but user-facing output and comparisons need the bare name.
73    pub fn bare_id(&self) -> &str {
74        self.id
75            .strip_prefix('"')
76            .and_then(|s| s.strip_suffix('"'))
77            .unwrap_or(&self.id)
78    }
79    pub fn url(&self) -> &str {
80        self.url.as_ref()
81    }
82    pub fn follows(&self) -> &Vec<Follows> {
83        self.follows.as_ref()
84    }
85}