~ubuntu-langpack/langpack-o-matic/main

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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/python

import tempfile
import shutil
import os
import subprocess
import logging
import tarfile

try:
    from urllib.request import urlopen
except ImportError:
    # python 2 fallback
    from urllib2 import urlopen

from macros import _file_map

from launchpadlib.launchpad import Launchpad

tarballs_since = '2013-10-01'


def _get_current_version(distro, distrorelease, sourcepkg):
    '''Get current version of a source package'''

    v = _get_current_version.cache.get(sourcepkg)
    if not v:
        try:
            v = distro.main_archive.getPublishedSources(
                exact_match=True, source_name=sourcepkg,
                distro_series=distrorelease)[0].source_package_version

        except IndexError:
            return None
        _get_current_version.cache[sourcepkg] = v

    return v

_get_current_version.cache = {}


def get_static_translation_tarballs(distro, from_release, to_release):
    '''Get URLs of current static translation tarballs for a release interval'''

    # get launchpadlib object
    lp = Launchpad.login_anonymously('langpack-o-matic', service_root='production')
    lpdistro = lp.distributions[distro]
    distrorelease = lpdistro.getSeries(name_or_version=to_release.split('-')[0])

    # to also catch packages which haven't been rebuilt in the given release,
    # we need to iterate through earlier releases
    releases = _get_release_interval(distro, from_release, to_release)
    releases.reverse()  # more efficient, as most packages get rebuilt in a release

    tarballs = {}

    for release in releases:
        for p in lpdistro.getSeries(name_or_version=release).getPackageUploads(
                created_since_date=tarballs_since, custom_type='raw-translations-static'):
            src = p.display_name.split(',')[0]
            if src in tarballs:
                # we get one tarball per architecture, just take one
                continue
            if p.display_version != _get_current_version(lpdistro, distrorelease, src):
                continue
            for u in p.custom_file_urls:
                if u and u.endswith('_static_translations.tar.gz'):
                    tarballs[src] = u

    return list(tarballs.values())


def _locale2pkgname(locale):
    try:
        return _locale2pkgname.cache[locale]
    except KeyError:
        if '_' in locale:
            try:
                pkgname = _file_map('maps/locale2pkgname',
                                    locale.lower().replace('_', '-'), ':')
            except KeyError:
                pkgname = locale.split('_')[0]
        else:
            # just a language code
            pkgname = locale

        _locale2pkgname.cache[locale] = pkgname
        return pkgname

_locale2pkgname.cache = {}


def create_static_tarballs(tarball_urls, output_dir):
    '''Fetch static translation tarballs and build per-langpack tarballs.

    Fetch all tarballs from the given URL list and unpack them into a temporary
    directory.  Then walk over the files, sort them into per-langpack maps, and
    build output_dir/pkgname.tar.gz, which should then be moved to
    langpack-base/static.tar.gz.
    '''
    unpack_dir = tempfile.mkdtemp('.')

    try:
        logging.debug('fetching tarballs...')
        for t in tarball_urls:
            logging.debug('    ' + t)
            response = urlopen(t)
            with tempfile.TemporaryFile() as f:
                shutil.copyfileobj(response, f)
                f.seek(0)
                subprocess.check_call(['tar', '-xzC', unpack_dir], stdin=f)

        # rename to *-langpack
        logging.debug('renaming to *-langpack...')
        for (root, dirs, _) in os.walk(unpack_dir):
            if root.endswith('/gnome') and 'help' in dirs:
                os.rename(os.path.join(root, 'help'),
                          os.path.join(root, 'help-langpack'))
                continue
            if root.endswith('/share'):
                if 'omf' in dirs:
                    os.rename(os.path.join(root, 'omf'),
                              os.path.join(root, 'omf-langpack'))
                if 'help' in dirs:
                    os.rename(os.path.join(root, 'help'),
                              os.path.join(root, 'help-langpack'))

        # sort files into langpack buckets
        map = {}
        logging.debug('sorting static files per language pack...')
        for (root, dirs, files) in os.walk(unpack_dir):
            root = root[len(unpack_dir) + 1:]
            comps = root.split(os.path.sep)

            # gnome help omf files
            if len(comps) == 5 and comps[-3] == 'share' and comps[-2] == 'omf-langpack':
                for f in files:
                    locale = f.rsplit('.', 1)[0].rsplit('-', 1)[1]
                    map.setdefault('gnome-' + _locale2pkgname(locale),
                                   []).append(os.path.join(root, f))

            # gnome help data files
            if len(comps) >= 7 and 'share/gnome/help-langpack/' in root:
                locale = comps[comps.index('help-langpack') + 2]
                for f in files:
                    map.setdefault('gnome-' + _locale2pkgname(locale),
                                   []).append(os.path.join(root, f))

            # Mallard help files
            if len(comps) >= 6 and 'share/help-langpack/' in root:
                locale = comps[comps.index('help-langpack') + 1]
                for f in files:
                    map.setdefault('gnome-' + _locale2pkgname(locale),
                                   []).append(os.path.join(root, f))

        # create static.tar.gz
        for pkgname, files in map.items():
            logging.debug('creating %s.tar...' % pkgname)
            tar = tarfile.open(os.path.join(output_dir, pkgname + '.tar'), 'w')
            for f in files:
                tar.add(os.path.join(unpack_dir, f), f[f.index('/') + 1:], False)
            tar.close()
    finally:
        shutil.rmtree(unpack_dir)


