flk 0.6.2

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
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
//! # Overlay Section Parser
//!
//! Parser for `pins.nix` overlay and source sections.
//!
//! This module handles parsing and modification of version pinning
//! configurations that enable specific package versions to be installed.
//!
//! ## File Structure (pins.nix)
//!
//! ```nix
//! {
//!   sources = {
//!     pkgs-abc123 = "github:NixOS/nixpkgs/abc123...";
//!   };
//!   pinnedPackages = {
//!     pkgs-abc123 = [
//!       { pkg = "ripgrep"; name = "ripgrep@15.1.0"; }
//!     ];
//!   };
//! }
//! ```

use crate::flake::parsers::utils::{identifier, multiws, string_literal};
use anyhow::{Context, Result};
use nom::sequence::preceded;
use nom::Parser;
use nom::{
    bytes::complete::tag, character::complete::char, combinator::map, multi::many0,
    sequence::delimited, IResult,
};

use crate::flake::interfaces::{
    overlays::{OverlayEntry, OverlaysSection, PinnedPackage, SourceEntry, SourcesSection},
    utils::INDENT_OUT,
};
use crate::flake::nix_render::{indent_line, nix_attr_key, nix_string};

// ============================================================================
// PINNED PACKAGE PARSERS
// ============================================================================

/// Parse a single pinned package entry:  { pkg = "... "; name = "..."; }
fn pinned_package_entry(input: &str) -> IResult<&str, PinnedPackage> {
    map(
        delimited(
            multiws,
            delimited(
                char('{'),
                delimited(
                    multiws,
                    (
                        preceded((tag("pkg"), multiws, char('='), multiws), string_literal),
                        preceded(
                            (
                                multiws,
                                char(';'),
                                multiws,
                                tag("name"),
                                multiws,
                                char('='),
                                multiws,
                            ),
                            string_literal,
                        ),
                        preceded((multiws, char(';'), multiws), nom::combinator::success(())),
                    ),
                    multiws,
                ),
                char('}'),
            ),
            multiws,
        ),
        |(pkg, pin_name, _)| PinnedPackage {
            name: pkg.to_string(),
            pin_name: pin_name.to_string(),
        },
    )
    .parse(input)
}

fn pinned_package_list(input: &str) -> IResult<&str, Vec<PinnedPackage>> {
    delimited(
        delimited(multiws, char('['), multiws),
        many0(pinned_package_entry),
        delimited(multiws, char(']'), multiws),
    )
    .parse(input)
}

/// Parse a pin entry: pin_name = [ ... ];
fn overlay_entry(input: &str) -> IResult<&str, OverlayEntry> {
    let (remaining, (_, name, _, _, _, packages, _, _)) = (
        multiws,
        identifier,
        multiws,
        char('='),
        multiws,
        pinned_package_list,
        multiws,
        char(';'),
    )
        .parse(input)?;

    Ok((
        remaining,
        OverlayEntry {
            name: name.to_string(),
            packages,
        },
    ))
}

/// Parse the full overlays section: everything between braces `{ ... }`
fn parse_overlays_content(input: &str) -> IResult<&str, Vec<OverlayEntry>> {
    many0(overlay_entry).parse(input)
}

/// Parse the pinnedPackages section from pins.nix content.
///
/// # Errors
///
/// Returns an error if the section cannot be found or parsed.
pub fn parse_overlay_section(content: &str) -> Result<OverlaysSection> {
    let section_start = content
        .find("pinnedPackages")
        .context("Could not find 'pinnedPackages'")?;

    let after_pinned = &content[section_start..];
    let brace_offset = after_pinned
        .find('{')
        .context("Could not find '{' after 'pinnedPackages'")?;

    let list_start = section_start + brace_offset + 1;

    // Find the matching closing brace
    let after_brace = &content[list_start..];
    let mut brace_count = 1usize;
    let mut list_end = list_start;

    for (i, ch) in after_brace.char_indices() {
        match ch {
            '{' => brace_count += 1,
            '}' => {
                brace_count -= 1;
                if brace_count == 0 {
                    list_end = list_start + i;
                    break;
                }
            }
            _ => {}
        }
    }

    if brace_count != 0 {
        return Err(anyhow::anyhow!(
            "Unmatched braces in pinnedPackages section"
        ));
    }

    let to_parse = &content[list_start..list_end];
    match parse_overlays_content(to_parse) {
        Ok((_, entries)) => Ok(OverlaysSection {
            entries,
            indentation: INDENT_OUT.to_string(),
        }),
        Err(e) => Err(anyhow::anyhow!("Failed to parse overlays section: {:?}", e)),
    }
}

