Skip to content

Commit

Permalink
Use wordexp to resolve variables in paths
Browse files Browse the repository at this point in the history
  • Loading branch information
zappolowski committed Oct 17, 2023
1 parent 45de8f6 commit 4a1ee5d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
26 changes: 21 additions & 5 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,14 +180,29 @@ 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) || STRN_EQ(string, "$HOME/", 6))) {
char *ret = g_strconcat(user_get_home(), strstr(string, "/"), NULL);
g_free(string);
return ret;
wordexp_t we;
if (wordexp(string, &we, WRDE_NOCMD | WRDE_UNDEF) != 0) {
LOG_W("Expansion of \"%s\" failed.", string);
return string;
}
g_free(string);

return string;
size_t tot_len = we.we_wordc; // (we.we_wordc - 1) * 1 (strlen(" ")) + 1 for spaces between fields and final \0
for (size_t i = 0; i < we.we_wordc; i++) {
tot_len += strlen(we.we_wordv[i]);
}

char *res = g_malloc0(tot_len);
for (size_t i = 0; i < we.we_wordc - 1; i++) {
strcat(res, we.we_wordv[i]);
strcat(res, " ");
}
strcat(res, we.we_wordv[we.we_wordc - 1]);
wordfree(&we);

return res;
}

/* see utils.h */
Expand Down
7 changes: 7 additions & 0 deletions test/option_parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -522,9 +522,13 @@ TEST test_string_to_path(void)
"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",
Expand All @@ -533,6 +537,7 @@ TEST test_string_to_path(void)
"p with multiple arguments",
expanded_home,
expanded_home,
expanded_env,
};

const char* results2[][5] = {
Expand All @@ -543,6 +548,7 @@ TEST test_string_to_path(void)
{"p", "with", "multiple", "arguments", NULL},
{expanded_home},
{expanded_home},
{expanded_env},
};

ARRAY_SAME_LENGTH(inputs, results);
Expand All @@ -560,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 4a1ee5d

Please sign in to comment.