summaryrefslogtreecommitdiffstats
path: root/src/util.c
blob: 91954ddddb18a0f3b0d68d424a15fc924779e833 (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include "util.h"

void statistics(DB *db) {
    DB_BTREE_STAT *statp;
    int ret;

    assert(db);
    
     if ((ret = db->stat(db, &statp, 0)) != 0) {
        db->err(db, ret, "DB->stat");
        return;
    }
    
    printf("Database contains %lu records\n", (long unsigned) statp->bt_ndata);
    free(statp);
}

char* normalize_path(char *s) {
    char *l, *p, *d;

    // deletes /./ and //

    if (*s == '/')
        l = p = d = s+1;
    else
        l = p = d = s;
    
    for (; *p; p++) {
        if (*p == '/') {

            if (l-p == 0) {
                l++;
                continue;
            }

            if (p-l == 1 && *l == '.') {
                l += 2;
                continue;
            }

            while (l <= p)
                *(d++) = *(l++);
        }
    }

    while (l <= p)
        *(d++) = *(l++);

    return s;
}

void rotdash(void) {
    static const char dashes[] = /* ".oOo"; */ "|/-\\";
    const static char *d = dashes;

    if (isatty(fileno(stderr))) {
        fprintf(stderr, "%c\b", *d);
        
        d++;
        if (!*d)
            d = dashes;
    }
}

const char* get_attached_filename(const char *path, const char *fn) {
    static char npath[PATH_MAX];
    struct stat st;

    if (stat(path, &st) < 0) {
        if (errno == ENOENT)
            return path;
        
        fprintf(stderr, "stat(%s) failed: %s\n", path, strerror(errno));
        return NULL;
    }

    if (S_ISREG(st.st_mode))
        return path;

    if (S_ISDIR(st.st_mode)) {
        snprintf(npath, sizeof(npath), "%s/.syrep", path);
        mkdir(npath, 0777);
        snprintf(npath, sizeof(npath), "%s/.syrep/%s", path, fn);
        return npath;
    }

    fprintf(stderr, "<%s> is not a valid syrep snapshot\n", path);
    return NULL;
}

int isdirectory(const char *path) {
    struct stat st;

    if (stat(path, &st) < 0)
        return -1;

    return !!S_ISDIR(st.st_mode);
}