at 21.11-pre 2.6 kB view raw
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, e. g. for configuration files. There are generators available for: <literal>INI</literal>, <literal>JSON</literal> and <literal>YAML</literal> 9 </para> 10 11 <para> 12 All generators follow a similar call interface: <code>generatorName configFunctions data</code>, where <literal>configFunctions</literal> 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 <code>mkSectionName ? (name: libStr.escape [ "[" "]" ] name)</code> from the <literal>INI</literal> generator. It receives the name of a section and sanitizes it. The default <literal>mkSectionName</literal> escapes <literal>[</literal> and <literal>]</literal> with a backslash. 13 </para> 14 15 <para> 16 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 <literal>: </literal> as separator, the strings <literal>"yes"</literal>/<literal>"no"</literal> as boolean values and requires all string values to be quoted: 17 </para> 18 19<programlisting> 20with lib; 21let 22 customToINI = generators.toINI { 23 # specifies how to format a key/value pair 24 mkKeyValue = generators.mkKeyValueDefault { 25 # specifies the generated string for a subset of nix values 26 mkValueString = v: 27 if v == true then ''"yes"'' 28 else if v == false then ''"no"'' 29 else if isString v then ''"${v}"'' 30 # and delegats all other values to the default generator 31 else generators.mkValueStringDefault {} v; 32 } ":"; 33 }; 34 35# the INI file can now be given as plain old nix values 36in customToINI { 37 main = { 38 pushinfo = true; 39 autopush = false; 40 host = "localhost"; 41 port = 42; 42 }; 43 mergetool = { 44 merge = "diff3"; 45 }; 46} 47</programlisting> 48 49 <para> 50 This will produce the following INI file as nix string: 51 </para> 52 53<programlisting> 54[main] 55autopush:"no" 56host:"localhost" 57port:42 58pushinfo:"yes" 59str\:ange:"very::strange" 60 61[mergetool] 62merge:"diff3" 63</programlisting> 64 65 <note> 66 <para> 67 Nix store paths can be converted to strings by enclosing a derivation attribute like so: <code>"${drv}"</code>. 68 </para> 69 </note> 70 71 <para> 72 Detailed documentation for each generator can be found in <literal>lib/generators.nix</literal>. 73 </para> 74</section>