src/config.c: Make config file reading more flexible

This adds one level of abstraction to config_load() by splitting out the
actual reading routine and the variable setter into two separate
functions. config_file_walk() can be used to read the configuration
file, strip comments and pass every key/value pair to a callback.
config_load_cb() is the new callback used in config_load().

Rationale: It makes sense to reuse the key/value parser to allow for a
much saner config_save() routine that changes single values only instead
of rewriting (and overwriting) the whole configuration file every time.

Signed-off-by: Lukas Fleischer <calcurse@cryptocrack.de>
This commit is contained in:
Lukas Fleischer 2012-02-16 09:29:52 +01:00
parent f73f500559
commit 4c5d6fe612

View File

@ -38,6 +38,8 @@
#include "calcurse.h" #include "calcurse.h"
typedef int (*config_fn_walk_cb_t) (const char *, const char *, void *);
static int static int
config_parse_bool (unsigned *dest, const char *val) config_parse_bool (unsigned *dest, const char *val)
{ {
@ -225,16 +227,14 @@ config_set_conf (const char *key, const char *value)
return -1; return -1;
} }
/* Load the user configuration. */ static void
void config_file_walk (config_fn_walk_cb_t fn_cb, void *data)
config_load (void)
{ {
FILE *data_file; FILE *data_file;
char *mesg_line1 = _("Failed to open config file"); char *mesg_line1 = _("Failed to open config file");
char *mesg_line2 = _("Press [ENTER] to continue"); char *mesg_line2 = _("Press [ENTER] to continue");
char buf[BUFSIZ], e_conf[BUFSIZ]; char buf[BUFSIZ], e_conf[BUFSIZ];
char *key, *value; char *key, *value;
int result;
data_file = fopen (path_conf, "r"); data_file = fopen (path_conf, "r");
if (data_file == NULL) if (data_file == NULL)
@ -272,16 +272,32 @@ config_load (void)
value = e_conf; value = e_conf;
} }
result = config_set_conf (key, value); fn_cb (key, value, data);
}
file_close (data_file, __FILE_POS__);
pthread_mutex_unlock (&nbar.mutex);
}
static int
config_load_cb (const char *key, const char *value, void *dummy)
{
int result = config_set_conf (key, value);
if (result < 0) if (result < 0)
EXIT (_("configuration variable unknown: \"%s\""), key); EXIT (_("configuration variable unknown: \"%s\""), key);
/* NOTREACHED */ /* NOTREACHED */
else if (result == 0) else if (result == 0)
EXIT (_("wrong configuration variable format for \"%s\""), key); EXIT (_("wrong configuration variable format for \"%s\""), key);
/* NOTREACHED */ /* NOTREACHED */
return 1;
} }
file_close (data_file, __FILE_POS__);
pthread_mutex_unlock (&nbar.mutex); /* Load the user configuration. */
void
config_load (void)
{
config_file_walk (config_load_cb, NULL);
} }
/* /*