如何测试Nix Flake输出中各系统的formatter属性?
如何测试Nix Flake中多系统的formatter输出?
我在创建Nix Flake时制定规则:所有输出需支持至少两个系统,主系统为x86_64-linux,次系统为i686-linux(后者可在x86_64-linux环境中运行)。
示例Flake配置
flake.nix
{ inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11"; outputs = { self, nixpkgs }: let supportedSystems = [ "i686-linux" "x86_64-linux" ]; forEachSupportedSystem = function: nixpkgs.lib.attrsets.genAttrs supportedSystems ( system: function nixpkgs.legacyPackages."${system}" ); in { devShells = forEachSupportedSystem (pkgs: { default = pkgs.mkShell { name = "example-shell"; packages = [ pkgs.hello ]; }; }); formatter = forEachSupportedSystem (pkgs: pkgs.nixfmt-rfc-style); }; }
flake.lock
{ "nodes": { "nixpkgs": { "locked": { "lastModified": 1745487689, "narHash": "sha256-FQoi3R0NjQeBAsEOo49b5tbDPcJSMWc3QhhaIi9eddw=", "owner": "NixOS", "repo": "nixpkgs", "rev": "5630cf13cceac06cefe9fc607e8dfa8fb342dde3", "type": "github" }, "original": { "owner": "NixOS", "ref": "nixos-24.11", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "nixpkgs": "nixpkgs" } } }, "root": "root", "version": 7 }
测试现状
devShells的多系统版本可通过以下命令正常测试:
nix --extra-experimental-features 'nix-command flakes' develop '.#devShells.i686-linux.default' nix --extra-experimental-features 'nix-command flakes' develop '.#devShells.x86_64-linux.default'
但测试formatter时,nix fmt仅能默认测试x86_64-linux版本,尝试用类似devShell的命令指定系统时,nix fmt会将属性路径当作文件名,报错如下:
$ nix --extra-experimental-features 'nix-command flakes' fmt '.#formatter.i686-linux' Passing directories or non-Nix files (such as ".#formatter.i686-linux") is deprecated and will be unsupported soon, please use https://treefmt.com/ instead, e.g. via https://github.com/numtide/treefmt-nix $ nix --extra-experimental-features 'nix-command flakes' fmt '.#formatter.x86_64-linux' Passing directories or non-Nix files (such as ".#formatter.x86_64-linux") is deprecated and will be unsupported soon, please use https://treefmt.com/ instead, e.g. via https://github.com/numtide/treefmt-nix
解决方法
1. 使用nix run直接运行指定系统的formatter
nix fmt的参数仅支持文件/目录路径,无法直接指定flake属性路径。要测试特定系统的formatter,可通过nix run调用对应的包并指定格式化目录:
# 测试i686-linux版本的formatter nix --extra-experimental-features 'nix-command flakes' run '.#formatter.i686-linux' -- . # 测试x86_64-linux版本的formatter nix --extra-experimental-features 'nix-command flakes' run '.#formatter.x86_64-linux' -- .
其中-- .表示格式化当前目录下的文件,和nix fmt默认行为一致。
2. 验证formatter输出的有效性(不执行格式化)
如果只需确认特定系统的formatter能否正常构建,无需实际格式化文件,可使用nix build:
# 构建i686-linux的formatter nix --extra-experimental-features 'nix-command flakes' build '.#formatter.i686-linux' # 构建x86_64-linux的formatter nix --extra-experimental-features 'nix-command flakes' build '.#formatter.x86_64-linux'
构建成功则说明该系统的formatter输出有效,产物会生成在result符号链接中。
3. 明确nix fmt的限制
nix fmt会自动匹配当前系统的formatter.<当前系统>输出,不支持手动指定其他系统的formatter属性。跨系统的formatter测试只能通过nix run或nix build实现。
内容的提问来源于stack exchange,提问作者Ginger Jesus
相关产品推荐
相关产品推荐