// ============================================================================
// SOURCE ENTRY PARSERS
// ============================================================================

/// Parse a single source entry:  name = "reference";
fn source_entry(input: &str) -> IResult<&str, SourceEntry> {
    let (remaining, (_, name, _, _, _, reference, _, _)) = (
        multiws,
        identifier,
        multiws,
        char('='),
        multiws,
        string_literal,
        multiws,
        char(';'),
    )
        .parse(input)?;

    Ok((
        remaining,
        SourceEntry {
            name: name.to_string(),
            reference: reference.to_string(),
        },
    ))
}

/// Parse the full sources section: everything between braces `{ ... }`
fn parse_sources_content(input: &str) -> IResult<&str, Vec<SourceEntry>> {
    many0(source_entry).parse(input)
}

/// Parse the sources section from pins.nix content.
///
/// # Errors
///
/// Returns an error if the section cannot be found or parsed.
pub fn parse_sources_section(content: &str) -> Result<SourcesSection> {
    let section_start = content
        .find("sources")
        .context("Could not find 'sources'")?;

    let after_sources = &content[section_start..];
    let brace_offset = after_sources
        .find('{')
        .context("Could not find '{' after 'sources'")?;

    let list_start = section_start + brace_offset + 1;

    // Find the matching closing brace
    let after_brace = &content[list_start..];
    let mut brace_count = 1usize;
    let mut list_end = list_start;

    for (i, ch) in after_brace.char_indices() {
        match ch {
            '{' => brace_count += 1,
            '}' => {
                brace_count -= 1;
                if brace_count == 0 {
                    list_end = list_start + i;
                    break;
                }
            }
            _ => {}
        }
    }

    if brace_count != 0 {
        return Err(anyhow::anyhow!("Unmatched braces in sources section"));
    }

    let to_parse = &content[list_start..list_end];

    match parse_sources_content(to_parse) {
        Ok((_, entries)) => Ok(SourcesSection {
            entries,
            indentation: INDENT_OUT.to_string(),
        }),
        Err(e) => Err(anyhow::anyhow!("Failed to parse sources section: {:?}", e)),
    }
}

// ============================================================================
// COMBINED OPERATIONS (parse -> modify -> render)
// ============================================================================

/// Normalize indentation between sections for consistent output.
fn normalize_indentation(sources: &mut SourcesSection, overlays: &mut OverlaysSection) {
    let indent = if !sources.indentation.is_empty() {
        sources.indentation.clone()
    } else if !overlays.indentation.is_empty() {
        overlays.indentation.clone()
    } else {
        "  ".to_string()
    };

    sources.indentation = indent.clone();
    overlays.indentation = indent;
}

