From aa94563eb54c97a5cc07e2fec699808485471c13 Mon Sep 17 00:00:00 2001 From: Gunnar Beutner Date: Mon, 3 Nov 2014 13:05:14 +0100 Subject: [PATCH] Implement the keys() function fixes #7557 --- doc/7-configuring-icinga-2.md | 1 + lib/base/scriptutils.cpp | 17 +++++++++++++++-- lib/base/scriptutils.hpp | 2 ++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/doc/7-configuring-icinga-2.md b/doc/7-configuring-icinga-2.md index a0c2e3d22..4412e324d 100644 --- a/doc/7-configuring-icinga-2.md +++ b/doc/7-configuring-icinga-2.md @@ -287,6 +287,7 @@ match(pattern, text) | Returns true if the wildcard pattern matches t len(value) | Returns the length of the value, i.e. the number of elements for an array or dictionary, or the length of the string in bytes. union(array, array, ...) | Returns an array containing all unique elements from the specified arrays. intersection(array, array, ...) | Returns an array containing all unique elements which are common to all specified arrays. +keys(dict) | Returns an array containing the dictionary's keys. string(value) | Converts the value to a string. number(value) | Converts the value to a number. bool(value) | Converts the value to a bool. diff --git a/lib/base/scriptutils.cpp b/lib/base/scriptutils.cpp index c7496640e..cf654e542 100644 --- a/lib/base/scriptutils.cpp +++ b/lib/base/scriptutils.cpp @@ -21,10 +21,9 @@ #include "base/scriptfunction.hpp" #include "base/utility.hpp" #include "base/convert.hpp" -#include "base/array.hpp" -#include "base/dictionary.hpp" #include "base/json.hpp" #include "base/logger.hpp" +#include "base/objectlock.hpp" #include #include #include @@ -41,6 +40,7 @@ REGISTER_SCRIPTFUNCTION(log, &ScriptUtils::Log); REGISTER_SCRIPTFUNCTION(range, &ScriptUtils::Range); REGISTER_SCRIPTFUNCTION(exit, &ScriptUtils::Exit); REGISTER_SCRIPTFUNCTION(typeof, &ScriptUtils::TypeOf); +REGISTER_SCRIPTFUNCTION(keys, &ScriptUtils::Keys); bool ScriptUtils::Regex(const String& pattern, const String& text) { @@ -196,3 +196,16 @@ Type::Ptr ScriptUtils::TypeOf(const Value& value) VERIFY(!"Invalid value type."); } } + +Array::Ptr ScriptUtils::Keys(const Dictionary::Ptr& dict) +{ + Array::Ptr result = make_shared(); + + ObjectLock olock(dict); + BOOST_FOREACH(const Dictionary::Pair& kv, dict) { + result->Add(kv.first); + } + + return result; +} + diff --git a/lib/base/scriptutils.hpp b/lib/base/scriptutils.hpp index 2a4bb549f..1ba25e0a4 100644 --- a/lib/base/scriptutils.hpp +++ b/lib/base/scriptutils.hpp @@ -23,6 +23,7 @@ #include "base/i2-base.hpp" #include "base/string.hpp" #include "base/array.hpp" +#include "base/dictionary.hpp" #include "base/type.hpp" namespace icinga @@ -42,6 +43,7 @@ public: static Array::Ptr Range(const std::vector& arguments); static void Exit(int code); static Type::Ptr TypeOf(const Value& value); + static Array::Ptr Keys(const Dictionary::Ptr& dict); private: ScriptUtils(void);