~saviq/elisa/subtitle_chardet

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
import sys
import os
import shutil
import glob
from optparse import OptionParser

sys.path.insert(0, os.path.abspath('elisa-plugins'))
sys.path.insert(0, os.path.abspath('elisa-core'))

import pkg_resources
from elisa.core import plugin_registry
from elisa.core.config import Config

def find_plugins():
    registry = plugin_registry.PluginRegistry(Config(), ['elisa-plugins',])
    registry.load_plugins()

    dists = dict([(name, status) for (name, status) in registry.get_plugins()
                  if name.startswith('elisa')])

    dist_names = dists.keys()
    return dist_names

def run_setup(path, distutils_command_name):
    cwd = os.getcwd()

    basename = os.path.basename(path)
    if basename != 'elisa-core':
        plugin_name = basename
    else:
        plugin_name = None

    print 'Executing %s %s' % (path, distutils_command_name)
    # go in plugin directory, execute setup.py and move the egg to our dist directory
    os.chdir(path)
    env = os.environ
    env.update({'PYTHONPATH': os.path.pathsep.join(sys.path)})
    os.spawnle(os.P_WAIT, sys.executable, sys.executable, 'setup.py',
               distutils_command_name, env)
    shutil.rmtree('build', ignore_errors=True)
    if plugin_name:
        shutil.rmtree('elisa_plugin_%s.egg-info' % plugin_name, ignore_errors=True)
    if distutils_command_name.startswith('bdist') or \
           distutils_command_name.startswith('sdist'):
        egg_name = os.listdir('dist')[0]
        egg_path = os.path.join('dist', egg_name)
        # we want egg file names without the python version
        egg_name_without_python_version = egg_name[:egg_name.index('-py')]+'.egg'
        shutil.copyfile(egg_path, os.path.join(cwd, 'dist', egg_name_without_python_version))
        shutil.rmtree('dist', ignore_errors=True)
    os.chdir(cwd)


def execute_plugin_setup(plugin_name, distutils_command_name=None):
    distutils_command_name = distutils_command_name or 'bdist_egg'
    path = os.path.join('elisa-plugins', 'elisa', 'plugins', plugin_name)
    run_setup(path, distutils_command_name)

def execute_elisa_setup(distutils_command_name=None):
    distutils_command_name = distutils_command_name or 'bdist_egg'
    run_setup('elisa-core', distutils_command_name)

def list_all(output=False):
    available = ['elisa',]
    available.extend(find_plugins())

    if output:
        print 'Available to build:'
        print '  %s' % ' '.join(available)

    return available

def assert_build_results(to_build, distutils_command_name):
    if distutils_command_name == 'bdist_egg':
        dist_contents = os.listdir('dist')
        for dist in to_build:
            egg_file = "%s.egg" % dist.egg_name()
            if egg_file not in dist_contents:
                raise AssertionError, "Egg not found for plugin %r" % dist
    elif distutils_command_name == 'build_po':
        for dist in to_build:
            plugin_name = dist.project_name[13:].replace('-', '_')
            plugin_path = os.path.join('elisa-plugins', 'elisa', 'plugins', plugin_name)
            i18n_path = os.path.join(plugin_path, 'i18n')
            po_files = glob.glob(os.path.join(i18n_path, '*.po'))
            mo_files = glob.glob(os.path.join(i18n_path, '*', 'LC_MESSAGES', '*.mo'))

            if not len(po_files) == len(mo_files):
                raise AssertionError, ".mo files not compiled for %r" % plugin_name

    print "Build results are fine. Congratulations."

def main(args):
    parser = OptionParser()
    parser.add_option("-c", "--command", dest="distutils_command_name",
                      default='bdist_egg',
                      help="run distutils command COMMAND", metavar="COMMAND")
    parser.add_option("-l", "--list",
                      action="store_true", dest="list_plugins", default=False,
                      help="list available plugins")
    parser.add_option("-t", "--test",
                      action="store_true", dest="test_build_result", default=False,
                      help="check the files produced exist")

    (options, args) = parser.parse_args(args=args)

    if options.list_plugins:
        list_all(True)
        return 0

    if args:
        to_build = args
    else:
        to_build = list_all()

    distutils_command_name = options.distutils_command_name

    dists = []
    for name in to_build:
        try:
            d = pkg_resources.require(name)[0]
        except Exception, exc:
            print 'Not building %r: %r' % (name, exc)
            continue
        dists.append(d)
    to_build = dists

    shutil.rmtree('build', ignore_errors=True)


    plugins_dir = "dist"
    if os.path.isfile(plugins_dir):
        os.unlink(plugins_dir)
    if not os.path.exists(plugins_dir):
        os.makedirs(plugins_dir)

    if 'elisa' in [d.project_name for d in to_build]:
        execute_elisa_setup(distutils_command_name)

    errors = []
    plugin_eggs = []
    built = []
    for dist in to_build:
        plugin_name = dist.project_name
        if plugin_name == 'elisa':
            continue

        plugin_name = plugin_name[13:].replace('-', '_')
        if plugin_name[1:] in ('good', 'bad', 'ugly'):
            continue
        plugin_path = os.path.join(dist.location, 'elisa', 'plugins', plugin_name)

        try:
            execute_plugin_setup(plugin_name, distutils_command_name)
        except Exception, error:
            errors.append((plugin_name,error))
            continue
        else:
            built.append(dist)

    if errors:
        print errors

    if options.test_build_result:
        assert_build_results(built, distutils_command_name)

    return plugin_eggs

if __name__ == '__main__':
    main(sys.argv[1:])