flake-edit 0.3.4

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
use nix_uri::{FlakeRef, RefLocation};
use ropey::Rope;
use std::cmp::Ordering;

use crate::channel::{UpdateStrategy, detect_strategy, find_latest_channel};
use crate::edit::InputMap;
use crate::input::Input;
use crate::uri::is_git_url;
use crate::version::parse_ref;

#[derive(Default, Debug)]
pub struct Updater {
    text: Rope,
    inputs: Vec<UpdateInput>,
    // Keeps track of offset for changing multiple inputs on a single pass.
    offset: i32,
}

enum UpdateTarget {
    GitUrl {
        parsed: Box<FlakeRef>,
        owner: String,
        repo: String,
        domain: String,
        parsed_ref: crate::version::ParsedRef,
    },
    ForgeRef {
        parsed: Box<FlakeRef>,
        owner: String,
        repo: String,
        parsed_ref: crate::version::ParsedRef,
    },
}

impl Updater {
    fn print_update_status(id: &str, previous_version: &str, final_change: &str) -> bool {
        let is_up_to_date = previous_version == final_change;
        let initialized = previous_version.is_empty();

        if is_up_to_date {
            println!(
                "{} is already on the latest version: {previous_version}.",
                id
            );
            return false;
        }

        if initialized {
            println!("Initialized {} version pin at {final_change}.", id);
        } else {
            println!("Updated {} from {previous_version} to {final_change}.", id);
        }

        true
    }
    fn parse_update_target(&self, input: &UpdateInput, init: bool) -> Option<UpdateTarget> {
        let uri = self.get_input_text(input);
        let is_git_url = is_git_url(&uri);

        let parsed = match uri.parse::<FlakeRef>() {
            Ok(parsed) => parsed,
            Err(e) => {
                tracing::error!("Failed to parse URI: {}", e);
                return None;
            }
        };

        let maybe_version = parsed.get_ref_or_rev().unwrap_or_default();
        let parsed_ref = parse_ref(&maybe_version, init);

        if !init && let Err(e) = semver::Version::parse(&parsed_ref.normalized_for_semver) {
            tracing::debug!("Skip non semver version: {}: {}", maybe_version, e);
            return None;
        }

        let owner = match parsed.r#type.get_owner() {
            Some(o) => o,
            None => {
                tracing::debug!("Skipping input without owner");
                return None;
            }
        };

