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
//! # Flake Parser
//!
//! Parser for top-level flake structure and inputs.
//!
//! This module provides functionality to parse the complete flake configuration
//! by combining the root flake.nix inputs with individual profile files.
//!
//! ## Workflow
//!
//! 1. Parse inputs from `flake.nix`
//! 2. Discover profiles in `.flk/profiles/`
//! 3. Parse each profile (packages, env vars, commands)
//! 4. Combine into a unified [`FlakeConfig`]

use anyhow::{Context, Result};
use nom::{
    bytes::complete::tag,
    character::complete::{char, line_ending},
    combinator::opt,
    IResult, Parser,
};
use std::fs;

use crate::flake::interfaces::profiles::{FlakeConfig, Profile};
use crate::flake::parsers::{
    commands::parse_shell_hook_section,
    env::parse_env_vars_section,
    packages::parse_packages_section,
    utils::{
        byte_offset, detect_indentation, identifier, list_profiles, multiws, string_literal, ws,
    },
};

/// Parse the entire flake configuration from the project.
///
/// Reads the root `flake.nix` for inputs and all profile files from
/// `.flk/profiles/` to build a complete [`FlakeConfig`].
///
/// # Arguments
///
/// * `path` - Path to the root `flake.nix` file
///
/// # Returns
///
/// A [`FlakeConfig`] containing all inputs and profiles.
///
/// # Errors
///
/// Returns an error if any file cannot be read or parsed.
pub fn parse_flake(path: &str) -> Result<FlakeConfig> {
    let content = fs::read_to_string(path).context("Failed to read flake.nix file")?;

    // Parse inputs from flake.nix
    let inputs_section =
        parse_inputs_section(&content).context("Failed to parse inputs section")?;

    // Parse profiles from individual profile files
    let profiles_list = list_profiles().context("Failed to list profiles")?;

    let mut profiles = Vec::new();

    for profile_path in profiles_list {
        let profile_data = fs::read_to_string(&profile_path).with_context(|| {
            format!(
                "Failed to read profile file: {}",
                profile_path.to_string_lossy()
            )
        })?;

        // Parse each section using nom parsers
        let packages_section = parse_packages_section(&profile_data).with_context(|| {
            format!(
                "Failed to parse packages in profile: {}",
                profile_path.to_string_lossy()
            )
        })?;

        let env_vars_section = parse_env_vars_section(&profile_data).with_context(|| {
            format!(
                "Failed to parse envVars in profile: {}",
                profile_path.to_string_lossy()
            )
        })?;

        let shell_hook_section = parse_shell_hook_section(&profile_data).with_context(|| {
            format!(
                "Failed to parse shellHook in profile: {}",
                profile_path.to_string_lossy()
            )
        })?;

        // Convert parsed sections to FlakeConfig types
        let packages = packages_section.to_packages();
        let env_vars = env_vars_section.to_env_vars();

        // Create profile
        let profile_name = profile_path
            .file_stem()
            .context("Failed to get profile name")?
            .to_string_lossy()
            .to_string();

        let mut profile = Profile::new(profile_name.clone());
        profile.packages = packages;
        profile.env_vars = env_vars;
        profile.shell_hook = shell_hook_section;

        profiles.push(profile);
    }

    // Build final config
    let config = FlakeConfig {
        inputs: inputs_section.to_input_names(),
        profiles,
    };

    Ok(config)
}

/// Parse a single profile file into a [`Profile`] struct.
///
/// Internal helper used by [`parse_flake`] to process each `.nix` file
/// in `.flk/profiles/`.
pub fn _parse_profile_file(path: &str) -> Result<Profile> {
    let content = fs::read_to_string(path).context("Failed to read profile file")?;

    let packages_section =
        parse_packages_section(&content).context("Failed to parse packages section")?;

    let env_vars_section =
        parse_env_vars_section(&content).context("Failed to parse envVars section")?;

    let shell_hook_section =
        parse_shell_hook_section(&content).context("Failed to parse shellHook section")?;

    let profile_name = std::path::Path::new(path)
        .file_stem()
        .context("Failed to get profile name")?
        .to_string_lossy()
        .to_string();

    let mut profile = Profile::new(profile_name);
    profile.packages = packages_section.to_packages();
    profile.env_vars = env_vars_section.to_env_vars();
    profile.shell_hook = shell_hook_section;

    Ok(profile)
}

