python310Packages.pydeconz: 104 -> 105
[NixPkgs.git] / doc / functions / generators.section.md
blobd54e5027c799c5ea3fc84ef987acb970b1a3e6d0
1 # Generators {#sec-generators}
2 Generators are functions that create file formats from nix data structures, e. g. for configuration files. There are generators available for: `INI`, `JSON` and `YAML`
4 All generators follow a similar call interface: `generatorName configFunctions data`, where `configFunctions` is an attrset of user-defined functions that format nested parts of the content. They each have common defaults, so often they do not need to be set manually. An example is `mkSectionName ? (name: libStr.escape [ "[" "]" ] name)` from the `INI` generator. It receives the name of a section and sanitizes it. The default `mkSectionName` escapes `[` and `]` with a backslash.
6 Generators can be fine-tuned to produce exactly the file format required by your application/service. One example is an INI-file format which uses `: ` as separator, the strings `"yes"`/`"no"` as boolean values and requires all string values to be quoted:
8 ```nix
9 with lib;
10 let
11   customToINI = generators.toINI {
12     # specifies how to format a key/value pair
13     mkKeyValue = generators.mkKeyValueDefault {
14       # specifies the generated string for a subset of nix values
15       mkValueString = v:
16              if v == true then ''"yes"''
17         else if v == false then ''"no"''
18         else if isString v then ''"${v}"''
19         # and delegats all other values to the default generator
20         else generators.mkValueStringDefault {} v;
21     } ":";
22   };
24 # the INI file can now be given as plain old nix values
25 in customToINI {
26   main = {
27     pushinfo = true;
28     autopush = false;
29     host = "localhost";
30     port = 42;
31   };
32   mergetool = {
33     merge = "diff3";
34   };
36 ```
38 This will produce the following INI file as nix string:
40 ```INI
41 [main]
42 autopush:"no"
43 host:"localhost"
44 port:42
45 pushinfo:"yes"
46 str\:ange:"very::strange"
48 [mergetool]
49 merge:"diff3"
50 ```
52 ::: {.note}
53 Nix store paths can be converted to strings by enclosing a derivation attribute like so: `"${drv}"`.
54 :::
56 Detailed documentation for each generator can be found in `lib/generators.nix`.