From 5abd8251370da46c2afb5f4477d8424f6324ce30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ekl=C3=B6f?= Date: Tue, 1 Jan 2019 23:25:36 +0100 Subject: [PATCH] yml: yml_load(): optionally allocates an error string (on error) --- main.c | 3 ++- yml.c | 27 +++++++++++++++++++++------ yml.h | 2 +- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/main.c b/main.c index eda7269..40e0f8f 100644 --- a/main.c +++ b/main.c @@ -62,7 +62,8 @@ main(int argc, const char *const *argv) if (conf_file == NULL) return 1; - struct yml_node *conf = yml_load(conf_file); + char *yml_error; + struct yml_node *conf = yml_load(conf_file, &yml_error); fclose(conf_file); if (conf == NULL) diff --git a/yml.c b/yml.c index 27e1c5c..1d27552 100644 --- a/yml.c +++ b/yml.c @@ -215,7 +215,7 @@ post_process(struct yml_node *node) } struct yml_node * -yml_load(FILE *yml) +yml_load(FILE *yml, char **error) { yaml_parser_t yaml; yaml_parser_initialize(&yaml); @@ -238,11 +238,26 @@ yml_load(FILE *yml) while (!done) { yaml_event_t event; if (!yaml_parser_parse(&yaml, &event)) { - //printf("yaml parser error\n"); - /* TODO: free node tree */ - root = NULL; - assert(false); - break; + if (error != NULL) { + int cnt = snprintf( + NULL, 0, "%zu:%zu: %s %s", + yaml.problem_mark.line, + yaml.problem_mark.column, + yaml.problem, + yaml.context != NULL ? yaml.context : ""); + + *error = malloc(cnt + 1); + snprintf(*error, cnt + 1, "%zu:%zu: %s %s", + yaml.problem_mark.line, + yaml.problem_mark.column, + yaml.problem, + yaml.context != NULL ? yaml.context : ""); + (*error)[cnt] = '\0'; + } + + yml_destroy(root); + yaml_parser_delete(&yaml); + return NULL; } switch (event.type) { diff --git a/yml.h b/yml.h index b079b58..51ec58c 100644 --- a/yml.h +++ b/yml.h @@ -4,7 +4,7 @@ struct yml_node; -struct yml_node *yml_load(FILE *yml); +struct yml_node *yml_load(FILE *yml, char **error); void yml_destroy(struct yml_node *root); bool yml_is_scalar(const struct yml_node *node);