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