Fix some memory/fd leaks for tag searching and empty account listing
[blerg.git] / tools / blergtool.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include "database.h"
4 #include "tags.h"
5
6 void help() {
7         printf("Usage: blergtool <store|fetch> <storename> [record]\n");
8 }
9
10 int main(int argc, char *argv[]) {
11         if (argc < 2) {
12                 help();
13                 exit(1);
14         }
15
16         if (strncmp(argv[1], "store", 5) == 0) {
17                 char *store = argv[2];
18                 struct blerg *f = blerg_open(store);
19                 if (!f) {
20                         printf("Blerg open failed\n");
21                         exit(1);
22                 }
23
24                 size_t bytes_read = 0;
25                 char *data = malloc(65536);
26                 do {
27                         bytes_read += fread(data + bytes_read, 1, 65536 - bytes_read, stdin);
28                 } while (bytes_read < 65536 && !feof(stdin));
29                 int record = blerg_store(f, data, bytes_read);
30                 blerg_close(f);
31                 free(data);
32
33                 if (record < 0) {
34                         fprintf(stderr, "Could not store\n");
35                         exit(1);
36                 } else {
37                         fprintf(stderr, "Stored record %d\n", record);
38                 }
39         } else if (strncmp(argv[1], "fetch", 5) == 0) {
40                 char *store = argv[2];
41                 int record = atoi(argv[3]);
42                 struct blerg *f = blerg_open(store);
43                 if (!f) {
44                         printf("Blerg open failed\n");
45                         exit(1);
46                 }
47
48                 char *data;
49                 int size;
50                 blerg_fetch(f, record, &data, &size);
51                 blerg_close(f);
52                 fwrite(data, 1, size, stdout);
53                 free(data);
54         } else if (strncmp(argv[1], "list", 4) == 0) {
55                 char *tag = argv[2];
56                 uint64_t count = 50;
57                 struct tag *list = tag_list(tag, 0, &count, -1);
58                 if (list == NULL) {
59                         printf("No entries");
60                 } else {
61                         int i;
62                         for (i = 0; i < count; i++) {
63                                 printf("%s %d\n", list[i].author, list[i].record);
64                         }
65                         free(list);
66                 }
67         } else {
68                 help();
69         }
70
71         return 0;
72 }