diff --git a/src/tools/kdb/command.c b/src/tools/kdb/command.c new file mode 100644 index 00000000000..65f149e66d4 --- /dev/null +++ b/src/tools/kdb/command.c @@ -0,0 +1,64 @@ +/** + * @file + * + * @brief Implementation of things used everywhere in the kdb tool + * + * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) + */ + +#include + +#include +#include + +/** + * Expands a keyname if it contains a bookmark. If @name does not contain a bookmark ref a copy of @name is returned. + * + * @param name the keyname that might contain a bookmark, and where the expanded name should be saved + * @param ks keyset that contains information about the bookmarks + * @param resolved will be set to true iff a bookmark was resolved successfully + * + * @return NULL if the bookmark could not be resolved, NULL was passed as @ks or @name + * @return string of the full key otherwise, has to be freed after usage + */ +char * expandKeyName (KeySet * ks, const char * name, bool * resolved) +{ + *resolved = false; + if (ks == NULL || name == NULL) + { + return NULL; + } + char * ret = NULL; + if (name[0] != '+') + { + ret = elektraMalloc (strlen (name)); + strcpy (ret, name); + } + else + { + int bookmarkEnd = strcspn (name, "/"); + char * bookmarkName = elektraMalloc (bookmarkEnd); + strncpy (bookmarkName, name + 1, bookmarkEnd - 1); + bookmarkName[bookmarkEnd - 1] = '\0'; + char * bookmarkKeyName = elektraMalloc (strlen (CLI_BASE_KEY) + strlen ("/bookmarks/") + strlen (bookmarkName) + 1); + strcpy (bookmarkKeyName, CLI_BASE_KEY); + strcat (bookmarkKeyName, "/bookmarks/"); + strcat (bookmarkKeyName, bookmarkName); + + Key * bookmarkKey = ksLookupByName (ks, bookmarkKeyName, 0); + elektraFree (bookmarkKeyName); + elektraFree (bookmarkName); + if (bookmarkKey != NULL) + { + const char * bookmarkValue = keyString (bookmarkKey); + ret = elektraMalloc (strlen (name + bookmarkEnd) + strlen (bookmarkValue)); + strcpy (ret, bookmarkValue); + strcat (ret, name + bookmarkEnd); + *resolved = true; + } + + keyDel (bookmarkKey); + return ret; + } + return NULL; +} diff --git a/src/tools/kdb/command.h b/src/tools/kdb/command.h index f5ef3c6af96..5fbad83396a 100644 --- a/src/tools/kdb/command.h +++ b/src/tools/kdb/command.h @@ -10,6 +10,7 @@ #define ELEKTRA_KDB_COMMAND_H #include +#include #define CLI_BASE_KEY "/sw/elektra/kdb/#0/current" @@ -63,6 +64,7 @@ sleep (1); \ } +char * expandKeyName (KeySet * ks, const char * name, bool * resolved); typedef struct command {