flk 0.6.3

A CLI tool for managing flake.nix devShell environments
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
//! # Update Command Handler
//!
//! Update flake inputs to their latest versions.
//!
//! Automatically creates a backup of `flake.lock` before updating,
//! allowing easy rollback via `flk lock restore`.

use anyhow::{Context, Result};
use colored::Colorize;
use serde_json::Value;
use std::fs;

use crate::nix::run_nix_command;
use flk::utils::{backup, visual::with_spinner};

/// Run the update command.
///
/// # Arguments
///
/// * `packages` - Specific packages to update (not yet supported)
/// * `show` - If true, preview updates without applying them
pub fn run_update(packages: Vec<String>, show: bool) -> Result<()> {
    if !packages.is_empty() {
        anyhow::bail!(
            "Updating specific packages requires version pinning (see issue #7). Use 'flk update' to update all packages."
        );
    }

    if show {
        show_update_preview()?;
    } else {
        perform_update()?;
    }

    Ok(())
}

/// Show what would be updated without actually updating
fn show_update_preview() -> Result<()> {
    println!("{}", "Checking for updates...".bold().cyan());
    println!();

    // Check if flake.lock exists
    if !std::path::Path::new("flake.lock").exists() {
        anyhow::bail!("flake.lock not found. Run 'nix flake lock' first.");
    }

    // Get current lock file
    let current_lock = read_lock_file()?;

    // Create a temporary backup
    fs::copy("flake.lock", "flake.lock.tmp")?;

    // Run the update
    let (_, stderr, success) =
        run_nix_command(&["flake", "update"]).context("Failed to check for updates")?;

    if !success {
        // Restore from temp backup if update failed
        fs::rename("flake.lock.tmp", "flake.lock")?;
        anyhow::bail!("Failed to check for updates: {}", stderr);
    }

    // Get updated lock file
    let updated_lock = read_lock_file()?;

    // Restore the original lock file since this is just a preview
    fs::rename("flake.lock.tmp", "flake.lock")?;

    // Compare and display differences
    display_update_diff(&current_lock, &updated_lock)?;

    println!();
    println!(
        "{}",
        "No changes were made. Run 'flk update' to apply these updates.".dimmed()
    );

    Ok(())
}

/// Perform the actual update
fn perform_update() -> Result<()> {
    println!("{}", "Updating flake inputs...".bold().cyan());

    // Ensure .flk directory exists
    backup::ensure_flk_dir()?;

    // Create a backup of the current lock file BEFORE updating
    if std::path::Path::new("flake.lock").exists() {
        let backup_path = backup::create_backup(std::path::Path::new("flake.lock"))?;
        println!(
            "{} Created backup: {}",
            "".blue().bold(),
            backup_path.file_name().unwrap().to_string_lossy().dimmed()
        );
    }

    // Run the update
    let (stdout, stderr, success) = with_spinner("Updating flake...", || {
        run_nix_command(&["flake", "update"]).context("Failed to execute nix flake update")
    })?;

    if !success {
        anyhow::bail!("Failed to update flake: {}", stderr);
    }

    if !stdout.trim().is_empty() {
        println!("{}", stdout);
    }

    println!("{}", "✓ Flake updated successfully!".green().bold());
    println!("\n{}", "Next steps:".bold());
    println!(
        "  • Run {} to see the updated configuration",
        "flk show".cyan()
    );
    println!(
        "  • Run {} to see lock file details",
        "flk lock show".cyan()
    );
    println!(
        "  • Run {} if you need to rollback",
        "flk lock restore latest".cyan()
    );

    Ok(())
}

/// Read and parse the flake.lock file
fn read_lock_file() -> Result<Value> {
    let lock_content = fs::read_to_string("flake.lock").context("Failed to read flake.lock")?;

    let lock_data: Value =
        serde_json::from_str(&lock_content).context("Failed to parse flake.lock")?;

    Ok(lock_data)
}

