Passed
Push — develop ( e76d2d...088138 )
by Jace
01:20
created

coveragespace.cache.Cache.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
crap 1
1 1
import logging
2 1
import os
3 1
import pickle
4
5
6 1
log = logging.getLogger(__name__)
7
8
9 1
class Cache(object):
10
11 1
    PATH = os.path.join('.cache', 'coveragespace')
12
13 1
    def __init__(self):
14 1
        self._data = {}
15 1
        self._load()
16
17 1
    def _load(self):
18 1
        try:
19 1
            with open(self.PATH, 'rb') as fin:
20 1
                text = fin.read()
21 1
        except IOError:
22 1
            text = None
23
24 1
        try:
25 1
            data = pickle.loads(text)
26 1
        except (TypeError, KeyError, IndexError):
27 1
            data = None
28
29 1
        if isinstance(data, dict):
30 1
            self._data = data
31
32 1
    def _store(self):
33 1
        directory = os.path.dirname(self.PATH)
34 1
        if not os.path.exists(directory):
35 1
            os.makedirs(directory)
36
37 1
        text = pickle.dumps(self._data)
38 1
        with open(self.PATH, 'wb') as fout:
39 1
            fout.write(text)
40
41 1
    def set(self, key, value):
42 1
        try:
43 1
            url, data = key
44 1
        except ValueError:
45 1
            log.debug("Setting cache for %s", key)
46
        else:
47 1
            log.debug("Setting cache for %s: %s", url, data)
48 1
            key = self._slugify(*key)
49 1
        self._data[key] = value
50 1
        log.debug("Cached value: %s", value)
51 1
        self._store()
52
53 1
    def get(self, key, default=None):
54 1
        try:
55 1
            url, data = key
56 1
        except ValueError:
57 1
            log.debug("Getting cache for %s", key)
58
        else:
59 1
            log.debug("Getting cache for %s: %s", url, data)
60 1
            key = self._slugify(*key)
61 1
        value = self._data.get(key, default)
62 1
        log.debug("Cached value: %s", value)
63 1
        return value
64
65 1
    @staticmethod
66
    def _slugify(url, data):
67
        return (url, hash(frozenset(data.items())))
68