c38d82c6c8c0da35fcba92f288f849fc2509011b
[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         make_option('-L', '--language', help='locales to load', dest='lang', default=None),
49         make_option('-n', '--poname', help='name of the po file [no extension]', dest='poname', default=None),
50         )
51     help = 'Export models from app to po files'
52     args = 'app'
53
54     def get_models(self, app):
55         r = []
56         for mdname in dir(app.models):
57             if mdname[0] == '_': continue
58             md = getattr(app.models, mdname)
59             try:
60                 opts = translator.get_options_for_model(md)
61                 r.append((md, opts))
62             except NotRegistered:
63                 continue
64         return r
65
66     def handle(self, appname, **options):
67         if not options['poname']: options['poname'] = appname
68         app = __import__(appname)
69
70         if options['load']:
71             objects = {}
72             modmod = {}
73             for md, opts in self.get_models(app):
74                 if not md.__name__ in objects:
75                     objects[md.__name__] = {}
76                     modmod['model'] = md
77
78 <<<<<<< Updated upstream
79             for lng in zip(*settings.LANGUAGES)[0]:
80                 pofile = os.path.join(options['directory'], lng, appname + '.po')
81 =======
82             languages = get_languages(options['lang'])
83
84             for lng in zip(*languages)[0]:
85                 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
86                 if not os.path.exists(pofile): raise OSError('%s po file: %s not found' % (appname, pofile))
87                 print pofile
88 >>>>>>> Stashed changes
89                 po = polib.pofile(pofile)
90                 for entry in po:
91                     loc, pk = entry.occurrences[0]
92                     _appname, modelname, fieldname = loc.split('/')
93                     try:
94                         obj = objects[modelname][pk]
95                     except KeyError:
96                         obj = modmod['model'].objects.get(pk=pk)
97                         objects[modelname][pk] = obj
98                     setattr(obj, fieldname, entry.msgstr)
99
100             for mod, objcs in objects.items():
101                 for o in objcs.values():
102                     o.save()
103
104         else:
105             pofiles = {}
106             for md, opts in self.get_models(app):
107                 for obj in md.objects.all().order_by('pk'):
108                     for fld in opts.fields:
109                         for locfld in opts.localized_fieldnames[fld]:
110                             cur_lang = lang(locfld)
111                             try:
112                                 po = pofiles[cur_lang]
113                             except:
114                                 po = make_po(cur_lang)
115                                 pofiles[cur_lang] = po
116
117                             entry = polib.POEntry(
118                                 msgid=getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE)),
119                                 msgstr=getattr(obj, locfld),
120                                 occurrences=[('%s/%s/%s' % (appname, md.__name__, locfld), obj.id)])
121                             po.append(entry)
122
123             directory = options['directory']
124             for lng, po in pofiles.items():
125                 try: os.makedirs(os.path.join(directory, lng))
126                 except OSError: pass
127                 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))