]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/makelsr.py
Merge branch 'lilypond/translation' into staging
[lilypond.git] / scripts / auxiliar / makelsr.py
1 #!/usr/bin/env python
2
3 import sys
4 import os
5 import glob
6 import re
7
8 sys.path.append ('python')
9 import langdefs
10
11 DEST = os.path.join ('Documentation', 'snippets')
12 NEW_LYS = os.path.join ('Documentation', 'snippets', 'new')
13 TEXIDOCS = [os.path.join ('Documentation', language_code, 'texidocs')
14             for language_code in langdefs.LANGDICT]
15
16 USAGE = '''  Usage: makelsr.py [LSR_SNIPPETS_DIR]
17 This script must be run from top of the source tree;
18 it updates snippets %(DEST)s with snippets
19 from %(NEW_LYS)s or LSR_SNIPPETS_DIR.
20 If a snippet is present in both directories, the one
21 from %(NEW_LYS)s is preferred.
22 ''' % vars ()
23
24 LY_HEADER_LSR = '''%% DO NOT EDIT this file manually; it is automatically
25 %% generated from LSR http://lsr.dsi.unimi.it
26 %% Make any changes in LSR itself, or in Documentation/snippets/new/ ,
27 %% and then run scripts/auxiliar/makelsr.py
28 %%
29 %% This file is in the public domain.
30 '''
31
32 LY_HEADER_NEW = '''%% DO NOT EDIT this file manually; it is automatically
33 %% generated from %s
34 %% Make any changes in Documentation/snippets/new/
35 %% and then run scripts/auxiliar/makelsr.py
36 %%
37 %% This file is in the public domain.
38 ''' % NEW_LYS
39
40 def exit_with_usage (n=0):
41     sys.stderr.write (USAGE)
42     sys.exit (n)
43
44 if len (sys.argv) >= 2:
45     in_dir = sys.argv[1]
46     if not (os.path.isdir (in_dir)):
47         sys.stderr.write (in_dir + ' is not a directory.\n')
48         exit (2)
49     if len (sys.argv) >= 3:
50         exit_with_usage (2)
51     if not (os.path.isdir (DEST) and os.path.isdir (NEW_LYS)):
52         exit_with_usage (3)
53 else:
54     in_dir = ''
55
56 TAGS = os.listdir (in_dir)
57
58 # which convert-ly to use
59 if os.path.isfile("out/bin/convert-ly"):
60     conv_path='out/bin/'
61 elif os.path.isfile("build/out/bin/convert-ly"):
62     conv_path='build/out/bin/'
63 else:
64     conv_path=''
65 convert_ly=conv_path+'convert-ly'
66 lilypond_bin=conv_path+'lilypond'
67
68 print 'using '+convert_ly
69
70 unsafe = []
71 unconverted = []
72 notags_files = []
73
74 # mark the section that will be printed verbatim by lilypond-book
75 end_header_re = re.compile ('(\\header {.+?doctitle = ".+?})\n', re.M | re.S)
76
77 doctitle_re = re.compile (r'(doctitle[a-zA-Z_]{0,6}\s*=\s*")((?:\\"|[^"\n])*)"')
78 texinfo_q_re = re.compile (r'@q{(.*?)}')
79 texinfo_qq_re = re.compile (r'@qq{(.*?)}')
80 def doctitle_sub (title_match):
81     # Comma forbidden in Texinfo node name
82     title = title_match.group (2).replace (',', '')
83     title = texinfo_q_re.sub (r"`\1'", title)
84     title = texinfo_qq_re.sub (r'\"\1\"', title)
85     return title_match.group (1) + title + '"'
86
87 def mark_verbatim_section (ly_code):
88     return end_header_re.sub ('\\1 % begin verbatim\n\n', ly_code, 1)
89
90 # '% LSR' comments are to be stripped
91 lsr_comment_re = re.compile (r'\s*%+\s*LSR.*')
92 begin_header_re = re.compile (r'\\header\s*{', re.M)
93 ly_new_version_re = re.compile (r'\\version\s*"(.+?)"')
94 strip_white_spaces_re = re.compile (r'[ \t]+(?=\n)')
95
96 # add tags to ly files from LSR
97 def add_tags (ly_code, tags):
98     return begin_header_re.sub ('\\g<0>\n  lsrtags = "' + tags + '"\n',
99                                 ly_code, 1)
100
101 # for snippets from input/new, add message for earliest working version
102 def add_version (ly_code):
103     return '''%% Note: this file works from version ''' + \
104         ly_new_version_re.search (ly_code).group (1) + '\n'
105
106 s = 'Translation of GIT [Cc]ommittish'
107 texidoc_chunk_re = re.compile (r'^(?:%+\s*' + s + \
108     r'.+)?\s*(?:texidoc|doctitle)([a-zA-Z]{2,4})\s+=(?:.|\n)*?(?=%+\s*' + \
109     s + r'|\n\} % begin verbatim|\n  (?:doctitle|texidoc|lsrtags) |$(?!.|\n))', re.M)
110
111 def update_translated_texidoc (m, snippet_path, visited_languages):
112     base = os.path.splitext (os.path.basename (snippet_path))[0]
113     language_code = m.group (1)
114     visited_languages.append (language_code)
115     texidoc_path = os.path.join ('Documentation', language_code,
116                                  'texidocs', base + '.texidoc')
117     if os.path.isfile (texidoc_path):
118         return open (texidoc_path).read ()
119     else:
120         return m.group (0)
121
122 def escape_backslashes_in_header(snippet):
123     # ASSUME: the \header exists.
124     header_char_number_start = snippet.find('\header {')
125     header_char_number_end = snippet.find('} % begin verbatim')
126
127     header = snippet[header_char_number_start:header_char_number_end]
128     # two levels of escaping happening here -- 4\ means 1\
129     # and the 10\ means two \ backslashes (that's 8\ ), and
130     # one backreference to group 1 (that's two 2\ ).
131     new_header = re.sub("@code\{\\\\([a-zA-Z])", "@code{\\\\\\\\\\1", header)
132     escaped_snippet = (snippet[:header_char_number_start] +
133         new_header + snippet[header_char_number_end:])
134     return escaped_snippet
135
136 def copy_ly (srcdir, name, tags):
137     global unsafe
138     global unconverted
139     dest = os.path.join (DEST, name)
140     tags = ', '.join (tags)
141     s = open (os.path.join (srcdir, name)).read ()
142     sys.stderr.write ('\nmakelsr.py: reading ' + os.path.join (srcdir, name) + '\n')
143
144     for path in TEXIDOCS:
145         texidoc_translation_path = \
146             os.path.join (path, os.path.splitext (name)[0] + '.texidoc')
147         if os.path.exists (texidoc_translation_path):
148             texidoc_translation = open (texidoc_translation_path).read ()
149             # Since we want to insert the translations verbatim using a 
150             # regexp, \\ is understood as ONE escaped backslash. So we have
151             # to escape those backslashes once more...
152             texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
153             s = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, s, 1)
154
155     s = doctitle_re.sub (doctitle_sub, s)
156     if in_dir and in_dir in srcdir:
157         s = LY_HEADER_LSR + add_tags (s, tags)
158     else:
159         s = LY_HEADER_NEW + add_version (s) + s
160
161     s = mark_verbatim_section (s)
162     s = lsr_comment_re.sub ('', s)
163     s = strip_white_spaces_re.sub ('', s)
164     s = escape_backslashes_in_header (s)
165     open (dest, 'w').write (s)
166     sys.stderr.write ('makelsr.py: writing ' + dest + '\n')
167
168     e = os.system (convert_ly+(" -d -e '%s'" % dest))
169     if e:
170         unconverted.append (dest)
171     if os.path.exists (dest + '~'):
172         os.remove (dest + '~')
173     # no need to check snippets from input/new
174     if in_dir and in_dir in srcdir:
175         e = os.system ("%s -dno-print-pages -dsafe -o /tmp/lsrtest '%s'" %(lilypond_bin, dest))
176         if e:
177             unsafe.append (dest)
178
179 def read_source_with_dirs (src):
180     s = {}
181     l = {}
182     for tag in TAGS:
183         srcdir = os.path.join (src, tag)
184         l[tag] = set (map (os.path.basename,
185                            glob.glob (os.path.join (srcdir, '*.ly'))))
186         for f in l[tag]:
187             if f in s:
188                 s[f][1].append (tag)
189             else:
190                 s[f] = (srcdir, [tag])
191     return s, l
192
193
194 tags_re = re.compile ('lsrtags\\s*=\\s*"(.+?)"')
195
196 def read_source (src):
197     s = {}
198     l = dict ([(tag, set()) for tag in TAGS])
199     for f in glob.glob (os.path.join (src, '*.ly')):
200         basename = os.path.basename (f)
201         m = tags_re.search (open (f, 'r').read ())
202         if m:
203             file_tags = [tag.strip() for tag in m.group (1). split(',')]
204             s[basename] = (src, file_tags)
205             [l[tag].add (basename) for tag in file_tags if tag in TAGS]
206         else:
207             notags_files.append (f)
208     return s, l
209
210
211 def dump_file_list (file, file_list, update=False):
212     if update:
213         old_list = set (open (file, 'r').read ().splitlines ())
214         old_list.update (file_list)
215         new_list = list (old_list)
216     else:
217         new_list = file_list
218     f = open (file, 'w')
219     f.write ('\n'.join (sorted (new_list)) + '\n')
220
221 def update_ly_in_place (snippet_path):
222     visited_languages = []
223     contents = open (snippet_path).read ()
224     contents = texidoc_chunk_re.sub \
225         (lambda m: update_translated_texidoc (m,
226                                               snippet_path,
227                                               visited_languages),
228          contents)
229     need_line_break_workaround = False
230     for language_code in langdefs.LANGDICT:
231         if not language_code in visited_languages:
232             base = os.path.splitext (os.path.basename (snippet_path))[0]
233             texidoc_path = os.path.join ('Documentation', language_code,
234                          'texidocs', base + '.texidoc')
235             if os.path.isfile (texidoc_path):
236                 texidoc_translation = open (texidoc_path).read ()
237                 texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
238                 contents = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, contents, 1)
239         else:
240             need_line_break_workaround = True
241     contents = doctitle_re.sub (doctitle_sub, contents)
242     contents = escape_backslashes_in_header (contents)
243
244     # workaround for a bug in the regex's that I'm not smart
245     # enough to figure out.  -gp
246     if need_line_break_workaround:
247         first_translated = contents.find('%% Translation of')
248         keep = contents[:first_translated+5]
249         contents = keep + contents[first_translated+5:].replace('%% Translation of', '\n%% Translation of')
250
251     open (snippet_path, 'w').write (contents)
252
253 if in_dir:
254     ## clean out existing lys and generated files
255     map (os.remove, glob.glob (os.path.join (DEST, '*.ly')) +
256          glob.glob (os.path.join (DEST, '*.snippet-list')))
257
258     # read LSR source where tags are defined by subdirs
259     snippets, tag_lists = read_source_with_dirs (in_dir)
260
261     # read input/new where tags are directly defined
262     s, l = read_source (NEW_LYS)
263     snippets.update (s)
264     for t in TAGS:
265         tag_lists[t].update (l[t])
266 else:
267     snippets, tag_lists = read_source (NEW_LYS)
268     ## update texidocs of snippets that don't come from NEW_LYS
269     for snippet_path in glob.glob (os.path.join (DEST, '*.ly')):
270         if not os.path.basename (snippet_path) in snippets:
271             update_ly_in_place (snippet_path)
272
273 for (name, (srcdir, tags)) in snippets.items ():
274     copy_ly (srcdir, name, tags)
275 for (tag, file_set) in tag_lists.items ():
276     dump_file_list (os.path.join (DEST, tag + '.snippet-list'),
277                     file_set, update=not(in_dir))
278 if unconverted:
279     sys.stderr.write ('These files could not be converted successfully by convert-ly:\n')
280     sys.stderr.write ('\n'.join (unconverted) + '\n\n')
281 if notags_files:
282     sys.stderr.write ('No tags could be found in these files:\n')
283     sys.stderr.write ('\n'.join (notags_files) + '\n\n')
284 if unsafe:
285     dump_file_list ('lsr-unsafe.txt', unsafe)
286     sys.stderr.write ('''
287
288 Unsafe files printed in lsr-unsafe.txt: CHECK MANUALLY!
289   git add %s/*.ly
290   xargs git diff HEAD < lsr-unsafe.txt
291
292 ''' % DEST)