commit 307c942

default  ·  2023-02-23 09:42:09 +0000 UTC
parent 4eec215
New function index_gc().
2 files changed,  +43, -0
M data.c
M snac.h
M data.c
+42, -0
 1@@ -285,6 +285,48 @@ int index_add(const char *fn, const char *id)
 2 }
 3 
 4 
 5+int index_gc(const char *fn)
 6+/* garbage-collects an index, deleting objects that are not here */
 7+{
 8+    FILE *i, *o;
 9+    int gc = -1;
10+
11+    pthread_mutex_lock(&data_mutex);
12+
13+    if ((i = fopen(fn, "r")) != NULL) {
14+        xs *nfn = xs_fmt("%s.new", fn);
15+        char line[256];
16+
17+        if ((o = fopen(nfn, "w")) != NULL) {
18+            gc = 0;
19+
20+            while (fgets(line, sizeof(line), i) != NULL) {
21+                line[32] = '\0';
22+
23+                if (object_here_by_md5(line))
24+                    fprintf(o, "%s\n", line);
25+                else
26+                    gc++;
27+            }
28+
29+            fclose(o);
30+
31+            xs *ofn = xs_fmt("%s.bak", fn);
32+
33+            unlink(ofn);
34+            link(fn, ofn);
35+            rename(nfn, fn);
36+        }
37+
38+        fclose(i);
39+    }
40+
41+    pthread_mutex_unlock(&data_mutex);
42+
43+    return gc;
44+}
45+
46+
47 int index_del_md5(const char *fn, const char *md5)
48 /* deletes an md5 from an index */
49 {
M snac.h
+1, -0
1@@ -60,6 +60,7 @@ double mtime_nl(const char *fn, int *n_link);
2 #define mtime(fn) mtime_nl(fn, NULL)
3 
4 int index_add(const char *fn, const char *md5);
5+int index_gc(const char *fn);
6 int index_del(const char *fn, const char *md5);
7 int index_first(const char *fn, char *buf, int size);
8 int index_len(const char *fn);