summaryrefslogtreecommitdiffstats
path: root/pykolab/setup/components.py
blob: d13e21a57dc0f3bfe2e1be4c2779e71c6a594c28 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# -*- coding: utf-8 -*-
#
# Copyright 2010-2012 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 or, at your option, any later version
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

import os

import pykolab

from pykolab.constants import *
from pykolab.translate import _

log = pykolab.getLogger('pykolab.setup')
conf = pykolab.getConf()

components = {}
component_groups = {}

def __init__():
    # We only want the base path
    components_base_path = os.path.dirname(__file__)

    for components_path, dirnames, filenames in os.walk(components_base_path):
        if not components_path == components_base_path:
            continue

        for filename in filenames:
            if filename.startswith('setup_') and filename.endswith('.py'):
                module_name = filename.replace('.py','')
                component_name = module_name.replace('setup_', '')
                #print "exec(\"from %s import __init__ as %s_register\"" %(module_name,component_name)
                exec("from %s import __init__ as %s_register" %(module_name,component_name))
                exec("%s_register()" %(component_name))

        for dirname in dirnames:
            register_group(components_path, dirname)

    register('help', list_setup, description=_("Display this help."))

def list_setup(*args, **kw):
    """
        List components
    """

    __components = {}

    for component in components.keys():
        if isinstance(component, tuple):
            component_group, component = component
            __components[component_group] = {
                    component: components[(component_group,component)]
                }
        else:
            __components[component] = components[component]

    _components = __components.keys()
    _components.sort()

    for _component in _components:
        if __components[_component].has_key('function'):
            # This is a top-level component
            if not __components[_component]['description'] == None:
                print "%-25s - %s" %(_component.replace('_','-'),__components[_component]['description'])
            else:
                print "%-25s" %(_component.replace('_','-'))

    for _component in _components:
        if not __components[_component].has_key('function'):
            # This is a nested component
            print "\n" + _("Command Group: %s") %(_component) + "\n"
            ___components = __components[_component].keys()
            ___components.sort()
            for __component in ___components:
                if not __components[_component][__component]['description'] == None:
                    print "%-4s%-21s - %s" %('',__component.replace('_','-'),__components[_component][__component]['description'])
                else:
                    print "%-4s%-21s" %('',__component.replace('_','-'))

def execute(component_name, *args, **kw):
    if not components.has_key(component_name):
        log.error(_("No such component."))
        sys.exit(1)

    if not components[component_name].has_key('function') and \
        not components[component_name].has_key('group'):
        log.error(_("No such component."))
        sys.exit(1)

    if components[component_name].has_key('group'):
        group = components[component_name]['group']
        component_name = components[component_name]['component_name']
        try:
            exec("from %s.cmd_%s import cli_options as %s_%s_cli_options" %(group,component_name,group,component_name))
            exec("%s_%s_cli_options()" %(group,component_name))
        except ImportError, e:
            pass

    else:
        try:
            exec("from cmd_%s import cli_options as %s_cli_options" %(component_name,component_name))
            exec("%s_cli_options()" %(component_name))
        except ImportError, e:
            pass

    conf.finalize_conf()
    _component_name = conf.cli_args.pop(0)
    components[component_name]['function'](conf.cli_args, kw)

def register_group(dirname, module):
    components_base_path = os.path.join(os.path.dirname(__file__), module)

    components[module] = {}

    for components_path, dirnames, filenames in os.walk(components_base_path):
        if not components_path == components_base_path:
            continue

        for filename in filenames:
            if filename.startswith('cmd_') and filename.endswith('.py'):
                module_name = filename.replace('.py','')
                component_name = module_name.replace('cmd_', '')
                #print "exec(\"from %s.%s import __init__ as %s_%s_register\"" %(module,module_name,module,component_name)
                exec("from %s.%s import __init__ as %s_%s_register" %(module,module_name,module,component_name))
                exec("%s_%s_register()" %(module,component_name))

def register(component_name, func, group=None, description=None, aliases=[]):
    if not group == None:
        component = "%s_%s" %(group,component_name)
    else:
        component = component_name

    if isinstance(aliases, basestring):
        aliases = [aliases]

    if components.has_key(component):
        log.fatal(_("Command '%s' already registered") %(component))
        sys.exit(1)

    if callable(func):
        if group == None:
            components[component_name] = {
                    'function': func,
                    'description': description
                }
        else:
            components[group][component_name] = {
                    'function': func,
                    'description': description
                }

            components[component] = components[group][component_name]
            components[component]['group'] = group
            components[component]['component_name'] = component_name

        for alias in aliases:
            components[alias] = {
                    'function': func,
                    'description': _("Alias for %s") %(component_name)
                }

##
## Commands not yet implemented
##

def not_yet_implemented(*args, **kw):
    print _("Not yet implemented")
    sys.exit(1)