/// Display the differences between current and updated lock files
fn display_update_diff(current: &Value, updated: &Value) -> Result<()> {
    println!("{}", "═══════════════════════════════════════".cyan());
    println!("{}", "Update Preview".bold().cyan());
    println!("{}", "═══════════════════════════════════════".cyan());
    println!();

    let current_nodes = &current["nodes"];
    let updated_nodes = &updated["nodes"];

    if let (Some(current_obj), Some(updated_obj)) =
        (current_nodes.as_object(), updated_nodes.as_object())
    {
        let mut changes_found = false;

        for (input_name, _) in current_obj.iter() {
            // Skip root and other non-input nodes
            if input_name == "root" {
                continue;
            }

            let current_info = &current_obj[input_name]["locked"];
            let updated_info = &updated_obj[input_name]["locked"];

            // Only show if there's an actual change
            if current_info != updated_info && !current_info.is_null() && !updated_info.is_null() {
                changes_found = true;
                display_input_change(input_name, current_info, updated_info);
            }
        }

        if !changes_found {
            println!(
                "{}",
                "  No updates available. All inputs are up to date! ✓".green()
            );
        }
    } else {
        println!("{}", "  Unable to compare lock files".yellow());
    }

    println!();
    println!("{}", "═══════════════════════════════════════".cyan());

    Ok(())
}

