Merge branch 'master' of github.com:fnp/wolnelektury
[wolnelektury.git] / apps / modeltranslation / management / commands / translation2po.py
1
2 import os
3 import sys
4 import time
5 from optparse import make_option
6 from django.conf import settings
7 from django.core.management.base import BaseCommand
8 from django.core.management.color import color_style
9
10 import polib
11 import modeltranslation.models
12 from modeltranslation.translator import translator, NotRegistered
13
14
15 def metadata(language=''):
16     "get metadata for PO, given language code"
17     t = time.strftime('%Y-%m-%d %H:%M%z')
18
19     return {
20         'Project-Id-Version': '1.0',
21         'Report-Msgid-Bugs-To': 'marcin.koziej@nowoczesnapolska.org.pl',
22         'POT-Creation-Date': '%s' % t,
23         'PO-Revision-Date': '%s' % t,
24         'Last-Translator': 'you <you@example.com>',
25         'Language-Team': '%s' % dict(settings.LANGUAGES).get(language, language),
26         'MIME-Version': '1.0',
27         'Content-Type': 'text/plain; charset=utf-8',
28         'Content-Transfer-Encoding': '8bit',
29         }
30
31
32 def lang(field_name):
33     "Get the language code from localized field name"
34     return field_name.split('_')[-1]
35
36
37 def make_po(language=''):
38     "Create new POFile object for language code"
39     po = polib.POFile()
40     po.metadata = metadata(language)
41     return po
42
43
44 def get_languages(langs):
45     if not langs: return settings.LANGUAGES
46     langs = langs.split(',')
47     lm = dict(settings.LANGUAGES)
48     return map(lambda l: (l, lm.get(l, l)), langs)
49
50
51 class Command(BaseCommand):
52     option_list = BaseCommand.option_list + (
53         make_option('-d', '--directory', help='Specify which directory should hold generated PO files', dest='directory'),
54         make_option('-l', '--load', help='load locales back to source', action='store_true', dest='load', default=False),
55         make_option('-L', '--language', help='locales to load', dest='lang', default=None),
56         make_option('-n', '--poname', help='name of the po file [no extension]', dest='poname', default=None),
57         )
58     help = 'Export models from app to po files'
59     args = 'app'
60
61     def get_models(self, app):
62         r = []
63         for mdname in dir(app.models):
64             if mdname[0] == '_': continue
65             md = getattr(app.models, mdname)
66             try:
67                 opts = translator.get_options_for_model(md)
68                 r.append((md, opts))
69             except NotRegistered:
70                 continue
71         return r
72
73     def handle(self, appname, **options):
74         if not options['poname']: options['poname'] = appname
75         app = __import__(appname)
76
77         if options['load']:
78             objects = {}
79             modmod = {}
80             for md, opts in self.get_models(app):
81                 if not md.__name__ in objects:
82                     objects[md.__name__] = {}
83                     modmod['model'] = md
84
85             languages = get_languages(options['lang'])
86
87             for lng in zip(*languages)[0]:
88                 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
89                 if not os.path.exists(pofile): raise OSError('%s po file: %s not found' % (appname, pofile))
90                 po = polib.pofile(pofile)
91                 for entry in po:
92                     loc, pk = entry.occurrences[0]
93                     _appname, modelname, fieldname = loc.split('/')
94                     try:
95                         obj = objects[modelname][pk]
96                     except KeyError:
97                         obj = modmod['model'].objects.get(pk=pk)
98                         objects[modelname][pk] = obj
99                     setattr(obj, fieldname, entry.msgstr)
100
101             for mod, objcs in objects.items():
102                 for o in objcs.values():
103                     o.save()
104
105         else:
106             pofiles = {}
107             for md, opts in self.get_models(app):
108                 for obj in md.objects.all().order_by('pk'):
109                     for fld in opts.fields:
110                         for locfld in opts.localized_fieldnames[fld]:
111                             cur_lang = lang(locfld)
112                             try:
113                                 po = pofiles[cur_lang]
114                             except:
115                                 po = make_po(cur_lang)
116                                 pofiles[cur_lang] = po
117
118                             entry = polib.POEntry(
119                                 msgid=getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE)),
120                                 msgstr=getattr(obj, locfld),
121                                 occurrences=[('%s/%s/%s' % (appname, md.__name__, locfld), obj.id)])
122                             po.append(entry)
123
124             directory = options['directory']
125             for lng, po in pofiles.items():
126                 try: os.makedirs(os.path.join(directory, lng))
127                 except OSError: pass
128                 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))