nex-pkg 0.23.0

Package manager UX for nix-darwin + homebrew
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
use anyhow::{Context, Result};
use console::style;

use crate::cli::DoctorScope;
use crate::config::Config;
use crate::{bootstrap, homebrew_bootstrap, output};

/// Check and fix common issues with the nex-managed config repo.
pub fn run(config: &Config, fix: bool, scope: Option<DoctorScope>) -> Result<()> {
    if matches!(scope, Some(DoctorScope::DarwinBootstrap)) {
        return check_bootstrap(config, fix);
    }
    if matches!(scope, Some(DoctorScope::HomebrewBootstrap)) {
        return homebrew_bootstrap::doctor(config, fix);
    }

    tracing::info!(fix, ?scope, "running doctor checks");
    println!();
    println!("  {} — checking configuration", style("nex doctor").bold());
    println!();

    // Identity checks (report-only, no auto-fix)
    check_identity();

    let mut fixed = 0;

    check_bootstrap(config, fix)?;
    homebrew_bootstrap::doctor(config, fix)?;

    // Check mac-app-util integration
    if check_mac_app_util(config, &mut fixed)? {
        // Changes were made — need a switch
    }

    // Check unfree packages allowed
    check_allow_unfree(config, &mut fixed)?;

    // Check ~/.local/bin is on PATH via home.sessionPath
    check_session_path(config, &mut fixed)?;

    if fixed > 0 {
        // Commit the changes so nix doesn't complain about dirty tree
        crate::exec::git_commit(&config.repo, "nex doctor: apply fixes");

        println!();
        println!(
            "  {} {fixed} issue(s) fixed. Run {} to activate.",
            style("").green().bold(),
            style("nex switch").bold()
        );
    } else {
        println!("  {} no issues found", style("").green().bold());
    }

    println!();
    Ok(())
}

fn check_bootstrap(config: &Config, fix: bool) -> Result<()> {
    let Some(report) = bootstrap::check(config.platform)? else {
        return Ok(());
    };
    if !report.has_blockers() {
        ok("darwin bootstrap", "ready");
        return Ok(());
    }
    bootstrap::print_recommendations(&report);
    if fix {
        bootstrap::repair(&report)?;
    }
    Ok(())
}