/// Add a pinned package to pins.nix.
///
/// This function handles the complete workflow:
/// 1. Adds the nixpkgs source if it doesn't exist
/// 2. Creates the pin entry if it doesn't exist
/// 3. Adds the package to the pin entry
///
/// # Arguments
///
/// * `content` - The full pins.nix content
/// * `pin_hash` - Short hash identifying the nixpkgs commit
/// * `source_ref` - Full git reference (e.g., "github:NixOS/nixpkgs/abc123")
/// * `package` - Original package name in nixpkgs
/// * `version` - Version being pinned
pub fn add_pinned_package(
    content: &str,
    pin_hash: &str,
    source_ref: &str,
    package: &str,
    version: &str,
) -> Result<String> {
    let pin_name = format!("pkgs-{}", pin_hash);
    let package_alias = format!("{}@{}", package, version);

    let mut sources_section = parse_sources_section(content)?;
    let mut overlays_section = parse_overlay_section(content)?;
    normalize_indentation(&mut sources_section, &mut overlays_section);

    // Step 1: Add source if it doesn't exist
    if !sources_section.source_exists(&pin_name) {
        sources_section.add_source(&pin_name, source_ref)?;
    }

    // Step 2: Add pin entry if it doesn't exist
    if !overlays_section.pin_entry_exists(&pin_name) {
        overlays_section.add_pin_entry(&pin_name)?;
    }

    // Step 3: Add package to pin if it doesn't exist
    if !overlays_section.package_in_pin_exists(&pin_name, &package_alias) {
        overlays_section.add_package_to_pin(&pin_name, package, &package_alias)?;
    }

    Ok(render_file(&sources_section, &overlays_section))
}

/// Remove a pinned package and cleanup empty pin entries.
///
/// If removing the package leaves a pin entry empty, the entry and its
/// corresponding source are also removed.
///
/// # Errors
///
/// Returns an error if the package is not found in any pin entry.
pub fn remove_pinned_package_with_cleanup(content: &str, package: &str) -> Result<String> {
    let mut sources_section = parse_sources_section(content)?;
    let mut overlays_section = parse_overlay_section(content)?;
    normalize_indentation(&mut sources_section, &mut overlays_section);

    // Find the pin entry that contains the package alias
    println!("Current overlays: {:?}", overlays_section.entries);
    let pin_name = overlays_section
        .entries
        .iter()
        .find(|entry| entry.packages.iter().any(|pkg| pkg.name == package))
        .map(|e| e.name.clone())
        .context(format!(
            "Could not find pin entry containing package '{}'",
            package
        ))?;

    // Step 1: Remove the package from the pin entry
    overlays_section.remove_package_from_pin(&pin_name, package)?;

    // Step 2: Remove pin entry and its source if pin is now empty
    let pin_is_empty = overlays_section
        .entries
        .iter()
        .find(|e| e.name == pin_name)
        .is_some_and(|e| e.packages.is_empty());

    if pin_is_empty {
        overlays_section.remove_pin_entry(&pin_name)?;
        sources_section.remove_source(&pin_name)?;
    }

    Ok(render_file(&sources_section, &overlays_section))
}

// ============================================================================
// RENDER HELPERS
// ============================================================================

/// Render the sources section back to Nix syntax.
///
/// Produces the `sources = { ... };` block for `pins.nix`.
pub fn render_sources_section(
    out: &mut String,
    indent: &str,
    level: usize,
    entries: &[crate::flake::interfaces::overlays::SourceEntry],
) {
    indent_line(out, indent, level);
    out.push_str("sources = {\n");

    for e in entries {
        indent_line(out, indent, level + 1);
        out.push_str(&nix_attr_key(&e.name));
        out.push_str(" = ");
        out.push_str(&nix_string(&e.reference));
        out.push_str(";\n");
    }

    indent_line(out, indent, level);
    out.push_str("};\n");
}

/// Render the pinned packages section back to Nix syntax.
///
/// Produces the `pinnedPackages = { ... };` block for `pins.nix`.
pub fn render_pinned_packages_section(
    out: &mut String,
    indent: &str,
    level: usize,
    overlays: &[crate::flake::interfaces::overlays::OverlayEntry],
) {
    indent_line(out, indent, level);
    out.push_str("pinnedPackages = {\n");

    for overlay in overlays {
        indent_line(out, indent, level + 1);
        out.push_str(&nix_attr_key(&overlay.name));
        out.push_str(" = [\n");

        for pkg in &overlay.packages {
            indent_line(out, indent, level + 2);
            out.push_str("{\n");

            indent_line(out, indent, level + 3);
            out.push_str("pkg = ");
            out.push_str(&nix_string(&pkg.name));
            out.push_str(";\n");

            indent_line(out, indent, level + 3);
            out.push_str("name = ");
            out.push_str(&nix_string(&pkg.pin_name));
            out.push_str(";\n");

            indent_line(out, indent, level + 2);
            out.push_str("}\n");
        }

        indent_line(out, indent, level + 1);
        out.push_str("];\n");
    }

    indent_line(out, indent, level);
    out.push_str("};\n");
}

