Completed
Push — develop ( b1df34...10b422 )
by Jace
8s
created

_check_base()   B

Complexity

Conditions 5

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 8.5454
cc 5
crap 5
1
"""Functions to interact with mapped classes and instances."""
2
3 1
from . import common, exceptions
4
5 1
log = common.logger(__name__)
6
7
8 1
def new(cls, *args):
9
    """Create a new mapped object."""
10 1
    instance = cls(*args)
11 1
    mapper = _ensure_mapped(instance)
12
13 1
    if mapper.exists:
14 1
        msg = "{!r} already exists".format(mapper.path)
15 1
        raise exceptions.DuplicateMappingError(msg)
16
17 1
    return save(instance)
18
19
20 1
def find(cls, *args, create=False):
21
    """Find a matching mapped object or return None."""
22 1
    instance = cls(*args)
23 1
    mapper = _ensure_mapped(instance)
24
25 1
    if mapper.exists:
26 1
        return instance
27 1
    elif create:
28 1
        return save(instance)
29
    else:
30 1
        return None
31
32
33 1
def load(cls, **kwargs):
34
    """Return a list of all matching mapped objects."""
35 1
    log.debug((cls, kwargs))
36 1
    raise NotImplementedError
37
38
39 1
def save(instance):
40
    """Save a mapped object to file."""
41 1
    mapper = _ensure_mapped(instance)
42
43 1
    if mapper.deleted:
44 1
        msg = "{!r} was deleted".format(mapper.path)
45 1
        raise exceptions.DeletedFileError(msg)
46
47 1
    if not mapper.exists:
48 1
        mapper.create()
49
50 1
    mapper.store()
51
52 1
    return instance
53
54
55 1
def delete(instance):
56
    """Delete a mapped object's file."""
57 1
    mapper = _ensure_mapped(instance)
58
59 1
    mapper.delete()
60
61 1
    return None
62
63
64 1
def _ensure_mapped(obj, *, expected=True):
65 1
    mapper = common.get_mapper(obj)
66
67 1
    if mapper and not expected:
68 1
        msg = "{!r} is already mapped".format(obj)
69 1
        raise TypeError(msg)
70
71 1
    if not mapper and expected:
72 1
        msg = "{!r} is not mapped".format(obj)
73 1
        raise TypeError(msg)
74
75
    return mapper
76