flk 0.7.0

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
//! # Global Environment Handler
//!
//! Manage a machine-scoped flk environment (Devbox-style "global mode") for
//! always-on developer tools like ripgrep, fd, or bat.
//!
//! The global environment is a regular flk project (slim layout) stored at
//! `~/.config/flk/global` by default. Every subcommand resolves that
//! directory, changes the process working directory into it, auto-initializes
//! it on first use, and then delegates to the existing project-scoped
//! handlers unchanged.
//!
//! Directory resolution order:
//! 1. `FLK_GLOBAL_DIR` environment variable
//! 2. `$XDG_CONFIG_HOME/flk/global`
//! 3. `~/.config/flk/global`

use anyhow::{anyhow, Context, Result};
use clap::Subcommand;
use colored::Colorize;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use crate::commands::hook::HookShell;
use crate::commands::profiles::ProfileAction;
use crate::commands::unfree::UnfreeAction;
use crate::commands::{activate, add, init, list, profiles, remove, unfree, update};
use crate::nix::run_nix_command;

/// Subcommands available under `flk global`.
#[derive(Subcommand)]
pub enum GlobalAction {
    /// Add a package to the global environment
    Add {
        /// Package name to add
        package: String,

        /// Pin to a specific version
        #[arg(short, long)]
        version: Option<String>,

        /// Target profile to add the package to
        #[arg(short = 'p', long)]
        profile: Option<String>,
    },

    /// Remove a package from the global environment
    Remove {
        /// Package name to remove
        package: String,

        /// Target profile to remove the package from
        #[arg(short = 'p', long)]
        profile: Option<String>,
    },

    /// List the packages of the global environment
    List {
        /// Target profile to list packages from
        #[arg(short = 'p', long)]
        profile: Option<String>,
    },

    /// Enter the global dev shell
    Activate {
        /// Target profile to activate
        #[arg(short = 'p', long)]
        profile: Option<String>,
    },

    /// Update global packages to latest version
    Update {
        /// Specific packages to update
        packages: Vec<String>,

        /// Show what would be updated without actually updating
        #[arg(short, long)]
        show: bool,
    },

    /// Print the global environment directory
    Path,

    /// Print the global flake reference (`<dir>#<profile>`) for shell hooks
    Ref {
        /// Target profile (defaults to the global default profile)
        #[arg(short = 'p', long)]
        profile: Option<String>,
    },

    /// Print shell code exposing global packages in every shell (eval in your rc file)
    Shellenv {
        /// Shell to generate code for
        shell: HookShell,

        /// Target profile (defaults to the global default profile)
        #[arg(short = 'p', long)]
        profile: Option<String>,
    },

    /// Manage profiles of the global environment
    Profile {
        #[command(subcommand)]
        action: ProfileAction,
    },

    /// Manage the allow-list of unfree packages in the global environment
    Unfree {
        #[command(subcommand)]
        action: UnfreeAction,
    },
}

/// Resolve the global environment directory.
///
/// Resolution order: `FLK_GLOBAL_DIR` env var, then
/// `$XDG_CONFIG_HOME/flk/global`, then `~/.config/flk/global`.
pub fn global_dir() -> Result<PathBuf> {
    global_dir_from(
        env::var("FLK_GLOBAL_DIR").ok().as_deref(),
        env::var("XDG_CONFIG_HOME").ok().as_deref(),
    )
}

/// Pure resolution logic behind [`global_dir`], separated so tests don't
/// need to mutate process environment variables (not thread-safe).
fn global_dir_from(flk_global_dir: Option<&str>, xdg_config_home: Option<&str>) -> Result<PathBuf> {
    if let Some(dir) = flk_global_dir {
        if !dir.trim().is_empty() {
            return Ok(PathBuf::from(dir));
        }
    }

    if let Some(xdg) = xdg_config_home {
        if !xdg.trim().is_empty() {
            return Ok(PathBuf::from(xdg).join("flk").join("global"));
        }
    }

    let home = dirs::home_dir().ok_or_else(|| anyhow!("Could not detect home directory"))?;
    Ok(home.join(".config").join("flk").join("global"))
}

