Jump to content

Flakes

From NixOS Wiki
Revision as of 19:29, 28 August 2025 by Weijia (talk | contribs) (Created page with "== 核心使用模式 ==")
⚟︎
This article or section needs cleanup. Please edit the article, paying special attention to fixing any formatting issues, inconsistencies, grammar, or phrasing. Make sure to consult the Manual of Style for guidance.

Nix FlakesNix 2.4 版本中首次引入的一项实验性功能[1][2],旨在解决 Nix 生态系统许多领域的改进问题:它们为 Nix 项目提供了一个统一结构、允许固定每个依赖项的特定版本并通过锁文件共享这些依赖项,同时总体上使编写可复现的 Nix 表达式变得更加方便。

Flake 是一个直接包含 flake.nix 文件的目录,该文件内容遵循一种特定结构。Flakes 引入了一种类似 URL 的语法[3] 来指定远程资源。为了简化这种 URL 语法,Flakes 使用符号标识符注册表[4],这允许通过类似 github:NixOS/nixpkgs 的语法直接指定资源。

Flakes 还允许锁定引用和版本,然后通过 inputs [5][6] 以可编程方式进行查询和更新。此外,一个实验性的 CLI 实用程序接受 flake 引用作为参数,该引用指向用于构建、运行和部署软件包的表达式。[7]

Flake 文件结构

一个最小化的 flake 文件包含该 flake 的描述(description),一组输入依赖项(inputs)和一个输出(outputs)。您可以随时使用 nix flake init 命令来生成一个非常基础的 flake 文件。这将在当前目录下创建一个名为 flake.nix 的文件,其内容类似于:

❄︎ flake.nix
{
  description = "一个非常基础的 flake";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  };

  outputs = { self, nixpkgs }: {

    packages.x86_64-linux.hello = nixpkgs.legacyPackages.x86_64-linux.hello;

    packages.x86_64-linux.default = self.packages.x86_64-linux.hello;

  };
}

在上述示例中,您可以看到对该 flake 的描述、指定为某 Github 仓库特定分支的输入(此为 nixos/nixpkgs 仓库的 nixos-unstable 分支)以及一个使用该输入的输出。该输出简单地指定了该 flake 包含一个用于 x86_64 架构名为 hello 的包。即使您的 flake 输出不使用其输入(尽管这在实践中极不可能),其输出仍需要是一个 Nix 函数。

Note: Flakes require you to specify its outputs for each architecture separately. For more information, read the related section below.

Nix 配置

为了推导 flake,您可以覆盖 nix.conf 文件中设置的全局 Nix 配置。例如,这可用于设置特定项目的二进制缓存源,同时保持全局配置不变。Flake 文件中可包含一个 nixConfig 属性,并在其中设置相关配置。例如,启用 nix-community 二进制缓存可以通过以下方式实现:

❄︎ flake.nix
{
  ...
  nixConfig = {
    extra-substituters = [
      "https://nix-community.cachix.org"
    ];
    extra-trusted-public-keys = [
      "nix-community.cachix.org-1:...="
    ];
  }
}
Note: 如果您习惯通过 NixOS 配置来设置 Nix 配置,则这些选项位于 nix.settings 下,而不是 nix 下。例如,您无法在 nix.optimization.enable 下指定自动存储优化。

设置

临时启用 Flakes

当使用任意 nix 命令时,添加如下命令行参数:

 --experimental-features 'nix-command flakes'

永久启用 Flakes

NixOS

添加如下内容至 NixOS 配置:

  nix.settings.experimental-features = [ "nix-command" "flakes" ];

Home Manager

添加如下内容至您的 home manager 配置:

  nix.settings.experimental-features = [ "nix-command" "flakes" ];

Nix 独立程序

Note: The Determinate Nix Installer enables flakes by default.

添加如下内容至 ~/.config/nix/nix.conf/etc/nix/nix.conf:

experimental-features = nix-command flakes

用法

⚠︎
Warning: 由于 flake 文件的内容会被复制到全局可读的 Nix Store 目录下,所以请不要在 flake 文件中写入任何未加密的秘密信息。您应该改用 秘密管理方案
Note: 对于 Git 仓库中的 flakes,只有工作区中的文件才会被复制到 Store 中。 因此,如果您使用 git 管理您的 flake,请确保在首次创建之后使用 git add添加所有项目文件。

