Nix (軟體包管理器)
Nix 是一個軟體包管理器和構建系統,它解析由 Nix 表達式語言 (惰性求值的純函數式語言) 指定的可復現的構建指令。Nix 表達式是純函數[1],它接受依賴作為參數,並生成一個 derivation,用於指定該軟體包的可復現的構建環境。Nix 把構建的結果存儲在由完整依賴樹的哈希值指定的唯一地址中,從而創建了一個不可變的包存儲 (即 nix store),使得原子升級、回滾、以及同時安裝同一軟體包的不同版本成為可能,從根本上消除了依賴地獄。
用法
安裝
在 NixOS 上,Nix 已經自動安裝好了。
如果你想在其他 Linux 發行版或在 macOS 上使用 Nix, 你可以按照 Nix 手冊的安裝章節來安裝 Nix。
Nix 命令
Nix 命令在Nix 參考手冊中有詳細記錄:主要命令,工具命令和實驗性命令。在 2.0 版本(於 2018 年 2 月發布)之前,命令有所不同。
配置
在 NixOS 上, Nix 可以通過 nix
選項進行配置。
獨立的 Nix 通過 nix.conf
進行配置(其通常位於 /etc/nix/
)。可用選項的詳細說明可在 Nix 參考手冊中找到.
你也可以使用 Home Manager 配置 Nix,它為單用戶管理聲明式環境。對於系統範圍的配置,可以在 Linux 上使用 System Manager,在 macOS 上使用 nix-darwin。
內部組成
Nix store
Packages built by Nix are placed in the read-only Nix store, normally found in /nix/store
. Each package is given a unique address specified by a cryptographic hash followed by the package name and version, for example /nix/store/nawl092prjblbhvv16kxxbk6j9gkgcqm-git-2.14.1
. These prefixes hash all the inputs to the build process, including the source files, the full dependency tree, compiler flags, etc. This allows Nix to simultaneously install different versions of the same package, and even different builds of the same version, for example variants built with different compilers. When adding, removing or updating a package, nothing is removed from the store; instead, symlinks to these packages are added, removed or changed in profiles.
Cleaning the Nix store
For information relating to cleaning the Nix store, refer to NixOS Manual: Chapter - Cleaning the Nix Store.
Nix store corruption
For information relating to fixing a corrupted Nix store, refer to NixOS Manual: Chapter - Nix Store Corruption.
Valid Nix store names
- Main article: Valid Nix store path names
Profiles
為了構建一個一致的用戶和系統設定,Nix 連結 Nix 商店入口進入 設定檔 (profile) 中。這些是 Nix 進行回滾的前端:由於商店是不可變的且保留先前版本的設定文件,將系統還原到先前的狀態只是簡單地將符號連結更改為先前的設定。更精確來說,Nix 將二進位檔案符號連結到 Nix 商店中的入口,這些入口代表了使用者環境。這些用戶環境隨後被符號連結到儲存在 /nix/var/nix/profiles
中被標注的設定檔,而它們則進一步符號連結到使用者的 ~/.nix-profile
。
沙盒化
當啟用沙盒構建時,Nix 會為每個構建過程設置一個隔離的環境。這樣可以去除構建環境中額外的隱藏依賴,以提高可復現性。這包括在構建過程中禁止訪問 fetch*
函數之外的網絡,以及禁止訪問 Nix store 之外的文件。根據作業系統的不同,對其他資源的訪問也會被阻止(例如在 Linux 上進程間通信會被隔離);詳細信息請參閱 Nix 手冊中的 nix.conf 章節。
沙盒在 Linux 上預設是開啟的,在 macOS 上則否。
在 Nixpkgs 的提取請求 (pull request) 中,請開啟沙盒模式進行測試(請見提取請求模版中的 Tested using sandboxing
),因為在 官方 Hydra 構建中,沙盒會被使用。
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.
可選的解釋器
目前正在進行一項計畫,從零開始使用 Rust 重新實作 Nix。
有一個社群領導的 Nix 2.18 分支叫做 Lix,專注於正確性、可用性和成長性。同時它還為 Nix 部份組件加入 Rust 埠,但不像從零開始重寫的 Tvix。
早期嘗試可以在 riir-nix 找到
Notes
- ↑ 值在計算過程中不會改變。當函數的輸入不變時,函數總是輸出相同的結果。