From 6089d6170a59c68dbb9c886a77e4dc7f1f3fd6d9 Mon Sep 17 00:00:00 2001 From: Jean Privat Date: Fri, 28 Aug 2015 12:37:57 -0400 Subject: [PATCH] lib/ini: let the user deal with undefined key instead of aborting Signed-off-by: Jean Privat --- lib/ini.nit | 35 +++++++++++++---------------------- 1 file changed, 13 insertions(+), 22 deletions(-) diff --git a/lib/ini.nit b/lib/ini.nit index 2f81240..84b200c 100644 --- a/lib/ini.nit +++ b/lib/ini.nit @@ -41,41 +41,32 @@ class ConfigTree # Get the config value for `key` # - # REQUIRE: `has_key(key)` - # # var config = new ConfigTree("config.ini") # assert config["goo"] == "goo" # assert config["foo.bar"] == "foobar" # assert config["foo.baz"] == "foobaz" - fun [](key: String): String do - if not has_key(key) then - print "error: config key `{key}` not found" - abort - end - var node = get_node(key).as(not null) - if node.value == null then - print "error: config key `{key}` has no value" - abort - end - return node.value.as(not null) + # assert config["fail.fail"] == null + fun [](key: String): nullable String do + var node = get_node(key) + if node == null then return null + return node.value end # Get the config values under `key` # - # REQUIRE: `has_key(key)` - # # var config = new ConfigTree("config.ini") # var values = config.at("foo") # assert values.has_key("bar") # assert values.has_key("baz") # assert not values.has_key("goo") - fun at(key: String): Map[String, String] do - if not has_key(key) then - print "error: config key `{key}` not found" - abort - end + # + # Return null if the key does not exists. + # + # assert config.at("fail.fail") == null + fun at(key: String): nullable Map[String, String] do + var node = get_node(key) + if node == null then return null var map = new HashMap[String, String] - var node = get_node(key).as(not null) for k, child in node.children do if child.value == null then continue map[k] = child.value.to_s @@ -278,7 +269,7 @@ class ConfigTree private fun get_node(key: String): nullable ConfigNode do var parts = key.split(".").reversed var node = get_root(parts.pop) - while not parts.is_empty do + while node != null and not parts.is_empty do node = node.get_child(parts.pop) end return node -- 1.7.9.5