coveragespace.cache.Cache.clear()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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