+ ctx->err = 0;
+ return changes;
+}
+
+static void uci_filter_history(struct uci_context *ctx, const char *name, const char *section, const char *option)
+{
+ struct uci_parse_context *pctx;
+ struct uci_element *e, *tmp;
+ struct uci_list list;
+ char *filename = NULL;
+ struct uci_ptr ptr;
+ FILE *f = NULL;
+
+ uci_list_init(&list);
+ uci_alloc_parse_context(ctx);
+ pctx = ctx->pctx;
+
+ if ((asprintf(&filename, "%s/%s", ctx->savedir, name) < 0) || !filename)
+ UCI_THROW(ctx, UCI_ERR_MEM);
+
+ UCI_TRAP_SAVE(ctx, done);
+ f = uci_open_stream(ctx, filename, SEEK_SET, true, false);
+ pctx->file = f;
+ while (!feof(f)) {
+ struct uci_element *e;
+ char *buf;
+
+ uci_getln(ctx, 0);
+ buf = pctx->buf;
+ if (!buf[0])
+ continue;
+
+ /* NB: need to allocate the element before the call to
+ * uci_parse_history_tuple, otherwise the original string
+ * gets modified before it is saved */
+ e = uci_alloc_generic(ctx, UCI_TYPE_HISTORY, pctx->buf, sizeof(struct uci_element));
+ uci_list_add(&list, &e->list);
+
+ uci_parse_history_tuple(ctx, &buf, &ptr);
+ if (section) {
+ if (!ptr.section || (strcmp(section, ptr.section) != 0))
+ continue;
+ }
+ if (option) {
+ if (!ptr.option || (strcmp(option, ptr.option) != 0))
+ continue;
+ }
+ /* match, drop this element again */
+ uci_free_element(e);
+ }
+
+ /* rebuild the history file */
+ rewind(f);
+ ftruncate(fileno(f), 0);
+ uci_foreach_element_safe(&list, tmp, e) {
+ fprintf(f, "%s\n", e->name);
+ uci_free_element(e);
+ }
+ UCI_TRAP_RESTORE(ctx);
+
+done:
+ if (filename)
+ free(filename);
+ uci_close_stream(pctx->file);
+ uci_foreach_element_safe(&list, tmp, e) {
+ uci_free_element(e);
+ }
+ uci_cleanup(ctx);
+}
+
+int uci_revert(struct uci_context *ctx, struct uci_ptr *ptr)
+{
+ char *package = NULL;
+ char *section = NULL;
+ char *option = NULL;
+
+ UCI_HANDLE_ERR(ctx);
+ expand_ptr(ctx, ptr, false);
+ UCI_ASSERT(ctx, ptr->p->has_history);
+
+ /*
+ * - flush unwritten changes
+ * - save the package name
+ * - unload the package
+ * - filter the history
+ * - reload the package
+ */
+ UCI_TRAP_SAVE(ctx, error);
+ UCI_INTERNAL(uci_save, ctx, ptr->p);
+
+ /* NB: need to clone package, section and option names,
+ * as they may get freed on uci_free_package() */
+ package = uci_strdup(ctx, ptr->p->e.name);
+ if (ptr->section)
+ section = uci_strdup(ctx, ptr->section);
+ if (ptr->option)
+ option = uci_strdup(ctx, ptr->option);
+
+ uci_free_package(&ptr->p);
+ uci_filter_history(ctx, package, section, option);
+
+ UCI_INTERNAL(uci_load, ctx, package, &ptr->p);
+ UCI_TRAP_RESTORE(ctx);
+ ctx->err = 0;
+
+error:
+ if (package)
+ free(package);
+ if (section)
+ free(section);
+ if (option)
+ free(option);
+ if (ctx->err)
+ UCI_THROW(ctx, ctx->err);
+ return 0;