1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from optparse import make_option
8 from django.conf import settings
9 from django.core.management.base import BaseCommand
10 from django.core.management.color import color_style
11 from django.db import models
14 import modeltranslation.models
15 from modeltranslation.translator import translator, NotRegistered
18 def metadata(language=''):
19 "get metadata for PO, given language code"
20 t = time.strftime('%Y-%m-%d %H:%M%z')
23 'Project-Id-Version': '1.0',
24 'Report-Msgid-Bugs-To': settings.CONTACT_EMAIL,
25 'POT-Creation-Date': '%s' % t,
26 'PO-Revision-Date': '%s' % t,
27 'Last-Translator': 'you <you@example.com>',
28 'Language-Team': '%s' % dict(settings.LANGUAGES).get(language, language),
29 'MIME-Version': '1.0',
30 'Content-Type': 'text/plain; charset=utf-8',
31 'Content-Transfer-Encoding': '8bit',
35 def make_po(language=''):
36 "Create new POFile object for language code"
38 po.metadata = metadata(language)
42 def get_languages(langs):
43 if not langs: return settings.LANGUAGES
44 langs = langs.split(',')
45 lm = dict(settings.LANGUAGES)
46 return map(lambda l: (l, lm.get(l, l)), langs)
49 class Command(BaseCommand):
50 option_list = BaseCommand.option_list + (
51 make_option('-d', '--directory', help='Specify which directory should hold generated PO files', dest='directory', default=''),
52 make_option('-l', '--load', help='load locales back to source', action='store_true', dest='load', default=False),
53 make_option('-L', '--language', help='locales to load', dest='lang', default=None),
54 make_option('-n', '--poname', help='name of the po file [no extension]', dest='poname', default=None),
55 make_option('-k', '--keep-running', help='keep running even when missing an input file', dest='keep_running', default=False, action='store_true'),
57 help = 'Export models from app to po files'
60 def get_models(self, app):
61 for mdname in dir(app.models):
62 if mdname[0] == '_': continue
63 md = getattr(app.models, mdname)
65 assert issubclass(md, models.Model)
66 except (AssertionError, TypeError):
70 opts = translator.get_options_for_model(md)
76 def handle(self, appname, **options):
77 if not options['poname']: options['poname'] = appname
78 app = __import__(appname)
83 for md, opts in self.get_models(app):
84 if not md.__name__ in objects:
85 objects[md.__name__] = {}
88 languages = get_languages(options['lang'])
90 for lng in zip(*languages)[0]:
91 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
92 if not os.path.exists(pofile):
93 if options['keep_running']:
96 raise OSError('%s po file: %s not found' % (appname, pofile))
97 po = polib.pofile(pofile)
99 loc, _ignored = entry.occurrences[0]
100 _appname, modelname, fieldname, pk = loc.split('/')
102 obj = objects[modelname][pk]
104 obj = modmod['model'].objects.get(pk=pk)
105 objects[modelname][pk] = obj
106 setattr(obj, fieldname, entry.msgstr)
108 for mod, objcs in objects.items():
109 for o in objcs.values():
114 for md, opts in self.get_models(app):
115 for obj in md.objects.all().order_by('pk'):
116 for fld, locflds in opts.local_fields.items():
117 k = getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE)) or ''
118 for locfld in locflds:
119 cur_lang = locfld.language
121 po = pofiles[cur_lang]
123 po = make_po(cur_lang)
124 pofiles[cur_lang] = po
125 v = locfld.value_from_object(obj) or ''
126 entry = polib.POEntry(
129 occurrences=[('%s/%s/%s/%s' % (appname, md.__name__, locfld.name, str(obj.pk)), 0)])
132 directory = options['directory']
133 for lng, po in pofiles.items():
134 os.makedirs(os.path.join(directory, lng))
135 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))