        let repo = match parsed.r#type.get_repo() {
            Some(r) => r,
            None => {
                tracing::debug!("Skipping input without repo");
                return None;
            }
        };

        if is_git_url {
            let domain = parsed.r#type.get_domain()?;
            return Some(UpdateTarget::GitUrl {
                parsed: Box::new(parsed),
                owner,
                repo,
                domain,
                parsed_ref,
            });
        }

        Some(UpdateTarget::ForgeRef {
            parsed: Box::new(parsed),
            owner,
            repo,
            parsed_ref,
        })
    }

    fn fetch_tags(&self, target: &UpdateTarget) -> Option<crate::api::Tags> {
        match target {
            UpdateTarget::GitUrl {
                owner,
                repo,
                domain,
                ..
            } => match crate::api::get_tags(repo, owner, Some(domain)) {
                Ok(tags) => Some(tags),
                Err(_) => {
                    tracing::error!("Failed to fetch tags for {}/{} on {}", owner, repo, domain);
                    None
                }
            },
            UpdateTarget::ForgeRef { owner, repo, .. } => {
                match crate::api::get_tags(repo, owner, None) {
                    Ok(tags) => Some(tags),
                    Err(_) => {
                        tracing::error!("Failed to fetch tags for {}/{}", owner, repo);
                        None
                    }
                }
            }
        }
    }

    fn apply_update(
        &mut self,
        input: &UpdateInput,
        target: &UpdateTarget,
        mut tags: crate::api::Tags,
        _init: bool,
    ) {
        tags.sort();
        if let Some(change) = tags.get_latest_tag() {
            let (parsed, parsed_ref) = match target {
                UpdateTarget::GitUrl {
                    parsed, parsed_ref, ..
                } => (parsed, parsed_ref),
                UpdateTarget::ForgeRef {
                    parsed, parsed_ref, ..
                } => (parsed, parsed_ref),
            };

            let final_change = if parsed_ref.has_refs_tags_prefix {
                format!("refs/tags/{}", change)
            } else {
                change.clone()
            };

            // set_ref() preserves storage location (path vs query param)
            let mut parsed = parsed.clone();
            let _ = parsed.set_ref(Some(final_change.clone()));
            let updated_uri = parsed.to_string();

            if !Self::print_update_status(&input.input.id, &parsed_ref.previous_ref, &final_change)
            {
                return;
            }

            self.update_input(input.clone(), &updated_uri);
        } else {
            tracing::error!("Could not find latest version for Input: {:?}", input);
        }
    }
    pub fn new(text: Rope, map: InputMap) -> Self {
        let mut inputs = vec![];
        for (_id, input) in map {
            // Skip inputs without a URL (e.g. expanded type/owner/repo/ref format
            // or follows-only stubs) — there is no quoted URL value to modify.
            if input.url.is_empty() || input.range.start == 0 && input.range.end == 0 {
                continue;
            }
            inputs.push(UpdateInput { input });
        }
        Self {
            inputs,
            text,
            offset: 0,
        }
    }
    fn get_index(&self, id: &str) -> Option<usize> {
        let bare = id
            .strip_prefix('"')
            .and_then(|s| s.strip_suffix('"'))
            .unwrap_or(id);
        self.inputs.iter().position(|n| n.input.bare_id() == bare)
    }
    /// Pin an input based on it's id to a specific rev.
    pub fn pin_input_to_ref(&mut self, id: &str, rev: &str) -> Result<(), String> {
        self.sort();
        let idx = self.get_index(id).ok_or_else(|| id.to_string())?;
        let input = self.inputs[idx].clone();
        tracing::debug!("Input: {:?}", input);
        self.change_input_to_rev(&input, rev);
        Ok(())
    }
    /// Remove any ?ref= or ?rev= parameters from a specific input.
    pub fn unpin_input(&mut self, id: &str) -> Result<(), String> {
        self.sort();
        let idx = self.get_index(id).ok_or_else(|| id.to_string())?;
        let input = self.inputs[idx].clone();
        tracing::debug!("Input: {:?}", input);
        self.remove_ref_and_rev(&input);
        Ok(())
    }
    /// Update all inputs to a specific semver release,
    /// if a specific input is given, just update the single input.
    pub fn update_all_inputs_to_latest_semver(&mut self, id: Option<String>, init: bool) {
        self.sort();
        let inputs = self.inputs.clone();
        for input in inputs.iter() {
            if let Some(ref input_id) = id {
                if input.input.id == *input_id {
                    self.query_and_update_all_inputs(input, init);
                }
            } else {
                self.query_and_update_all_inputs(input, init);
            }
        }
    }
    pub fn get_changes(&self) -> String {
        self.text.to_string()
    }

    fn get_input_text(&self, input: &UpdateInput) -> String {
        self.text
            .slice(
                ((input.input.range.start as i32) + 1 + self.offset) as usize
                    ..((input.input.range.end as i32) + self.offset - 1) as usize,
            )
            .to_string()
    }

    /// Change a specific input to a specific rev.
    pub fn change_input_to_rev(&mut self, input: &UpdateInput, rev: &str) {
        let uri = self.get_input_text(input);
        match uri.parse::<FlakeRef>() {
            Ok(mut parsed) => {
                // set_rev() preserves storage location (path vs query param)
                let _ = parsed.set_rev(Some(rev.into()));
                self.update_input(input.clone(), &parsed.to_string());
            }
            Err(e) => {
                tracing::error!("Error while changing input: {}", e);
            }
        }
    }
    fn remove_ref_and_rev(&mut self, input: &UpdateInput) {
        let uri = self.get_input_text(input);
        match uri.parse::<FlakeRef>() {
            Ok(mut parsed) => {
                if parsed.ref_source_location() == RefLocation::None {
                    return;
                }
                // set_ref/set_rev handle both path-based and query param storage
                let _ = parsed.set_ref(None);
                let _ = parsed.set_rev(None);
                self.update_input(input.clone(), &parsed.to_string());
            }
            Err(e) => {
                tracing::error!("Error while changing input: {}", e);
            }
        }
    }
    /// Query a forge api for the latest release and update, if necessary.
    pub fn query_and_update_all_inputs(&mut self, input: &UpdateInput, init: bool) {
        let uri = self.get_input_text(input);

        let parsed = match uri.parse::<FlakeRef>() {
            Ok(parsed) => parsed,
            Err(e) => {
                tracing::error!("Failed to parse URI: {}", e);
                return;
            }
        };

        let owner = match parsed.r#type.get_owner() {
            Some(o) => o,
            None => {
                tracing::debug!("Skipping input without owner");
                return;
            }
        };

        let repo = match parsed.r#type.get_repo() {
            Some(r) => r,
            None => {
                tracing::debug!("Skipping input without repo");
                return;
            }
        };

        let strategy = detect_strategy(&owner, &repo);
        tracing::debug!("Update strategy for {}/{}: {:?}", owner, repo, strategy);

        match strategy {
            UpdateStrategy::NixpkgsChannel
            | UpdateStrategy::HomeManagerChannel
            | UpdateStrategy::NixDarwinChannel => {
                self.update_channel_input(input, &parsed);
            }
            UpdateStrategy::SemverTags => {
                self.update_semver_input(input, init);
            }
        }
    }

    /// Update an input using channel-based versioning (nixpkgs, home-manager, nix-darwin).
    fn update_channel_input(&mut self, input: &UpdateInput, parsed: &FlakeRef) {
        let owner = parsed.r#type.get_owner().unwrap();
        let repo = parsed.r#type.get_repo().unwrap();
        let domain = parsed.r#type.get_domain();

        let current_ref = parsed.get_ref_or_rev().unwrap_or_default();

        if current_ref.is_empty() {
            tracing::debug!("Skipping unpinned channel input: {}", input.input.id);
            return;
        }

        let has_refs_heads_prefix = current_ref.starts_with("refs/heads/");

        let latest = match find_latest_channel(&current_ref, &owner, &repo, domain.as_deref()) {
            Some(latest) => latest,
            // Either already on latest, unstable, or not a recognized channel
            None => return,
        };

        let final_ref = if has_refs_heads_prefix {
            format!("refs/heads/{}", latest)
        } else {
            latest.clone()
        };

        let mut parsed = parsed.clone();
        let _ = parsed.set_ref(Some(final_ref.clone()));
        let updated_uri = parsed.to_string();

        if Self::print_update_status(&input.input.id, &current_ref, &final_ref) {
            self.update_input(input.clone(), &updated_uri);
        }
    }

    /// Update an input using semver tag-based versioning (standard behavior).
    fn update_semver_input(&mut self, input: &UpdateInput, init: bool) {
        let target = match self.parse_update_target(input, init) {
            Some(target) => target,
            None => return,
        };

        let tags = match self.fetch_tags(&target) {
            Some(tags) => tags,
            None => return,
        };

        self.apply_update(input, &target, tags, init);
    }

    // Sort the entries, so that we can adjust multiple values together
    fn sort(&mut self) {
        self.inputs.sort();
    }
    fn update_input(&mut self, input: UpdateInput, change: &str) {
        self.text.remove(
            (input.input.range.start as i32 + 1 + self.offset) as usize
                ..(input.input.range.end as i32 - 1 + self.offset) as usize,
        );
        self.text.insert(
            (input.input.range.start as i32 + 1 + self.offset) as usize,
            change,
        );
        self.update_offset(input.clone(), change);
    }
    fn update_offset(&mut self, input: UpdateInput, change: &str) {
        let previous_len = input.input.range.end as i32 - input.input.range.start as i32 - 2;
        let len = change.len() as i32;
        let offset = len - previous_len;
        self.offset += offset;
    }
}

// Wrapper around  individual inputs
#[derive(Debug, Clone)]
pub struct UpdateInput {
    input: Input,
}

impl Ord for UpdateInput {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.input.range.start).cmp(&(other.input.range.start))
    }
}

impl PartialEq for UpdateInput {
    fn eq(&self, other: &Self) -> bool {
        self.input.range.start == other.input.range.start
    }
}

impl PartialOrd for UpdateInput {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Eq for UpdateInput {}