Skip to content

Commit

Permalink
Use wordexp to resolve variables like $HOME in path like settings
Browse files Browse the repository at this point in the history
  • Loading branch information
zappolowski committed Oct 23, 2023
1 parent 19865c0 commit ece52ce
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <wordexp.h>

#include "log.h"
#include "settings_data.h"
Expand Down Expand Up @@ -179,16 +180,19 @@ int string_array_length(char **s)
/* see utils.h */
char *string_to_path(char *string)
{
ASSERT_OR_RET(string, string);

if (string && STRN_EQ(string, "~/", 2)) {
char *home = g_strconcat(user_get_home(), "/", NULL);

string = string_replace_at(string, 0, 2, home);

g_free(home);
wordexp_t we;
if (wordexp(string, &we, WRDE_NOCMD | WRDE_UNDEF) != 0) {
LOG_W("Expansion of \"%s\" failed.", string);
return string;
}
g_free(string);

char *res = g_strjoinv(" ", we.we_wordv);
wordfree(&we);

return string;
return res;
}

/* see utils.h */
Expand Down
10 changes: 10 additions & 0 deletions test/option_parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -521,16 +521,23 @@ TEST test_string_to_path(void)
"/path/p argument",
"p with multiple arguments",
"~/p/p",
"$HOME/p/p",
"$TEST_ENV/p/p",
};

setenv("TEST_ENV", "foobar", 1);

char *expanded_home = g_strconcat(user_get_home(), "/", "p/p", NULL);
char *expanded_env = g_strconcat("foobar", "/p/p", NULL);
const char* results[] = {
"/bin/something",
"something",
"/path/path/path/",
"/path/p argument",
"p with multiple arguments",
expanded_home,
expanded_home,
expanded_env,
};

const char* results2[][5] = {
Expand All @@ -540,6 +547,8 @@ TEST test_string_to_path(void)
{"/path/p", "argument", NULL},
{"p", "with", "multiple", "arguments", NULL},
{expanded_home},
{expanded_home},
{expanded_env},
};

ARRAY_SAME_LENGTH(inputs, results);
Expand All @@ -557,6 +566,7 @@ TEST test_string_to_path(void)
}

g_free(val);
g_free(expanded_env);
g_free(expanded_home);
g_strfreev(val2);
PASS();
Expand Down

0 comments on commit ece52ce

Please sign in to comment.