merge changes from locale test branch
[wolnelektury.git] / apps / wolnelektury_core / management / commands / localepack.py
1
2 from optparse import make_option
3 from django.conf import settings
4 from django.core.management.base import BaseCommand
5 from django.core.management import call_command
6 from modeltranslation.management.commands.translation2po import get_languages
7
8 import os
9 import shutil
10 import tempfile
11 import sys
12
13 import allauth
14
15 ROOT = os.path.dirname(settings.PROJECT_DIR)
16
17
18 def is_our_app(mod):
19     return mod.__path__[0].startswith(ROOT)
20
21
22 class Locale(object):
23     def save(self, output_directory, languages):
24         pass
25
26     def generate(self, languages):
27         pass
28
29
30 class AppLocale(Locale):
31     def __init__(self, appmod):
32         self.app = appmod
33         if not os.path.exists(os.path.join(self.path, 'locale')):
34             raise LookupError('No locale for app %s' % appmod)
35
36     @property
37     def path(self):
38         return self.app.__path__[0]
39
40     @property
41     def name(self):
42         return self.app.__name__
43
44     def save(self, output_directory, languages):
45         for lc in languages:
46             lc = lc[0]
47             if os.path.exists(os.path.join(self.path, 'locale', lc)):
48                 shutil.copy2(os.path.join(self.path, 'locale', lc, 'LC_MESSAGES', 'django.po'),
49                          os.path.join(output_directory, lc, self.name + '.po'))
50
51     def load(self, input_directory, languages):
52         for lc in zip(*languages)[0]:
53             if os.path.exists(os.path.join(input_directory, lc, self.name + '.po')):
54                 shutil.copy2(os.path.join(input_directory, lc, self.name + '.po'),
55                              os.path.join(self.path, 'locale', lc, 'LC_MESSAGES', 'django.po'))
56
57     def generate(self, languages):
58         wd = os.getcwd()
59         os.chdir(self.path)
60         try:
61             call_command('makemessages', all=True)
62         except:
63             pass
64         finally:
65             os.chdir(wd)
66
67
68 class ModelTranslation(Locale):
69     def __init__(self, appname, poname=None):
70         self.appname = appname
71         self.poname = poname and poname or appname
72
73     def save(self, output_directory, languages):
74         call_command('translation2po', self.appname, directory=output_directory, poname=self.poname)
75
76     def load(self, input_directory, languages):
77         call_command('translation2po', self.appname, directory=input_directory,
78                      load=True, lang=','.join(zip(*languages)[0]), poname=self.poname)
79
80
81 class CustomLocale(Locale):
82     def __init__(self, app_dir,
83                  config=os.path.join(ROOT, "babel.cfg"),
84                  out_file=os.path.join(ROOT, 'wolnelektury/locale-contrib/django.pot'),
85                  name=None):
86         self.app_dir = app_dir
87         self.config = config
88         self.out_file = out_file
89         self.name = name
90
91     def generate(self, languages):
92         os.system('pybabel extract -F "%s" -o "%s" "%s"' % (self.config, self.out_file, self.app_dir))
93         os.system('pybabel update -D django -i %s -d %s' % (self.out_file, os.path.dirname(self.out_file)))
94
95     def po_file(self, language):
96         d = os.path.dirname(self.out_file)
97         n = os.path.basename(self.out_file).split('.')[0]
98         return os.path.join(d, language, 'LC_MESSAGES', n + '.po')
99
100     def save(self, output_directory, languages):
101         for lc in zip(*languages)[0]:
102             if os.path.exists(self.po_file(lc)):
103                 shutil.copy2(self.po_file(lc),
104                              os.path.join(output_directory, lc, self.name + '.po'))
105
106     def load(self, input_directory, languages):
107         for lc in zip(*languages)[0]:
108             shutil.copy2(os.path.join(input_directory, lc, self.name + '.po'),
109                          self.po_file(lc))
110         os.system('pybabel compile -D django -d %s' % os.path.dirname(self.out_file))
111
112
113 SOURCES = []
114
115 for appn in settings.INSTALLED_APPS:
116     app = __import__(appn)
117     if is_our_app(app):
118         try:
119             SOURCES.append(AppLocale(app))
120         except LookupError, e:
121             print "no locales in %s" % app.__name__
122
123 SOURCES.append(ModelTranslation('infopages', 'infopages_db'))
124 SOURCES.append(CustomLocale(os.path.dirname(allauth.__file__), name='contrib'))
125
126
127 class Command(BaseCommand):
128     option_list = BaseCommand.option_list + (
129         make_option('-l', '--load', help='load locales back to source', action='store_true', dest='load', default=False),
130         make_option('-L', '--lang', help='load just one language', dest='lang', default=None),
131         make_option('-d', '--directory', help='load from this directory', dest='directory', default=None),
132         make_option('-o', '--outfile', help='Resulting zip file', dest='outfile', default='./wl-locale.zip'),
133         make_option('-m', '--merge', help='Use git to merge. Please use with clean working directory.', dest='merge', default=False),
134         )
135     help = 'Make a locale pack'
136     args = ''
137
138     def save(self, options):
139         tmp_dir = tempfile.mkdtemp('-wl-locale')
140         out_dir = os.path.join(tmp_dir, 'wl-locale')
141         os.mkdir(out_dir)
142
143         try:
144             for lang in settings.LANGUAGES:
145                 os.mkdir(os.path.join(out_dir, lang[0]))
146
147             for src in SOURCES:
148                 src.generate(settings.LANGUAGES)
149                 src.save(out_dir, settings.LANGUAGES)
150                 #                src.save(settings.LANGUAGES)
151
152             # write out revision
153             rev = os.popen('git rev-parse HEAD').read()
154             rf = open(os.path.join(out_dir, '.revision'), 'w')
155             rf.write(rev)
156             rf.close()
157
158             packname = options.get('outfile')
159             packname_b = os.path.basename(packname).split('.')[0]
160             fmt = '.'.join(os.path.basename(packname).split('.')[1:])
161             shutil.make_archive(packname_b, fmt, root_dir=os.path.dirname(out_dir), base_dir=os.path.basename(out_dir))
162         finally:
163             shutil.rmtree(tmp_dir, ignore_errors=True)
164
165     def load(self, options):
166         if not options['directory'] or not os.path.exists(options['directory']):
167             print "Directory not provided or does not exist, please use -d"
168             sys.exit(1)
169
170         langs = get_languages(options['lang'])
171
172         for src in SOURCES:
173             src.load(options['directory'], langs)
174
175     def handle(self, *a, **options):
176         if options['load']:
177             self.load(options)
178         else:
179             self.save(options)