config: allow whitespaces in config path

(cherry picked from commit 1d62d6bfa0)
This commit is contained in:
columbarius 2021-03-25 17:22:26 +01:00 committed by Simon Ser
parent a9563a3710
commit 8f5c546fca

View file

@ -338,35 +338,60 @@ static bool file_exists(const char *path) {
return path && access(path, R_OK) != -1; return path && access(path, R_OK) != -1;
} }
static char *config_path(const char *prefix, const char *config_folder) {
if (!prefix || !prefix[0] || !config_folder || !config_folder[0]) {
return NULL;
}
const char *filename = "config";
size_t size = 3 + strlen(prefix) + strlen(config_folder) + strlen(filename);
char *path = calloc(size, sizeof(char));
snprintf(path, size, "%s/%s/%s", prefix, config_folder, filename);
return path;
}
static char *get_config_path(void) { static char *get_config_path(void) {
static const char *config_paths[] = { char *path = NULL;
"$HOME/.sway/config", const char *home = getenv("HOME");
"$XDG_CONFIG_HOME/sway/config", size_t size_fallback = 1 + strlen(home) + strlen("/.config");
"$HOME/.i3/config", char *config_home_fallback = calloc(size_fallback, sizeof(char));
"$XDG_CONFIG_HOME/i3/config", snprintf(config_home_fallback, size_fallback, "%s/.config", home);
SYSCONFDIR "/sway/config",
SYSCONFDIR "/i3/config", const char *config_home = getenv("XDG_CONFIG_HOME");
if (config_home == NULL || config_home[0] == '\0') {
config_home = config_home_fallback;
}
struct config_path {
const char *prefix;
const char *config_folder;
}; };
char *config_home = getenv("XDG_CONFIG_HOME"); struct config_path config_paths[] = {
if (!config_home || !*config_home) { { .prefix = home, .config_folder = ".sway"},
config_paths[1] = "$HOME/.config/sway/config"; { .prefix = config_home, .config_folder = "sway"},
config_paths[3] = "$HOME/.config/i3/config"; { .prefix = home, .config_folder = ".i3"},
} { .prefix = config_home, .config_folder = "i3"},
{ .prefix = SYSCONFDIR, .config_folder = "sway"},
{ .prefix = SYSCONFDIR, .config_folder = "i3"}
};
for (size_t i = 0; i < sizeof(config_paths) / sizeof(char *); ++i) { size_t num_config_paths = sizeof(config_paths)/sizeof(config_paths[0]);
wordexp_t p; for (size_t i = 0; i < num_config_paths; i++) {
if (wordexp(config_paths[i], &p, WRDE_UNDEF) == 0) { path = config_path(config_paths[i].prefix, config_paths[i].config_folder);
char *path = strdup(p.we_wordv[0]); if (!path) {
wordfree(&p); continue;
if (file_exists(path)) {
return path;
}
free(path);
} }
if (file_exists(path)) {
break;
}
free(path);
path = NULL;
} }
return NULL; free(config_home_fallback);
return path;
} }
static bool load_config(const char *path, struct sway_config *config, static bool load_config(const char *path, struct sway_config *config,