From 7cd935026e3b6c9d9e3977062dc236f5074bca68 Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Fri, 18 Nov 2022 22:46:17 +0300 Subject: [PATCH] add dict item --- lib.nix | 34 ++++++++++++++++++++-------------- lib.test.nix | 10 +++++++++- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/lib.nix b/lib.nix index ae7db62..eacc0e3 100644 --- a/lib.nix +++ b/lib.nix @@ -3,10 +3,21 @@ let inherit (builtins) concatStringsSep filter mapAttrs attrValues; mkLuaNil = { _type = "nil"; }; - isLuaNil = val: isAttrs val && val ? _type && val._type == "nil"; + isLuaNil = val: getType val == "nil"; + + mkDictItem = name: value: { + _type = "dict_item"; + name = validString name; + value = toLua value; + }; + isDictItem = val: getType val == "dict_item"; + toLuaDictItem = name: value: + if isNull value then null + else "[${toLuaStr name}] = ${value}"; toLua = val: if isLuaNil val then "nil" + else if isDictItem val then toLuaDictItem val.name val.value else if isAttrs val then toLuaDict val else if isList val then toLuaList val else if isString val then toLuaStr val @@ -18,29 +29,24 @@ let toLuaList = val: wrapObj (excludeNull (map toLua val)); - toLuaDict = val: - let - toDictItem = name: value: - let luaValue = toLua value; - in - if isNull luaValue then null - else "[${toLuaStr name}] = ${luaValue}"; - - dictItems = excludeNull (attrValues (mapAttrs toDictItem val)); - in - wrapObj dictItems; + toLuaDict = val: toLua (attrValues (mapAttrs mkDictItem val)); excludeNull = val: filter (v: !(isNull v)) val; wrapObj = val: "{ ${concatStringsSep ", " val} }"; - toLuaStr = val: "\"${val}\""; + toLuaStr = val: "\"${validString val}\""; toLuaBool = val: if val then "true" else "false"; + getType = val: if isAttrs val && val ? _type then val._type else null; + + validString = value: + if isString value then value + else throw "Value '${toString value}' is not a valid string"; in { inherit toLua; - inherit mkLuaNil; + inherit mkLuaNil mkDictItem; } diff --git a/lib.test.nix b/lib.test.nix index eb28900..f9f94d4 100644 --- a/lib.test.nix +++ b/lib.test.nix @@ -2,7 +2,7 @@ let nix2lua = import ./lib.nix; - inherit (nix2lua) toLua mkLuaNil; + inherit (nix2lua) toLua mkLuaNil mkDictItem; in pkgs.lib.runTests { "test returns null" = { @@ -69,4 +69,12 @@ pkgs.lib.runTests { }; expected = "{ [\"first\"] = { [\"second\"] = { [\"last\"] = \"hello\" } } }"; }; + "test returns array with dict items" = { + expr = toLua [ + "foo" + (mkDictItem "foo" "hello") + 10 + ]; + expected = "{ \"foo\", [\"foo\"] = \"hello\", 10 }"; + }; }