Nix Flakes 命令

Main article: Nix (command)

nix flake 的子命令在 Nix 手册命令参考页面 中被描述。

此 flake 生成一个单 Flake 输出 packages。其中,x86_64-linux 是系统特定的属性集。其中包含两个软件包的 Derivations(派生/定义)defaulthello。您可以使用 show 命令 给出某 flake 的输出,如下所示:

$ nix flake show
└───packages
    └───x86_64-linux
        ├───default: package 'hello-2.12.2'
        └───hello: package 'hello-2.12.2'

开发环境 Shell

devShell 是定义在 flake 中由 Nix 提供的开发环境。它允许您声明一个可复用的 Shell 环境,其中将包含开发特定项目所需的工具、库和环境变量。这相当于在 flake 中定义一个 nix-shell

{
  description = "带有 devShell 的示例 flake";

  inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";

  outputs = { self, nixpkgs}:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { inherit system; };
    in {
      devShells.x86_64-linux.default = pkgs.mkShell {
        buildInputs = with pkgs; [
          hello
        ];
        shellHook = ''
          echo "欢迎进入 devShell!"
        '';
      };
    };
}

进入开发环境 Shell:

$ nix develop
Note: 使用 nix develop 命令进入开发 shell 无需定义 devShell。 如果未定义 devShell,nix develop 命令会将您带入一个包含 flake 默认构建依赖项(如果有)的环境。

在 flake 仓库中构建特定属性

运行 nix build 将在 legacyPackagespackages 输出属性中查找相应的 derivation,然后基于您的系统架构构建默认输出项。如果您想在 flake 仓库中指定构建属性,可以运行 nix build .#<attr>。在上面的示例中,如果您想构建 packages.x86_64-linux.hello 属性,请运行:

$ nix build .#hello

同样,您可以给 run 命令:nix run .#hellodevelop命令:nix develop .#hello指定属性。

Flake 规范

flake.nix 文件是一个具有特殊限制的 Nix 文件(稍后会详细介绍)。

它有 4 个顶级属性:

  • description:描述此 flake 的字符串。
  • inputs:一个包含此 flake 所有依赖项的属性集。相关规范见下述内容。
  • outputs: 一个接收参数的函数,其参数为所有所需输入的属性集,并输出另一个属性集,其规范如下所述。

输入规范

Nix flake inputs 手册.

Nix flake 引用手册.

inputs 属性定义了 flake 的依赖项。例如,为了让系统能够正确构建,nixpkgs 必须被定义为系统 flake 的依赖项。

Nixpkgs 可使用以下代码进行定义:

inputs.nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";

Nixpkgs can alternatively also point to an url cached by the NixOS organization:

inputs.nixpkgs.url = "https://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz";

In this example the input would point to the `nixpkgs-unstable` channel.


对于任何包含 flake.nix 文件的仓库,其所属网站也必须被定义。Nix 知道 nixpkgs 仓库的位置,因此没有必要声明它在 GitHub 上。

例如,将 Hyprland 添加为输入看起来像这样:

inputs.hyprland.url = "github:hyprwm/Hyprland";

如果您想让 Hyprland 的 nixpkgs 依赖跟随 nixpkgs 输入以避免出现多个版本的 nixpkgs,可以使用以下代码来完成:

inputs.hyprland.inputs.nixpkgs.follows = "nixpkgs";

使用大括号 ({}),我们可以缩短这些内容并将其放在一个表中。代码如下所示:

inputs = {
  nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";
  hyprland = {
    url = "github:hyprwm/Hyprland";
    inputs.nixpkgs.follows = "nixpkgs";
  };
};

默认情况下,包 src 中的 Git 子模块不会被复制到 Nix Store,这可能会导致构建失败。Git 仓库中的 Flakes 可以声明它们需要启用 Git 子模块。从 Nix 版本 2.27 开始,您可以通过以下方式启用子模块:

  inputs.self.submodules = true;

输出规范

This is described in the nix package manager src/nix/flake-check.md.

一旦 Inputs 被解析,它们就会与 self 一起传递给函数 outputsself 是此 flake 在 Store 中的目录。outputs 根据以下规范返回 flake 的输出。

