1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from django.conf import settings
7 from django.core.management.base import BaseCommand
8 from django.db import models
10 from modeltranslation.translator import translator, NotRegistered
11 from wolnelektury.utils import makedirs
14 def metadata(language=''):
15 """get metadata for PO, given language code"""
16 t = time.strftime('%Y-%m-%d %H:%M%z')
19 'Project-Id-Version': '1.0',
20 'Report-Msgid-Bugs-To': settings.CONTACT_EMAIL,
21 'POT-Creation-Date': '%s' % t,
22 'PO-Revision-Date': '%s' % t,
23 'Last-Translator': 'you <you@example.com>',
24 'Language-Team': '%s' % dict(settings.LANGUAGES).get(language, language),
25 'MIME-Version': '1.0',
26 'Content-Type': 'text/plain; charset=utf-8',
27 'Content-Transfer-Encoding': '8bit',
31 def make_po(language=''):
32 """Create new POFile object for language code"""
34 po.metadata = metadata(language)
38 def get_languages(langs):
40 return settings.LANGUAGES
41 langs = langs.split(',')
42 lm = dict(settings.LANGUAGES)
43 return map(lambda l: (l, lm.get(l, l)), langs)
46 class Command(BaseCommand):
47 help = 'Export models from app to po files'
49 def add_arguments(self, parser):
51 '-d', '--directory', dest='directory', default='',
52 help='Specify which directory should hold generated PO files')
54 '-l', '--load', help='load locales back to source',
55 action='store_true', dest='load', default=False)
57 '-L', '--language', help='locales to load',
58 dest='lang', default=None)
60 '-n', '--poname', help='name of the po file [no extension]',
61 dest='poname', default=None)
63 '-k', '--keep-running', dest='keep_running',
64 help='keep running even when missing an input file',
65 default=False, action='store_true')
66 parser.add_argument('app')
68 def get_models(self, app):
69 for mdname in dir(app.models):
72 md = getattr(app.models, mdname)
74 assert issubclass(md, models.Model)
75 except (AssertionError, TypeError):
79 opts = translator.get_options_for_model(md)
85 def handle(self, **options):
86 appname = options['app']
87 if not options['poname']:
88 options['poname'] = appname
89 app = __import__(appname)
94 for md, opts in self.get_models(app):
95 if md.__name__ not in objects:
96 objects[md.__name__] = {}
99 languages = get_languages(options['lang'])
101 for lng in zip(*languages)[0]:
102 pofile = os.path.join(options['directory'], lng, options['poname'] + '.po')
103 if not os.path.exists(pofile):
104 if options['keep_running']:
107 raise OSError('%s po file: %s not found' % (appname, pofile))
108 po = polib.pofile(pofile)
110 loc, _ignored = entry.occurrences[0]
111 _appname, modelname, fieldname, pk = loc.split('/')
113 obj = objects[modelname][pk]
115 obj = modmod['model'].objects.get(pk=pk)
116 objects[modelname][pk] = obj
117 setattr(obj, fieldname, entry.msgstr)
119 for mod, objcs in objects.items():
120 for o in objcs.values():
125 for md, opts in self.get_models(app):
126 for obj in md.objects.all().order_by('pk'):
127 for fld, locflds in opts.local_fields.items():
128 k = getattr(obj, '%s_%s' % (fld, settings.LANGUAGE_CODE)) or ''
129 for locfld in locflds:
130 cur_lang = locfld.language
132 po = pofiles[cur_lang]
134 po = make_po(cur_lang)
135 pofiles[cur_lang] = po
136 v = locfld.value_from_object(obj) or ''
137 entry = polib.POEntry(
140 occurrences=[('%s/%s/%s/%s' % (appname, md.__name__, locfld.name, str(obj.pk)), 0)])
143 directory = options['directory']
144 for lng, po in pofiles.items():
145 makedirs(os.path.join(directory, lng))
146 po.save(os.path.join(directory, lng, '%s.po' % options['poname']))