TemplateService.aliases()   A
last analyzed

Complexity

Conditions 5

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nop 2
dl 0
loc 8
rs 9.3333
c 0
b 0
f 0
1
import log
2
3
from ._base import Service
4
from ..domain import Template, Placeholder
5
6
7
class TemplateService(Service):
8
9
    def __init__(self, template_store, **kwargs):
10
        super().__init__(**kwargs)
11
        self.template_store = template_store
12
13
    def all(self):
14
        """Get all templates."""
15
        templates = self.template_store.filter()
16
        return templates
17
18
    def find(self, key, *, allow_missing=False):
19
        """Find a template with a matching key."""
20
21
        # Find an exact match
22
        key2 = Template.strip(key, keep_special=True)
23
        template = self.template_store.read(key2)
24
        if template:
25
            return template
26
27
        # Else, find an alias match
28
        key2 = Template.strip(key2)
29
        for template in self.all():
30
            if key2 in template.aliases_stripped:
31
                return template
32
33
        # Else, no match
34
        if allow_missing:
35
            return Placeholder(key)
36
37
        raise self.exceptions.TemplateNotFound
38
39
    def aliases(self, query=None):
40
        """Get all aliases with an optional name filter."""
41
        names = []
42
        for template in self.all():
43
            for name in [template.key] + template.aliases:
44
                if query is None or query in name:
45
                    names.append(name)
46
        return names
47
48
    def validate(self):
49
        """Ensure all templates are valid and conflict-free."""
50
        templates = self.all()
51
        keys = {template.key: template for template in templates}
52
        for template in templates:
53
            log.info(f"Checking template '{template}'")
54
            if not template.validate():
55
                return False
56
            for alias in template.aliases:
57
                log.info(f"Checking alias '{alias}' -> '{template.key}'")
58
                if alias not in template.aliases_lowercase:
59
                    msg = "Alias '%s' should be lowercase characters or dashes"
60
                    log.error(msg, alias)
61
                    return False
62
                try:
63
                    existing = keys[alias]
64
                except KeyError:
65
                    keys[alias] = template
66
                else:
67
                    msg = "Alias '%s' already used in template: %s"
68
                    log.error(msg, alias, existing)
69
                    return False
70
        return True
71