/// A parsed input entry with position information.
#[derive(Debug, Clone)]
pub struct InputEntry {
    /// Input name (e.g., "nixpkgs", "flake-utils")
    pub name: String,
    /// Input URL (e.g., "github:NixOS/nixpkgs/nixos-unstable")
    pub _url: String,
    /// Byte position where this entry starts
    pub _start_pos: usize,
    /// Byte position where this entry ends
    pub _end_pos: usize,
}

/// Parsed inputs section with editing support.
#[derive(Debug)]
pub struct InputsSection {
    /// All input entries
    pub entries: Vec<InputEntry>,
    /// Byte position where the section starts
    pub _section_start: usize,
    /// Byte position of the content start (after `{`)
    pub _content_start: usize,
    /// Byte position of the content end (before `}`)
    pub _content_end: usize,
    /// Byte position where the section ends
    pub _section_end: usize,
    /// Detected indentation
    pub _indentation: String,
}

/// Parse a single input entry:   name. url = "value";
fn input_entry<'a>(
    input: &'a str,
    base_offset: usize,
    original_input: &'a str,
) -> IResult<&'a str, InputEntry> {
    let start_pos = base_offset + byte_offset(original_input, input);

    let (remaining, _) = multiws(input)?;
    let (remaining, name) = identifier(remaining)?;
    let (remaining, _) = ws(remaining)?;
    let (remaining, _) = char('.')(remaining)?;
    let (remaining, _) = tag("url")(remaining)?;
    let (remaining, _) = ws(remaining)?;
    let (remaining, _) = char('=')(remaining)?;
    let (remaining, _) = ws(remaining)?;
    let (remaining, url) = string_literal(remaining)?;
    let (remaining, _) = ws(remaining)?;
    let (remaining, _) = char(';')(remaining)?;
    let (remaining, _) = opt(line_ending).parse(remaining)?;

    let end_pos = base_offset + byte_offset(original_input, remaining);

    Ok((
        remaining,
        InputEntry {
            name: name.to_string(),
            _url: url.to_string(),
            _start_pos: start_pos,
            _end_pos: end_pos,
        },
    ))
}

/// Parse the full inputs section with nom
fn parse_inputs_with_nom(input: &str, base_offset: usize) -> IResult<&str, Vec<InputEntry>> {
    let original_input = input; // Store original for offset calculations
    let (input, _) = ws(input)?;
    let (input, _) = char('{')(input)?;

    let mut entries = Vec::new();
    let mut remaining = input;

    loop {
        // Skip whitespace
        let (rest, _) = multiws(remaining)?;

        // Check for closing brace
        if rest.starts_with('}') {
            remaining = rest;
            break;
        }

        // Try to parse input entry
        match input_entry(rest, base_offset, original_input) {
            Ok((rest, entry)) => {
                entries.push(entry);
                remaining = rest;
            }
            Err(_) => {
                // Skip this line if it doesn't parse
                if let Some(newline_pos) = rest.find('\n') {
                    remaining = &rest[newline_pos + 1..];
                } else {
                    break;
                }
            }
        }
    }

    let (input, _) = char('}')(remaining)?;
    let (input, _) = ws(input)?;
    let (input, _) = char(';')(input)?;

    Ok((input, entries))
}

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

    let parse_from = section_start + "inputs =".len();
    let to_parse = &content[parse_from..];

    match parse_inputs_with_nom(to_parse, parse_from) {
        Ok((remaining, entries)) => {
            let content_start = content[parse_from..]
                .find('{')
                .context("Could not find '{'")?
                + parse_from
                + 1;

            let section_end = parse_from + byte_offset(to_parse, remaining);

            let content_end = content[content_start..section_end]
                .rfind('}')
                .context("Could not find '}'")?
                + content_start;

            let inputs_content = &content[content_start..content_end];
            let indentation = detect_indentation(inputs_content);

            Ok(InputsSection {
                entries,
                _section_start: section_start,
                _content_start: content_start,
                _content_end: content_end,
                _section_end: section_end,
                _indentation: indentation,
            })
        }
        Err(e) => Err(anyhow::anyhow!("Failed to parse inputs section: {:?}", e)),
    }
}

