aboutsummaryrefslogtreecommitdiff
path: root/importer/main.c
blob: 087fc48ae3baeae869ddd9d6631cfa5c17fc7b93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "../lib/util.h"
#include "../lib/data.h"

int run(const char *db, const char *txt);

int main(int argc, char** argv)
{
    int opt;
    char* txt = NULL;
    char* db = NULL;

    while ((opt = getopt(argc, argv, "t:d:h")) != -1) {
        switch(opt) {
        case 't':
            txt = copy_achar(optarg);
            break;
        case 'd':
            db = copy_achar(optarg);
            break;
        case 'h':
        // fall through
        default:
            printf("Usage: %s", argv[0]);
            goto end;
        }
    }

    int r = run(db, txt);

end:
    if (txt != NULL)
        free(txt);
    if (db != NULL)
        free(db);

    return r;
}

int run(const char *db, const char *txt)
{
    char * line = NULL;
    size_t len = 0;
    int count = 0;
    ssize_t read;
    Data *data;
    FILE *f;
    int total;

    printf("\33[?25l"); // hide cursor

    data = new_data(":memory:");
    f = fopen(txt, "r");

    bootstrap(data);

    total = count_file_lines(f);
    fseek(f, 0, SEEK_SET);

    while ((read = getline(&line, &len, f)) != -1) {
        if (line[0] == '#' || line[0] == '\n')
            continue;

        insert(data, line, read-1);
        count++;

        float t = ((float)count/(float)total)*100;
        printf("\rLoading data [%03.0f%%] %d/%d", t, count, total);
    }

    float t = ((float)count/(float)total)*100;
    printf("\rLoading data [%03.0f%%] %d/%d", t, count, total);
    int r = load_or_save_db(data->db, db, 1);

    printf("\rDONE!");
    printf("\33[?25h"); // reenable cursor

    return r;
}