/// Ensure the global environment exists and make it the working directory.
///
/// Creates the directory if needed, changes the process working directory
/// into it (all project handlers are cwd-relative), and initializes a
/// generic flk environment on first use.
fn ensure_global_env() -> Result<PathBuf> {
    let dir = global_dir()?;

    fs::create_dir_all(&dir).with_context(|| {
        format!(
            "Failed to create global environment directory '{}'",
            dir.display()
        )
    })?;
    env::set_current_dir(&dir).with_context(|| {
        format!(
            "Failed to enter global environment directory '{}'",
            dir.display()
        )
    })?;

    // A project shell exports FLK_FLAKE_REF for its own profile; it must not
    // leak into the global environment's profile resolution.
    env::remove_var("FLK_FLAKE_REF");

    println!(
        "{} Using global environment: {}",
        "".blue(),
        dir.display().to_string().cyan()
    );

    if !Path::new("flake.nix").exists() {
        init::run(Some("generic".to_string()), false, false)?;
        println!(
            "\n{} Enter your global tools shell anytime with: {}",
            "".blue(),
            "flk global activate".cyan()
        );
    }

    Ok(dir)
}

/// Dispatch a `flk global` subcommand.
///
/// `Path` only prints the resolved directory (no side effects); every other
/// action ensures the global environment exists and delegates to the
/// corresponding project-scoped handler.
pub fn run(action: GlobalAction) -> Result<()> {
    if let GlobalAction::Path = action {
        println!("{}", global_dir()?.display());
        return Ok(());
    }

    // `Ref` is plumbing for the hook's `refresh -g`/`switch -g`: its stdout
    // is consumed by command substitution, so it must print exactly the
    // flake reference and never the init/info banners.
    if let GlobalAction::Ref { profile } = action {
        let dir = global_dir()?;
        if !dir.join("flake.nix").exists() {
            anyhow::bail!(
                "Global environment not initialized. Run any 'flk global' command (e.g. 'flk global list') first."
            );
        }
        env::set_current_dir(&dir).with_context(|| {
            format!(
                "Failed to enter global environment directory '{}'",
                dir.display()
            )
        })?;
        env::remove_var("FLK_FLAKE_REF");
        let profile = flk::flake::parsers::utils::resolve_profile(profile)?;
        println!("{}#{}", dir.display(), profile);
        return Ok(());
    }

    // `Shellenv` is eval'd from shell rc files on every shell start: stdout
    // must be valid shell code (or comments), never banners.
    if let GlobalAction::Shellenv { shell, profile } = action {
        return run_shellenv(shell, profile);
    }

    // Where the user actually is — `global activate` opens the shell here,
    // not in the global environment directory.
    let user_dir = env::current_dir().context("Failed to read current directory")?;

    ensure_global_env()?;

    match action {
        GlobalAction::Add {
            package,
            version,
            profile,
        } => add::run_add(&package, version, profile),
        GlobalAction::Remove { package, profile } => remove::run_remove(&package, profile),
        GlobalAction::List { profile } => list::run_list(profile),
        GlobalAction::Activate { profile } => activate::run_activate_in(profile, Some(&user_dir)),
        GlobalAction::Update { packages, show } => update::run_update(packages, show),
        GlobalAction::Profile { action } => match action {
            ProfileAction::Add {
                name,
                template,
                force,
            } => profiles::run_add(name, template, force),
            ProfileAction::Remove { name } => profiles::run_remove(name),
            ProfileAction::List => profiles::run_list(),
            ProfileAction::SetDefault { profile } => profiles::run_set_default(profile),
        },
        GlobalAction::Unfree { action } => unfree::run(action),
        GlobalAction::Path | GlobalAction::Ref { .. } | GlobalAction::Shellenv { .. } => {
            unreachable!("handled above")
        }
    }
}