/// Render a complete `pins.nix` file from sources and overlay sections.
pub fn render_file(
    sources: &crate::flake::interfaces::overlays::SourcesSection,
    overlays: &crate::flake::interfaces::overlays::OverlaysSection,
) -> String {
    // fall back to two spaces.
    let indent = if sources.indentation.is_empty() {
        "  "
    } else {
        sources.indentation.as_str()
    };

    let mut out = String::new();
    out.push_str("{\n");

    render_sources_section(&mut out, indent, 1, &sources.entries);
    out.push('\n');
    render_pinned_packages_section(&mut out, indent, 1, &overlays.entries);

    out.push_str("}\n");
    out
}

// =============================================================================
// TESTS
// =============================================================================
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_add_pinned_package() {
        let original_content = r#"{
  sources = {
    pkgs-abc123 = "github:user/repo/commit";
  };
    pinnedPackages = {
        pkgs-abc123 = [
        {
            pkg = "example-package";
            name = "example-package@1.0.0";
        }
        ];
    };
}"#;

        let updated_content = add_pinned_package(
            original_content,
            "def456",
            "github:another/repo/commit",
            "new-package",
            "2.0.0",
        )
        .context("Failed to add pinned package")
        .unwrap();

        assert!(updated_content.contains("pkgs-abc123"));
        assert!(updated_content.contains("pkgs-def456"));
        assert!(updated_content.contains("example-package@1.0.0"));
        assert!(updated_content.contains("new-package@2.0.0"));
    }

    #[test]
    fn test_add_pinned_package_to_existent_pin() {
        let original_content = r#"{
  sources = {
    pkgs-abc123 = "github:user/repo/commit";
  };
    pinnedPackages = {
        pkgs-abc123 = [
        {
            pkg = "example-package";
            name = "example-package@1.0.0";
        }
        ];
    };
}"#;

        let updated_content = add_pinned_package(
            original_content,
            "abc123",
            "github:user/repo/commit",
            "new-package",
            "2.0.0",
        )
        .context("Failed to add pinned package")
        .unwrap();

        assert!(updated_content.contains("pkgs-abc123"));
        assert!(updated_content.contains("example-package@1.0.0"));
        assert!(updated_content.contains("new-package@2.0.0"));
    }

    #[test]
    fn test_remove_pinned_package() {
        let original_content = r#"{
  sources = {
    pkgs-abc123 = "github:user/repo/commit";
  };
    pinnedPackages = {
        pkgs-abc123 = [
        {
            pkg = "example-package";
            name = "example-package@1.0.0";
        }
        {
            pkg = "another-package";
            name = "another-package@2.0.0";
        }
        ];
    };
}"#;

        let updated_content =
            remove_pinned_package_with_cleanup(original_content, "example-package")
                .context("Failed to remove pinned package")
                .unwrap();

        assert!(!updated_content.contains("example-package"));
        assert!(!updated_content.contains("example-package@1.0.0"));
        assert!(updated_content.contains("another-package@2.0.0"));
        assert!(updated_content.contains("pkgs-abc123"));
    }

    #[test]
    fn test_remove_last_pinned_package_from_existent_pin() {
        let original_content = r#"{
  sources = {
    pkgs-abc123 = "github:user/repo/commit";
  };
    pinnedPackages = {
        pkgs-abc123 = [
        {
            pkg = "example-package";
            name = "example-package@1.0.0";
        }
        ];
    };
}"#;

        let updated_content =
            remove_pinned_package_with_cleanup(original_content, "example-package")
                .context("Failed to remove pinned package")
                .unwrap();

        assert!(!updated_content.contains("pkgs-abc123"));
        assert!(!updated_content.contains("example-package"));
        assert!(!updated_content.contains("example-package@1.0.0"));
    }
}