找出我在 nix 中使用的系统类型

Kal*_*ule 8 nix

我想以在 NixOs (linux) 和 MacOs (darwin) 上都能工作的方式编写我的 nixos-configuration 和 home-manager-configuration 文件。

虽然有些东西在两个系统上的配置方式相同(例如 git),但其他东西仅在其中一个系统上有意义(例如 wayland-windowmanagers 仅在 Linux 上)。

Nix 语言具有if-else-语句,所以现在我需要的是一种方法来找出我所在的系统类型。

我所追求的是这样的:

wayland.sway.enable = if (os == "MacOs") then false else true;
Run Code Online (Sandbox Code Playgroud)

有没有办法找出我在 nix 上的系统?

Kal*_*ule 9

我(独立地)找到了与 @robert-hensing 的答案类似的答案。所以为了完整性起见,这里是:

以下配置将在 MacO 上安装“hello”,在其他系统上安装“tree”。

{ config, pkgs, ... }:

let
  my_packages = if pkgs.system == "x86_64-darwin"
                then [ pkgs.hello ]
                else [ pkgs.tree ];
in
{
  environment.systemPackages = my_packages;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过运行找到您的 pkgs.system 字符串nix repl '<nixpkgs>',然后输入system


Rob*_*ing 2

在 NixOS 模块中,您可以执行以下操作:

{ config, lib, pkgs, ... }:
{
  wayland.sway.enable = if pkgs.stdenv.isLinux then true else false;

  # or if you want to be more specific
  wayland.sway.enable = if pkgs.system == "x86_64-linux" then true else false;

  # or if you want to use the default otherwise
  # this works for any option type
  wayland.sway.enable = lib.mkIf pkgs.stdenv.isLinux true;
}
Run Code Online (Sandbox Code Playgroud)

但是,我更喜欢将配置分解为模块,然后仅imports分解我需要的配置。

darwin-configuration.nix

{ ... }:
{
  imports = [ ./common-configuration.nix ];

  launchd.something.something = "...";
}
Run Code Online (Sandbox Code Playgroud)

对于 NixOS:

configuration.nix

{ ... }:
{
  imports = [ ./common-configuration.nix ];

  wayland.sway.enable = true;
}
Run Code Online (Sandbox Code Playgroud)