From 2cb6dc90acfa16a37c055f6786de06a031f12326 Mon Sep 17 00:00:00 2001 From: Minijackson Date: Tue, 20 Dec 2022 10:18:33 +0100 Subject: [PATCH] formats.pythonVars: init --- pkgs/pkgs-lib/formats.nix | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/pkgs/pkgs-lib/formats.nix b/pkgs/pkgs-lib/formats.nix index 13aada3681f7..3a47d3dc849c 100644 --- a/pkgs/pkgs-lib/formats.nix +++ b/pkgs/pkgs-lib/formats.nix @@ -417,4 +417,39 @@ rec { ''; }; + # Outputs a succession of Python variable assignments + # Useful for many Django-based services + pythonVars = {}: { + type = with lib.types; let + valueType = nullOr(oneOf [ + bool + float + int + path + str + (attrsOf valueType) + (listOf valueType) + ]) // { + description = "Python value"; + }; + in attrsOf valueType; + generate = name: value: pkgs.callPackage ({ runCommand, python3, black }: runCommand name { + nativeBuildInputs = [ python3 black ]; + value = builtins.toJSON value; + pythonGen = '' + import json + import os + + with open(os.environ["valuePath"], "r") as f: + for key, value in json.load(f).items(): + print(f"{key} = {repr(value)}") + ''; + passAsFile = [ "value" "pythonGen" ]; + } '' + cat "$valuePath" + python3 "$pythonGenPath" > $out + black $out + '') {}; + }; + }