Completed
Push — develop ( f1f88a...e832cb )
by Jace
02:39
created

_ensure_mapped()   B

Complexity

Conditions 5

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5
Metric Value
dl 0
loc 12
rs 8.5454
cc 5
ccs 9
cts 9
cp 1
crap 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A _instantiate() 0 8 3
1
"""Functions to interact with mapped classes and instances."""
2
3 1
import inspect
4 1
import logging
5 1
import warnings
6
7 1
from . import common, exceptions
8
9 1
log = logging.getLogger(__name__)
10
11
12 1
def create(class_or_instance, *args, overwrite=False):
13
    """Create a new mapped object."""
14 1
    instance = _instantiate(class_or_instance, *args)
15 1
    mapper = common.get_mapper(instance, expected=True)
16
17 1
    if mapper.auto_create:
18
        msg = "'create' is called automatically with 'auto_create' enabled"
19
        warnings.warn(msg)
20
21 1
    if mapper.exists and not overwrite:
22 1
        msg = "{!r} already exists".format(mapper.path)
23 1
        raise exceptions.DuplicateMappingError(msg)
24
25 1
    return save(instance)
26
27
28 1
def find(class_or_instance, *args, create=False):  # pylint: disable=redefined-outer-name
29
    """Find a matching mapped object or return None."""
30 1
    instance = _instantiate(class_or_instance, *args)
31 1
    mapper = common.get_mapper(instance, expected=True)
32
33 1
    if mapper.exists:
34 1
        return instance
35 1
    elif create:
36 1
        return save(instance)
37
    else:
38 1
        return None
39
40
41 1
def find_all(cls, **kwargs):
42
    """Return a list of all matching mapped objects."""
43 1
    log.debug((cls, kwargs))
44 1
    raise NotImplementedError
45
46
47 1
def load(instance):
48
    """Force the loading of a mapped object's file."""
49 1
    mapper = common.get_mapper(instance, expected=True)
50
51 1
    warnings.warn("'load' is called automatically")
52
53 1
    mapper.load()
54
55 1
    return instance
56
57
58 1
def save(instance):
59
    """Save a mapped object to file."""
60 1
    mapper = common.get_mapper(instance, expected=True)
61
62 1
    if mapper.auto_save:
63 1
        msg = "'save' is called automatically with 'auto_save' enabled"
64 1
        warnings.warn(msg)
65
66 1
    if mapper.deleted:
67 1
        msg = "{!r} was deleted".format(mapper.path)
68 1
        raise exceptions.DeletedFileError(msg)
69
70 1
    if not mapper.exists:
71 1
        mapper.create()
72
73 1
    mapper.save()
74
75 1
    return instance
76
77
78 1
def delete(instance):
79
    """Delete a mapped object's file."""
80 1
    mapper = common.get_mapper(instance, expected=True)
81
82 1
    mapper.delete()
83
84 1
    return None
85
86
87 1
def _instantiate(class_or_instance, *args):
88 1
    if inspect.isclass(class_or_instance):
89 1
        instance = class_or_instance(*args)
90
    else:
91 1
        assert not args
92 1
        instance = class_or_instance
93
94
    return instance
95