Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

flk and Flik, the mascot

flk manages Nix flake dev environments in the style of Devbox: you run commands instead of editing Nix files by hand.

The main difference is that all nix code involved is transparent and readable for you to check! Both your local flk environments, or the nix-profile-lib helper are public and available any time. Because for one, I did not want yet another wrapper/abstraction layer, and secondly and most important, you should be able to check what your PC is running.

Features

  • Detects typical project types on init
  • Add and remove packages, with optional version pins
  • Custom shell commands
  • Per-project environment variables
  • Multiple profiles per project
  • Option to combine said profiles
  • Flake updates with rollback and backup options similar to nix/os generations
  • Global flk environment for generally used packages within your system

Example

flk init
flk add ripgrep
flk command add build "cargo build --release"
flk activate
build

Staying on flk before v0.5.0

On flk older than v0.5.0, flk update or nix flake update can pull a newer nix-profile-lib whose activation changes break switch and refresh commands. To stay on the old version, either:

  1. Don’t update flake inputs. If you already did, restore a backup:

    flk lock restore <BACKUP>
    
  2. Pin nix-profile-lib to v0.1.0 in flake.nix:

    inputs = {
      nix-profile-lib.url = "git+https://gitlab.com/pixel-racks/flakes/nix-profile-lib?ref=v0.1.0";
    };
    

    and update the lock entry:

    nix flake lock --update-input nix-profile-lib
    

    (or nix flake update --update-input nix-profile-lib)

flk v0.5.0 and later don’t have this problem.

Questions and bugs: GitLab issues.

Installation

Prerequisites

  • Nix with flakes enabled
  • Rust 1.83+ (if building from source)

Shell hook

Optional. See flk hook.

From source

git clone https://gitlab.com/pixel-racks/flk.git
cd flk
cargo build --release
sudo cp target/release/flk /usr/local/bin/

From Cargo (crates.io)

cargo install flk

From release binaries

  1. Go to https://gitlab.com/pixel-racks/flk/-/releases
  2. Download the archive for your platform (Linux x86_64, macOS Intel, macOS ARM).
  3. Unpack it and put flk on your PATH.

Nix (with Cachix binaries)

Prebuilt binaries are on Cachix.

  1. Install Cachix (once):
nix profile install nixpkgs#cachix
  1. Trust the cache:
cachix use flk-cache

or add the cache to nix.conf:

substituters = https://flk-cache.cachix.org  ...
trusted-public-keys = flk-cache.cachix.org-1:6xobbpP9iIK5sIH/75DQrsJYKN/61nTOChcH9MJnBR0=  ...
  1. Use the flake:
  • Run (no install): nix run gitlab:pixel-racks/flk#flk
  • Install to your profile: nix profile install gitlab:pixel-racks/flk#flk

Nix flake input

Use the package directly or through the overlay.

Direct (no overlay):

{
  description = "My NixOS config with flk";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flk.url = "gitlab:pixel-racks/flk";
  };

  outputs = { self, nixpkgs, flk, ... }:
    let
      system = "x86_64-linux"; # set per host
      pkgs = import nixpkgs { inherit system; };
    in {
      nixosConfigurations.myhost = nixpkgs.lib.nixosSystem {
        inherit system;
        modules = [
          {
            environment.systemPackages = [
              flk.packages.${system}.flk
            ];
          }
        ];
      };
    };
}

With overlay (exposes pkgs.flk):

{
  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
  inputs.flk.url = "gitlab:pixel-racks/flk";

  outputs = { self, nixpkgs, flk, ... }:
    let
      system = "x86_64-linux"; # set per host

      pkgs = import nixpkgs {
        inherit system;
        overlays = [ flk.overlay ];
      };
    in {
      nixosConfigurations.myhost = nixpkgs.lib.nixosSystem {
        inherit system;
        modules = [
          { environment.systemPackages = [ pkgs.flk ]; }
        ];
      };
    };
}

Home Manager example (per-user install via flake):

{
  inputs.flk.url = "gitlab:pixel-racks/flk";

  outputs = { self, flk, ... }: {
    homeConfigurations.myhost = {
      # ...
      home.packages = [ flk.packages.${system}.flk ];
    };
  };
}

Architectures covered by the cache

  • x86_64-linux
  • x86_64-darwin
  • aarch64-darwin
  • aarch64-linux (built with qemu in CI, so occasionally missing)

Other systems build from source.

Next: Getting Started.

Getting Started

1. Create the project

Run the init command in the selected project dir and wait for flk to generate the baseline structure. Either let flk detect your toolchain or force a specific template to be used during init as seen below.

flk init                    # detects the project type
flk init --template rust    # or pick one: rust, python, node, go, generic

Detection is described in Project Templates.

2. Add packages

First you can search for any packages needed. Search subcommand shows packages matching the given name using a fuzzy search. Deep-search looks for a specific (literal) package name and provides the available versions that could be pinned to.

Add any packages you need to your environment. This can take a while on first run since nix needs to build the index prior to the addition, so that packages can be verified.

flk search ripgrep
flk deep-search ripgrep             # available versions
flk add ripgrep
flk add ripgrep --version 15.1.0    # pinned

3. Add commands and environment variables

Commands are basically shell functions that will only be available inside your flk env. Env vars are exported and used as normal .env files. But do not add any PRIVATE keys. Environment variables in flk are committed as they follow the profile, so make sure to keep that in mind.

