Skip to content

Instantly share code, notes, and snippets.

@nazarewk
Created October 26, 2023 12:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazarewk/8988facb6118f73d2db3d28b64463cba to your computer and use it in GitHub Desktop.
Save nazarewk/8988facb6118f73d2db3d28b64463cba to your computer and use it in GitHub Desktop.
Standalone Nix module for modelling JSON data

This is an example of a standalone single-file module that outputs a JSON file out of it's configuration.

Standalone in this context means it's not meant to be used by NixOS or Home Manager configurations.

# cat $(nix-build --no-out-link test.nix)
{ pkgs ? import <nixpkgs> { }, lib ? pkgs.lib, ... }:
let
contains = value: list: lib.lists.any (entry: entry == value) list;
jsonify = data: lib.trivial.pipe data [
(lib.filterAttrs (name: value: !(contains value [
"output"
])))
(lib.filterAttrsRecursive
(name: value:
!(contains name [ "_module" ]) &&
!(lib.attrsets.isDerivation value) &&
(contains (builtins.typeOf value) [
"int"
"bool"
"string"
#"path"
"null"
"set"
"list"
#"lambda"
"float"
])
))
];
modules.options = { lib, config, ... }: {
options = {
output.jsonFile = lib.mkOption {
readOnly = true;
internal = true;
default = pkgs.writeText "output.json" (builtins.toJSON (jsonify config));
};
env = lib.mkOption {
type = with lib.types; attrsOf (submodule ({ name, ... }: {
options = {
name = lib.mkOption { type = lib.types.str; default = name; };
};
}));
default = { };
};
user = lib.mkOption {
type = with lib.types; attrsOf (submodule ({ name, ... }: {
options = {
id = lib.mkOption { type = lib.types.str; };
};
}));
default = { };
};
};
};
modules.config = {
config = {
env.env1 = { };
user.test.id = "testid";
};
};
in
(lib.modules.evalModules { modules = [ modules.options modules.config ]; }).config.output.jsonFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment