Nix包管理器

From NixOS Wiki
This page is a translated version of the page Nix package manager and the translation is 67% complete.

Nix是一个包管理器和构建系统, 解析用 Nix表达式语言 (惰性求值的纯函数式语言) 指定的可再现的构建指令. Nix表达式是纯函数[1], 接受依赖作为参数,并为包产生一个指定了可再现的构建环境的 derivation . Nix把构建的结果存储在由完整依赖树的哈希值指定的唯一地址中, 创建了一个不可变的包存储 (即nix存储), 这使得原子升级, 回滚, 以及不同版本的包的同时安装成为可能, 从根本上消除了依赖地狱.

用法

安装

NixOS: 当你在安装NixOS时, Nix就已经安装好了.

如果你想在另一个Linux发行版或一台Mac电脑上使用Nix, 你可以进行独立安装: Nix手册的安装部分讲述了从二进制文件或源代码的独立的Nix安装过程

Nix命令

Nix命令被记录在Nix参考手册: 主要命令, 工具命令和实验性命令. 在2.0版本(于2018年2月发布)之前, 命令有所不同.

配置

在NixOS上, Nix通过nix 选项进行配置.

独立的Nix的配置需要通过nix.conf (通常位于 /etc/nix/), 它定义了一系列和求值,构建,垃圾回收,沙盒,以及用户权限的设置. 这些可用选项的细节可在Nix参考手册中找到.

单用户可使用 Home Manager 进一步配置对声明式环境的管理. 对于Linux上的系统级配置, 你可以使用 System Manager. 对于macOS上的系统级配置, nix-darwin 是更佳的解决方案.

内部组成

Nix store(Nix存储库)

由Nix构建的包被放在只读的Nix存储库, 通常位于/nix/store. 每个包会被赋予一个由加密hash值指定的独一无二的地址, 该地址位于包的名称和版本之后, 例如/nix/store/nawl092prjblbhvv16kxxbk6j9gkgcqm-git-2.14.1. 这些前缀的哈希处理使用到了对构建过程的所有输入, 包括源文件, 完整依赖关系树, 编译器标志, 等等. 这让Nix可以同时安装同一个包的不同版本, 甚至同一版本的不同构建, 比如由不同的编译器构建的变体. 当添加, 移除, 或者更新一个包时, 什么都没有从Nix存储库中被移除; 作为替代,指向这些包的符号链接在profile中被添加, 移除或者修改.

Profiles(系统画像)

为了建构一个连贯的用户或系统环境, Nix将Nix存储库中的条目符号链接到profile. 这些是Nix允许回滚的"前端": 因为存储库是不可变的, 而且以前的profile版本被保留了下来, 回到更早的状态只需要简单地让符号链接指向一个先前的profile. 更精确地说, Nix将二进制文件符号链接到Nix存储库中描述用户环境的条目中. 这些用户环境随之被符号链接到/nix/var/nix/profiles中带有标签的profile, 而这些profile又被符号链接到用户的~/.nix-profile.

沙盒化

当沙盒构建被启用时, Nix会为每一个构建进程设置一个孤立的环境.It is used to remove further hidden dependencies set by the build environment to improve reproducibility. This includes access to the network during the build outside of fetch* functions and files outside the Nix store. Depending on the operating system access to other resources are blocked as well (ex. inter process communication is isolated on Linux); see nix.conf section in the Nix manual for details.

Sandboxing is enabled by default on Linux, and disabled by default on macOS. In pull requests for Nixpkgs people are asked to test builds with sandboxing enabled (see Tested using sandboxing in the pull request template) because in official Hydra builds sandboxing is also used.

To configure Nix for sandboxing, set sandbox = true in /etc/nix/nix.conf; to configure NixOS for sandboxing set nix.useSandbox = true; in configuration.nix. The nix.useSandbox option is true by default since NixOS 17.09.

可选的解释器

There is an ongoing effort to reimplement Nix, from the ground up, in Rust.

There is also a community-led fork of Nix 2.18 named Lix, focused on correctness, usability, and growth. While it has also ported some components of Nix to Rust, it is not a ground-up rewrite like Tvix.

Earlier attempts can be found on riir-nix

Notes

  1. 计算过程中,值不可改变. 当函数的输入不变时,函数总是输出相同的结果.