~robru/friends/early-dbus-interface

« back to all changes in this revision

Viewing changes to friends/utils/manager.py

  • Committer: Ken VanDine
  • Date: 2012-10-13 01:27:15 UTC
  • Revision ID: ken.vandine@canonical.com-20121013012715-gxfoi1oo30wdm8dv
initial import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# friends-service -- send & receive messages from any social network
 
2
# Copyright (C) 2012  Canonical Ltd
 
3
#
 
4
# This program is free software: you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation, version 3 of the License.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
15
 
 
16
"""Protocol base class and manager."""
 
17
 
 
18
 
 
19
__all__ = [
 
20
    'ProtocolManager',
 
21
    'protocol_manager',
 
22
    ]
 
23
 
 
24
 
 
25
import os
 
26
import importlib
 
27
 
 
28
from pkg_resources import resource_listdir
 
29
 
 
30
from friends.utils.base import Base
 
31
 
 
32
 
 
33
class ProtocolManager:
 
34
    """Discover all protocol classes."""
 
35
 
 
36
    def __init__(self):
 
37
        self.protocols = dict((cls.__name__.lower(), cls)
 
38
                              for cls in self._protocol_classes)
 
39
 
 
40
    @property
 
41
    def _protocol_classes(self):
 
42
        """Search for and return all protocol classes."""
 
43
        for filename in resource_listdir('friends', 'protocols'):
 
44
            basename, extension = os.path.splitext(filename)
 
45
            if extension != '.py':
 
46
                continue
 
47
            module_path = 'friends.protocols.' + basename
 
48
            module = importlib.import_module(module_path)
 
49
            # Scan all the objects in the module's __all__ and add any which
 
50
            # are subclasses of the base protocol class.  Essentially skip any
 
51
            # modules that don't have an __all__ (e.g. the __init__.py).
 
52
            # However, the module better not lie about its __all__ members.
 
53
            for name in getattr(module, '__all__', []):
 
54
                obj = getattr(module, name)
 
55
                if issubclass(obj, Base):
 
56
                    yield obj
 
57
 
 
58
 
 
59
protocol_manager = ProtocolManager()