/// Check if mac-app-util is configured for Spotlight-indexable app aliases.
/// If missing, patch flake.nix and mkHost.nix.
fn check_mac_app_util(config: &Config, fixed: &mut usize) -> Result<bool> {
    let flake_path = config.repo.join("flake.nix");
    let mkhost_path = config.repo.join("nix/lib/mkHost.nix");

    let flake = std::fs::read_to_string(&flake_path)
        .with_context(|| format!("reading {}", flake_path.display()))?;

    if flake.contains("mac-app-util") {
        ok("mac-app-util", "Spotlight app aliases enabled");
        return Ok(false);
    }

    warn(
        "mac-app-util",
        "not configured — nix apps won't appear in Spotlight",
    );

    // Patch flake.nix using line-by-line insertion logic
    let lines: Vec<&str> = flake.lines().collect();
    let mut result_lines: Vec<String> = Vec::new();
    let mut added_input = false;
    let mut patched_outputs = false;
    let mut patched_inherit = false;

    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();

        // Find the `};` that closes the inputs block (it precedes the outputs line)
        if !added_input && trimmed == "};" {
            // Check if a subsequent line starts with "outputs"
            let is_inputs_close = lines[i + 1..]
                .iter()
                .take(3)
                .any(|l| l.trim().starts_with("outputs"));
            if is_inputs_close {
                // Insert the mac-app-util input before this closing `};`
                result_lines
                    .push("    mac-app-util.url = \"github:hraban/mac-app-util\";".to_string());
                added_input = true;
            }
        }

        // Patch the outputs line to include mac-app-util
        if !patched_outputs
            && trimmed.starts_with("outputs")
            && trimmed.contains("home-manager")
            && !trimmed.contains("mac-app-util")
        {
            let patched = line.replace("home-manager }", "home-manager, mac-app-util }");
            let patched = patched.replace("home-manager }:", "home-manager, mac-app-util }:");
            result_lines.push(patched);
            patched_outputs = true;
            continue;
        }

        // Patch the inherit line
        if !patched_inherit
            && trimmed.starts_with("inherit")
            && trimmed.contains("home-manager")
            && !trimmed.contains("mac-app-util")
        {
            let patched = line.replace("home-manager;", "home-manager mac-app-util;");
            result_lines.push(patched);
            patched_inherit = true;
            continue;
        }

        result_lines.push(line.to_string());
    }

    let mut patched_flake = result_lines.join("\n");
    // Add trailing newline if original had one
    if flake.ends_with('\n') && !patched_flake.ends_with('\n') {
        patched_flake.push('\n');
    }

    if !patched_flake.contains("mac-app-util") {
        output::warn("could not auto-patch flake.nix — manual edit required");
        return Ok(false);
    }

    // Validate the patched flake has all required elements before writing
    let has_input = patched_flake.contains("mac-app-util.url");
    let has_output = patched_flake.contains("mac-app-util }");
    let has_inherit = patched_flake.contains("mac-app-util;");
    if !has_input || !has_output || !has_inherit {
        output::warn(
            "could not fully patch flake.nix — partial changes would break the flake.\n\
             Add mac-app-util manually: https://github.com/hraban/mac-app-util",
        );
        return Ok(false);
    }

    crate::edit::atomic_write_bytes(&flake_path, patched_flake.as_bytes())
        .with_context(|| format!("writing {}", flake_path.display()))?;
    info("patched", &flake_path.display().to_string());

    // Patch mkHost.nix
    if mkhost_path.exists() {
        let mkhost = std::fs::read_to_string(&mkhost_path)
            .with_context(|| format!("reading {}", mkhost_path.display()))?;

        if !mkhost.contains("mac-app-util") {
            let patched = mkhost
                .replace(
                    "{ nixpkgs, nix-darwin, home-manager }:",
                    "{ nixpkgs, nix-darwin, home-manager, mac-app-util }:",
                )
                .replace(
                    "    hostModule\n    home-manager.darwinModules.home-manager",
                    "    hostModule\n    mac-app-util.darwinModules.default\n    home-manager.darwinModules.home-manager",
                )
                .replace(
                    "        extraSpecialArgs = { inherit hostname username; };\n      };",
                    "        extraSpecialArgs = { inherit hostname username; };\n        sharedModules = [\n          mac-app-util.homeManagerModules.default\n        ];\n      };",
                );

            crate::edit::atomic_write_bytes(&mkhost_path, patched.as_bytes())
                .with_context(|| format!("writing {}", mkhost_path.display()))?;
            info("patched", &mkhost_path.display().to_string());
        }
    }

    tracing::info!(fix = "mac-app-util", "applied fix");
    *fixed += 1;
    Ok(true)
}

/// Check if nixpkgs.config.allowUnfree is set. Many common packages
/// (vscode, slack, spotify, terraform, vault) are unfree.
fn check_allow_unfree(config: &Config, fixed: &mut usize) -> Result<bool> {
    // Check all nix files in the repo for any unfree config
    let base_path = config.repo.join("nix/modules/darwin/base.nix");
    if !base_path.exists() {
        return Ok(false);
    }

    let content = std::fs::read_to_string(&base_path)
        .with_context(|| format!("reading {}", base_path.display()))?;

    if content.contains("allowUnfree") {
        ok("unfree packages", "nixpkgs.config.allowUnfree is set");
        return Ok(false);
    }

    warn(
        "unfree packages",
        "not allowed — vscode, slack, spotify, etc. will fail to install",
    );

    // Insert after the nix.enable or nix.settings line
    let patched = if content.contains("nix.enable = false;") {
        content.replace(
            "nix.enable = false;",
            "nix.enable = false;\n\n  nixpkgs.config.allowUnfree = true;",
        )
    } else if content.contains("nix.settings.experimental-features") {
        content.replace(
            "nix.settings.experimental-features",
            "nixpkgs.config.allowUnfree = true;\n\n  nix.settings.experimental-features",
        )
    } else {
        // Can't find a good insertion point
        output::warn(
            "could not auto-patch base.nix — add `nixpkgs.config.allowUnfree = true;` manually",
        );
        return Ok(false);
    };

    crate::edit::atomic_write_bytes(&base_path, patched.as_bytes())
        .with_context(|| format!("writing {}", base_path.display()))?;
    info("patched", &base_path.display().to_string());

    tracing::info!(fix = "allow-unfree", "applied fix");
    *fixed += 1;
    Ok(true)
}

