Load configuration file from ~/.i3/config or /etc/i3/config

This commit is contained in:
Michael Stapelberg 2009-03-04 09:16:18 +01:00
parent 3c6d4f7663
commit 415b5cc0e8
3 changed files with 34 additions and 12 deletions

View File

@ -9,6 +9,6 @@ struct Config {
const char *font; const char *font;
}; };
void load_configuration(const char *configfile); void load_configuration(const char *override_configfile);
#endif #endif

View File

@ -12,6 +12,7 @@
#include <string.h> #include <string.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <stdlib.h> #include <stdlib.h>
#include <glob.h>
#include "i3.h" #include "i3.h"
#include "util.h" #include "util.h"
@ -20,10 +21,27 @@
Config config; Config config;
/* /*
* Reads the configuration from the given file * This function resolves ~ in pathnames.
* *
*/ */
void load_configuration(const char *configfile) { static char *glob_path(const char *path) {
static glob_t globbuf;
if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
die("glob() failed");
char *result = sstrdup(globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path);
globfree(&globbuf);
return result;
}
/*
* Reads the configuration from ~/.i3/config or /etc/i3/config if not found.
*
* If you specify override_configpath, only this path is used to look for a
* configuration file.
*
*/
void load_configuration(const char *override_configpath) {
#define OPTION_STRING(name) \ #define OPTION_STRING(name) \
if (strcasecmp(key, #name) == 0) { \ if (strcasecmp(key, #name) == 0) { \
config.name = sstrdup(value); \ config.name = sstrdup(value); \
@ -37,14 +55,18 @@ void load_configuration(const char *configfile) {
/* Clear the old config or initialize the data structure */ /* Clear the old config or initialize the data structure */
memset(&config, 0, sizeof(config)); memset(&config, 0, sizeof(config));
/* check if the file exists */ FILE *handle;
struct stat buf; if (override_configpath != NULL) {
if (stat(configfile, &buf) < 0) if ((handle = fopen(override_configpath, "r")) == NULL)
return; die("Could not open configfile \"%s\".\n", override_configpath);
} else {
FILE *handle = fopen(configfile, "r"); /* We first check for ~/.i3/config, then for /etc/i3/config */
if (handle == NULL) char *globbed = glob_path("~/.i3/config");
die("Could not open configfile\n"); if ((handle = fopen(globbed, "r")) == NULL)
if ((handle = fopen("/etc/i3/config", "r")) == NULL)
die("Neither \"%s\" nor /etc/i3/config could be opened\n", globbed);
free(globbed);
}
char key[512], value[512], buffer[1026]; char key[512], value[512], buffer[1026];
while (!feof(handle)) { while (!feof(handle)) {

View File

@ -304,7 +304,7 @@ int main(int argc, char *argv[], char *env[]) {
byChild = alloc_table(); byChild = alloc_table();
byParent = alloc_table(); byParent = alloc_table();
load_configuration("i3.config"); load_configuration(NULL);
c = xcb_connect(NULL, &screens); c = xcb_connect(NULL, &screens);