f2/nix: provide a high-level wrapper for calling builtins

Change-Id: I357bd7630b96e55d000fbff1032efcf8c98dfb7b
This commit is contained in:
rootile
2026-04-19 10:10:37 +00:00
committed by Rutile
parent 62b728e766
commit ae4b3d585d
2 changed files with 26 additions and 1 deletions
+14
View File
@@ -238,6 +238,20 @@ class Nix:
self._settings = orig
return cmd.run()
def eval_builtin(self, name: str, *args: _NixValue) -> CommandResult:
"""
This is a high-level wrapper, to easily evaluate and obtain the result of a builtin.
In the background, it calls `nix eval --json --expr builtins.{name} {args}`
It is recommended to call `.json()` on the return value.
:param name: name of the builtin
:param args: list of arguments to provide to the builtin
:return: result of the evaluation
"""
args = [serialise_nix(arg) for arg in args]
return self.eval(f"builtins.{name} {' '.join(args)}")
@property
def store_dir(self) -> Path:
"""
+12 -1
View File
@@ -3,7 +3,7 @@ from pathlib import Path
import pytest
from testlib.fixtures.env import ManagedEnv
from testlib.fixtures.nix import NixSettings, serialise_nix
from testlib.fixtures.nix import NixSettings, Nix, serialise_nix
from textwrap import dedent
@@ -119,6 +119,17 @@ def test_nix_settings_to_env_overlay_no_store_dir(tmp_path: Path):
assert "store = local?root=/some/path\n" in env._env["NIX_CONFIG"]
class TestNixEvalBuiltins:
def test_add(self, nix: Nix):
assert nix.eval_builtin("add", 1, 2).ok().stdout_plain == "3"
def test_attrnames(self, nix: Nix):
assert nix.eval_builtin("attrNames", {"a": "b", "c": 1}).json() == ["a", "c"]
def test_attrvalues(self, nix: Nix):
assert nix.eval_builtin("attrValues", {"a": "b", "c": 1}).json() == ["b", 1]
class TestSerialiseNix:
def test_list(self):
assert serialise_nix(["a", 1, None]) == '["a" 1 null]'