lib/generators: add toKeyValue & mkKeyValueLine (#20903)

generators for the common use case of simple config files which hold keys and
values. Used in the implementation for toINI.

authored by Profpatsch and committed by GitHub ea412cd5 2f861e6b

+41 -4
+25 -4
lib/generators.nix
··· 17 17 18 18 rec { 19 19 20 - /* Generates an INI-style config file from an 20 + /* Generate a line of key k and value v, separated by 21 + * character sep. If sep appears in k, it is escaped. 22 + * Helper for synaxes with different separators. 23 + * 24 + * mkKeyValueLine ":" "f:oo" "bar" 25 + * > "f\:oo:bar" 26 + */ 27 + mkKeyValueLine = sep: k: v: 28 + "${libStr.escape [sep] k}${sep}${toString v}"; 29 + 30 + 31 + /* Generate a key-value-style config file from an attrset. 32 + * 33 + * mkKeyValue is the same as in toINI. 34 + */ 35 + toKeyValue = { 36 + mkKeyValue ? mkKeyValueLine "=" 37 + }: attrs: 38 + let mkLine = k: v: mkKeyValue k v + "\n"; 39 + in libStr.concatStrings (libAttr.mapAttrsToList mkLine attrs); 40 + 41 + 42 + /* Generate an INI-style config file from an 21 43 * attrset of sections to an attrset of key-value pairs. 22 44 * 23 45 * generators.toINI {} { ··· 41 63 # apply transformations (e.g. escapes) to section names 42 64 mkSectionName ? (name: libStr.escape [ "[" "]" ] name), 43 65 # format a setting line from key and value 44 - mkKeyValue ? (k: v: "${libStr.escape ["="] k}=${toString v}") 66 + mkKeyValue ? mkKeyValueLine "=" 45 67 }: attrsOfAttrs: 46 68 let 47 69 # map function to string for each key val 48 70 mapAttrsToStringsSep = sep: mapFn: attrs: 49 71 libStr.concatStringsSep sep 50 72 (libAttr.mapAttrsToList mapFn attrs); 51 - mkLine = k: v: mkKeyValue k v + "\n"; 52 73 mkSection = sectName: sectValues: '' 53 74 [${mkSectionName sectName}] 54 - '' + libStr.concatStrings (libAttr.mapAttrsToList mkLine sectValues); 75 + '' + toKeyValue { inherit mkKeyValue; } sectValues; 55 76 in 56 77 # map input to ini sections 57 78 mapAttrsToStringsSep "\n" mkSection attrsOfAttrs;
+16
lib/tests.nix
··· 135 135 # these tests assume attributes are converted to lists 136 136 # in alphabetical order 137 137 138 + testMkKeyValueLine = { 139 + expr = generators.mkKeyValueLine ":" "f:oo" "bar"; 140 + expected = ''f\:oo:bar''; 141 + }; 142 + 143 + testToKeyValue = { 144 + expr = generators.toKeyValue {} { 145 + key = "value"; 146 + "other=key" = "baz"; 147 + }; 148 + expected = '' 149 + key=value 150 + other\=key=baz 151 + ''; 152 + }; 153 + 138 154 testToINIEmpty = { 139 155 expr = generators.toINI {} {}; 140 156 expected = "";