]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/makelsr.py
fixed issue 1148: makelsr.py now uses local convert-ly in out/bin if existing
[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; it is automatically
25 %% generated from LSR http://lsr.dsi.unimi.it
26 %% This file is in the public domain.
27 '''
28
29 LY_HEADER_NEW = '''%% Do not edit this file; it is automatically
30 %% generated from %s
31 %% This file is in the public domain.
32 ''' % NEW_LYS
33
34 TAGS = []
35 # NR 1
36 TAGS.extend (['pitches', 'rhythms', 'expressive-marks',
37 'repeats', 'simultaneous-notes', 'staff-notation',
38 'editorial-annotations', 'text'])
39 # NR 2
40 TAGS.extend (['vocal-music', 'chords', 'keyboards',
41 'percussion', 'fretted-strings', 'unfretted-strings',
42 'ancient-notation', 'winds', 'world-music'
43 ])
44
45 # other
46 TAGS.extend (['contexts-and-engravers', 'tweaks-and-overrides',
47 'paper-and-layout', 'breaks', 'spacing', 'midi', 'titles', 'template'])
48
49 def exit_with_usage (n=0):
50     sys.stderr.write (USAGE)
51     sys.exit (n)
52
53 if len (sys.argv) >= 2:
54     in_dir = sys.argv[1]
55     if len (sys.argv) >= 3:
56         exit_with_usage (2)
57     if not (os.path.isdir (DEST) and os.path.isdir (NEW_LYS)):
58         exit_with_usage (3)
59 else:
60     in_dir = ''
61
62 # which convert-ly to use
63 if os.path.isfile("out/bin/convert-ly"):
64     conv_path='out/bin/'
65 else:
66     conv_path=''
67 convert_ly=conv_path+'convert-ly'
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 copy_ly (srcdir, name, tags):
123     global unsafe
124     global unconverted
125     dest = os.path.join (DEST, name)
126     tags = ', '.join (tags)
127     s = open (os.path.join (srcdir, name)).read ()
128
129     for path in TEXIDOCS:
130         texidoc_translation_path = \
131             os.path.join (path, os.path.splitext (name)[0] + '.texidoc')
132         if os.path.exists (texidoc_translation_path):
133             texidoc_translation = open (texidoc_translation_path).read ()
134             # Since we want to insert the translations verbatim using a 
135             # regexp, \\ is understood as ONE escaped backslash. So we have
136             # to escape those backslashes once more...
137             texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
138             s = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, s, 1)
139
140     s = doctitle_re.sub (doctitle_sub, s)
141     if in_dir and in_dir in srcdir:
142         s = LY_HEADER_LSR + add_tags (s, tags)
143     else:
144         s = LY_HEADER_NEW + add_version (s) + s
145
146     s = mark_verbatim_section (s)
147     s = lsr_comment_re.sub ('', s)
148     s = strip_white_spaces_re.sub ('', s)
149     open (dest, 'w').write (s)
150
151     e = os.system (convert_ly+(" -e '%s'" % dest))
152     if e:
153         unconverted.append (dest)
154     if os.path.exists (dest + '~'):
155         os.remove (dest + '~')
156     # no need to check snippets from input/new
157     if in_dir and in_dir in srcdir:
158         # -V seems to make unsafe snippets fail nicer/sooner
159         e = os.system ("lilypond -V -dno-print-pages -dsafe -o /tmp/lsrtest '%s'" % dest)
160         if e:
161             unsafe.append (dest)
162
163 def read_source_with_dirs (src):
164     s = {}
165     l = {}
166     for tag in TAGS:
167         srcdir = os.path.join (src, tag)
168         l[tag] = set (map (os.path.basename,
169                            glob.glob (os.path.join (srcdir, '*.ly'))))
170         for f in l[tag]:
171             if f in s:
172                 s[f][1].append (tag)
173             else:
174                 s[f] = (srcdir, [tag])
175     return s, l
176
177
178 tags_re = re.compile ('lsrtags\\s*=\\s*"(.+?)"')
179
180 def read_source (src):
181     s = {}
182     l = dict ([(tag, set()) for tag in TAGS])
183     for f in glob.glob (os.path.join (src, '*.ly')):
184         basename = os.path.basename (f)
185         m = tags_re.search (open (f, 'r').read ())
186         if m:
187             file_tags = [tag.strip() for tag in m.group (1). split(',')]
188             s[basename] = (src, file_tags)
189             [l[tag].add (basename) for tag in file_tags if tag in TAGS]
190         else:
191             notags_files.append (f)
192     return s, l
193
194
195 def dump_file_list (file, file_list, update=False):
196     if update:
197         old_list = set (open (file, 'r').read ().splitlines ())
198         old_list.update (file_list)
199         new_list = list (old_list)
200     else:
201         new_list = file_list
202     f = open (file, 'w')
203     f.write ('\n'.join (sorted (new_list)) + '\n')
204
205 def update_ly_in_place (snippet_path):
206     visited_languages = []
207     contents = open (snippet_path).read ()
208     contents = texidoc_chunk_re.sub \
209         (lambda m: update_translated_texidoc (m,
210                                               snippet_path,
211                                               visited_languages),
212          contents)
213     for language_code in langdefs.LANGDICT:
214         if not language_code in visited_languages:
215             base = os.path.splitext (os.path.basename (snippet_path))[0]
216             texidoc_path = os.path.join ('Documentation', language_code,
217                          'texidocs', base + '.texidoc')
218             if os.path.isfile (texidoc_path):
219                 texidoc_translation = open (texidoc_path).read ()
220                 texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
221                 contents = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, contents, 1)
222     contents = doctitle_re.sub (doctitle_sub, contents)
223     open (snippet_path, 'w').write (contents)
224
225 if in_dir:
226     ## clean out existing lys and generated files
227     map (os.remove, glob.glob (os.path.join (DEST, '*.ly')) +
228          glob.glob (os.path.join (DEST, '*.snippet-list')))
229
230     # read LSR source where tags are defined by subdirs
231     snippets, tag_lists = read_source_with_dirs (in_dir)
232
233     # read input/new where tags are directly defined
234     s, l = read_source (NEW_LYS)
235     snippets.update (s)
236     for t in TAGS:
237         tag_lists[t].update (l[t])
238 else:
239     snippets, tag_lists = read_source (NEW_LYS)
240     ## update texidocs of snippets that don't come from NEW_LYS
241     for snippet_path in glob.glob (os.path.join (DEST, '*.ly')):
242         if not os.path.basename (snippet_path) in snippets:
243             update_ly_in_place (snippet_path)
244
245 for (name, (srcdir, tags)) in snippets.items ():
246     copy_ly (srcdir, name, tags)
247 for (tag, file_set) in tag_lists.items ():
248     dump_file_list (os.path.join (DEST, tag + '.snippet-list'),
249                     file_set, update=not(in_dir))
250 if unconverted:
251     sys.stderr.write ('These files could not be converted successfully by convert-ly:\n')
252     sys.stderr.write ('\n'.join (unconverted) + '\n\n')
253 if notags_files:
254     sys.stderr.write ('No tags could be found in these files:\n')
255     sys.stderr.write ('\n'.join (notags_files) + '\n\n')
256 if unsafe:
257     dump_file_list ('lsr-unsafe.txt', unsafe)
258     sys.stderr.write ('''
259
260 Unsafe files printed in lsr-unsafe.txt: CHECK MANUALLY!
261   git add %s/*.ly
262   xargs git diff HEAD < lsr-unsafe.txt
263
264 ''' % DEST)