fix
[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 import zipfile
13
14 import allauth
15
16 ROOT = os.path.dirname(settings.PROJECT_DIR)
17
18
19 def is_our_app(mod):
20     return mod.__path__[0].startswith(ROOT)
21
22
23 class Locale(object):
24     def save(self, output_directory, languages):
25         pass
26
27     def generate(self, languages):
28         pass
29
30
31 class AppLocale(Locale):
32     def __init__(self, appmod):
33         self.app = appmod
34         if not os.path.exists(os.path.join(self.path, 'locale')):
35             raise LookupError('No locale for app %s' % appmod)
36
37     @property
38     def path(self):
39         return self.app.__path__[0]
40
41     @property
42     def name(self):
43         return self.app.__name__
44
45     def save(self, output_directory, languages):
46         for lc in languages:
47             lc = lc[0]
48             out = os.path.join(output_directory, lc, self.name + '.po')
49             if os.path.exists(os.path.join(self.path, 'locale', lc)):
50                 if not os.path.exists(os.path.dirname(out)):
51                     os.makedirs(os.path.dirname(dir))
52                 shutil.copy2(os.path.join(self.path, 'locale', lc, 'LC_MESSAGES', 'django.po'),
53                          out)
54
55     def load(self, input_directory, languages):
56         for lc in zip(*languages)[0]:
57             if os.path.exists(os.path.join(input_directory, lc, self.name + '.po')):
58                 shutil.copy2(os.path.join(input_directory, lc, self.name + '.po'),
59                              os.path.join(self.path, 'locale', lc, 'LC_MESSAGES', 'django.po'))
60
61     def generate(self, languages):
62         wd = os.getcwd()
63         os.chdir(self.path)
64         try:
65             call_command('makemessages', all=True)
66         except:
67             pass
68         finally:
69             os.chdir(wd)
70
71
72 class ModelTranslation(Locale):
73     def __init__(self, appname, poname=None):
74         self.appname = appname
75         self.poname = poname and poname or appname
76
77     def save(self, output_directory, languages):
78         call_command('translation2po', self.appname, directory=output_directory, poname=self.poname)
79
80     def load(self, input_directory, languages):
81         call_command('translation2po', self.appname, directory=input_directory,
82                      load=True, lang=','.join(zip(*languages)[0]), poname=self.poname)
83
84
85 class CustomLocale(Locale):
86     def __init__(self, app_dir,
87                  config=os.path.join(ROOT, "babel.cfg"),
88                  out_file=os.path.join(ROOT, 'wolnelektury/locale-contrib/django.pot'),
89                  name=None):
90         self.app_dir = app_dir
91         self.config = config
92         self.out_file = out_file
93         self.name = name
94
95     def generate(self, languages):
96         os.system('pybabel extract -F "%s" -o "%s" "%s"' % (self.config, self.out_file, self.app_dir))
97         os.system('pybabel update -D django -i %s -d %s' % (self.out_file, os.path.dirname(self.out_file)))
98
99     def po_file(self, language):
100         d = os.path.dirname(self.out_file)
101         n = os.path.basename(self.out_file).split('.')[0]
102         return os.path.join(d, language, 'LC_MESSAGES', n + '.po')
103
104     def save(self, output_directory, languages):
105         for lc in zip(*languages)[0]:
106             if os.path.exists(self.po_file(lc)):
107                 shutil.copy2(self.po_file(lc),
108                              os.path.join(output_directory, lc, self.name + '.po'))
109
110     def load(self, input_directory, languages):
111         for lc in zip(*languages)[0]:
112             shutil.copy2(os.path.join(input_directory, lc, self.name + '.po'),
113                          self.po_file(lc))
114         os.system('pybabel compile -D django -d %s' % os.path.dirname(self.out_file))
115
116
117 SOURCES = []
118
119 for appn in settings.INSTALLED_APPS:
120     app = __import__(appn)
121     if is_our_app(app):
122         try:
123             SOURCES.append(AppLocale(app))
124         except LookupError, e:
125             print "no locales in %s" % app.__name__
126
127 SOURCES.append(ModelTranslation('infopages', 'infopages_db'))
128 SOURCES.append(CustomLocale(os.path.dirname(allauth.__file__), name='contrib'))
129
130
131 class Command(BaseCommand):
132     option_list = BaseCommand.option_list + (
133         make_option('-l', '--load', help='load locales back to source', action='store_true', dest='load', default=False),
134         make_option('-L', '--lang', help='load just one language', dest='lang', default=None),
135         make_option('-d', '--directory', help='load from this directory', dest='directory', default=None),
136         make_option('-o', '--outfile', help='Resulting zip file', dest='outfile', default='./wl-locale.zip'),
137         make_option('-m', '--merge', help='Use git to merge. Please use with clean working directory.', action='store_true', dest='merge', default=False),
138         make_option('-M', '--message', help='commit message', dest='message', default='New locale'),
139
140         )
141     help = 'Make a locale pack'
142     args = ''
143
144     def current_rev(self):
145         return os.popen('git rev-parse HEAD').read()
146
147     def current_branch(self):
148         return os.popen("git branch |grep '^[*]' | cut -c 3-").read()
149
150     def save(self, options):
151         packname = options.get('outfile')
152         packname_b = os.path.basename(packname).split('.')[0]
153         fmt = '.'.join(os.path.basename(packname).split('.')[1:])
154
155         if fmt != 'zip':
156             raise NotImplementedError('Sorry. Only zip format supported at the moment.')
157
158         tmp_dir = tempfile.mkdtemp('-wl-locale')
159         out_dir = os.path.join(tmp_dir, packname)
160         os.mkdir(out_dir)
161
162         try:
163             for lang in settings.LANGUAGES:
164                 os.mkdir(os.path.join(out_dir, lang[0]))
165
166             for src in SOURCES:
167                 src.generate(settings.LANGUAGES)
168                 src.save(out_dir, settings.LANGUAGES)
169                 #                src.save(settings.LANGUAGES)
170
171             # write out revision
172             rev = self.current_rev()
173             rf = open(os.path.join(out_dir, '.revision'), 'w')
174             rf.write(rev)
175             rf.close()
176
177
178             cwd = os.getcwd()
179             try:
180                 os.chdir(os.path.dirname(out_dir))
181                 self.system('zip -r %s %s' % (os.path.join(cwd, packname_b+'.zip'), os.path.basename(out_dir)))
182             finally:
183                 os.chdir(cwd)
184                 #            shutil.make_archive(packname_b, fmt, root_dir=os.path.dirname(out_dir), base_dir=os.path.basename(out_dir))
185         finally:
186             shutil.rmtree(tmp_dir, ignore_errors=True)
187
188     def load(self, options):
189         langs = get_languages(options['lang'])
190
191         for src in SOURCES:
192             src.load(options['directory'], langs)
193
194     def handle(self, *a, **options):
195         if options['load']:
196             if not options['directory'] or not os.path.exists(options['directory']):
197                 print "Directory not provided or does not exist, please use -d"
198                 sys.exit(1)
199                 
200             if options['merge']: self.merge_setup(options['directory'])
201             self.load(options)
202             if options['merge']: self.merge_finish(options['message'])
203         else:
204             self.save(options)
205
206     merge_branch = 'wl-locale-merge'
207     last_branch = None
208     
209     def merge_setup(self, directory):
210         self.last_branch = self.current_branch()
211         rev = open(os.path.join(directory, '.revision')).read()
212
213         self.system('git checkout -b %s %s' % (self.merge_branch, rev))
214
215     def merge_finish(self, message):
216         self.system('git commit -a -m "%s"' % message.replace('"', '\\"'))
217         self.system('git checkout %s' % self.last_branch)
218         self.system('git merge -s recursive -X theirs %s' % self.merge_branch)
219         self.system('git branch -d %s' % self.merge_branch)
220
221     def system(self, fmt, *args):
222         code = os.system(fmt % args)
223         if code != 0:
224             raise OSError('Command %s returned with exit code %d' % (fmt % args, code))
225         return code