From 8c4e6aa594adde9a9c34d6b69495eec0d45971d9 Mon Sep 17 00:00:00 2001 From: Jordan Bancino Date: Wed, 1 Mar 2023 19:33:25 +0000 Subject: [PATCH] Implement DbList() --- TODO.txt | 2 +- src/Db.c | 47 ++++++++++++++++++++++++++++++++++++++++++++--- src/include/Db.h | 3 +++ 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/TODO.txt b/TODO.txt index 5cc50a9..581b0bb 100644 --- a/TODO.txt +++ b/TODO.txt @@ -16,7 +16,7 @@ Milestone: v0.2.0 [~] Db API [x] If object is in cache, but doesn't exist on disk, delete from cache [ ] Allow cache to be totally disabled (no MIN_CACHE_SIZE) - [ ] List keys under a path (DbList() using POSIX opendir()) + [x] List keys under a path (DbList() using POSIX opendir()) [~] User login [x] User manipulation functions (so we don't use the DB directly) [x] Refresh tokens diff --git a/src/Db.c b/src/Db.c index 28f9a3f..1168f67 100644 --- a/src/Db.c +++ b/src/Db.c @@ -28,6 +28,9 @@ #include #include +#include +#include + #include #include #include @@ -214,12 +217,12 @@ DbHashKey(Array * args) } static char * -DbDirName(Db * db, Array * args) +DbDirName(Db * db, Array * args, size_t strip) { size_t i; char *str = StrConcat(2, db->dir, "/"); - for (i = 0; i < ArraySize(args) - 1; i++) + for (i = 0; i < ArraySize(args) - strip; i++) { char *tmp; @@ -597,7 +600,7 @@ DbCreate(Db * db, size_t nArgs,...) return NULL; } - dir = DbDirName(db, args); + dir = DbDirName(db, args, 1); if (UtilMkdir(dir, 0750) < 0) { Free(file); @@ -798,6 +801,11 @@ Array * DbList(Db * db, size_t nArgs,...) { Array *result; + Array *path; + DIR* files; + struct dirent* file; + char* dir; + va_list ap; if (!db || !nArgs) { @@ -810,9 +818,42 @@ DbList(Db * db, size_t nArgs,...) return NULL; } + va_start(ap, nArgs); + path = ArrayFromVarArgs(nArgs, ap); + dir = DbDirName(db, path, 0); + + files = opendir(dir); + if (!files) + { + ArrayFree(path); + Free(dir); + return NULL; + } + while((file = readdir(files))) { + if (file->d_type == DT_REG && file->d_namlen > 5) + { + int nameOffset = file->d_namlen - 5; + if (strcmp(file->d_name + nameOffset, ".json") == 0) + { + file->d_name[nameOffset] = '\0'; + ArrayAdd(result, StrDuplicate(file->d_name)); + } + } + } + closedir(files); + + ArrayFree(path); + Free(dir); + return result; } +void +DbListFree(Array *arr) +{ + StringArrayFree(arr); +} + HashMap * DbJson(DbRef * ref) { diff --git a/src/include/Db.h b/src/include/Db.h index 6934263..4be8b07 100644 --- a/src/include/Db.h +++ b/src/include/Db.h @@ -60,6 +60,9 @@ extern int extern Array * DbList(Db *, size_t,...); +extern void +DbListFree(Array *); + extern HashMap * DbJson(DbRef *);