implement more suggestions by lorenz schori
[project/uci.git] / libuci.c
1 /*
2 * libuci - Library for the Unified Configuration Interface
3 * Copyright (C) 2008 Felix Fietkau <nbd@openwrt.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 */
14
15 /*
16 * This file contains some common code for the uci library
17 */
18
19 #include <sys/types.h>
20 #include <stdbool.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include "uci.h"
25 #include "err.h"
26
27 static const char *uci_errstr[] = {
28 [UCI_OK] = "Success",
29 [UCI_ERR_MEM] = "Out of memory",
30 [UCI_ERR_INVAL] = "Invalid argument",
31 [UCI_ERR_NOTFOUND] = "Entry not found",
32 [UCI_ERR_IO] = "I/O error",
33 [UCI_ERR_PARSE] = "Parse error",
34 [UCI_ERR_UNKNOWN] = "Unknown error",
35 };
36
37 #include "util.c"
38 #include "list.c"
39 #include "file.c"
40
41 /* exported functions */
42 struct uci_context *uci_alloc_context(void)
43 {
44 struct uci_context *ctx;
45
46 ctx = (struct uci_context *) malloc(sizeof(struct uci_context));
47 memset(ctx, 0, sizeof(struct uci_context));
48 uci_list_init(&ctx->root);
49
50 return ctx;
51 }
52
53 void uci_free_context(struct uci_context *ctx)
54 {
55 struct uci_element *e, *tmp;
56
57 UCI_TRAP_SAVE(ctx, ignore);
58 uci_cleanup(ctx);
59 uci_foreach_element_safe(&ctx->root, tmp, e) {
60 uci_free_package(uci_to_package(e));
61 }
62 free(ctx);
63 UCI_TRAP_RESTORE(ctx);
64
65 ignore:
66 return;
67 }
68
69 int uci_cleanup(struct uci_context *ctx)
70 {
71 UCI_HANDLE_ERR(ctx);
72 uci_file_cleanup(ctx);
73 return 0;
74 }
75
76 void uci_perror(struct uci_context *ctx, const char *str)
77 {
78 int err;
79
80 if (!ctx)
81 err = UCI_ERR_INVAL;
82 else
83 err = ctx->errno;
84
85 if ((err < 0) || (err >= UCI_ERR_LAST))
86 err = UCI_ERR_UNKNOWN;
87
88 switch (err) {
89 case UCI_ERR_PARSE:
90 if (ctx->pctx) {
91 fprintf(stderr, "%s: %s (%s) at line %d, byte %d\n", str, uci_errstr[err], (ctx->pctx->reason ? ctx->pctx->reason : "unknown"), ctx->pctx->line, ctx->pctx->byte);
92 break;
93 }
94 /* fall through */
95 default:
96 fprintf(stderr, "%s: %s\n", str, uci_errstr[err]);
97 break;
98 }
99 }
100
101