cover inheritance tests and fix
[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         make_option('-k', '--keep-running', help='keep running even when missing an input file', dest='keep_running', default=False, action='store_true'),
58         )
59     help = 'Export models from app to po files'
60     args = 'app'
61
62     def get_models(self, app):
63         r = []
64         for mdname in dir(app.models):
65             if mdname[0] == '_': continue
66             md = getattr(app.models, mdname)
67             try:
68                 opts = translator.get_options_for_model(md)
69                 r.append((md, opts))
70             except NotRegistered:
71                 continue
72         return r
73
74     def handle(self, appname, **options):
75         if not options['poname']: options['poname'] = appname
76         app = __import__(appname)
77
78         if options['load']:
79             objects = {}
80             modmod = {}
81             for md, opts in self.get_models(app):
82                 if not md.__name__ in objects:
83                     objects[md.__name__] = {}
84                     modmod['model'] = md
85
86             languages = get_languages(options['lang'])
87
88             for lng in zip(*languages)[0]:
89                 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
90                 if not os.path.exists(pofile): 
91                     if options['keep_running']:
92                         continue
93                     else:
94                         raise OSError('%s po file: %s not found' % (appname, pofile))
95                 po = polib.pofile(pofile)
96                 for entry in po:
97                     loc, pk = entry.occurrences[0]
98                     _appname, modelname, fieldname = loc.split('/')
99                     try:
100                         obj = objects[modelname][pk]
101                     except KeyError:
102                         obj = modmod['model'].objects.get(pk=pk)
103                         objects[modelname][pk] = obj
104                     setattr(obj, fieldname, entry.msgstr)
105
106             for mod, objcs in objects.items():
107                 for o in objcs.values():
108                     o.save()
109
110         else:
111             pofiles = {}
112             for md, opts in self.get_models(app):
113                 for obj in md.objects.all().order_by('pk'):
114                     for fld in opts.fields:
115                         for locfld in opts.localized_fieldnames[fld]:
116                             cur_lang = lang(locfld)
117                             try:
118                                 po = pofiles[cur_lang]
119                             except:
120                                 po = make_po(cur_lang)
121                                 pofiles[cur_lang] = po
122
123                             k = getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE))
124                             if k is None: k = ''
125                             v = getattr(obj, locfld)
126                             if v is None: v = ''
127                             entry = polib.POEntry(
128                                 msgid=k,
129                                 msgstr=v,
130                                 occurrences=[('%s/%s/%s' % (appname, md.__name__, locfld), obj.id)])
131                             po.append(entry)
132
133             directory = options['directory']
134             for lng, po in pofiles.items():
135                 try: os.makedirs(os.path.join(directory, lng))
136                 except OSError: pass
137                 print lng, options
138                 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))