1# Generators {#sec-generators}
2Generators are functions that create file formats from nix data structures, e. g. for configuration files. There are generators available for: `INI`, `JSON` and `YAML`
3
4All 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.
5
6Generators 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:
7
8```nix
9let
10 inherit (lib) generators isString;
11
12 customToINI = generators.toINI {
13 # specifies how to format a key/value pair
14 mkKeyValue = generators.mkKeyValueDefault {
15 # specifies the generated string for a subset of nix values
16 mkValueString =
17 v:
18 if v == true then
19 ''"yes"''
20 else if v == false then
21 ''"no"''
22 else if isString v then
23 ''"${v}"''
24 # and delegates all other values to the default generator
25 else
26 generators.mkValueStringDefault { } v;
27 } ":";
28 };
29
30 # the INI file can now be given as plain old nix values
31in
32customToINI {
33 main = {
34 pushinfo = true;
35 autopush = false;
36 host = "localhost";
37 port = 42;
38 };
39 mergetool = {
40 merge = "diff3";
41 };
42}
43```
44
45This will produce the following INI file as nix string:
46
47```INI
48[main]
49autopush:"no"
50host:"localhost"
51port:42
52pushinfo:"yes"
53str\:ange:"very::strange"
54
55[mergetool]
56merge:"diff3"
57```
58
59::: {.note}
60Nix store paths can be converted to strings by enclosing a derivation attribute like so: `"${drv}"`.
61:::
62
63Detailed documentation for each generator can be found [here](#sec-functions-library-generators)