forked from quantifiedcode/quantifiedcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.py
More file actions
73 lines (59 loc) · 2.61 KB
/
hooks.py
File metadata and controls
73 lines (59 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# -*- coding: utf-8 -*-
"""
Contains functions to call hooks provided by plugins.
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import logging
from collections import defaultdict
LOGGER = logging.getLogger(__name__)
class Hooks(object):
def __init__(self):
self.hooks = defaultdict(lambda: defaultdict(list))
def register(self, source, name, hook):
""" Registers a new hook for the given source with the given hook name.
:param source: source of the hook, i.e. plugin name
:param name: name of the hook
:param hook: hook function
"""
LOGGER.debug("Registering new hook for {}: {} {}".format(source, name, hook))
if not hook in self.hooks[name][source]:
self.hooks[name][source].append(hook)
else:
LOGGER.debug("Hook already registered, skipping...")
def call(self, source, name, *args, **kwargs):
""" Calls all hooks under the given hook name belonging to the given source.
:param source: source of the hook
:param name: name of the hooks to execute
:param args: arguments passed to the hook function
:param kwargs: keyword arguments passed to the hook function
"""
for hook in self.hooks[name][source]:
hook(*args, **kwargs)
def call_all(self, name, *args, **kwargs):
""" Calls all hooks under the given hook name.
:param name: name of the hooks to execute
:param args: arguments passed to the hook function
:param kwargs: keyword arguments passed to the hook function
"""
for source in self.hooks[name]:
self.call(source, name, *args, **kwargs)
def call_async(self, source, name, *args, **kwargs):
""" Calls all hooks under the given hook name belonging to the given source.
The hooks MUST be celery tasks.
:param source: source of the hook
:param name: name of the hooks to execute
:param args: arguments passed to the hook function
:param kwargs: keyword arguments passed to the hook function
"""
kwargs['delay'] = True
self.call(source, name, *args, **kwargs)
def call_all_async(self, name, *args, **kwargs):
""" Calls all hooks under the given hook name.
:param name: name of the hooks to execute
:param args: arguments passed to the hook function
:param kwargs: keyword arguments passed to the hook function
"""
for source in self.hooks[name]:
self.call_async(source, name, *args, **kwargs)