diff options
author | mrb0nk500 <b0nk@b0nk.xyz> | 2022-07-26 17:46:54 -0300 |
---|---|---|
committer | mrb0nk500 <b0nk@b0nk.xyz> | 2022-07-26 17:46:54 -0300 |
commit | 45b91d6057fc67db1491d301cf44f4f93764c783 (patch) | |
tree | 4649e17b0d569136e48ec20cc9c91a8026218e31 /index.c | |
parent | 6fec7170544009fe3ce95b0d2b7e6ab65c97922d (diff) |
git, index: Move index related functions to `index.{c,h}`
Diffstat (limited to 'index.c')
-rw-r--r-- | index.c | 70 |
1 files changed, 70 insertions, 0 deletions
@@ -0,0 +1,70 @@ +#include <stddef.h> +#include <stdint.h> +#include <stdlib.h> +#include "index.h" +#include "macros.h" + +int is_valid_index(index *idx) { + int did_alloc = 0; + char *err_str = NULL; + + /* Is the index NULL? */ + if (idx == NULL) { + err_str = "Index is NULL."; + /* Is the index type invalid? */ + } else if (idx->type > 1) { + did_alloc = 1; + err_str = calloc(format_len("Invalid index type: %u.", idx->type)+1, sizeof(char)); + sprintf(err_str, "Invalid index type: %u.", idx->type); + /* Is this named index empty? */ + } else if (idx->type == 0 && is_empty(idx->name)) { + err_str = "Named index is empty."; + } + + /* Did we get an error? */ + if (err_str != NULL) { + log_reason(LOG_ERR, "Invalid index.", reason); + if (did_alloc) { + free(err_str); + } + /* Invalid index, return false. */ + return 0; + /* Is there another index after this one? */ + } else if (idx->next != NULL) { + /* Return the validity of the next index. */ + return is_valid_index(idx->next); + } + /* Valid index, return true. */ + return 1; +} + +char *make_index_path(const char *root, index *idx, int path_type) { + char *path; + char *tmp; + int path_len = strlen(root) + 1; + /* Is the index invalid? */ + if (!is_valid_index(idx)) { + return NULL; + } + + /* Get the length of the path. */ + for (index *i = idx; i != NULL; i = i->next) { + const int is_last = (i->next == NULL); + const char *fmt = (i->type) "%llu" : "%s"; + path_len += format_len(fmt, (i->type) ? i->num : i->name) + !is_last; + } + + path = calloc(path_len+1, sizeof(char)); + tmp = path; + + /* Create the path. */ + tmp += sprintf(tmp, "%s/", root); + for (index *i = idx; i != NULL; i = i->next) { + const int is_last = (i->next == NULL); + const char *delm = (path_type) ? "-" : "/"; + const char *fmt = (i->type) "%llu%s" : "%s%s"; + tmp += sprintf(tmp, fmt, (i->type) ? i->num : i->name, (!is_last) ? delm : ""); + } + + return path; +} |