/// Check that ~/.local/bin is in home.sessionPath so nex is always on PATH.
fn check_session_path(config: &Config, fixed: &mut usize) -> Result<bool> {
    let base_path = &config.nix_packages_file;
    if !base_path.exists() {
        return Ok(false);
    }

    let content = std::fs::read_to_string(base_path)
        .with_context(|| format!("reading {}", base_path.display()))?;

    let in_nix_config = content.contains("sessionPath");
    let on_path = is_local_bin_on_path();

    if in_nix_config && on_path {
        ok("sessionPath", "~/.local/bin is on PATH");
        return Ok(false);
    }

    if in_nix_config && !on_path {
        warn(
            "sessionPath",
            "configured in nix but ~/.local/bin is not on PATH — run `nex switch` then open a new shell",
        );
        return Ok(false);
    }

    // Not in nix config at all
    warn(
        "sessionPath",
        "~/.local/bin not in PATH — nex may not be found after install",
    );

    // Insert after the home block
    let patched = if content.contains("stateVersion =") {
        content.replace(
            "stateVersion =",
            "sessionPath = [ \"$HOME/.local/bin\" ];\n    stateVersion =",
        )
    } else {
        output::warn(
            "could not auto-patch — add `home.sessionPath = [ \"$HOME/.local/bin\" ];` manually",
        );
        return Ok(false);
    };

    crate::edit::atomic_write_bytes(base_path, patched.as_bytes())
        .with_context(|| format!("writing {}", base_path.display()))?;
    info("patched", &base_path.display().to_string());

    tracing::info!(fix = "session-path", "applied fix");
    *fixed += 1;
    Ok(true)
}

/// Check if ~/.local/bin (or its expanded form) is on the current $PATH.
fn is_local_bin_on_path() -> bool {
    let path_var = std::env::var("PATH").unwrap_or_default();
    let home = std::env::var("HOME").unwrap_or_default();
    let expanded = format!("{home}/.local/bin");

    path_var
        .split(':')
        .any(|entry| entry == "~/.local/bin" || entry == "$HOME/.local/bin" || entry == expanded)
}

/// Check identity file health and git signing configuration.
fn check_identity() {
    let identity_path = styrene_identity::file_signer::FileSigner::default_path();

    if !identity_path.exists() {
        warn("identity", "no identity file — run `nex identity init`");
    } else {
        match std::fs::metadata(&identity_path) {
            Ok(meta) => {
                if meta.len() != 97 {
                    warn(
                        "identity",
                        &format!("unexpected file size ({} bytes, expected 97)", meta.len()),
                    );
                } else {
                    ok("identity", &format!("{}", identity_path.display()));
                }

                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    let mode = meta.permissions().mode() & 0o777;
                    if mode != 0o600 {
                        warn(
                            "identity permissions",
                            &format!("{:#o} — should be 0o600", mode),
                        );
                    }
                }
            }
            Err(e) => warn("identity", &format!("cannot read: {e}")),
        }
    }

    // Git signing
    let gpg_format = std::process::Command::new("git")
        .args(["config", "--global", "gpg.format"])
        .output();
    match gpg_format {
        Ok(ref out) if crate::exec::captured_text(&out.stdout).trim() == "ssh" => {
            ok("git signing", "gpg.format = ssh");
        }
        _ => {
            info("git signing", "not configured — run `nex identity git`");
        }
    }

    // SSH labels
    match crate::config::load_identity_config() {
        Ok(id_config) => {
            let labels = id_config.ssh.and_then(|s| s.labels).unwrap_or_default();
            if labels.is_empty() {
                info(
                    "ssh labels",
                    "none registered — try `nex identity ssh --add github`",
                );
            } else {
                ok(
                    "ssh labels",
                    &format!("{}: {}", labels.len(), labels.join(", ")),
                );
            }
        }
        Err(_) => {
            info("ssh labels", "no identity config");
        }
    }
}

fn ok(label: &str, detail: &str) {
    eprintln!(
        "  {} {}: {}",
        style("").green().bold(),
        label,
        style(detail).dim()
    );
}

fn warn(label: &str, detail: &str) {
    eprintln!(
        "  {} {}: {}",
        style("!").yellow().bold(),
        label,
        style(detail).dim()
    );
}

fn info(label: &str, detail: &str) {
    eprintln!("  {} {}: {}", style("").cyan(), label, style(detail).dim());
}