lib/generators: Add toINI option for duplicate keys

This commit is contained in:
Silvan Mosberger 2020-03-10 02:38:28 +01:00
parent 169fc2eeca
commit 575354babf
No known key found for this signature in database
GPG key ID: E8F1E9EAD284E17D
2 changed files with 24 additions and 6 deletions

View file

@ -76,10 +76,14 @@ rec {
* mkKeyValue is the same as in toINI. * mkKeyValue is the same as in toINI.
*/ */
toKeyValue = { toKeyValue = {
mkKeyValue ? mkKeyValueDefault {} "=" mkKeyValue ? mkKeyValueDefault {} "=",
}: attrs: listsAsDuplicateKeys ? false
let mkLine = k: v: mkKeyValue k v + "\n"; }:
in libStr.concatStrings (libAttr.mapAttrsToList mkLine attrs); let mkLine = k: v: mkKeyValue k v + "\n";
mkLines = if listsAsDuplicateKeys
then k: v: map (mkLine k) (if lib.isList v then v else [v])
else k: v: [ (mkLine k v) ];
in attrs: libStr.concatStrings (lib.concatLists (libAttr.mapAttrsToList mkLines attrs));
/* Generate an INI-style config file from an /* Generate an INI-style config file from an
@ -106,7 +110,9 @@ rec {
# apply transformations (e.g. escapes) to section names # apply transformations (e.g. escapes) to section names
mkSectionName ? (name: libStr.escape [ "[" "]" ] name), mkSectionName ? (name: libStr.escape [ "[" "]" ] name),
# format a setting line from key and value # format a setting line from key and value
mkKeyValue ? mkKeyValueDefault {} "=" mkKeyValue ? mkKeyValueDefault {} "=",
# allow lists as values for duplicate keys
listsAsDuplicateKeys ? false
}: attrsOfAttrs: }: attrsOfAttrs:
let let
# map function to string for each key val # map function to string for each key val
@ -115,7 +121,7 @@ rec {
(libAttr.mapAttrsToList mapFn attrs); (libAttr.mapAttrsToList mapFn attrs);
mkSection = sectName: sectValues: '' mkSection = sectName: sectValues: ''
[${mkSectionName sectName}] [${mkSectionName sectName}]
'' + toKeyValue { inherit mkKeyValue; } sectValues; '' + toKeyValue { inherit mkKeyValue listsAsDuplicateKeys; } sectValues;
in in
# map input to ini sections # map input to ini sections
mapAttrsToStringsSep "\n" mkSection attrsOfAttrs; mapAttrsToStringsSep "\n" mkSection attrsOfAttrs;

View file

@ -348,6 +348,18 @@ runTests {
''; '';
}; };
testToINIDuplicateKeys = {
expr = generators.toINI { listsAsDuplicateKeys = true; } { foo.bar = true; baz.qux = [ 1 false ]; };
expected = ''
[baz]
qux=1
qux=false
[foo]
bar=true
'';
};
testToINIDefaultEscapes = { testToINIDefaultEscapes = {
expr = generators.toINI {} { expr = generators.toINI {} {
"no [ and ] allowed unescaped" = { "no [ and ] allowed unescaped" = {