impl InputsSection {
    /// Convert parsed entries to a list of input names for [`FlakeConfig`].
    pub fn to_input_names(&self) -> Vec<String> {
        self.entries.iter().map(|e| e.name.clone()).collect()
    }

    /// Add a new input entry to the section (internal).
    pub fn _add_input(&self, original_content: &str, name: &str, url: &str) -> String {
        // Check if exists
        if self.entries.iter().any(|e| e.name == name) {
            return original_content.to_string();
        }

        let new_entry = format!("{}{}.url = \"{}\";\n", self._indentation, name, url);

        let mut result = String::new();
        result.push_str(&original_content[..self._content_end]);
        result.push_str(&new_entry);
        result.push_str(&original_content[self._content_end..]);

        result
    }

    /// Remove an input entry by name (internal).
    pub fn _remove_input(&self, original_content: &str, name: &str) -> Result<String> {
        let entry = self
            .entries
            .iter()
            .find(|e| e.name == name)
            .context(format!("Input '{}' not found", name))?;

        let before = &original_content[..entry._start_pos];
        let after = &original_content[entry._end_pos..];

        let after = after.strip_prefix('\n').unwrap_or(after);

        Ok(format!("{}{}", before, after))
    }

    /// Update an existing input's URL (internal).
    pub fn _update_input(
        &self,
        original_content: &str,
        name: &str,
        new_url: &str,
    ) -> Result<String> {
        let entry = self
            .entries
            .iter()
            .find(|e| e.name == name)
            .context(format!("Input '{}' not found", name))?;

        let new_line = format!("{}{}.url = \"{}\";\n", self._indentation, name, new_url);

        let mut result = String::new();
        result.push_str(&original_content[..entry._start_pos]);
        result.push_str(&new_line);
        result.push_str(&original_content[entry._end_pos..]);

        Ok(result)
    }
}

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

    #[test]
    fn test_parse_inputs() {
        let content = r#"{
  description = "Development environment managed by flk";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flake-utils.url = "github:numtide/flake-utils";
    profile-lib.url = "github:AEduardo-dev/nix-profile-lib";
  };

  outputs = inputs:  import ./.flk/default.nix inputs;
}"#;

        let section = parse_inputs_section(content).unwrap();

        assert_eq!(section.entries.len(), 3);
        assert_eq!(section.entries[0].name, "nixpkgs");
        assert_eq!(
            section.entries[0]._url,
            "github:NixOS/nixpkgs/nixos-unstable"
        );
        assert_eq!(section.entries[1].name, "flake-utils");
        assert_eq!(section.entries[2].name, "profile-lib");

        let names = section.to_input_names();
        assert_eq!(names, vec!["nixpkgs", "flake-utils", "profile-lib"]);
    }

    #[test]
    fn test_add_input() {
        let content = r#"{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
  };
}"#;

        let section = parse_inputs_section(content).unwrap();
        let new_content =
            section._add_input(content, "rust-overlay", "github:oxalica/rust-overlay");

        assert!(new_content.contains("rust-overlay.url"));
        assert!(new_content.contains("oxalica/rust-overlay"));
    }

    #[test]
    fn test_remove_input() {
        let content = r#"{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flake-utils.url = "github:numtide/flake-utils";
  };
}"#;

        let section = parse_inputs_section(content).unwrap();
        let new_content = section._remove_input(content, "flake-utils").unwrap();

        assert!(!new_content.contains("flake-utils"));
        assert!(new_content.contains("nixpkgs"));
    }

    #[test]
    fn test_update_input() {
        let content = r#"{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
  };
}"#;

        let section = parse_inputs_section(content).unwrap();
        let new_content = section
            ._update_input(content, "nixpkgs", "github:NixOS/nixpkgs/nixos-24.05")
            .unwrap();

        assert!(new_content.contains("nixos-24.05"));
        assert!(!new_content.contains("nixos-unstable"));
    }
}