iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
❄️

LazyNix: Reproducible Development Environments for Everyone

に公開

Introduction

Nix is gaining popularity

Last year, I published an article titled "Improving Python Development Environment Reproducibility with Nix and uv." I was grateful to receive so much feedback.

https://zenn.dev/shundeveloper/articles/36307d821d40f7

Nix is wonderful

With Nix, you can solve most of the pain points of development environments. You can achieve reproducible "development environment setup" and "package distribution." How wonderful is that?

It is true that Nix requires computing resources and storage. But in this day and age, that can be solved with money.

The syntax looks difficult

On the other hand, there were opinions that "mise is fine" due to the intimidating nature of the syntax.

In reality, the Nix language, which is the configuration language for the Nix package manager, looks unique (to many engineers).

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = import nixpkgs { inherit system; };
      in {
        devShell = pkgs.mkShell {
          buildInputs = [
            pkgs.python312
            pkgs.uv
          ];
        };
      });
}

For comparison, here is the configuration file for mise, mise.toml.

[env]
NODE_ENV = 'production'

[tools]
terraform = '1.0.0'
erlang = '24.0'

[tasks.build]
run = 'echo "running build tasks"'

Solving it with a self-made tool

While the Nix language is excellently designed, it is a fact that it requires study.

Therefore, I have created a tool that maintains the reproducibility of Nix while being "usable by anyone at first glance" like mise. Introducing LazyNix.

https://github.com/shunsock/LazyNix

Intended audience

This time, I will introduce a case study in Python, assuming it is for participants of the study group "Kenro.py" (Robust Python) that I operate. The tool itself is not limited to Python and can be widely used.

Target

  • Those who want to create an immediately reproducible development environment

Non-target

  • Those who have already memorized the syntax of the Nix language
  • Those who want to extract the maximum power from Nix
  • Those whose purpose or joy is learning the Nix language itself

Overview and Usage of LazyNix

What is LazyNix?

As the name suggests, LazyNix is a tool for using Nix "lazily." You describe Nix development shells in YAML, a syntax that anyone can use.

devShell:
  allowUnfree: false
  package:
    stable:
      - python312
      - uv
    unstable: []

See, isn't it simple?

Coping this template is bothersome

I imagine you might think that. For such people, LazyNix provides an initialization command.

$ lnix init
✓ Initialized LazyNix project
  - Created: ./lazynix.yaml
  - Created: flake.nix

Next steps:
  1. Run 'git add flake.nix ./lazynix.yaml' to stage the files
  2. Edit ./lazynix.yaml to configure your environment
  3. Run 'lnix develop' to generate flake.nix and enter the shell

When you run this command, the following YAML is generated. All you need to do is rewrite 'hello' to 'uv' and add 'python312'.

devShell:
  allowUnfree: false
  package:
    stable:
      - hello
    unstable: []
  shellHook:
    - "echo Welcome to LazyNix DevShell!"

Once you have rewritten it, execute the following command. With just that, a development environment with everything you need is complete.

$ lnix develop
...
Welcome to LazyNix DevShell!

Let's confirm if the command is actually in the Nix store using the which command.

bash-5.3$ which uv; which python
/nix/store/minm0w6bz5db2zklya7blkakah6p7qky-uv-0.9.26/bin/uv
/nix/store/47pv2m9ykvr8fqb14mkniqqbs5rpa1sj-python3-3.12.12/bin/python

I also want to set environment variables, not just packages

I imagine you might think that too. The YAML generated by the init command mentioned earlier has more content.

devShell:
  allowUnfree: false
  package:
    stable:
      - hello
    unstable: []
  shellHook:
    - "echo Welcome to LazyNix DevShell!"

  # Optional: Environment variables configuration
  # Load variables from .env files and/or define them directly in YAML
  # Remove the comment marks (#) to use this feature
  # See documentation: docs/attribute/dotenv/README.md
  # env:
  #   dotenv:
  #     - .env              # Load from .env file
  #     - .env.local        # Load and override with .env.local (gitignore recommended)
  #   envvar:
  #     - name: PYTHONPATH
  #       value: ./src
  #     - name: LOG_LEVEL
  #       value: info

  # Optional: Test commands executed by 'lnix test'
  # Tests run sequentially in the development environment
  # Remove the comment marks (#) and add your test commands
  # test:
  #   - pytest
  #   - cargo test
  #   - npm run test