/// Print shell code that appends the global environment's store paths to
/// PATH — Devbox-style "shellenv" integration for rc files.
///
/// The PATH is extracted from `nix print-dev-env` on the profile's GC root
/// (fast and offline: no flake evaluation) and *appended*, so system tools
/// and project shells always win; global packages only fill the gaps.
///
/// Only entries belonging to the shell's `buildInputs` are exported (see
/// [`exported_path_entries`]). Taking the raw PATH would drag the whole
/// stdenv build toolchain — gcc, binutils, glibc-bin, make, patch, tar —
/// into *every* shell on the machine, where it would silently answer for a
/// missing system `cc` or `make`.
///
/// Degrades to a comment (never an error) when the environment isn't
/// initialized or built yet, so rc files stay safe.
fn run_shellenv(shell: HookShell, profile: Option<String>) -> Result<()> {
    let dir = global_dir()?;
    if !dir.join("flake.nix").exists() {
        println!("# flk global shellenv: global environment not initialized; run any 'flk global' command first");
        return Ok(());
    }
    env::set_current_dir(&dir).with_context(|| {
        format!(
            "Failed to enter global environment directory '{}'",
            dir.display()
        )
    })?;
    env::remove_var("FLK_FLAKE_REF");
    let profile = flk::flake::parsers::utils::resolve_profile(profile)?;

    let profile_link = dir.join(".flk").join(format!(".nix-profile-{profile}"));
    if !profile_link.exists() {
        println!(
            "# flk global shellenv: environment not built yet; run 'flk global activate' once"
        );
        return Ok(());
    }

    let link = profile_link.display().to_string();
    let (stdout, stderr, success) = run_nix_command(&["print-dev-env", &link, "--json"])?;
    if !success {
        anyhow::bail!("nix print-dev-env failed for '{}': {}", link, stderr);
    }

    let env_json: serde_json::Value =
        serde_json::from_str(&stdout).context("Failed to parse nix print-dev-env output")?;
    let path_value = env_json["variables"]["PATH"]["value"]
        .as_str()
        .context("nix print-dev-env output has no PATH variable")?;

    // `pkgsHostTarget` is the devShell's buildInputs. Without it there is no
    // way to tell the environment's packages from the stdenv toolchain, and
    // exporting the unfiltered PATH is exactly the bug this filter exists to
    // prevent — so export nothing rather than guess.
    let owners: Vec<String> = env_json["variables"]["pkgsHostTarget"]["value"]
        .as_array()
        .map(|values| {
            values
                .iter()
                .filter_map(|value| value.as_str().map(ToOwned::to_owned))
                .collect()
        })
        .unwrap_or_default();
    if owners.is_empty() {
        println!("# flk global shellenv: cannot determine the environment's packages (nix print-dev-env has no pkgsHostTarget); nothing exported");
        return Ok(());
    }

    let entries = exported_path_entries(path_value, &owners);
    if entries.is_empty() {
        println!("# flk global shellenv: global environment provides no store paths");
        return Ok(());
    }

    // Idempotency: append only when PATH doesn't already contain this exact
    // entry set. A marker variable won't do — it would be inherited by
    // nested/exec'd shells and skip re-appending after the environment was
    // rebuilt with different entries (stale PATH would win).
    match shell {
        HookShell::Bash | HookShell::Zsh => {
            let joined = entries.join(":");
            println!(
                "case \":$PATH:\" in\n  *\":{joined}:\"*) ;;\n  *) export PATH=\"$PATH:{joined}\" ;;\nesac"
            );
        }
        HookShell::Fish => {
            let joined = entries.join(":");
            println!(
                "if not string match -q '*{joined}*' (string join : $PATH)\n  set -gx PATH $PATH {}\nend",
                entries.join(" ")
            );
        }
    }

    Ok(())
}

