66 lines
1.5 KiB
C
66 lines
1.5 KiB
C
|
|
#include "cache.h"
|
||
|
|
|
||
|
|
#include <stdio.h>
|
||
|
|
#include <string.h>
|
||
|
|
#include <errno.h>
|
||
|
|
|
||
|
|
/* Name of the dotfile kept inside each cloned repo. */
|
||
|
|
#define CACHE_FILENAME ".gbuild_cache"
|
||
|
|
|
||
|
|
/* ----------------------------------------------------------------- helpers */
|
||
|
|
|
||
|
|
static void cache_path(char *out, size_t n, const char *repo_path)
|
||
|
|
{
|
||
|
|
snprintf(out, n, "%s/" CACHE_FILENAME, repo_path);
|
||
|
|
}
|
||
|
|
|
||
|
|
/* ----------------------------------------------------------------- public API */
|
||
|
|
|
||
|
|
int cache_read(const char *repo_path, char *out, size_t n)
|
||
|
|
{
|
||
|
|
char path[1024];
|
||
|
|
cache_path(path, sizeof(path), repo_path);
|
||
|
|
|
||
|
|
out[0] = '\0';
|
||
|
|
|
||
|
|
FILE *f = fopen(path, "r");
|
||
|
|
if (!f)
|
||
|
|
return -1; /* file doesn't exist yet — not an error, just a cache miss */
|
||
|
|
|
||
|
|
char buf[CACHE_HASH_LEN] = {0};
|
||
|
|
int ok = (fgets(buf, sizeof(buf), f) != NULL);
|
||
|
|
fclose(f);
|
||
|
|
|
||
|
|
if (!ok || buf[0] == '\0')
|
||
|
|
return -1;
|
||
|
|
|
||
|
|
/* strip trailing newline */
|
||
|
|
size_t l = strlen(buf);
|
||
|
|
if (l > 0 && buf[l - 1] == '\n')
|
||
|
|
buf[--l] = '\0';
|
||
|
|
|
||
|
|
if (l == 0)
|
||
|
|
return -1;
|
||
|
|
|
||
|
|
strncpy(out, buf, n - 1);
|
||
|
|
out[n - 1] = '\0';
|
||
|
|
return 0;
|
||
|
|
}
|
||
|
|
|
||
|
|
int cache_write(const char *repo_path, const char *hash)
|
||
|
|
{
|
||
|
|
char path[1024];
|
||
|
|
cache_path(path, sizeof(path), repo_path);
|
||
|
|
|
||
|
|
FILE *f = fopen(path, "w");
|
||
|
|
if (!f) {
|
||
|
|
fprintf(stderr, "[WARN ] cache_write: cannot open %s: %s\n",
|
||
|
|
path, strerror(errno));
|
||
|
|
return -1;
|
||
|
|
}
|
||
|
|
|
||
|
|
fprintf(f, "%s\n", hash);
|
||
|
|
fclose(f);
|
||
|
|
return 0;
|
||
|
|
}
|