localepack command
[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 class Command(BaseCommand):
45     option_list = BaseCommand.option_list + (
46         make_option('-d', '--directory', help='Specify which directory should hold generated PO files', dest='directory'),
47         make_option('-l', '--load', help='load locales back to source', action='store_true', dest='load', default=False),
48         )
49     help = 'Export models from app to po files'
50     args = 'app'
51
52     def get_models(self, app):
53         r = []
54         for mdname in dir(app.models):
55             if mdname[0] == '_': continue
56             md = getattr(app.models, mdname)
57             try:
58                 opts = translator.get_options_for_model(md)
59                 r.append((md, opts))
60             except NotRegistered:
61                 continue
62         return r
63
64     def handle(self, appname, **options):
65         app = __import__(appname)
66         if options['load']:
67             objects = {}
68             modmod = {}
69             for md, opts in self.get_models(app):
70                 if not md.__name__ in objects:
71                     objects[md.__name__] = {}
72                     modmod['model'] = md
73
74             for lng in zip(*settings.LANGUAGES)[0]:
75                 pofile = os.path.join(options['directory'], lng, appname + '.po')
76                 po = polib.pofile(pofile)
77                 for entry in po:
78                     loc, pk = entry.occurrences[0]
79                     _appname, modelname, fieldname = loc.split('/')
80                     try:
81                         obj = objects[modelname][pk]
82                     except KeyError:
83                         obj = modmod['model'].objects.get(pk=pk)
84                         objects[modelname][pk] = obj
85                     setattr(obj, fieldname, entry.msgstr)
86
87             for mod, objcs in objects.items():
88                 for o in objcs.values():
89                     o.save()
90
91         else:
92             pofiles = {}
93             for md, opts in self.get_models(app):
94                 for obj in md.objects.all().order_by('pk'):
95                     for fld in opts.fields:
96                         for locfld in opts.localized_fieldnames[fld]:
97                             cur_lang = lang(locfld)
98                             try:
99                                 po = pofiles[cur_lang]
100                             except:
101                                 po = make_po(cur_lang)
102                                 pofiles[cur_lang] = po
103
104                             entry = polib.POEntry(
105                                 msgid=getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE)),
106                                 msgstr=getattr(obj, locfld),
107                                 occurrences=[('%s/%s/%s' % (appname, md.__name__, locfld), obj.id)])
108                             po.append(entry)
109
110             directory = options['directory']
111             for lng, po in pofiles.items():
112                 try: os.makedirs(os.path.join(directory, lng))
113                 except OSError: pass
114                 po.save(os.path.join(directory, lng, '%s.po' % appname))