/// Select the PATH entries worth exporting into every shell.
///
/// `path_value` is `nix print-dev-env`'s PATH; `owners` are the store paths
/// of the shell's `buildInputs` (`pkgsHostTarget`). An entry survives only
/// if it is one of the owners or lives inside one — which drops the stdenv
/// toolchain contributed by `pkgsBuildHost` (gcc, binutils, patchelf, make,
/// …) while keeping the environment's actual packages and their propagated
/// binaries. Order is preserved and duplicates are collapsed.
///
/// Pure so it can be tested without invoking nix, like [`global_dir_from`].
fn exported_path_entries<'a>(path_value: &'a str, owners: &[String]) -> Vec<&'a str> {
    let owned_by_env = |entry: &str| {
        owners
            .iter()
            .any(|owner| entry == owner || entry.starts_with(&format!("{owner}/")))
    };

    let mut seen = std::collections::HashSet::new();
    path_value
        .split(':')
        .filter(|entry| owned_by_env(entry) && seen.insert(*entry))
        .collect()
}

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

    #[test]
    fn global_dir_prefers_flk_global_dir() {
        assert_eq!(
            global_dir_from(Some("/custom/global"), Some("/xdg")).unwrap(),
            PathBuf::from("/custom/global")
        );
    }

    #[test]
    fn global_dir_falls_back_to_xdg_config_home() {
        assert_eq!(
            global_dir_from(None, Some("/xdg")).unwrap(),
            PathBuf::from("/xdg/flk/global")
        );
    }

    fn owners(paths: &[&str]) -> Vec<String> {
        paths.iter().map(ToString::to_string).collect()
    }

    #[test]
    fn exported_path_entries_drops_the_stdenv_toolchain() {
        // gcc-wrapper and patchelf come from pkgsBuildHost: they are not
        // owned by any buildInput and must never reach a user's PATH.
        let path = concat!(
            "/nix/store/aaa-gcc-wrapper-15.2.0/bin:",
            "/nix/store/bbb-ripgrep-14.1.0/bin:",
            "/nix/store/ccc-patchelf-0.15.2/bin"
        );
        assert_eq!(
            exported_path_entries(path, &owners(&["/nix/store/bbb-ripgrep-14.1.0"])),
            vec!["/nix/store/bbb-ripgrep-14.1.0/bin"]
        );
    }

    #[test]
    fn exported_path_entries_matches_owners_and_their_subdirectories() {
        let path = concat!(
            "/nix/store/aaa-hello-1.0:",
            "/nix/store/aaa-hello-1.0/bin:",
            "/nix/store/aaa-hello-1.0-suffix/bin"
        );
        // The owner itself and paths inside it match; a store path that
        // merely shares its prefix does not.
        assert_eq!(
            exported_path_entries(path, &owners(&["/nix/store/aaa-hello-1.0"])),
            vec!["/nix/store/aaa-hello-1.0", "/nix/store/aaa-hello-1.0/bin"]
        );
    }

    #[test]
    fn exported_path_entries_dedupes_and_preserves_order() {
        let path = concat!(
            "/nix/store/bbb-fd-10.2.0/bin:",
            "/usr/bin:",
            "/nix/store/aaa-hello-1.0/bin:",
            "/nix/store/bbb-fd-10.2.0/bin"
        );
        assert_eq!(
            exported_path_entries(
                path,
                &owners(&["/nix/store/aaa-hello-1.0", "/nix/store/bbb-fd-10.2.0"])
            ),
            vec![
                "/nix/store/bbb-fd-10.2.0/bin",
                "/nix/store/aaa-hello-1.0/bin"
            ]
        );
    }

    #[test]
    fn exported_path_entries_without_owners_exports_nothing() {
        let path = "/nix/store/aaa-gcc-wrapper-15.2.0/bin:/usr/bin";
        assert!(exported_path_entries(path, &[]).is_empty());
    }

    #[test]
    fn global_dir_ignores_empty_overrides() {
        let home = dirs::home_dir().expect("test environment must have a home dir");
        assert_eq!(
            global_dir_from(Some("  "), Some("")).unwrap(),
            home.join(".config").join("flk").join("global")
        );
    }
}