Factor out code for reading metadata.json

This commit is contained in:
Eric Fischer
2017-11-30 15:49:38 -08:00
parent 1acd771743
commit d7f44ab082
6 changed files with 131 additions and 188 deletions
+2 -50
View File
@@ -143,55 +143,6 @@ void handle(std::string message, int z, unsigned x, unsigned y, int describe, st
}
}
sqlite3 *meta2tmp(const char *fname, std::vector<zxy> &tiles) {
sqlite3 *db;
char *err = NULL;
if (sqlite3_open("", &db) != SQLITE_OK) {
fprintf(stderr, "Temporary db: %s\n", sqlite3_errmsg(db));
exit(EXIT_FAILURE);
}
if (sqlite3_exec(db, "CREATE TABLE metadata (name text, value text);", NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "Create metadata table: %s\n", err);
exit(EXIT_FAILURE);
}
std::string name = fname;
name += "/metadata.json";
FILE *f = fopen(name.c_str(), "r");
if (f == NULL) {
perror(name.c_str());
exit(EXIT_FAILURE);
}
json_pull *jp = json_begin_file(f);
json_object *o = json_read_tree(jp);
if (o->type != JSON_HASH) {
fprintf(stderr, "%s: bad metadata format\n", name.c_str());
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < o->length; i++) {
if (o->keys[i]->type != JSON_STRING || o->values[i]->type != JSON_STRING) {
fprintf(stderr, "%s: non-string in metadata\n", name.c_str());
}
char *sql = sqlite3_mprintf("INSERT INTO metadata (name, value) VALUES (%Q, %Q);", o->keys[i]->string, o->values[i]->string);
if (sqlite3_exec(db, sql, NULL, NULL, &err) != SQLITE_OK) {
fprintf(stderr, "set %s in metadata: %s\n", o->keys[i]->string, err);
}
sqlite3_free(sql);
}
json_end(jp);
fclose(f);
tiles = enumerate_dirtiles(fname);
return db;
}
void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) {
sqlite3 *db = NULL;
bool isdir = false;
@@ -235,7 +186,8 @@ void decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> co
if (stat(fname, &st) == 0 && (st.st_mode & S_IFDIR) != 0) {
isdir = true;
db = meta2tmp(fname, tiles);
db = dirmeta2tmp(fname);
tiles = enumerate_dirtiles(fname);
} else {
if (sqlite3_open(fname, &db) != SQLITE_OK) {
fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db));