/// Display changes for a single input
fn display_input_change(name: &str, current: &Value, updated: &Value) {
    println!("{} {}", "Input:".bold(), name.cyan());

    // Show type if available
    if let Some(input_type) = current["type"].as_str() {
        println!("  {} {}", "Type:".dimmed(), input_type);
    }

    // Show revision changes if available
    if let (Some(current_rev), Some(updated_rev)) =
        (current["rev"].as_str(), updated["rev"].as_str())
    {
        if current_rev != updated_rev {
            // Show shortened commit hashes (first 12 chars)
            let current_short = if current_rev.len() >= 12 {
                &current_rev[..12]
            } else {
                current_rev
            };
            let updated_short = if updated_rev.len() >= 12 {
                &updated_rev[..12]
            } else {
                updated_rev
            };

            println!("  {} {}", "From:".dimmed(), current_short.yellow());
            println!("  {} {}", "To:  ".dimmed(), updated_short.green());
        }
    }

    // Show lastModified changes if available
    if let (Some(current_modified), Some(updated_modified)) = (
        current["lastModified"].as_i64(),
        updated["lastModified"].as_i64(),
    ) {
        if current_modified != updated_modified {
            println!("  {} {}", "Last Modified:".dimmed(), "updated".green());
        }
    }

    // Show narHash changes if available
    if let (Some(current_hash), Some(updated_hash)) =
        (current["narHash"].as_str(), updated["narHash"].as_str())
    {
        if current_hash != updated_hash {
            println!("  {} {}", "Content:".dimmed(), "changed ✓".green());
        }
    }

    println!();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::cwd_test_guard;
    use crate::nix::with_nix_runner;
    use tempfile::TempDir;

    const LOCK_BEFORE: &str = r#"{
  "nodes": {
    "root": { "inputs": { "nixpkgs": "nixpkgs" } },
    "nixpkgs": {
      "locked": {
        "lastModified": 1700000000,
        "narHash": "sha256-aaa",
        "owner": "NixOS",
        "repo": "nixpkgs",
        "rev": "0123456789abcdef00000000000000000000aaaa",
        "type": "github"
      },
      "original": {
        "owner": "NixOS",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    }
  },
  "root": "root",
  "version": 7
}
"#;

    const LOCK_AFTER: &str = r#"{
  "nodes": {
    "root": { "inputs": { "nixpkgs": "nixpkgs" } },
    "nixpkgs": {
      "locked": {
        "lastModified": 1800000000,
        "narHash": "sha256-bbb",
        "owner": "NixOS",
        "repo": "nixpkgs",
        "rev": "fedcba987654321000000000000000000000bbbb",
        "type": "github"
      },
      "original": {
        "owner": "NixOS",
        "ref": "nixos-unstable",
        "repo": "nixpkgs",
        "type": "github"
      }
    }
  },
  "root": "root",
  "version": 7
}
"#;

    /// Build a tempdir with `flake.lock` set to `lock` and chdir into it.
    fn setup_lock(lock: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("flake.lock"), lock).unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();
        tmp
    }

    #[test]
    fn rejects_specific_packages() {
        // No cwd needed — the bail happens before any IO.
        let err = run_update(vec!["ripgrep".into()], false).unwrap_err();
        assert!(
            err.to_string().to_lowercase().contains("version pinning"),
            "got: {err}"
        );
    }

    #[test]
    fn preview_errors_when_lock_missing() {
        let _guard = cwd_test_guard();
        let tmp = TempDir::new().unwrap();
        std::env::set_current_dir(tmp.path()).unwrap();

        let err = run_update(vec![], true).unwrap_err();
        assert!(
            err.to_string().contains("flake.lock not found"),
            "got: {err}"
        );
    }

    #[test]
    fn preview_success_displays_diff_and_restores_original() {
        let _guard = cwd_test_guard();
        let tmp = setup_lock(LOCK_BEFORE);
        let lock_path = tmp.path().join("flake.lock");

        // The mock simulates `nix flake update` by overwriting flake.lock.
        // show_update_preview must then restore the original from flake.lock.tmp.
        let updated = LOCK_AFTER.to_string();
        with_nix_runner(
            move |args| {
                assert_eq!(args, &["flake", "update"]);
                std::fs::write("flake.lock", &updated).unwrap();
                Ok((String::new(), String::new(), true))
            },
            || run_update(vec![], true).unwrap(),
        );

        // Original lock must be back in place; temp must be gone.
        assert_eq!(std::fs::read_to_string(&lock_path).unwrap(), LOCK_BEFORE);
        assert!(!tmp.path().join("flake.lock.tmp").exists());
    }

    #[test]
    fn preview_no_changes_when_lock_unchanged() {
        let _guard = cwd_test_guard();
        let tmp = setup_lock(LOCK_BEFORE);

        with_nix_runner(
            // Mock that returns success but doesn't modify flake.lock.
            |_| Ok((String::new(), String::new(), true)),
            || run_update(vec![], true).unwrap(),
        );

        assert_eq!(
            std::fs::read_to_string(tmp.path().join("flake.lock")).unwrap(),
            LOCK_BEFORE
        );
    }

    #[test]
    fn preview_restores_lock_when_nix_fails() {
        let _guard = cwd_test_guard();
        let tmp = setup_lock(LOCK_BEFORE);

        let err = with_nix_runner(
            |_| Ok((String::new(), "boom".into(), false)),
            || run_update(vec![], true).unwrap_err(),
        );

        assert!(err.to_string().contains("boom"), "got: {err}");
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("flake.lock")).unwrap(),
            LOCK_BEFORE,
            "lock must be unchanged after failure"
        );
        assert!(
            !tmp.path().join("flake.lock.tmp").exists(),
            "tmp must be cleaned up (renamed onto flake.lock) on failure"
        );
    }

    #[test]
    fn update_creates_backup_and_succeeds() {
        let _guard = cwd_test_guard();
        let tmp = setup_lock(LOCK_BEFORE);

        with_nix_runner(
            |args| {
                assert_eq!(args, &["flake", "update"]);
                Ok(("updated nixpkgs\n".into(), String::new(), true))
            },
            || run_update(vec![], false).unwrap(),
        );

        // A backup file should exist under .flk/backups/.
        let backups: Vec<_> = std::fs::read_dir(tmp.path().join(".flk/backups"))
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().to_string())
            .collect();
        assert!(
            backups.iter().any(|n| n.starts_with("flake.lock.")),
            "expected a flake.lock.* backup; found {backups:?}"
        );
    }

    #[test]
    fn update_errors_when_nix_fails() {
        let _guard = cwd_test_guard();
        let _tmp = setup_lock(LOCK_BEFORE);

        let err = with_nix_runner(
            |_| Ok((String::new(), "network down".into(), false)),
            || run_update(vec![], false).unwrap_err(),
        );

        assert!(err.to_string().contains("network down"), "got: {err}");
    }
}