其中:

  • <system> 为类似“x86_64-linux”、“aarch64-linux”、“i686-linux”、“x86_64-darwin”的值
  • <name> 是一个属性名称,如“hello”。
  • <flake> 是一个 flake 名称, 如“nixpkgs”。
  • <store-path>/nix/store.. 的路径。
{ self, ... }@inputs:
{
  # Executed by `nix flake check`
  checks."<system>"."<name>" = derivation;
  # Executed by `nix build .#<name>`
  packages."<system>"."<name>" = derivation;
  # Executed by `nix build .`
  packages."<system>".default = derivation;
  # Executed by `nix run .#<name>`
  apps."<system>"."<name>" = {
    type = "app";
    program = "<store-path>";
  };
  # Executed by `nix run . -- <args?>`
  apps."<system>".default = { type = "app"; program = "..."; };

  # Formatter (alejandra, nixfmt or nixpkgs-fmt)
  formatter."<system>" = derivation;
  # Used for nixpkgs packages, also accessible via `nix build .#<name>`
  legacyPackages."<system>"."<name>" = derivation;
  # Overlay, consumed by other flakes
  overlays."<name>" = final: prev: { };
  # Default overlay
  overlays.default = final: prev: { };
  # Nixos module, consumed by other flakes
  nixosModules."<name>" = { config, ... }: { options = {}; config = {}; };
  # Default module
  nixosModules.default = { config, ... }: { options = {}; config = {}; };
  # Used with `nixos-rebuild switch --flake .#<hostname>`
  # nixosConfigurations."<hostname>".config.system.build.toplevel must be a derivation
  nixosConfigurations."<hostname>" = {};
  # Used by `nix develop .#<name>`
  devShells."<system>"."<name>" = derivation;
  # Used by `nix develop`
  devShells."<system>".default = derivation;
  # Hydra build jobs
  hydraJobs."<attr>"."<system>" = derivation;
  # Used by `nix flake init -t <flake>#<name>`
  templates."<name>" = {
    path = "<store-path>";
    description = "template description goes here?";
  };
  # Used by `nix flake init -t <flake>`
  templates.default = { path = "<store-path>"; description = ""; };
}

您还可以定义其他任意属性,但以上这些是 Nix 已知的输出。

核心使用模式

Making your evaluations pure

Nix flakes are evaluated in a pure evaluation mode, meaning that access to the external environment is restricted to ensure reproducibility. To maintain purity when working with flakes, consider the following:

  • builtins.currentSystem is non-hermetic and impure as it reflects the host system performing the evauluation. This can usually be avoided by passing the system (i.e., x86_64-linux) explicitly to derivations requiring it.
  • builtins.getEnv is also impure. Avoid reading from environment variables and likewise, do not reference files outside of the flake's directory.

Defining a flake for multiple architectures

Flakes force you to specify a program for each supported architecture. An example below shows how to write a flake that targets multiple architectures.

{
  description = "A flake targeting multiple architectures";
</div>

  <div lang="en" dir="ltr" class="mw-content-ltr">
inputs = {
    nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  };
</div>

  <div lang="en" dir="ltr" class="mw-content-ltr">
outputs = { self, nixpkgs }: let
    systems = [ "x86_64-linux" "aarch64-linux" ];
    forAllSystems = f: builtins.listToAttrs (map (system: {
      name = system;
      value = f system;
    }) systems);
  in {
    packages = forAllSystems (system: let
      pkgs = nixpkgs.legacyPackages.${system};
    in {
      hello = pkgs.hello;
      default = pkgs.hello;
    });
  };
}

You can also use third-parties projects like flake-utils or flake-parts that automatically provide code to avoid this boilerplate. To avoid re-defining the program multiple times, refer to Flake Utils#Defining a flake for multiple architectures

Using overlays

To use Overlays with flakes, refer to Overlays#In a Nix flake page.

Enable unfree software

To allow for unfree software in a flake project, you need to explicitly allow it by setting config.allowUnree = true; when importing Nixpkgs.

{
  inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  outputs = { self, nixpkgs, flake-compat }:
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { inherit system; config.allowUnfree = true;};
    in {
      ...
    };
}