As shown, adding environment variables and testing for command existence can be done seamlessly.

How to migrate to Nix

Since LazyNix generates a flake.nix, if you delete lazynix.yaml, it becomes a normal Nix project.

$ lnix init
...
$ ls
flake.nix       lazynix.yaml 👈 Delete this to complete the transition to Nix

Thanks to this characteristic, you can proceed with projects like "create a development environment with LazyNix, and migrate to Nix when you want to distribute packages."

Installation is very easy

There is nothing required other than Nix. Since Nix can be installed in a single command line, it can be set up with just two commands.

  1. Install Nix
    Download | Nix & NixOS
# For MacOS
$ sh <(curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install)
# For Linux
$ sh <(curl --proto '=https' --tlsv1.2 -L https://nixos.org/nix/install) --no-daemon
  1. Install LazyNix
$ nix profile install github:shunsock/lazynix

How LazyNix Works

I will explain the internal structure of how LazyNix achieves both "the ease of YAML" and "the strict reproducibility of Nix."

Transpiling from YAML to Nix

At its core, LazyNix is a transpiler that converts settings described in YAML into the Nix language (flake.nix).

It uses Rust's serde-yaml to strictly parse lazynix.yaml and, based on the parsed information, automatically generates a flake.nix that follows Nix best practices. The following code is the part that generates flake.nix:

https://github.com/shunsock/lazynix/blob/main/src/flake-generator/src/generator.rs

Hiding Nix commands

Beyond just creating files, it hides complex options of the nix commands and executes them in the optimal order. For example, the previously mentioned lnix develop updates flake.nix before invoking nix develop.

Similarly, lnix test temporarily launches a shell within the development environment, sequentially executes the commands written in the test section, and verifies that the environment has been constructed as expected.

devShell:
  allowUnfree: false
  package:
    stable:
      - hello
    unstable: []

  test:
    - which hello | grep store

Running the test yields the following result:

$ lnix test
Reading configuration from ....
Validating configuration...
Generating flake.nix...
✓ flake.nix generated successfully
Skipping flake.lock update (use --update to update)

Running tests in nix develop environment...
Welcome to LazyNix DevShell!
Running tests...
=================

Running: which hello | grep store
---
/nix/store/sr8bld33izybqx4l9c9i8kbfz7xp83vk-hello-2.12.2/bin/hello
[PASS] which hello | grep store

=================
Test Results: 1 passed, 0 failed

Differences from Existing Tools

Differentiation from Nix Wrappers like devenv

If you are well-versed in Nix, you might wonder, "Isn't an existing tool like devenv sufficient?"

{ pkgs, config, ... }: {
  env.GREET = "determinism";

  packages = [
    pkgs.ncdu
  ];

  enterShell = ''
    echo hello ${config.env.GREET}
    ncdu --version
  '';
}

However, existing tools are ultimately JSON-like[1] and require understanding unique syntax. Additionally, since settings for each language exist specifically, users have to look up the best practices.

{ pkgs, config, ... }: {
  languages.python = {
    enable = true;
    version = "3.11";
    venv.enable = true;
    venv.requirements = ''
      requests
      torch
    '';
    uv.enable = true;
  };
}

I believe there is a psychological barrier there.

With LazyNix, all settings can be understood instantly from their names. Furthermore, because a YAML file is generated via the lnix init command, it is ready to use immediately.

Thanks to this design, users can use it with confidence without studying LazyNix or Nix at all. I hope to reduce the psychological barrier to Nix, even slightly, through this tool.

Differentiation from Language-Specific Package Managers like uv

Excellent package managers like npm and uv exist as established software for each language. While these features are indeed excellent, the packages available are limited to those registered in each language's registry.

On the other hand, since LazyNix is a wrapper for Nix, it can utilize all Nix packages. Nix is renowned for having the largest number of packages in the world today.

However, there may be times when you want to utilize assets only available in a language registry. With LazyNix, I recommend "using language package managers via LazyNix."

Technologies Supporting LazyNix

Rust

To create reproducible artifacts, Nix builds all necessary dependencies within a sandbox. Consequently, build times are long.

Early in the project, I decided: "Since Nix builds are long, let's make LazyNix startup and YAML parsing fast." Therefore, I adopted Rust. (I thought about using .NET 10 if I didn't mind it being somewhat slow.)

main determines the exit logic, and run handles routing to each function. cmd_.+ are the controllers.

fn main() {
    if let Err(e) = run() {
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();
    let config_dir = &cli.config_dir; // Extract once

    match cli.command {
        Commands::Init { force } => cmd_init(config_dir, force)?,
        Commands::Test { update } => cmd_test(config_dir, update)?,
        Commands::Update => cmd_update()?,
        Commands::Develop { update } => cmd_develop(config_dir, update)?,
        Commands::Run {
            update,
            no_regen,
            command,
        } => {
            let exit_code = cmd_run(config_dir, update, !no_regen, command)?;
            if exit_code != 0 {
                std::process::exit(exit_code);
            }
        }
        Commands::Task { task_name, args } => {
            let exit_code = cmd_task(config_dir, task_name, args)?;
            if exit_code != 0 {
                std::process::exit(exit_code);
            }
        }
        Commands::Lint { verbose, arch } => {
            let config_dir_str = config_dir.to_str().unwrap_or(".");
            let success = commands::lint::execute(config_dir_str, verbose, arch.as_deref())?;
            if !success {
                std::process::exit(1);
            }
        }
    }

    Ok(())
}

The libraries I use are no different from a typical CLI application. If you use Rust, you likely recognize these libraries:

  • clap: CLI parser
  • serde, serde-yaml: YAML parser
  • thiserror: A crate that makes writing error enums easier
  • anyhow: A convenient crate that allows writing Result<T, E> as Result<T>

crane

crane is a library that helps when "building Rust projects using Nix." Its feature is separating "building dependencies" from "building the application itself."

Normally, when building with Nix, recompiling all dependencies can occur even after changing just one character of source code. Using crane allows you to cache dependencies (those listed in Cargo.lock) as a separate layer.

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    crane.url = "github:ipetkov/crane";
    rust-overlay.url = "github:oxalica/rust-overlay";
  };

  outputs = { self, nixpkgs, crane, rust-overlay, ... }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs {
        inherit system;
        overlays = [ (import rust-overlay) ];
      };
      
      craneLib = crane.mkLib pkgs;
      
      # Exclude unnecessary files to improve cache efficiency
      src = craneLib.cleanCargoSource (craneLib.path ./.);

      cargoArtifacts = craneLib.buildDepsOnly {
        inherit src;
      };
    in
    {
      packages.${system}.default = craneLib.buildPackage {
        inherit src cargoArtifacts; # Reuse cache
        strictDeps = true;
      };

      checks.${system}.clippy = craneLib.cargoClippy {
        inherit src cargoArtifacts;
        cargoClippyExtraArgs = "--all-targets -- -D warnings";
      };
    };
}

Conclusion

That was an introduction to LazyNix. To summarize, LazyNix is a development environment construction tool created with the goal of being "affordable, fast, and tasty."

If you find this tool useful, please go ahead and use it, and give it a star!

https://github.com/shunsock/lazynix

References

https://nixos.org/

https://repology.org/repositories/graphs

https://github.com/ipetkov/crane

Supplement

脚注
  1. The official devenv page describes it as a "Simple JSON-like language". ↩︎

Discussion