Skip to content
This repository has been archived by the owner on Oct 15, 2024. It is now read-only.

Commit

Permalink
kdb-cli: add expandKeyName function
Browse files Browse the repository at this point in the history
...to command.c for resolving bookmarks in keynames.
  • Loading branch information
hannes99 committed Sep 21, 2022
1 parent a25c97c commit a210512
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/tools/kdb/command.c
Original file line number Diff line number Diff line change
@@ -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 <command.h>

#include <kdberrors.h>
#include <string.h>

/**
* 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;
}
2 changes: 2 additions & 0 deletions src/tools/kdb/command.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#define ELEKTRA_KDB_COMMAND_H

#include <kdb.h>
#include <stdbool.h>

#define CLI_BASE_KEY "/sw/elektra/kdb/#0/current"

Expand Down Expand Up @@ -63,6 +64,7 @@
sleep (1); \
}

char * expandKeyName (KeySet * ks, const char * name, bool * resolved);

typedef struct command
{
Expand Down

0 comments on commit a210512

Please sign in to comment.