diff --git a/nixos/lib/ini.nix b/nixos/lib/ini.nix index 4269c0f9db6bf9225fc58773810cdb6e478c735f..39a0f96b7ff264b31a67dfa9819531d321f84a59 100644 --- a/nixos/lib/ini.nix +++ b/nixos/lib/ini.nix @@ -1,6 +1,14 @@ { pkgs ? import <nixpkgs> { } }: let lib = pkgs.lib; in rec { + # Get the .ini-file-appropriate string representation of a simple value. + # + # toINIString "hello" -> "hello" + # toINIString true -> "true" + toINIString = v: + if builtins.isBool v then builtins.toJSON v + else builtins.toString v; + # Map a function over an attrset and concatenate the string results. # # concatMapAttrsToList (n: v: "${n} = ${v}\n") { a = "b"; c = "d"; } -> "a = b\nc = d\n" @@ -11,7 +19,7 @@ in rec { # # oneConfigItemText "foo" "bar" -> "foo = bar\n" oneConfigItemText = name: value: - "${name} = ${builtins.toString value}\n"; + "${name} = ${toINIString value}\n"; # Generate all lines of configuration defining all items in one section. # @@ -25,8 +33,7 @@ in rec { # oneConfigSectionText "foo" { bar = "baz"; } -> "[foo]\nbar = baz\n" oneConfigSectionText = name: value: '' [${name}] - ${allConfigItemsText value} - ''; + ${allConfigItemsText value}''; # Generate all lines of configuration for all sections, headers # and items included. diff --git a/nixos/lib/tests/test_ini.nix b/nixos/lib/tests/test_ini.nix index 4f77ccab6b98b3289d0c319e9f4bbe8bb3c757ce..e0053115eeb32ade5d6a6216373792d082c66904 100644 --- a/nixos/lib/tests/test_ini.nix +++ b/nixos/lib/tests/test_ini.nix @@ -1,20 +1,59 @@ -let - pkgs = import <nixpkgs> { }; - ini = import ../ini.nix { inherit pkgs; }; -in -pkgs.lib.runTests +ini: { test_empty = - { name = "test_empty"; - expected = ""; + { expected = ""; expr = ini.allConfigSectionsText { }; }; - test_one_section = - { name = "test_one_empty_section"; - expected = '' + test_one_empty_section = + { expected = '' [foo] - ''; expr = ini.allConfigSectionsText { foo = { }; }; }; + + test_one_section_one_item = + { expected = '' + [foo] + bar = baz + ''; + expr = ini.allConfigSectionsText { foo = { bar = "baz"; }; }; + }; + + test_one_section_two_items = + { expected = '' + [foo] + bar = baz + foobar = quux + ''; + expr = ini.allConfigSectionsText { foo = { bar = "baz"; foobar = "quux"; }; }; + }; + + test_two_sections = + { expected = '' + [alpha] + beta = gamma + [foo] + bar = baz + foobar = quux + ''; + expr = ini.allConfigSectionsText + { foo = { bar = "baz"; foobar = "quux"; }; + alpha = { beta = "gamma"; }; + }; + }; + + test_true = + { expected = "x = true\n"; + expr = ini.oneConfigItemText "x" true; + }; + + test_false = + { expected = "x = false\n"; + expr = ini.oneConfigItemText "x" false; + }; + + test_integer = + { expected = "x = 12345\n"; + expr = ini.oneConfigItemText "x" 12345; + }; }