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. 計算過程中,值不可改變. 當函數的輸入不變時,函數總是輸出相同的結果.