62 lines
1.7 KiB
C
62 lines
1.7 KiB
C
#include "tree.h"
|
|
|
|
void snapshot_tree(PathBuffer* tree) {
|
|
PathBuffer* files = path_buffer_new();
|
|
char relative[PATH_MAX] = "";
|
|
char* root = find_root(relative);
|
|
if (!root) {
|
|
perror("ERROR: unable to find root directory of the repository!");
|
|
path_buffer_free(files);
|
|
return;
|
|
}
|
|
|
|
walk(root, relative, relative, files, 1, root);
|
|
path_buffer_sort(files);
|
|
|
|
char tmp[1024];
|
|
size_t offset = 0;
|
|
|
|
offset += snprintf(tmp, sizeof(tmp), "%zu:", files->len);
|
|
|
|
for (size_t idx = 0; idx < files->len; idx++) {
|
|
size_t remaining = sizeof(tmp) - offset;
|
|
|
|
int written = snprintf(tmp + offset, remaining, "%s:", files->items[idx]);
|
|
if (written < 0 || (size_t)written >= remaining) {
|
|
perror("ERROR: buffer overflow in snapshot_tree!\n");
|
|
return;
|
|
}
|
|
|
|
offset += (size_t)written;
|
|
}
|
|
|
|
char hash[41];
|
|
object_hash(TreeObject, tmp, hash);
|
|
|
|
printf("hash: %s\n", hash);
|
|
|
|
char dir_path[PATH_MAX];
|
|
char file_path[PATH_MAX];
|
|
|
|
snprintf(dir_path, sizeof(dir_path), "%s/.merk/objects/%.2s", root, hash);
|
|
mkdir(dir_path, 0755);
|
|
|
|
snprintf(file_path, sizeof(file_path), "%s/%s", dir_path, hash+2);
|
|
|
|
FILE* fp = fopen(file_path, "wb");
|
|
if (!fp) { perror("ERROR: cannot open path in snapshot_tree!\n"); return; }
|
|
|
|
|
|
uLong originalLen = strlen(tmp) + 1;
|
|
|
|
uLong compressedLen = compressBound(originalLen);
|
|
Bytef compressed[compressedLen];
|
|
|
|
if (compress(compressed, &compressedLen, (const Bytef*)tmp, originalLen) != Z_OK) {
|
|
perror("ERROR: compression failed in snapshot_tree!");
|
|
return;
|
|
}
|
|
|
|
fwrite(compressed, sizeof(Bytef), compressedLen, fp);
|
|
fclose(fp);
|
|
}
|