Add management command for localizing contrib apps.
[fnpdjango.git] / fnpdjango / management / commands / makecontribmessages.py
1 # -*- coding: utf-8 -*-
2 # This file is part of FNPDjango, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import os
6 from optparse import make_option
7 from django.core.management.base import BaseCommand
8
9 class Command(BaseCommand):
10     help = 'Builds .po files for contrib apps.'
11
12     def handle(self, **options):
13         from django.conf import settings
14
15         if not hasattr(settings, 'CONTRIB_LOCALE_APPS') or not settings.CONTRIB_LOCALE_APPS:
16             print "CONTRIB_LOCALE_APPS not set, no contrib locale needed."
17             return
18
19         from subprocess import call
20         import babel
21
22         app_names = settings.CONTRIB_LOCALE_APPS
23         print 'L10n for:', ", ".join(app_names)
24         app_dirs = [os.path.dirname(__import__(app).__file__)
25                         for app in app_names]
26         assert settings.LOCALE_PATHS
27         locale_path = settings.LOCALE_PATHS[0]
28         print 'Using:', locale_path
29
30         # Create the POT file.
31         babel_cfg = os.path.join(locale_path,  "babel.cfg")
32         if not os.path.exists(babel_cfg):
33             babel_cfg = os.path.join(os.path.dirname(__file__), 'babel.cfg')
34         pot_path = os.path.join(locale_path,  "django.pot")
35         call(["pybabel", "extract",
36                 "-F", babel_cfg,
37                 "-o", pot_path] + app_dirs)
38
39         # Lose the unneeded absolute file paths in the POT.
40         with open(pot_path) as f:
41             pot = f.read()
42         for i, app_dir in enumerate(app_dirs):
43             pot = pot.replace("\n#: " + app_dir, "\n#: " + app_names[i])
44         with open(pot_path, 'w') as f:
45             f.write(pot)
46
47         # Create/update the PO files.
48         call(["pybabel", "update", "-D", "django",
49                 "-i", pot_path,
50                 "-d", locale_path])