def _get_release_interval(distro, min, max):
    '''Get list of releases in between the "min" and "max" names.'''

    min_num = _file_map('maps/releaseversions-' + distro, min.split('-')[0])
    max_num = _file_map('maps/releaseversions-' + distro, max.split('-')[0])
    result = []

    def _cmp(v1, v2):
        '''Compare two Ubuntu release numbers'''

        (y1, m1) = v1.split('.')
        (y2, m2) = v2.split('.')
        c = cmp(int(y1), int(y2))
        if c != 0:
            return c
        return cmp(int(m1), int(m2))

    for l in open('maps/releaseversions-' + distro):
        l = l.strip()
        if not l:
            continue
        (name, num) = l.split()
        if _cmp(num, min_num) >= 0 and _cmp(num, max_num) <= 0:
            result.append(name)

    return result


if __name__ == '__main__':
    import unittest

    class _T(unittest.TestCase):
        def setUp(self):
            self.workdir = tempfile.mkdtemp()

        def tearDown(self):
            shutil.rmtree(self.workdir)

        def test_gnome2_help(self):
            '''create_static_tarballs() for GNOME 2 help files'''

            create_static_tarballs(['file://%s/test/gnome2help_static_translations.tar.gz'
                                   % os.getcwd()],
                                   self.workdir)

            self.assertEqual(set(os.listdir(self.workdir)),
                             set(['gnome-de.tar', 'gnome-en.tar', 'gnome-zh-hans.tar']))

            t = os.path.join(self.workdir, 'gnome-de.tar')
            self.assertEqual(
                set(tarfile.open(t).getnames()),
                set(['usr/share/gnome/help-langpack/mousetweaks/de/mousetweaks.xml',
                     'usr/share/gnome/help-langpack/mousetweaks/de/figures/mouse-a11y-dwell-click-type-applet.png',
                     'usr/share/gnome/help-langpack/mousetweaks/de/figures/mouse-a11y-dwell-checkbox.png',
                     'usr/share/omf-langpack/mousetweaks/mousetweaks-config-de.omf',
                     'usr/share/omf-langpack/mousetweaks/mousetweaks-de.omf']))

            t = os.path.join(self.workdir, 'gnome-en.tar')
            self.assertEqual(set(tarfile.open(t).getnames()),
                             set(['usr/share/gnome/help-langpack/mousetweaks/en_GB/mousetweaks.xml',
                                  'usr/share/omf-langpack/mousetweaks/mousetweaks-en_GB.omf']))

            t = os.path.join(self.workdir, 'gnome-zh-hans.tar')
            self.assertEqual(
                set(tarfile.open(t).getnames()),
                set(['usr/share/gnome/help-langpack/mousetweaks/zh_CN/mousetweaks.xml',
                     'usr/share/gnome/help-langpack/mousetweaks/zh_CN/figures/mouse-a11y-dwell-click-type-applet.png',
                     'usr/share/gnome/help-langpack/mousetweaks/zh_CN/figures/mouse-a11y-dwell-checkbox.png',
                     'usr/share/omf-langpack/mousetweaks/mousetweaks-zh_CN.omf']))

        def test_mallard_help(self):
            '''create_static_tarballs() for Mallard help files'''

            create_static_tarballs(['file://%s/test/mallard-help_static_translations.tar.gz'
                                   % os.getcwd()],
                                   self.workdir)

            self.assertEqual(set(os.listdir(self.workdir)),
                             set(['gnome-de.tar', 'gnome-en.tar']))

            t = os.path.join(self.workdir, 'gnome-de.tar')
            self.assertEqual(set(tarfile.open(t).getnames()),
                             set(['usr/share/help-langpack/de/ubuntu-help/legal.xml',
                                  'usr/share/help-langpack/de/ubuntu-help/a11y.page']))

            t = os.path.join(self.workdir, 'gnome-en.tar')
            self.assertEqual(set(tarfile.open(t).getnames()),
                             set(['usr/share/help-langpack/en_AU/ubuntu-help/legal.xml',
                                  'usr/share/help-langpack/en_AU/ubuntu-help/a11y.page']))

        def test_get_release_interval(self):
            '''_get_release_interfal()'''

            self.assertEqual(_get_release_interval('ubuntu', 'precise', 'raring-updates'),
                             ['precise', 'quantal', 'raring'])
            self.assertEqual(_get_release_interval('ubuntu', 'raring-security', 'saucy'),
                             ['raring', 'saucy'])
            self.assertEqual(_get_release_interval('ubuntu', 'saucy', 'raring'), [])
            self.assertEqual(_get_release_interval('ubuntu-rtm', '14.09', '14.09'), ['14.09'])
            self.assertEqual(_get_release_interval('ubuntu-rtm', '14.09', '15.04'), ['14.09', '15.04'])
            self.assertRaises(KeyError, _get_release_interval, 'ubuntu', 'unknown', 'trusty')

        def disabled_test_get_static_translation_tarballs(self):
            '''get_static_translation_tarballs() (no auto tests)'''

            # not automatically tested
            tarballs = get_static_translation_tarballs('ubuntu', 'trusty', 'utopic')
            for t in tarballs:
                print(t)

    unittest.main()