diff mbox series

[2/9] Factorize function to load a dictionary from a file

Message ID 20180906114041.21828-2-sbabic@denx.de
State Accepted
Headers show
Series [1/9] Use provided macro for exit() | expand

Commit Message

Stefano Babic Sept. 6, 2018, 11:40 a.m. UTC
Signed-off-by: Stefano Babic <sbabic@denx.de>
---
 corelib/swupdate_dict.c | 41 +++++++++++++++++++++++++++++++++++++++++
 include/swupdate_dict.h |  1 +
 2 files changed, 42 insertions(+)
diff mbox series

Patch

diff --git a/corelib/swupdate_dict.c b/corelib/swupdate_dict.c
index 11d3cd9..a5f14db 100644
--- a/corelib/swupdate_dict.c
+++ b/corelib/swupdate_dict.c
@@ -170,3 +170,44 @@  void dict_drop_db(struct dict *dictionary)
 		remove_entry(entry);
 	}
 }
+
+int dict_parse_script(struct dict *dictionary, const char *script)
+{
+	FILE *fp = NULL;
+	int ret = 0;
+	char *line = NULL, *key = NULL, *value = NULL;
+	size_t len = 0;
+
+	/* open script generated during sw-description parsing */
+	fp = fopen(script, "rb");
+	if (!fp) {
+		ERROR("Failed to open script file: %s\n", script);
+		ret = -1;
+		goto cleanup;
+	}
+
+	/* load  key-value pairs from script into dictionary */
+
+	while ((getline(&line, &len, fp)) != -1) {
+		key = strtok(line, " \t\n");
+		value = strtok(NULL, "\t\n");
+		if (value != NULL && key != NULL) {
+			ret = dict_set_value(dictionary, key, value);
+			if (ret) {
+				ERROR("Adding pair [%s] = %s into dictionary"
+					"list failed\n", key, value);
+				goto cleanup;
+			}
+		}
+
+		if (value == NULL && key != NULL) {
+			dict_remove(dictionary, key);
+		}
+	}
+
+cleanup:
+	if (fp) fclose(fp);
+	/* free(null) should not harm anything */
+	free(line);
+	return ret;
+}
diff --git a/include/swupdate_dict.h b/include/swupdate_dict.h
index 82988ac..1c988b1 100644
--- a/include/swupdate_dict.h
+++ b/include/swupdate_dict.h
@@ -34,5 +34,6 @@  int dict_set_value(struct dict *dictionary, const char *key, const char *value);
 int dict_insert_value(struct dict *dictionary, const char *key, const char *value);
 void dict_remove(struct dict *dictionary, const char *key);
 void dict_drop_db(struct dict *dictionary);
+int dict_parse_script(struct dict *dictionary, const char *script);
 
 #endif