From 72e5aeba587dfa2b83ede26b71e952faa5aa98a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=99emysl=20Janouch?= Date: Sun, 3 May 2015 19:34:01 +0200 Subject: [PATCH] degesch: implement /save Fuck yes. :) --- degesch.c | 169 ++++++++++++++++++++++++++---------------------------- 1 file changed, 82 insertions(+), 87 deletions(-) diff --git a/degesch.c b/degesch.c index a60c4e9..6a7e0db 100644 --- a/degesch.c +++ b/degesch.c @@ -785,6 +785,59 @@ get_config_boolean (struct app_context *ctx, const char *key) return item->value.boolean; } +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +static char * +write_configuration_file (const struct str *data, struct error **e) +{ + struct str path; + str_init (&path); + get_xdg_home_dir (&path, "XDG_CONFIG_HOME", ".config"); + str_append (&path, "/" PROGRAM_NAME); + + if (!mkdir_with_parents (path.str, e)) + goto error; + + str_append (&path, "/" PROGRAM_NAME ".conf"); + FILE *fp = fopen (path.str, "w"); + if (!fp) + { + error_set (e, "could not open `%s' for writing: %s", + path.str, strerror (errno)); + goto error; + } + + errno = 0; + fwrite (data->str, data->len, 1, fp); + fclose (fp); + + if (errno) + { + error_set (e, "writing to `%s' failed: %s", path.str, strerror (errno)); + goto error; + } + return str_steal (&path); + +error: + str_free (&path); + return NULL; +} + +static void +serialize_configuration (struct app_context *ctx, struct str *output) +{ + str_append (output, + "# " PROGRAM_NAME " " PROGRAM_VERSION " configuration file\n" + "#\n" + "# Relative paths are searched for in ${XDG_CONFIG_HOME:-~/.config}\n" + "# /" PROGRAM_NAME " as well as in $XDG_CONFIG_DIRS/" PROGRAM_NAME "\n" + "#\n" + "# Everything is in UTF-8. Any custom comments will be overwritten.\n" + "\n"); + + config_item_write (ctx->config.root, true, output); +} + // --- Attributed output ------------------------------------------------------- static struct @@ -3981,6 +4034,33 @@ handle_command_set (struct app_context *ctx, char *arguments) return result; } +static bool +handle_command_save (struct app_context *ctx, char *arguments) +{ + if (*arguments) + return false; + + struct str data; + str_init (&data); + serialize_configuration (ctx, &data); + + struct error *e = NULL; + char *filename = write_configuration_file (&data, &e); + str_free (&data); + + if (!filename) + { + buffer_send_error (ctx, ctx->global_buffer, + "%s: %s", "Saving configuration failed", e->message); + error_free (e); + } + else + buffer_send_status (ctx, ctx->global_buffer, + "Configuration written to `%s'", filename); + free (filename); + return true; +} + static bool handle_command_msg (struct app_context *ctx, char *arguments) { @@ -4211,6 +4291,8 @@ g_command_handlers[] = "list | clear | move | { close [ | ] } | " }, { "set", handle_command_set, "Manage configuration", "[