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 已知的輸出。

核心使用模式

使您的推導更純

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