Source

transifex-client / txclib / project.py

  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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import base64
import copy
import getpass
import os
import re
import urllib2
import ConfigParser
import datetime, time

from txclib.web import *
from txclib.utils import *
from txclib.urls import API_URLS
from txclib.config import OrderedRawConfigParser

class ProjectNotInit(Exception):
    pass


class Project(object):
    """
    Represents an association between the local and remote project instances.
    """

    def __init__(self, path_to_tx=None):
        """
        Initialize the Project attributes.
        """
        # The path to the root of the project, where .tx lives!
        self.root = path_to_tx or find_dot_tx()
        if not self.root:
            MSG("Cannot find any .tx directory!")
            MSG("Run 'tx init' to initialize your project first!")
            raise ProjectNotInit()

        # The path to the config file (.tx/config)
        self.config_file = os.path.join(self.root, ".tx", "config")
        # Touch the file if it doesn't exist
        if not os.path.exists(self.config_file):
            MSG("Cannot find the config file (.tx/config)!")
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()

        # The dictionary which holds the config parameters after deser/tion.
        # Read the config in memory
        self.config = OrderedRawConfigParser()
        try:
            self.config.read(self.config_file)
        except Exception, err:
            MSG("WARNING: Cannot open/parse .tx/config file", err)
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()


        home = os.path.expanduser("~")
        self.txrc_file = os.path.join(home, ".transifexrc")
        if not os.path.exists(self.txrc_file):
            MSG("No configuration file found.")
            # Writing global configuration file
            mask = os.umask(077)
            open(self.txrc_file, 'w').close()
            os.umask(mask)

        self.txrc = ConfigParser.RawConfigParser()
        try:
            self.txrc.read(self.txrc_file)
        except Exception, err:
            MSG("WARNING: Cannot global conf file (%s)" %  err)
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()


    def create_resource(self):
        pass


    def validate_config(self):
        """
        To ensure the json structure is correctly formed.
        """
        pass

    def getset_host_credentials(self, host, user=None, password=None):
        """
        Read .transifexrc and report user,pass for a specific host else ask the
        user for input.
        """
        try:
            username = self.txrc.get(host, 'username')
            passwd = self.txrc.get(host, 'password')
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            MSG("No entry found for host %s. Creating..." % host)
            username = user or raw_input("Please enter your transifex username: ")
            while (not username):
                username = raw_input("Please enter your transifex username: ")
            passwd = password
            while (not passwd):
                passwd = getpass.getpass()

            MSG("Updating %s file..." % self.txrc_file)
            self.txrc.add_section(host)
            self.txrc.set(host, 'username', username)
            self.txrc.set(host, 'password', passwd)
            self.txrc.set(host, 'token', '')
            self.txrc.set(host, 'hostname', host)

        return username, passwd

    def set_remote_resource(self, resource, source_lang, i18n_type, host,
            file_filter="translations<sep>%(proj)s.%(res)s<sep><lang>.%(extension)s"):
        """
        Method to handle the add/conf of a remote resource.
        """
        if not self.config.has_section(resource):
            self.config.add_section(resource)

        p_slug, r_slug = resource.split('.')
        file_filter = re.sub("<sep>", r"%s" % os.sep, file_filter)

        self.config.set(resource, 'source_lang', source_lang)
        self.config.set(resource, 'file_filter', file_filter % {'proj': p_slug,
            'res': r_slug, 'extension': FILE_EXTENSIONS[i18n_type]})
        if host != self.config.get('main', 'host'):
            self.config.set(resource, 'host', host)

    def get_resource_host(self, resource):
        """
        Returns the host that the resource is configured to use. If there is no
        such option we return the default one
        """
        if self.config.has_option(resource, 'host'):
            return self.config.get(resource, 'host')
        return self.config.get('main', 'host')

    def get_resource_files(self, resource):
        """
        Get a dict for all files assigned to a resource. First we calculate the
        files matching the file expression and then we apply all translation
        excpetions. The resulting dict will be in this format:

        { 'en': 'path/foo/en/bar.po', 'de': 'path/foo/de/bar.po', 'es': 'path/exceptions/es.po'}

        NOTE: All paths are relative to the root of the project
        """
        tr_files = {}
        if self.config.has_section(resource):
            try:
                file_filter = self.config.get(resource, "file_filter")
            except ConfigParser.NoOptionError:
                file_filter = "$^"
            source_lang = self.config.get(resource, "source_lang")

            expr_re = re.escape(file_filter)
            expr_re = re.sub(r"\\<lang\\>", '<lang>', expr_re)
            expr_re = re.sub(r"<lang>", '([^/]+)', '.*?%s$' % expr_re)
            expr_rec = re.compile(expr_re)
            for root, dirs, files in os.walk(self.root):
                for f in files:
                    f_path = os.path.join(root, f).replace(os.path.sep, '/')
                    match = expr_rec.match(f_path)
                    if match:
                        lang = match.group(1)
                        if lang != source_lang:
                            f_path = relpath(f_path, self.root)
                            tr_files.update({lang: f_path})

            for (name, value) in self.config.items(resource):
                if name.startswith("trans."):
                    lang = name.split('.')[1]
                    tr_files.update({lang:value})

            return tr_files

        return None

    def get_resource_option(self, resource, option):
        """
        Return the requested option for a specific resource

        If there is no such option, we return None
        """

        if self.config.has_section(resource):
            if self.config.has_option(resource, option):
                return self.config.get(resource,option)
        return None

    def get_resource_list(self, project=None):
        """
        Parse config file and return tuples with the following format

        [ (project_slug, resource_slug), (..., ...)]
        """

        resource_list= []
        for r in self.config.sections():
            if r == 'main':
                continue
            p_slug, r_slug = r.split('.')
            if project and p_slug != project:
                continue
            resource_list.append(r)

        return resource_list

    def save(self):
        """
        Store the config dictionary in the .tx/config file of the project.
        """
        fh = open(self.config_file,"w")
        self.config.write(fh)
        fh.close()

        # Writing global configuration file
        mask = os.umask(077)
        fh = open(self.txrc_file, 'w')
        self.txrc.write(fh)
        fh.close()
        os.umask(mask)

    def get_full_path(self, relpath):
        if relpath[0] == "/":
            return relpath
        else:
            return os.path.join(self.root, relpath)

    def pull(self, languages=[], resources=[], overwrite=True, fetchall=False,
        force=False):
        """
        Pull all translations file from transifex server
        """
        if resources:
            resource_list = resources
        else:
            resource_list = self.get_resource_list()

        for resource in resource_list:
            project_slug, resource_slug = resource.split('.')
            files = self.get_resource_files(resource)
            slang = self.get_resource_option(resource, 'source_lang')
            sfile = self.get_resource_option(resource, 'source_file')
            host = self.get_resource_host(resource)
            try:
                file_filter = self.config.get(resource, 'file_filter')
            except ConfigParser.NoOptionError:
                file_filter = None

            # Pull source file
            MSG("Pulling translations for resource %s (source: %s)" %
                (resource, sfile))

            pull_languages = []
            new_translations = []

            if fetchall:
                timestamp = time.time()
                raw = self.do_url_request('resource_details',
                    host=host,
                    project=project_slug,
                    resource=resource_slug)

                details = parse_json(raw)
                langs = details['available_languages']

                for l in langs:
                    if not l['code'] in files.keys() and\
                      not l['code'] == slang:
                        new_translations.append(l['code'])

                if new_translations:
                    MSG("New translations found for the following languages: %s" %
                        ', '.join(new_translations))

            # Check if given language codes exist
            if not languages:
                pull_languages = files.keys()
            else:
                pull_languages.extend(languages)
                f_langs = files.keys()
                for l in languages:
                    if l not in f_langs:
                        pull_languages.remove(l)
                        ERRMSG("Warning: No mapping found for language code '%s'." %
                            color_text(l,"RED"))

            for lang in pull_languages:
                local_file = files[lang]

                if languages and lang not in pull_languages:
                    continue

                if not force:
                    # Check remote timestamp for file and skip update if needed
                    r = self.do_url_request('resource_stats',
                        host=host,
                        project=project_slug,
                        resource=resource_slug,
                        language=lang)

                    stats = parse_json(r)
                    if stats.has_key(lang):
                        time_format = "%Y-%m-%d %H:%M:%S"

                        try:
                            remote_time = time.mktime(datetime.datetime.strptime(stats[lang]['last_update'], time_format).utctimetuple())
                        except TypeError,e:
                            remote_time = None
                        local_time = time.mktime(time.gmtime(os.path.getmtime(local_file)))

                        if not remote_time or remote_time and remote_time < local_time:
                            MSG("Skipping '%s' translation (file: %s)." % (color_text(lang, "RED"), local_file))
                            continue

                if not overwrite:
                    local_file = ("%s.new" % local_file)
                MSG(" -> %s: %s" % (color_text(lang,"RED"), local_file))
                r = self.do_url_request('pull_file',
                    host=host,
                    project=project_slug,
                    resource=resource_slug,
                    language=lang)
                base_dir = os.path.split(local_file)[0]
                mkdir_p(base_dir)
                fd = open(local_file, 'w')
                fd.write(r)
                fd.close()

            if new_translations:
                MSG("Pulling translations for resource %s (source: %s)" %
                (resource, sfile))
                for lang in new_translations:
                    if file_filter:
                        local_file = relpath(os.path.join(self.root,
                            re.sub('<lang>', lang, file_filter)), os.curdir)
                    else:
                        trans_dir = os.path.join(self.root, ".tx", resource)
                        if not os.path.exists(trans_dir):
                            os.mkdir(trans_dir)
                        local_file = relpath(os.path.join(trans_dir, '%s_translation' %
                            lang, os.curdir))

                    MSG(" -> %s: %s" % (color_text(lang, "RED"), local_file))
                    r = self.do_url_request('pull_file',
                        host=host,
                        project=project_slug,
                        resource=resource_slug,
                        language=lang)

                    base_dir = os.path.split(local_file)[0]
                    mkdir_p(base_dir)
                    fd = open(local_file, 'w')
                    fd.write(r)
                    fd.close()


    def push(self, source=False, translations=False, force=False, resources=[], languages=[],
        skip=False, no_interactive=False):
        """
        Push all the resources
        """
        if resources:
            resource_list = resources
        else:
            resource_list = self.get_resource_list()

        for resource in resource_list:
            project_slug, resource_slug = resource.split('.')
            files = self.get_resource_files(resource)
            slang = self.get_resource_option(resource, 'source_lang')
            sfile = self.get_resource_option(resource, 'source_file')
            host = self.get_resource_host(resource)

            MSG("Pushing translations for resource %s:" % resource)

            if force and not no_interactive:
                answer = raw_input("Warning: By using --force, the uploaded"
                    " files will overwrite remote translations, even if they"
                    " are newer than your uploaded files.\nAre you sure you"
                    " want to continue? [y/N] ")

                if not answer in ["", 'Y', 'y', "yes", 'YES']:
                    return

            if source:
                if sfile == None:
                    ERRMSG("You don't seem to have a proper source file"
                        " mapping for resource %s. Try without the --source"
                        " option or set a source file first and then try again." %
                        resource)
                    continue
                # Push source file
                try:
                    MSG("Pushing source file (%s)" % sfile)
                    r = self.do_url_request('push_file', host=host, multipart=True,
                            files=[( "%s;%s" % (resource_slug, slang),
                            self.get_full_path(sfile))],
                            method="POST",
                            project=project_slug)
                    r = parse_json(r)
                    uuid = r['files'][0]['uuid']
                    self.do_url_request('extract_source',
                        host=host,
                        data=compile_json({"uuid":uuid,"slug":resource_slug}),
                        encoding='application/json',
                        method="POST",
                        project=project_slug)
                except Exception, e:
                    if not skip:
                        raise e
                    else:
                        MSG(e)
            else:
                try:
                    self.do_url_request('resource_details', host=host,
                        project=project_slug, resource=resource_slug)
                except Exception, e:
                    try:
                        code = e.code
                    except:
                        raise e
                    if e.code == 404:
                        ERRMSG("Resource %s doesn't exist on the server. Use the"
                            " --source option to create it." % resource)
                        continue

            if translations:
                # Check if given language codes exist
                if not languages:
                    languages = files.keys()
                else:
                    f_langs = files.keys()
                    for l in languages:
                        if l not in f_langs:
                            languages.remove(l)
                            ERRMSG("Warning: No mapping found for language code '%s'." %
                                color_text(l,"RED"))

                # Push translation files one by one
                for lang in languages:
                    local_file = files[lang]
                    if languages and lang not in languages:
                        continue

                    if not force:
                        try:
                            r = self.do_url_request('resource_stats',
                                host=host,
                                project=project_slug,
                                resource=resource_slug,
                                language=lang)

                            # Check remote timestamp for file and skip update if needed
                            stats = parse_json(r)
                            time_format = "%Y-%m-%d %H:%M:%S"
                            remote_time = time.mktime(datetime.datetime.strptime(stats[lang]['last_update'], time_format).utctimetuple())
                        except Exception, e:
                            remote_time = None
                        local_time = time.mktime(time.gmtime(os.path.getmtime(local_file)))

                        if remote_time and remote_time > local_time:
                            MSG("Skipping '%s' translation (file: %s)." % (color_text(lang, "RED"), local_file))
                            continue

                    MSG("Pushing '%s' translations (file: %s)" % (color_text(lang, "RED"), local_file))
                    try:
                        r = self.do_url_request('push_file', host=host, multipart=True,
                            files=[( "%s;%s" % (resource_slug, lang),
                            self.get_full_path(local_file))],
                            method="POST",
                            project=project_slug)
                        r = parse_json(r)
                        uuid = r['files'][0]['uuid']
                        self.do_url_request('extract_translation',
                            host=host,
                            data=compile_json({"uuid":uuid}),
                            encoding='application/json',
                            method="PUT",
                            project=project_slug,
                            resource=resource_slug,
                            language=lang)
                    except Exception, e:
                        if not skip:
                            raise e
                        else:
                            ERRMSG(e)


    def do_url_request(self, api_call, host=None, multipart=False, data=None,
                       files=[], encoding=None, method="GET", **kwargs):
        """
        Issues a url request.
        """
        # Read the credentials from the config file (.transifexrc)
        
        try:
            username = self.txrc.get(host, 'username')
            passwd = self.txrc.get(host, 'password')
            token = self.txrc.get(host, 'token')
            hostname = self.txrc.get(host, 'hostname')
        except ConfigParser.NoSectionError:
            raise Exception("No user credentials found for host %s. Edit"
                " ~/.transifexrc and add the appropriate info in there." %
                host)

        # Create the Url
        kwargs['hostname'] = hostname
        url = API_URLS[api_call] % kwargs

        password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
        password_manager.add_password(None, hostname, username, passwd)
        auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)

        opener = None
        headers = None
        req = None

        if multipart:
            opener = urllib2.build_opener(MultipartPostHandler)
            for info,filename in files:
                data = { "resource" : info.split(';')[0],
                         "language" : info.split(';')[1],
                         "uploaded_file" :  open(filename,'rb') }

            urllib2.install_opener(opener)
            req = RequestWithMethod(url=url, data=data, method=method)
        else:
            opener = urllib2.build_opener(auth_handler)
            urllib2.install_opener(opener)
            req = RequestWithMethod(url=url, data=data, method=method)
            if encoding:
                req.add_header("Content-Type",encoding)

        base64string = base64.encodestring('%s:%s' % (username, passwd))[:-1]
        authheader = "Basic %s" % base64string
        req.add_header("Authorization", authheader)

        try:
            fh = urllib2.urlopen(req)
        except urllib2.HTTPError, e:
            if e.code in [401, 403, 404]:
                raise e
            else:
                # For other requests, we should print the message as well
                raise Exception("Remote server replied: %s" % e.read())
        except urllib2.URLError, e:
            error = e.args[0]
            raise Exception("Remote server replied: %s" % error[1])

        raw = fh.read()
        fh.close()
        return raw
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.