macros.c: deduplicate code in expand_macros()

Use `goto` statements to reduce code duplication.
This commit is contained in:
Kelvin M. Klann 2026-04-22 03:01:11 -03:00
parent 8e1954d887
commit 68d16bf9da

View file

@ -209,55 +209,46 @@ char *expand_macros(const char *path) {
EUID_ASSERT();
// Replace home macro
char *new_name = NULL;
char *rv = NULL;
if (strncmp(path, "$HOME", 5) == 0) {
fprintf(stderr, "Error: $HOME is not allowed in profile files, please replace it with ${HOME}\n");
exit(1);
}
else if (strncmp(path, "${HOME}", 7) == 0) {
if (asprintf(&new_name, "%s%s", cfg.homedir, path + 7) == -1)
if (asprintf(&rv, "%s%s", cfg.homedir, path + 7) == -1)
errExit("asprintf");
if (called_as_root)
EUID_ROOT();
return new_name;
goto out;
}
else if (*path == '~') {
if (asprintf(&new_name, "%s%s", cfg.homedir, path + 1) == -1)
if (asprintf(&rv, "%s%s", cfg.homedir, path + 1) == -1)
errExit("asprintf");
if (called_as_root)
EUID_ROOT();
return new_name;
goto out;
}
else if (strncmp(path, "${CFG}", 6) == 0) {
if (asprintf(&new_name, "%s%s", SYSCONFDIR, path + 6) == -1)
if (asprintf(&rv, "%s%s", SYSCONFDIR, path + 6) == -1)
errExit("asprintf");
if (called_as_root)
EUID_ROOT();
return new_name;
goto out;
}
else if (strncmp(path, "${RUNUSER}", 10) == 0) {
if (asprintf(&new_name, "/run/user/%u%s", getuid(), path + 10) == -1)
if (asprintf(&rv, "/run/user/%u%s", getuid(), path + 10) == -1)
errExit("asprintf");
if (called_as_root)
EUID_ROOT();
return new_name;
goto out;
}
else {
char *directory = resolve_macro(path);
if (directory) {
if (asprintf(&new_name, "%s/%s", cfg.homedir, directory) == -1)
if (asprintf(&rv, "%s/%s", cfg.homedir, directory) == -1)
errExit("asprintf");
if (called_as_root)
EUID_ROOT();
free(directory);
return new_name;
goto out;
}
}
char *rv = strdup(path);
assert(rv == NULL);
rv = strdup(path);
if (!rv)
errExit("strdup");
out:
if (called_as_root)
EUID_ROOT();