NixOS configuration with flakes

It is possible to manage a NixOS system configuration using flakes, gaining the benefits of reproducible, declarative inputs and streamlined updates.

Development tricks

Automatically switch nix shells with direnv

It is possible to automatically activate different Nix shells when navigating between project directories by using Direnv. Additional Nix integration with Direnv can be achieved with nix-direnv.

Pushing Flakes to Cachix

https://docs.cachix.org/pushing#flakes

Flake support in projects without flakes

The flake-compat library provides a compatibility layer that allows projects using traditional default.nix and shell.nix files to operate with flakes. For more details and usage examples, see the Flake Compat page.

Another project that allows consuming flakes from non-flake projects is flake-inputs.

Accessing flakes from Nix expressions

If you want to access a flake from within a regular Nix expression on a system that has flakes enabled, you can use something like (builtins.getFlake "/path/to/directory").packages.x86_64-linux.default, where 'directory' is the directory that contains your flake.nix.

Efficiently build multiple flake outputs

To push all flake outputs automatically, checkout devour-flake.

Build a package added in a PR

nix build github:nixos/nixpkgs?ref=pull/<PR_NUMBER>/head#<PACKAGE>

this allows building a package that has not yet been added to nixpkgs.

note that this will download a full source tarball of nixpkgs. if you already have a local clone, using that may be faster due to delta compression:

git fetch upstream pull/<PR_NUMBER>/head && git checkout FETCH_HEAD && nix build .#PACKAGE

this allows building a package that has not yet been added to nixpkgs.

How to add a file locally in git but not include it in commits

When a git folder exists, flake will only copy files added in git to maximize reproducibility (this way if you forgot to add a local file in your repo, you will directly get an error when you try to compile it). However, for development purpose you may want to create an alternative flake file, for instance containing configuration for your preferred editors as described here… of course without committing this file since it contains only your own preferred tools. You can do so by doing something like that (say for a file called extra/flake.nix):

git add --intent-to-add extra/flake.nix
git update-index --skip-worktree --assume-unchanged extra/flake.nix

Rapid iteration of a direct dependency

One common pain point with using Nix as a development environment is the need to completely rebuild dependencies and re-enter the dev shell every time they are updated. The nix develop --redirect <flake> <directory> command allows you to provide a mutable dependency to your shell as if it were built by Nix.

Consider a situation where your executable, consumexe, depends on a library, libdep. You're trying to work on both at the same time, where changes to libdep are reflected in real time for consumexe. This workflow can be achieved like so:

cd ~/libdep-src-checkout/
nix develop # Or `nix-shell` if applicable.
export prefix="./install" # configure nix to install it here
buildPhase   # build it like nix does
installPhase # install it like nix does

Now that you've built the dependency, consumexe can take it as an input. In another terminal:

cd ~/consumexe-src-checkout/
nix develop --redirect libdep ~/libdep-src-checkout/install
echo $buildInputs | tr " " "\n" | grep libdep
# Output should show ~/libdep-src-checkout/ so you know it worked

If Nix warns you that your redirected flake isn't actually used as an input to the evaluated flake, try using the --inputs-from . flag. If all worked well you should be able to buildPhase && installPhase when the dependency changes and rebuild your consumer with the new version without exiting the development shell.

See also

Official sources

  • RFC 49 (2019) - Original flakes specification

Guides

  • NixOS & Flakes Book(Ryan4yin, 2023) - 🛠️ ❤️ An unofficial NixOS & Flakes book for beginners.

Useful flake modules

  • flake-utils: Library to avoid some boiler-code when writing flakes
  • flake-parts: Library to help write modular and organized flakes

References

  1. Nix Reference Manual, §13.8. Experimental Features, 📖︎ flakes subsection
  2. Nix Reference Manual, §14.27. 📖︎ Release 2.4 (2021-11-01)
  3. Nix Reference Manual, §8.5.17. nix flake, 📖︎ URL-like syntax subsection
  4. Nix Reference Manual, §8.5.62. 📖︎ nix registry
  5. Nix Reference Manual, §7.5.19. 📖︎ nix flake lock
  6. Nix Reference Manual, §7.5.17. 📖︎ nix flake info
  7. Nix Reference Manual, §8.5.1. 📖︎ nix