flk command add test "cargo test --all"
flk env add DATABASE_URL "postgresql://localhost/mydb"
flk env list
flk env remove DATABASE_URL

4. Enter the environment

This can also take some time as nix will need to pull all the packages from the cache, and in some specific cases, build them.

flk activate
test

5. Shell completions

This is completely optional, but completions are available following the steps below.

flk completions             # print the script
flk completions --install   # install it for the detected shell

6. direnv (optional)

If you want to use direnv to activate your flk environment, please use the provided flk commands below to set and unset the connection.

flk direnv init      # new .envrc
flk direnv attach    # existing .envrc
flk direnv detach

7. Shell hook (optional)

The hook adds refresh and switch inside the environment. Setup is on the flk hook page.

Next: Core Concepts, Commands.

Core Concepts

Projects

A flk project is a directory with a flake.nix. Profiles live in .flk/profiles/, and flake.nix loads them when you activate the environment.

flk init

Profiles

A profile is a set of packages, commands and environment variables stored in .flk/profiles/<name>.nix. With the shell hook installed, switch moves between profiles.

flk profile add backend

Custom commands

Custom commands are shell functions defined in a profile. They are available in the shell once the environment is active.

flk command add test "cargo test --all"

Environment variables

Environment variables are defined in a profile and exported when the environment is activated. They do not affect your global environment.

Warning: Do not store secrets in plain text in profile files, especially if the project is shared or version-controlled.

flk env add DATABASE_URL "postgres://localhost/dev"

Lock files

flake.lock records the exact input revisions, so the same environment can be rebuilt later or on another machine. flk update backs it up before updating, and flk lock lets you inspect and restore backups.

flk lock history

Overlays

Overlays modify existing packages or add new ones to the Nix package set. flk uses them for version pins, which are recorded in .flk/pins.nix alongside the lock file.

flk add ripgrep --version 14.1.0

Shell integration

The shell hook adds refresh and switch commands. They reload the environment or change profile without leaving the shell.

eval "$(flk hook bash)"

direnv integration

flk direnv init writes a .envrc that loads the flk environment when you enter the project directory. flk direnv attach and flk direnv detach manage it afterwards.

flk direnv init

Container exporting

flk export builds a Docker or Podman image from your environment, including packages, commands and environment variables. It is useful where flk itself is not available.

flk export --format docker

Examples

Python data science

flk init --template python

flk add python312
flk add python312Packages.numpy
flk add python312Packages.pandas
flk add python312Packages.matplotlib
flk add python312Packages.scikit-learn
flk add jupyter

flk command add notebook "jupyter notebook --port=8888"
flk command add lab "jupyter lab --port=8888"
flk command add ipython "python -m IPython"

flk env add JUPYTER_CONFIG_DIR "./.jupyter"
flk env add PYTHONDONTWRITEBYTECODE "1"

flk activate
notebook

Rust web backend

flk init --template rust

flk add postgresql
flk add redis
flk add sqlx-cli
flk add cargo-watch

flk command add dev "cargo watch -x run"
flk command add test "cargo test --all-features"
flk command add migrate "sqlx migrate run"
flk command add db "psql $DATABASE_URL"

flk env add DATABASE_URL "postgresql://localhost/myapp"
flk env add REDIS_URL "redis://localhost:6379"
flk env add RUST_LOG "debug"

flk activate
dev

Node.js app

flk init --template node

flk add nodejs_20
flk add postgresql
flk add docker-compose
flk add nodePackages.typescript
flk add nodePackages.eslint

flk command add dev "npm run dev"
flk command add build "npm run build"
flk command add db-start "docker-compose up -d postgres"
flk command add db-stop "docker-compose down"
flk command add lint "npm run lint"
flk command add typecheck "tsc --noEmit"

flk env add NODE_ENV "development"
flk env add DATABASE_URL "postgresql://localhost/myapp"
flk env add PORT "3000"

flk activate
db-start
dev

Go service

flk init --template go

flk add go
flk add gopls
flk add golangci-lint
flk add mockgen
flk add protobuf

flk command add run "go run ./cmd/server"
flk command add test "go test ./..."
flk command add lint "golangci-lint run"
flk command add proto "protoc --go_out=. --go-grpc_out=. ./proto/*.proto"
flk command add build "go build -o bin/server ./cmd/server"

flk env add GOPROXY "https://proxy.golang.org,direct"
flk env add CGO_ENABLED "0"

flk activate
run

Monorepo with several profiles

flk init --template generic
flk profile add frontend --template node
flk profile add backend --template go

# shared tools go in the default profile
flk add docker-compose
flk add gnumake
flk command add up "docker-compose up -d"
flk command add down "docker-compose down"

# per-profile packages
flk add nodejs_20 -p frontend
flk add gopls -p backend

Inside the shell, switch frontend and switch backend move between them (needs the shell hook).

Pinned versions

flk add ripgrep --version 14.1.0
flk add nodejs --version 20.10.0
flk add python3 --version 3.11.6

flk list

Pins are stored in .flk/pins.nix.

direnv

flk direnv init
direnv allow

The environment now loads when you cd into the project and unloads when you leave.

Container export

flk export --format docker
flk export --format podman
flk export --format json     # writes flake.json

Project Templates

flk init writes a profile from a template. flk profile add uses the same templates.

flk init --template rust     # rust, python, node, go, generic
flk profile add backend --template go

Detection

Without --template, flk init looks for:

FileTemplate
Cargo.tomlrust
package.jsonnode
pyproject.toml or requirements.txtpython
go.modgo
none of thesegeneric

