1<section xmlns="http://docbook.org/ns/docbook"
2 xmlns:xlink="http://www.w3.org/1999/xlink"
3 xmlns:xi="http://www.w3.org/2001/XInclude"
4 xml:id="sec-generators">
5 <title>Generators</title>
6
7 <para>
8 Generators are functions that create file formats from nix data structures,
9 e. g. for configuration files. There are generators available for:
10 <literal>INI</literal>, <literal>JSON</literal> and <literal>YAML</literal>
11 </para>
12
13 <para>
14 All generators follow a similar call interface: <code>generatorName
15 configFunctions data</code>, where <literal>configFunctions</literal> is an
16 attrset of user-defined functions that format nested parts of the content.
17 They each have common defaults, so often they do not need to be set manually.
18 An example is <code>mkSectionName ? (name: libStr.escape [ "[" "]" ]
19 name)</code> from the <literal>INI</literal> generator. It receives the name
20 of a section and sanitizes it. The default <literal>mkSectionName</literal>
21 escapes <literal>[</literal> and <literal>]</literal> with a backslash.
22 </para>
23
24 <para>
25 Generators can be fine-tuned to produce exactly the file format required by
26 your application/service. One example is an INI-file format which uses
27 <literal>: </literal> as separator, the strings
28 <literal>"yes"</literal>/<literal>"no"</literal> as boolean values and
29 requires all string values to be quoted:
30 </para>
31
32<programlisting>
33with lib;
34let
35 customToINI = generators.toINI {
36 # specifies how to format a key/value pair
37 mkKeyValue = generators.mkKeyValueDefault {
38 # specifies the generated string for a subset of nix values
39 mkValueString = v:
40 if v == true then ''"yes"''
41 else if v == false then ''"no"''
42 else if isString v then ''"${v}"''
43 # and delegats all other values to the default generator
44 else generators.mkValueStringDefault {} v;
45 } ":";
46 };
47
48# the INI file can now be given as plain old nix values
49in customToINI {
50 main = {
51 pushinfo = true;
52 autopush = false;
53 host = "localhost";
54 port = 42;
55 };
56 mergetool = {
57 merge = "diff3";
58 };
59}
60</programlisting>
61
62 <para>
63 This will produce the following INI file as nix string:
64 </para>
65
66<programlisting>
67[main]
68autopush:"no"
69host:"localhost"
70port:42
71pushinfo:"yes"
72str\:ange:"very::strange"
73
74[mergetool]
75merge:"diff3"
76</programlisting>
77
78 <note>
79 <para>
80 Nix store paths can be converted to strings by enclosing a derivation
81 attribute like so: <code>"${drv}"</code>.
82 </para>
83 </note>
84
85 <para>
86 Detailed documentation for each generator can be found in
87 <literal>lib/generators.nix</literal>.
88 </para>
89</section>