nex-pkg 0.13.1

Package manager UX for nix-darwin + homebrew
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
use std::fs;
use std::path::Path;

use anyhow::{Context, Result};
use tempfile::NamedTempFile;

use crate::nixfile::NixList;

/// Find the line range (start inclusive, end inclusive) of a NixList in the file lines.
fn find_list_range(lines: &[String], list: &NixList) -> Result<(usize, usize)> {
    let open = lines
        .iter()
        .position(|l| l.trim_start().starts_with(list.open_line))
        .context(format!("could not find list opening: {}", list.open_line))?;

    // Walk forward from open to find the matching close.
    // The close must be at the same or lesser indentation as the open line.
    let open_indent = lines[open].len() - lines[open].trim_start().len();
    let close = lines
        .iter()
        .enumerate()
        .skip(open + 1)
        .find(|(_, l)| {
            let trimmed = l.trim_start();
            let indent = l.len() - trimmed.len();
            trimmed.starts_with(list.close_line) && indent <= open_indent
        })
        .map(|(i, _)| i)
        .context(format!(
            "could not find list closing for: {}",
            list.open_line
        ))?;

    Ok((open, close))
}

/// Check whether a package is present in a list within the given file.
pub fn contains(path: &Path, list: &NixList, pkg: &str) -> Result<bool> {
    let content =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let lines: Vec<String> = content.lines().map(String::from).collect();

    let (open, close) = match find_list_range(&lines, list) {
        Ok(range) => range,
        Err(_) => return Ok(false),
    };

    for line in &lines[open + 1..close] {
        if let Some(name) = list.parse_item(line) {
            if name == pkg {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

/// Validate that a package name is safe to insert into a nix file.
/// Rejects names with characters that could break nix syntax or enable injection.
fn validate_pkg_name(pkg: &str) -> Result<()> {
    if pkg.is_empty() {
        anyhow::bail!("package name cannot be empty");
    }
    for ch in pkg.chars() {
        if !(ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.') {
            anyhow::bail!(
                "invalid character '{}' in package name \"{}\": \
                 only alphanumeric, hyphen, underscore, and period are allowed",
                ch,
                pkg
            );
        }
    }
    Ok(())
}

/// Insert a package into a list. Returns true if inserted, false if already present.
pub fn insert(path: &Path, list: &NixList, pkg: &str) -> Result<bool> {
    validate_pkg_name(pkg)?;
    let content =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let mut lines: Vec<String> = content.lines().map(String::from).collect();

    let (open, close) = find_list_range(&lines, list)?;

    // Check for duplicate
    for line in &lines[open + 1..close] {
        if let Some(name) = list.parse_item(line) {
            if name == pkg {
                return Ok(false);
            }
        }
    }

    // Insert before the closing line
    let new_line = list.format_item(pkg);
    lines.insert(close, new_line);

    atomic_write(path, &lines).with_context(|| format!("writing {}", path.display()))?;

    Ok(true)
}

/// Remove a package from a list. Returns true if removed, false if not found.
pub fn remove(path: &Path, list: &NixList, pkg: &str) -> Result<bool> {
    let content =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let mut lines: Vec<String> = content.lines().map(String::from).collect();

    let (open, close) = find_list_range(&lines, list)?;

    let found = lines[open + 1..close]
        .iter()
        .enumerate()
        .find(|(_, line)| list.parse_item(line).is_some_and(|name| name == pkg))
        .map(|(i, _)| open + 1 + i);

    match found {
        Some(idx) => {
            lines.remove(idx);
            atomic_write(path, &lines).with_context(|| format!("writing {}", path.display()))?;
            Ok(true)
        }
        None => Ok(false),
    }
}

/// Check whether any of the given package names is present in a list.
/// Reads the file once and checks all names in a single pass.
/// Returns the matched name, or None if no match.
pub fn contains_any(path: &Path, list: &NixList, names: &[&str]) -> Result<Option<String>> {
    let content =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let lines: Vec<String> = content.lines().map(String::from).collect();

    let (open, close) = match find_list_range(&lines, list) {
        Ok(range) => range,
        Err(_) => return Ok(None),
    };

    for line in &lines[open + 1..close] {
        if let Some(name) = list.parse_item(line) {
            if names.contains(&name.as_str()) {
                return Ok(Some(name));
            }
        }
    }
    Ok(None)
}

/// List all package names in a list within the given file.
pub fn list_packages(path: &Path, list: &NixList) -> Result<Vec<String>> {
    let content =
        fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let lines: Vec<String> = content.lines().map(String::from).collect();

    let (open, close) = find_list_range(&lines, list)?;

    let mut pkgs = Vec::new();
    for line in &lines[open + 1..close] {
        if let Some(name) = list.parse_item(line) {
            pkgs.push(name);
        }
    }
    Ok(pkgs)
}

/// Write lines to a file atomically (temp file + fsync + rename).
fn atomic_write(path: &Path, lines: &[String]) -> Result<()> {
    let dir = path.parent().context("file has no parent directory")?;
    let content = lines.join("\n") + "\n";

    let mut tmp = NamedTempFile::new_in(dir)?;
    std::io::Write::write_all(&mut tmp, content.as_bytes())?;
    tmp.as_file().sync_all()?;
    tmp.persist(path)?;
    Ok(())
}

/// Write bytes to a file atomically (temp file + fsync + rename).
/// Use this instead of `std::fs::write` for any file that must survive power loss.
pub fn atomic_write_bytes(path: &Path, content: &[u8]) -> Result<()> {
    let dir = path.parent().context("file has no parent directory")?;
    let mut tmp = NamedTempFile::new_in(dir)?;
    std::io::Write::write_all(&mut tmp, content)?;
    tmp.as_file().sync_all()?;
    tmp.persist(path)?;
    Ok(())
}

/// Back up a file before editing. Returns the backup path.
pub fn backup(path: &Path) -> Result<std::path::PathBuf> {
    let backup_path = path.with_extension("nix.nex-backup");
    let dir = path.parent().context("file has no parent directory")?;
    let content = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
    let mut tmp = NamedTempFile::new_in(dir)?;
    std::io::Write::write_all(&mut tmp, &content)?;
    tmp.as_file().sync_all()?;
    tmp.persist(&backup_path)
        .with_context(|| format!("backing up {}", path.display()))?;
    Ok(backup_path)
}

/// Restore a file from its backup. Returns an error if the backup file is missing.
pub fn restore(path: &Path, backup_path: &Path) -> Result<()> {
    if !backup_path.exists() {
        anyhow::bail!(
            "backup file missing for {}: expected {}",
            path.display(),
            backup_path.display()
        );
    }
    fs::rename(backup_path, path).with_context(|| format!("restoring {}", path.display()))?;
    Ok(())
}

/// Delete a backup file.
pub fn delete_backup(backup_path: &Path) -> Result<()> {
    if backup_path.exists() {
        fs::remove_file(backup_path)?;
    }
    Ok(())
}

/// An edit session tracks backups for atomic multi-file operations.
pub struct EditSession {
    backups: Vec<(std::path::PathBuf, std::path::PathBuf)>, // (original, backup)
}

impl EditSession {
    pub fn new() -> Self {
        Self {
            backups: Vec::new(),
        }
    }

    /// Back up a file before editing. Idempotent per path.
    pub fn backup(&mut self, path: &Path) -> Result<()> {
        if self.backups.iter().any(|(p, _)| p == path) {
            return Ok(());
        }
        let bp = backup(path)?;
        self.backups.push((path.to_path_buf(), bp));
        Ok(())
    }

    /// Revert all edits by restoring backups.
    pub fn revert_all(&self) -> Result<()> {
        let mut errors = Vec::new();
        for (original, bp) in &self.backups {
            if let Err(e) = restore(original, bp) {
                errors.push(format!("{}: {e}", original.display()));
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            anyhow::bail!("failed to revert some files:\n  {}", errors.join("\n  "))
        }
    }

    /// Commit all edits by deleting backups.
    pub fn commit_all(&self) -> Result<()> {
        for (_, bp) in &self.backups {
            delete_backup(bp)?;
        }
        Ok(())
    }

    #[allow(dead_code)]
    pub fn has_changes(&self) -> bool {
        !self.backups.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nixfile;
    use tempfile::TempDir;

    fn write_fixture(dir: &Path, name: &str, content: &str) -> std::path::PathBuf {
        let path = dir.join(name);
        fs::write(&path, content).expect("write fixture");
        path
    }

    const BASE_NIX: &str = r#"{ pkgs, username, ... }:

{
  home.packages = with pkgs; [
    ## Shell
    bash
    git
    vim
  ];
}
"#;

    const BREW_NIX: &str = r#"{ ... }:

{
  homebrew = {
    brews = [
      "rustup"
      "esptool"
    ];

    casks = [
      "firefox"
      "kitty"
    ];
  };
}
"#;

    #[test]
    fn test_contains_bare() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "base.nix", BASE_NIX);
        assert!(contains(&path, &nixfile::NIX_PACKAGES, "bash").expect("contains"));
        assert!(contains(&path, &nixfile::NIX_PACKAGES, "vim").expect("contains"));
        assert!(!contains(&path, &nixfile::NIX_PACKAGES, "htop").expect("contains"));
    }

    #[test]
    fn test_contains_quoted() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "brew.nix", BREW_NIX);
        assert!(contains(&path, &nixfile::HOMEBREW_BREWS, "rustup").expect("contains"));
        assert!(!contains(&path, &nixfile::HOMEBREW_BREWS, "qemu").expect("contains"));
        assert!(contains(&path, &nixfile::HOMEBREW_CASKS, "firefox").expect("contains"));
        assert!(!contains(&path, &nixfile::HOMEBREW_CASKS, "slack").expect("contains"));
    }

    #[test]
    fn test_insert_bare() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "base.nix", BASE_NIX);
        assert!(insert(&path, &nixfile::NIX_PACKAGES, "htop").expect("insert"));
        assert!(contains(&path, &nixfile::NIX_PACKAGES, "htop").expect("contains"));
        // Duplicate returns false
        assert!(!insert(&path, &nixfile::NIX_PACKAGES, "htop").expect("insert dup"));
    }

    #[test]
    fn test_insert_quoted() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "brew.nix", BREW_NIX);
        assert!(insert(&path, &nixfile::HOMEBREW_CASKS, "slack").expect("insert"));
        assert!(contains(&path, &nixfile::HOMEBREW_CASKS, "slack").expect("contains"));
    }

    #[test]
    fn test_remove_bare() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "base.nix", BASE_NIX);
        assert!(remove(&path, &nixfile::NIX_PACKAGES, "vim").expect("remove"));
        assert!(!contains(&path, &nixfile::NIX_PACKAGES, "vim").expect("contains"));
        // Remove non-existent returns false
        assert!(!remove(&path, &nixfile::NIX_PACKAGES, "vim").expect("remove again"));
    }

    #[test]
    fn test_remove_quoted() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "brew.nix", BREW_NIX);
        assert!(remove(&path, &nixfile::HOMEBREW_BREWS, "esptool").expect("remove"));
        assert!(!contains(&path, &nixfile::HOMEBREW_BREWS, "esptool").expect("contains"));
    }

    #[test]
    fn test_list_packages() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "base.nix", BASE_NIX);
        let pkgs = list_packages(&path, &nixfile::NIX_PACKAGES).expect("list");
        assert_eq!(pkgs, vec!["bash", "git", "vim"]);
    }

    #[test]
    fn test_list_packages_quoted() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "brew.nix", BREW_NIX);
        let brews = list_packages(&path, &nixfile::HOMEBREW_BREWS).expect("list");
        assert_eq!(brews, vec!["rustup", "esptool"]);
        let casks = list_packages(&path, &nixfile::HOMEBREW_CASKS).expect("list");
        assert_eq!(casks, vec!["firefox", "kitty"]);
    }

    #[test]
    fn test_edit_session_revert() {
        let dir = TempDir::new().expect("tmpdir");
        let path = write_fixture(dir.path(), "base.nix", BASE_NIX);

        let mut session = EditSession::new();
        session.backup(&path).expect("backup");

        insert(&path, &nixfile::NIX_PACKAGES, "htop").expect("insert");
        assert!(contains(&path, &nixfile::NIX_PACKAGES, "htop").expect("contains"));

        session.revert_all().expect("revert");
        assert!(!contains(&path, &nixfile::NIX_PACKAGES, "htop").expect("contains after revert"));
    }
}