Templates

TemplatePackages
ruststable Rust from rust-overlay, rust-analyzer, pkg-config, openssl, cargo-watch, cargo-edit, cargo-dist
pythonPython 3.14, pip, poetry, uv, ruff, mypy, pyright
nodeNode.js 24, pnpm, yarn, eslint, prettier
gogo, gopls, gotools, go-tools, delve, golangci-lint
generic / basenone

base and generic are the same empty template. flk profile add uses base when no template is given.

Source files

Templates live in templates/ and are embedded in the binary at compile time:

  • templates/profiles/*.nix: profile templates
  • templates/slim/: flake.nix and .flk/config.nix for the default layout
  • templates/flake.nix, templates/default.nix, templates/overlays.nix, templates/profiles/default.nix: the legacy layout (flk init --legacy)
  • templates/pins.nix: empty version pins

See also flk init, flk profile, Architecture.

Custom Commands

Custom commands are named scripts stored in a profile. They are available in the shell once the environment is active.

flk command add dev "npm run dev"
flk command add test "cargo test --all"
flk command list
flk command remove dev

Read the script from a file with --file:

flk command add deploy --file scripts/deploy.sh

Target another profile with --profile, placed before the subcommand:

flk command --profile backend add build "cargo build --release"
flk command --profile frontend list

Storage

Commands go in the commands list of .flk/profiles/<profile>.nix:

commands = [
  { name = "dev"; script = ''npm run dev''; }
  { name = "test"; script = ''cargo test --all''; }
];

Names

Letters, numbers, - and _, not starting with -. For example dev, run-tests, build_release.

More examples

flk command add watch "cargo watch -x 'run -- --port 8080'"
flk command add migrate "npx prisma migrate dev"
flk command add ci --file scripts/ci.sh

See also flk command.

Environment Variables

Variables are stored per profile and exported when the environment is activated (flk activate, nix develop or direnv).

flk env add DATABASE_URL "postgresql://localhost:5432/mydb"
flk env --profile backend add API_URL "http://localhost:3000"
flk env list
flk env remove DATABASE_URL

Storage

They go in the envVars block of .flk/profiles/<profile>.nix:

envVars = {
  DATABASE_URL = "postgresql://localhost:5432/mydb";
  NODE_ENV = "development";
};

Names

Must start with a letter or _ and contain only letters, digits and _. DATABASE_URL and _KEY are valid; 123VAR, my-var are not.

Secrets

Warning: Profile files are plain text and usually committed. Don’t put secrets in them.

Keep secrets in an untracked file instead, for example a .envrc line such as source_env_if_exists .envrc.local with .envrc.local in .gitignore, or load them from a secrets manager.

See also flk env.

Lock File Management

flk update backs up flake.lock before changing it, and flk lock lets you inspect and restore those backups.

flk update                              # back up flake.lock, then nix flake update
flk update --show                       # preview updates without applying
flk lock show                           # inputs, revisions, dates
flk lock history                        # backups in .flk/backups/
flk lock restore latest                 # most recent backup
flk lock restore 2025-01-27_14-30-00    # specific timestamp

Backups

flk update and flk lock restore copy the current flake.lock to .flk/backups/ first:

.flk/backups/
├── flake.lock.2025-01-27_14-30-00
├── flake.lock.2025-02-15_09-45-22
└── flake.lock.2025-03-01_16-00-00

Backups are never deleted automatically. Remove old ones from .flk/backups/ by hand.

Updating

flk update runs nix flake update after taking the backup. flk update --show updates the lock file, prints the diff, then puts the original back. If an update breaks something, flk lock restore latest undoes it.

Inspecting and restoring

flk lock show prints each input with its type, source, revision and last-modified date. flk lock history lists the backups. flk lock restore takes latest or a timestamp from that list, and backs up the current flake.lock before replacing it, so a restore can be undone too.

Version pins

Pins from flk add --version live in .flk/pins.nix, not flake.lock, so backups and restores don’t touch them.

Commands Overview

AreaCommands
Projectinit, import, migrate, activate, profile, hook, direnv
Packagessearch, deep-search, add, remove, list, show, unfree
Shellcommand, env
Lock fileupdate, lock
Otherexport, global, prune, completions

flk <command> --help prints the options for each.

flk activate

Enters the dev shell.

flk activate
flk activate --profile backend

Options

  • -p, --profile <PROFILE>: profile to activate instead of the default

Behavior

  • Runs nix develop .#<profile> --impure
  • Reuses a cached develop profile from .flk/.nix-profile-<profile> when your flake config is unchanged
  • Refreshes that cached profile when flake.nix, flake.lock, or the relevant .flk profile files change
  • Picks the profile as described in profile selection
  • Exports FLK_FLAKE_REF and FLK_PROFILE so refresh/switch know the active profile (flk global activate also exports FLK_ENV_DIR)
  • Exports FLK_ORIG_PATH, the PATH before activation, which refresh/switch reset to

Shell selection

The shell started inside the environment is, in order:

  1. FLK_SHELL
  2. $SHELL, unless it points into /nix/store. nix develop and nix-shell set SHELL to nixpkgs’ non-interactive bash, which has no completion and a broken prompt.
  3. The login shell from /etc/passwd
  4. /bin/sh

refresh and switch use the same order.

See also flk hook for refresh/switch, and flk direnv to activate on cd.

flk add

flk add ripgrep
flk add ripgrep --version 15.1.0
flk add cargo-watch --profile backend
  • Checks the package exists with nix-versions before writing.
  • Writes to .flk/profiles/<profile>.nix. With --version, also records the pin in .flk/pins.nix.
  • If the package is already declared, the old entry is replaced, so adding with a different version changes the pin.

flk command

flk command add test "cargo test --all"
flk command add deploy --file scripts/deploy.sh
flk command list
flk command remove test
flk command --profile backend list

--profile goes before the subcommand. Names may contain letters, digits, - and _, and can’t start with -.

See Custom Commands.

flk completions

flk completions             # print for the detected shell
flk completions zsh         # print for a given shell
flk completions --install   # write to the shell's completion directory

Shells: bash, zsh, fish, elvish, powershell. After --install, flk prints what to add to your rc file, if anything.

flk env

flk env add DATABASE_URL "postgresql://localhost:5432/mydb"
flk env remove DATABASE_URL
flk env list
flk env --profile backend list

--profile goes before the subcommand. add fails if the variable already exists; remove it first to change it. Names must start with a letter or _ and contain only letters, digits and _.

See Environment Variables.

flk export

Builds a container image of a profile, or writes the parsed config as JSON.

flk export --format docker
flk export --format podman
flk export --format json
flk export --format docker --profile backend

Options

  • -f, --format <FORMAT>: docker, podman or json (required)
  • -p, --profile <PROFILE>: profile to export

Formats

Docker

Runs nix build .#docker-<profile> --impure --no-link (no GC root is left behind) and loads the image with docker load. Docker must be running.

Podman

Same, with .#podman-<profile> and podman load.

JSON

Writes inputs and all profiles to flake.json in the project root.

flk global

A machine-wide environment for tools you want everywhere, like ripgrep, fd or bat, similar to Devbox’s global mode. It replaces nix profile install or a system package manager for those tools.

The global environment is an ordinary flk project stored outside any repository. Each flk global subcommand works like the project command of the same name, but on that directory.

Location

The global directory is resolved in this order:

  1. FLK_GLOBAL_DIR
  2. $XDG_CONFIG_HOME/flk/global
  3. ~/.config/flk/global

It is created with the generic template on first use. path, ref and shellenv never create it.

Subcommands

flk global add

flk global add ripgrep
flk global add fd --version 10.2.0        # pin a version
flk global add bat --profile cli-tools    # target a specific global profile

flk global remove

flk global remove ripgrep

flk global list

flk global list
flk global list --profile cli-tools

flk global activate

Enters the global shell, with the same caching as flk activate. The shell opens in your current directory, not the global one.

flk global activate
flk global activate --profile cli-tools

Inside it, refresh and switch work on the global environment (activation exports FLK_ENV_DIR), even if the current directory is a project. So flk global add jq then refresh picks up jq, and switch cli-tools changes global profile.

From a project shell, refresh -g and switch -g <profile> move to the global environment; switch -l <profile> moves back. The new shell replaces the current one.

flk global update

Same as flk update, including the lock backup.

flk global update
flk global update --show

flk global path

Prints the global directory. It never creates it, unlike the other subcommands.

flk global path
# /home/you/.config/flk/global
nix develop "$(flk global path)#generic"

flk global ref

Prints the global flake reference (<dir>#<profile>) and nothing else. The hook uses it for refresh -g and switch -g. Fails if the global environment doesn’t exist yet.

flk global ref
# /home/you/.config/flk/global#generic
flk global ref --profile cli-tools

flk global profile

flk profile for the global environment.

flk global profile add cli-tools
flk global profile list
flk global profile set-default cli-tools
flk global profile remove cli-tools

flk global unfree

flk unfree for the global environment.

flk global unfree add slack                # default global profile
flk global unfree add slack -p cli-tools   # a specific global profile
flk global unfree add slack --all          # every global profile
flk global unfree list
flk global unfree remove slack

flk global shellenv

Prints shell code that appends the global packages to PATH, like Devbox’s shellenv. Eval it in your rc file to have the tools in every shell, project shells included:

# .bashrc / .zshrc
eval "$(flk global shellenv zsh)"    # or bash

# ~/.config/fish/config.fish
flk global shellenv fish | source
  • Only the environment’s packages are exported. The stdenv toolchain that nix develop adds (gcc, binutils, make, patch, tar, …) is filtered out, so it can’t stand in for a missing system cc in every shell.
  • Paths are appended, so system tools and project packages win.
  • Nothing is appended if PATH already has the entries, so nested shells and re-sourced rc files don’t grow it.
  • It reads the profile’s GC root through nix print-dev-env and doesn’t evaluate the flake, so it’s fast and works offline.
  • If the environment isn’t built yet, or the packages can’t be told apart from the toolchain, it prints only a comment. Run flk global activate once to build it.
  • It reflects the environment when it ran. After flk global add or remove, open a new shell.

Notes

  • flk never edits your rc files. Use shellenv, run flk global activate when needed, or add your own alias.
  • A project shell’s FLK_FLAKE_REF is ignored when choosing the global profile.
  • Everything (flake.nix, .flk/, backups, caches) lives in the global directory; nothing is written to the current directory.

flk hook

Prints shell code that defines the refresh and switch functions. Add it to your rc file:

eval "$(flk hook bash)"   # ~/.bashrc
eval "$(flk hook zsh)"    # ~/.zshrc
flk hook fish | source    # ~/.config/fish/config.fish

To keep the rc file working on machines without flk:

if command -v flk >/dev/null; then eval "$(flk hook bash)"; fi

Supported shells: bash, zsh, fish. What the two functions do is described in switch / refresh.

flk import

Imports another tool’s environment file into an flk profile. The only source so far is Devbox’s devbox.json. If there is no flake.nix yet, flk import runs flk init first.

flk import devbox

flk import devbox                      # import ./devbox.json into the default profile
flk import devbox --dry-run            # show the translation, write nothing
flk import devbox --file ../devbox.json
flk import devbox --profile backend    # import into a specific profile

What gets translated

devbox.jsonflk equivalent
packagesthe profile’s packages list
packages with @versionpackages + a pin in .flk/pins.nix
envthe profile’s envVars
shell.scriptsthe profile’s commands (see flk command)
shell.init_hookappended to the profile’s shellHook

packages may be a list or an object:

{ "packages": ["ripgrep", "go@1.22"] }
{ "packages": { "go": { "version": "1.22" } } }

shell.init_hook and each script may be a string or a list of strings. A version of latest is treated as unpinned.

Version pinning

name@version is handled like flk add --version: the pin is resolved against nixpkgs, recorded in .flk/pins.nix, and the profile declares pkgs."name@version". Each pinned package costs several network round-trips, so --dry-run first is a good idea for large manifests.

What does not get translated

These are listed under “Not imported” at the end of the run:

  • include: Devbox plugins have no flk equivalent; translate them by hand.
  • env_from: dotenv sourcing. Add the variables with flk env add.
  • per-package platforms / excluded_platforms: the package is imported for all systems.
  • keys flk doesn’t recognise, for example from a newer Devbox release.

Devbox template variables such as {{ .DevboxDir }} in env values are copied as-is with a warning. They don’t expand, so edit them afterwards.

Conflicts and failures

  • A package that is already declared is replaced, as with flk add.
  • An environment variable or command that already exists is skipped with a warning.
  • An entry that fails (say, a package that isn’t in nixpkgs) doesn’t stop the run. The rest is imported, failures are listed at the end, and the exit code is non-zero.

Options

FlagDescription
-f, --file <PATH>Manifest to read (defaults to ./devbox.json)
-p, --profile <NAME>Target profile (defaults to the project default)
--dry-runPrint the translation and exit without writing

Example

$ cat devbox.json
{
  "packages": ["ripgrep", "go@1.22"],
  "env": { "GOFLAGS": "-mod=vendor" },
  "shell": {
    "init_hook": ["echo 'entering the shell'"],
    "scripts": { "build": ["go build ./..."] }
  }
}

$ flk import devbox
$ flk show
$ flk activate

See also flk add and flk command.

flk init

flk init                   # detect the project type
flk init --template rust   # rust, python, node, go, generic
flk init --force           # overwrite an existing flake.nix
flk init --legacy          # old in-repo layout

Writes flake.nix, .flk/config.nix, .flk/pins.nix, .flk/profiles/<type>.nix and .flk/.gitignore. flk owns .flk/.gitignore and overwrites it; flk migrate writes it for existing projects. Detection rules are in Project Templates.

Inspecting

flk list prints the packages of one profile. flk show prints the whole flake. Neither changes any files.

flk list
flk list --profile backend
flk show

flk list prints one package per line:

• ripgrep
• cargo-watch

flk show prints the flake inputs and every profile with its packages, environment variables and commands:

Flake configuration

Inputs:
  • flk

Profiles: (1)
rust
  Packages: (2)
    • ripgrep (latest)
    • cargo-watch (latest)
  Environment Variables: (1)
    • RUST_LOG = debug
  Commands:
    • dev

flk remove

flk remove ripgrep
flk remove ripgrep --profile backend

Removes every entry for the package from .flk/profiles/<profile>.nix. If it was pinned and no other package uses the pin, the pin is removed from .flk/pins.nix too. Fails if the package isn’t declared.

Searching

Both commands use nix-versions. flk search finds packages by name; flk deep-search lists the versions of one package.

flk search ripgrep
flk search python --limit 20   # default limit is 10
flk deep-search ripgrep

flk search matches names across nixpkgs and prints up to --limit results. Once you know the package, flk deep-search prints every version nix-versions knows about, which is what you pass to flk add --version.

flk switch / refresh

Shell functions defined by the shell hook, not flk subcommands. They only work inside an activated environment.

refresh

Reloads the current environment after a config change.

flk add ripgrep
refresh

Behavior

  • With direnv: runs direnv reload
  • Without direnv: reuses a saved nix develop profile when it is current
  • Without direnv: refreshes that saved profile when the environment definition changes
  • Reads the active profile from FLK_FLAKE_REF (fallback: FLK_PROFILE)
  • Resets PATH to FLK_ORIG_PATH (the PATH before activation) first, so removed packages are gone. Manual PATH changes made in the shell are lost too.

switch <profile>

Moves to another profile.

switch backend
switch frontend

Behavior

  • Validates the profile name (alphanumeric, -, _ only)
  • Sets FLK_FLAKE_REF and FLK_PROFILE to the new profile reference
  • Reloads via direnv or nix develop as appropriate, reusing the saved profile cache when possible

Global environments

In a shell started by flk global activate, FLK_ENV_DIR points at the global directory and both functions work on it, whatever the current directory. In project shells (FLK_ENV_DIR unset) they work on the current directory. direnv is not used for global shells.

To move between environments explicitly (the new shell replaces the current one with exec; shells never stack):

refresh -g            # jump to (or reload) the global env, default profile
switch -g cli-tools   # jump to a specific global profile
switch -l backend     # back to the cwd project's 'backend' profile

-g/--global resolves the target via flk global ref / flk global path; -l/--local returns to the current directory’s project.

direnv

With direnv installed and an .envrc present, both functions run direnv reload. Otherwise they exec nix develop, replacing the current shell.

flk unfree

Nix refuses to evaluate packages with an unfree license by default, so adding something like vscode, slack, or terraform to a profile fails with “has an unfree license, refusing to evaluate”.

flk unfree keeps an allow-list of package names and turns it into nixpkgs.config.allowUnfreePredicate. Only the named packages are allowed; any other unfree package is still refused.

Scope

By default the list lives in the profile that needs it:

# .flk/profiles/rust.nix
{pkgs, ...}: {
  allowUnfree = ["terraform"];

  packages = [
    pkgs.terraform
  ];
}

Without -p it targets the current or default profile:

flk unfree add terraform            # -> default profile
flk unfree add terraform -p rust    # -> .flk/profiles/rust.nix

--all writes a list that applies to every profile, in .flk/config.nix:

flk unfree add vscode --all
# .flk/config.nix
{
  defaultProfile = "rust";
  maxCombinations = 3;
  allowUnfree = ["vscode"];
}

A profile shell allows the environment-wide list plus its own. A combination shell (rust-node) allows the union of its members’ lists.

Subcommands

flk unfree add

flk unfree add vscode
flk unfree add terraform --profile rust
flk unfree add slack --all

Options

  • -p, --profile <NAME>: target profile (default: current or default profile)
  • --all: the environment-wide list; can’t be combined with --profile

The list is kept sorted, and adding a name twice does nothing. It only allows the package; install it with flk add. Fails if the profile doesn’t exist.

flk unfree remove

flk unfree remove vscode
flk unfree remove slack --all

Fails if the name isn’t in the target list. It removes from that list only, so a name in both the environment-wide and a profile list has to be removed from each. The package itself stays installed; use flk remove for that.

flk unfree list

flk unfree list             # environment-wide + default profile
flk unfree list -p rust     # environment-wide + the rust profile
flk unfree list --all       # environment-wide only

Both lists are shown by default because the shell uses both.

Package names

Entries are package names as returned by lib.getName, not attribute paths or versioned store names:

Write thisNot this
vscodepkgs.vscode
google-chromegoogle-chrome-131.0.6778.85

Nix’s refusal message contains the name: in “Refusing to evaluate package ‘slack-4.49.89’” it is slack.

Global environment

flk global unfree add slack
flk global unfree add slack -p cli-tools
flk global unfree list

Applying the change

An open shell keeps the old list until you reload it:

refresh      # project
refresh -g   # global environment

Why a list instead of allowUnfree = true

allowUnfree = true allows every current and future dependency without anyone noticing. A list keeps each exception visible in the file and in review.

A hand-written allowUnfree = true; still works, but flk won’t edit it: flk unfree add asks you to switch to a list first. A true in either place wins for that profile.

Known limitation: pinned packages on the legacy layout

On the slim layout (the flk init default), the allow-list also covers version-pinned packages from .flk/pins.nix.

The legacy layout resolves pins through .flk/overlays.nix, which doesn’t get the allow-list, so unfree pinned packages still fail there. Unpinned packages work with both lists. flk migrate moves a project to the slim layout.

flk direnv

flk direnv init     # create .envrc with the flk directive
flk direnv attach   # append it to an existing .envrc
flk direnv detach   # remove it again

Run direnv allow afterwards. init refuses to overwrite an existing .envrc; use attach for that.

flk profile

A profile is one .flk/profiles/<name>.nix file with its own packages, commands and environment variables.

flk profile add backend --template rust
flk profile list
flk profile set-default backend
flk profile remove backend

add

flk profile add <NAME> [-t <TEMPLATE>] [-f]

Creates .flk/profiles/<NAME>.nix from a template (base, rust, python, node, go, generic; default base). Names may contain letters, digits, - and _. Fails if the profile exists, unless --force is given.

remove

Deletes the profile file and its cached environment (.flk/.nix-profile-<NAME>*). The default profile can’t be removed; change the default first.

list

Lists the .nix files in .flk/profiles/, sorted, without default.nix.

set-default

Sets defaultProfile in .flk/config.nix (defaultShell in .flk/default.nix on the legacy layout). The profile must exist.

Which profile a command uses

Commands that take -p, --profile pick the profile in this order:

  1. --profile
  2. FLK_FLAKE_REF, which flk activate, refresh and switch set inside the shell
  3. defaultProfile in .flk/config.nix
  4. defaultShell in .flk/default.nix (legacy layout)
  5. the first file in .flk/profiles/

Example

flk init --template generic
flk profile add backend --template rust
flk profile add frontend --template node
flk add cargo-watch --profile backend
flk add nodejs_20 --profile frontend
flk profile set-default backend
flk add ripgrep      # goes to backend

See also flk activate, switch.

flk prune

flk prune              # current project
flk prune --global     # global environment
flk prune --dry-run    # list what would be removed

Every flk activate, refresh or switch that rebuilds an environment keeps only the newest generation of that profile’s .flk/.nix-profile-<profile> link. flk prune cleans up what older flk versions left behind:

  • old .nix-profile-<profile>-<N>-link generations,
  • links and stamps of profiles that no longer exist,
  • .flk/result from older flk export runs.

flk does not run garbage collection itself. Run nix-collect-garbage (or nix store gc) afterwards to free the store paths.

Architecture

Overview

flk is a Rust CLI that reads and edits flake.nix and the files in .flk/.

Crate structure

  • Binary crate (src/main.rs): CLI entrypoint using clap. Parses arguments and dispatches to command handlers in src/commands/.

  • Library crate (src/lib.rs):

    • flk::flake: generation, parsing and data types
    • flk::devbox: devbox.json import
    • flk::utils: backups, spinner and output helpers
  • src/nix/: runs nix subprocesses.

Parser design

Parsers in src/flake/parsers/ use the nom library to read and modify specific sections of Nix files:

They parse only the sections flk writes (packages, env vars, commands, pins), not whole Nix files. Each parser returns the entries plus their byte positions and indentation, so an edit replaces one span and leaves comments and formatting elsewhere alone.

Template system

Templates in templates/ are embedded at compile time via include_str!:

src/flake/generator.rs picks one by project type. See Project Templates for the list.

Data layout

project/
├── flake.nix          # calls flk.lib.mkProject
├── flake.lock
└── .flk/
    ├── config.nix     # defaultProfile, maxCombinations, allowUnfree
    ├── pins.nix       # version pins
    ├── profiles/
    │   ├── rust.nix
    │   └── ...
    └── backups/       # flake.lock backups

Projects created with flk init --legacy also have .flk/default.nix, .flk/overlays.nix and .flk/profiles/default.nix. flk migrate converts them. On a slim project created before it declared nixpkgs, flk migrate adds that input and makes flk follow it. flk migrate --global does the same for the global environment.

Command flow

src/main.rs parses arguments and calls a handler in src/commands/. Handlers read and edit .flk/ files through the parsers, call nix through src/nix/, and print through src/utils/visual.rs.

Key interfaces

  • FlakeConfig: inputs and profiles
  • Profile: packages, env vars and commands of one profile
  • Package: name and optional pinned version
  • SourcesSection, OverlaysSection: the two halves of pins.nix

API Documentation

The flk crate is also a library. Build its docs with:

cargo doc --no-deps --open

Modules

  • flk::flake::generator: templates
    • generate_flake(project_type): profile content for a project type
    • generate_slim_flake(), generate_config(default_profile), generate_pins(): files for a new project
  • flk::flake::parsers: section parsers
    • packages: packages = [ ... ];
    • env: envVars = { ... };
    • commands: commands = [ ... ];
    • shellhook: appending to shellHook
    • overlays: pins.nix
    • config: .flk/config.nix
    • flake: inputs and the combined FlakeConfig
    • utils: profile resolution and shared combinators
  • flk::flake::interfaces: FlakeConfig, Profile, Package, EnvVar and the pin types
  • flk::flake::nix_render: nix_string, nix_attr_key and other escaping helpers
  • flk::devbox: parsing devbox.json
  • flk::utils::backup: flake.lock backups
  • flk::utils::visual: spinner and list output

Example

#![allow(unused)]
fn main() {
use flk::flake::parsers::packages::parse_packages_section;

let path = ".flk/profiles/rust.nix";
let content = std::fs::read_to_string(path)?;
let section = parse_packages_section(&content)?;
let updated = section.add_package(&content, "ripgrep", None);
std::fs::write(path, updated)?;
}

Conventions

  • Public items get a /// comment when the name and signature don’t say enough.
  • Prefix internal or unstable functions with _.
  • cargo doc --no-deps should build without new warnings.

Troubleshooting

Nix not found

command not found: nix or flk commands fail with Nix errors.

  1. Install Nix (see Installation) and check nix --version.
  2. Enable flakes in ~/.config/nix/nix.conf:
    experimental-features = nix-command flakes
    
  3. Open a new shell.

Search or version lookup errors

flk search or flk add --version fails with network or evaluation errors.

Both run nix run github:vic/nix-versions, which needs network access. Try it directly to see the real error:

nix run github:vic/nix-versions -- -p ripgrep

Behind a proxy, check Nix’s proxy settings.

Lock file missing or corrupted

error: getting status of flake.lock: No such file or directory

nix flake lock          # regenerate
flk lock restore latest # or restore a backup

Shell hook not working

switch and refresh don’t exist after activating.

  1. Check the hook is in your rc file (flk hook).
  2. Open a new shell and run flk activate.
  3. type switch should print a function.

direnv not loading the environment

The environment doesn’t load when you enter the directory.

  1. Run flk direnv init, then direnv allow.
  2. Check direnv’s own hook is in your rc file.
  3. Check .envrc contains a use flake line.

Package not found

flk add <package> fails with “package not found”.

The nixpkgs name may differ from the binary name (ripgrep, not rg). Look it up with flk search <term>; flk deep-search <package> lists versions.

Unfree license refusal

Entering the shell fails with “has an unfree license (‘unfree’), refusing to evaluate”.

Allow the package by the name in the error (the quoted slack-4.49.89 means flk unfree add slack), then run refresh. See flk unfree.

Profile errors

“Profile not found” or profile-related errors.

Run flk profile list to see what exists. Profile names may contain only letters, digits, - and _.

Activation fails

flk activate or nix develop fails with evaluation errors.

  1. Look for syntax errors in .flk/profiles/*.nix.
  2. Run nix flake check.
  3. If an input broke, flk lock restore latest; if it’s just old, flk update.

Container export issues

flk export --format docker fails.

Docker or Podman must be installed and running, and you need permission to use it. docker info or podman info should succeed.

FAQ

General

What is flk?

A CLI for Nix flake dev environments. It manages packages, environment variables and custom commands so you don’t edit Nix files by hand.

Does flk work without Nix?

No, it needs Nix with flakes enabled. On machines without Nix, use an image built with flk export --format docker.

What Nix version do I need?

2.4 or later, with nix-command and flakes enabled.

Environment management

How do I reload or change profile without leaving the shell?

With the shell hook installed, refresh reloads the environment after changes and switch <profile> moves to another profile. Both work only inside an activated environment.

How do I pin a package version?

flk add ripgrep --version 14.1.0

The pin goes into .flk/pins.nix, together with the nixpkgs commit that has that version.

Can I have multiple profiles in one project?

Yes. Profiles live in .flk/profiles/, one file each. The default is defaultProfile in .flk/config.nix (defaultShell in .flk/default.nix on the legacy layout). Change it with flk profile set-default <name>.

How do I see what’s in the environment?

flk list           # packages
flk command list   # custom commands
flk env list       # environment variables
flk show           # everything

Updates and lock files

Can I preview updates?

flk update --show prints the diff and then restores the original flake.lock.

How do I restore a previous lock file?

Backups are in .flk/backups/:

flk lock restore <backup-name>   # or: flk lock restore latest

What does flk update do?

It backs up flake.lock, then runs nix flake update.

Integration

Can I use flk with direnv?

Run flk direnv init, then direnv allow. The environment loads when you enter the directory.

Does flk work with VS Code or other editors?

flk doesn’t depend on an editor. In VS Code, the direnv extension picks up the environment once flk direnv init is set up.

Can I export the environment to a container?

flk export --format docker
flk export --format podman
flk export --format json     # writes flake.json

Troubleshooting

Why can’t flk find my package?

The nixpkgs name may differ from the common one. Find it with flk search <term>, or list versions with flk deep-search <package>.

Why isn’t my shell hook working?

Check the hook is in your rc file and open a new shell. switch and refresh only exist inside an activated flk environment.

Contributing

Contributing

Bug reports and merge requests are welcome. For anything larger than a small fix, open an issue first so we can agree on the approach.

Issues: https://gitlab.com/pixel-racks/flk/-/issues

Report security problems in a confidential issue, not a public one.

Setup

git clone https://gitlab.com/pixel-racks/flk.git && cd flk
nix develop --impure .#rust   # or use Rust 1.83+

Before opening a merge request

cargo fmt --all
cargo clippy -- -D warnings
cargo test

Commit messages

Use Conventional Commits: feat:, fix:, docs:, chore:, ci:, test:, refactor:. release-plz and git-cliff build the changelog and version bumps from them.

Code of Conduct

Contributor Covenant Code of Conduct

Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

Our Standards

Examples of behavior that contributes to creating a positive environment include:

  • Using welcoming and inclusive language
  • Being respectful of differing viewpoints and experiences
  • Gracefully accepting constructive criticism
  • Focusing on what is best for the community
  • Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

  • The use of sexualized language or imagery and unwelcome sexual attention or advances
  • Trolling, insulting/derogatory comments, and personal or political attacks
  • Public or private harassment
  • Publishing others’ private information, such as a physical or electronic address, without explicit permission
  • Other conduct which could reasonably be considered inappropriate in a professional setting

Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at development@pixlracks.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project’s leadership.

Attribution

This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

Development Setup

Requirements

  • Nix with flakes enabled (Lix or the Determinate installer)
  • Rust 1.83+
  • Git

Dev shell

git clone https://gitlab.com/pixel-racks/flk.git
cd flk
nix develop --impure .#rust

--impure is needed because the rust profile fetches rust-overlay with builtins.getFlake. The shell has the Rust toolchain, clippy, rustfmt and the cargo helpers.

Build

cargo build              # debug
cargo build --release    # target/release/flk

Tests

cargo test
cargo test test_add_package    # one test
cargo test -- --nocapture      # show output

Lint and format

cargo fmt --all -- --check
cargo fmt --all
cargo clippy --all-targets -- -D warnings

Running the CLI

cargo run -- init --template rust
cargo run -- add ripgrep
cargo run -- list
cargo run --release -- search git

To use your build as flk:

cargo install --path .
# or
alias flk="cargo run --release --"

Docs

cargo doc --no-deps --open     # API docs

cd flk-book
mdbook serve                   # http://localhost:3000, reloads on change
mdbook build                   # output in flk-book/book/

nix build .#docs               # both, output in result/

Project layout

flk/
├── src/
│   ├── main.rs          # CLI entrypoint
│   ├── lib.rs           # library exports
│   ├── commands/        # one module per subcommand
│   ├── flake/           # generation and parsing
│   │   ├── generator.rs # templates
│   │   ├── parsers/     # Nix section parsers
│   │   └── interfaces/  # data types
│   ├── nix/             # nix subprocess wrappers
│   └── utils/           # backups, spinner, output helpers
├── templates/           # Nix templates, embedded at compile time
├── tests/               # integration tests
├── flk-book/            # this book
└── flake.nix

Before a merge request

cargo fmt --all -- --check
cargo clippy --all-targets -- -D warnings
cargo test
cargo doc --no-deps

For a crash, run with RUST_BACKTRACE=1.