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