]> git.donarmstrong.com Git - lilypond.git/blob - scripts/auxiliar/makelsr.py
fixed issue 1109: makelsr.py now strips right-hand whitespace
[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 unsafe = []
63 unconverted = []
64 notags_files = []
65
66 # mark the section that will be printed verbatim by lilypond-book
67 end_header_re = re.compile ('(\\header {.+?doctitle = ".+?})\n', re.M | re.S)
68
69 doctitle_re = re.compile (r'(doctitle[a-zA-Z_]{0,6}\s*=\s*")((?:\\"|[^"\n])*)"')
70 texinfo_q_re = re.compile (r'@q{(.*?)}')
71 texinfo_qq_re = re.compile (r'@qq{(.*?)}')
72 def doctitle_sub (title_match):
73     # Comma forbidden in Texinfo node name
74     title = title_match.group (2).replace (',', '')
75     title = texinfo_q_re.sub (r"`\1'", title)
76     title = texinfo_qq_re.sub (r'\"\1\"', title)
77     return title_match.group (1) + title + '"'
78
79 def mark_verbatim_section (ly_code):
80     return end_header_re.sub ('\\1 % begin verbatim\n\n', ly_code, 1)
81
82 # '% LSR' comments are to be stripped
83 lsr_comment_re = re.compile (r'\s*%+\s*LSR.*')
84 begin_header_re = re.compile (r'\\header\s*{', re.M)
85 ly_new_version_re = re.compile (r'\\version\s*"(.+?)"')
86 strip_white_spaces_re = re.compile (r'[ \t]+(?=\n)')
87
88 # add tags to ly files from LSR
89 def add_tags (ly_code, tags):
90     return begin_header_re.sub ('\\g<0>\n  lsrtags = "' + tags + '"\n',
91                                 ly_code, 1)
92
93 # for snippets from input/new, add message for earliest working version
94 def add_version (ly_code):
95     return '''%% Note: this file works from version ''' + \
96         ly_new_version_re.search (ly_code).group (1) + '\n'
97
98 s = 'Translation of GIT [Cc]ommittish'
99 texidoc_chunk_re = re.compile (r'^(?:%+\s*' + s + \
100     r'.+)?\s*(?:texidoc|doctitle)([a-zA-Z]{2,4})\s+=(?:.|\n)*?(?=%+\s*' + \
101     s + r'|\n\} % begin verbatim|\n  (?:doctitle|texidoc|lsrtags) |$(?!.|\n))', re.M)
102
103 def update_translated_texidoc (m, snippet_path, visited_languages):
104     base = os.path.splitext (os.path.basename (snippet_path))[0]
105     language_code = m.group (1)
106     visited_languages.append (language_code)
107     texidoc_path = os.path.join ('Documentation', language_code,
108                                  'texidocs', base + '.texidoc')
109     if os.path.isfile (texidoc_path):
110         return open (texidoc_path).read ()
111     else:
112         return m.group (0)
113
114 def copy_ly (srcdir, name, tags):
115     global unsafe
116     global unconverted
117     dest = os.path.join (DEST, name)
118     tags = ', '.join (tags)
119     s = open (os.path.join (srcdir, name)).read ()
120
121     for path in TEXIDOCS:
122         texidoc_translation_path = \
123             os.path.join (path, os.path.splitext (name)[0] + '.texidoc')
124         if os.path.exists (texidoc_translation_path):
125             texidoc_translation = open (texidoc_translation_path).read ()
126             # Since we want to insert the translations verbatim using a 
127             # regexp, \\ is understood as ONE escaped backslash. So we have
128             # to escape those backslashes once more...
129             texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
130             s = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, s, 1)
131
132     s = doctitle_re.sub (doctitle_sub, s)
133     if in_dir and in_dir in srcdir:
134         s = LY_HEADER_LSR + add_tags (s, tags)
135     else:
136         s = LY_HEADER_NEW + add_version (s) + s
137
138     s = mark_verbatim_section (s)
139     s = lsr_comment_re.sub ('', s)
140     s = strip_white_spaces_re.sub ('', s)
141     open (dest, 'w').write (s)
142
143     e = os.system ("convert-ly -e '%s'" % dest)
144     if e:
145         unconverted.append (dest)
146     if os.path.exists (dest + '~'):
147         os.remove (dest + '~')
148     # no need to check snippets from input/new
149     if in_dir and in_dir in srcdir:
150         # -V seems to make unsafe snippets fail nicer/sooner
151         e = os.system ("lilypond -V -dno-print-pages -dsafe -o /tmp/lsrtest '%s'" % dest)
152         if e:
153             unsafe.append (dest)
154
155 def read_source_with_dirs (src):
156     s = {}
157     l = {}
158     for tag in TAGS:
159         srcdir = os.path.join (src, tag)
160         l[tag] = set (map (os.path.basename,
161                            glob.glob (os.path.join (srcdir, '*.ly'))))
162         for f in l[tag]:
163             if f in s:
164                 s[f][1].append (tag)
165             else:
166                 s[f] = (srcdir, [tag])
167     return s, l
168
169
170 tags_re = re.compile ('lsrtags\\s*=\\s*"(.+?)"')
171
172 def read_source (src):
173     s = {}
174     l = dict ([(tag, set()) for tag in TAGS])
175     for f in glob.glob (os.path.join (src, '*.ly')):
176         basename = os.path.basename (f)
177         m = tags_re.search (open (f, 'r').read ())
178         if m:
179             file_tags = [tag.strip() for tag in m.group (1). split(',')]
180             s[basename] = (src, file_tags)
181             [l[tag].add (basename) for tag in file_tags if tag in TAGS]
182         else:
183             notags_files.append (f)
184     return s, l
185
186
187 def dump_file_list (file, file_list, update=False):
188     if update:
189         old_list = set (open (file, 'r').read ().splitlines ())
190         old_list.update (file_list)
191         new_list = list (old_list)
192     else:
193         new_list = file_list
194     f = open (file, 'w')
195     f.write ('\n'.join (sorted (new_list)) + '\n')
196
197 def update_ly_in_place (snippet_path):
198     visited_languages = []
199     contents = open (snippet_path).read ()
200     contents = texidoc_chunk_re.sub \
201         (lambda m: update_translated_texidoc (m,
202                                               snippet_path,
203                                               visited_languages),
204          contents)
205     for language_code in langdefs.LANGDICT:
206         if not language_code in visited_languages:
207             base = os.path.splitext (os.path.basename (snippet_path))[0]
208             texidoc_path = os.path.join ('Documentation', language_code,
209                          'texidocs', base + '.texidoc')
210             if os.path.isfile (texidoc_path):
211                 texidoc_translation = open (texidoc_path).read ()
212                 texidoc_translation = texidoc_translation.replace ('\\', '\\\\')
213                 contents = begin_header_re.sub ('\\g<0>\n' + texidoc_translation, contents, 1)
214     contents = doctitle_re.sub (doctitle_sub, contents)
215     open (snippet_path, 'w').write (contents)
216
217 if in_dir:
218     ## clean out existing lys and generated files
219     map (os.remove, glob.glob (os.path.join (DEST, '*.ly')) +
220          glob.glob (os.path.join (DEST, '*.snippet-list')))
221
222     # read LSR source where tags are defined by subdirs
223     snippets, tag_lists = read_source_with_dirs (in_dir)
224
225     # read input/new where tags are directly defined
226     s, l = read_source (NEW_LYS)
227     snippets.update (s)
228     for t in TAGS:
229         tag_lists[t].update (l[t])
230 else:
231     snippets, tag_lists = read_source (NEW_LYS)
232     ## update texidocs of snippets that don't come from NEW_LYS
233     for snippet_path in glob.glob (os.path.join (DEST, '*.ly')):
234         if not os.path.basename (snippet_path) in snippets:
235             update_ly_in_place (snippet_path)
236
237 for (name, (srcdir, tags)) in snippets.items ():
238     copy_ly (srcdir, name, tags)
239 for (tag, file_set) in tag_lists.items ():
240     dump_file_list (os.path.join (DEST, tag + '.snippet-list'),
241                     file_set, update=not(in_dir))
242 if unconverted:
243     sys.stderr.write ('These files could not be converted successfully by convert-ly:\n')
244     sys.stderr.write ('\n'.join (unconverted) + '\n\n')
245 if notags_files:
246     sys.stderr.write ('No tags could be found in these files:\n')
247     sys.stderr.write ('\n'.join (notags_files) + '\n\n')
248 if unsafe:
249     dump_file_list ('lsr-unsafe.txt', unsafe)
250     sys.stderr.write ('''
251
252 Unsafe files printed in lsr-unsafe.txt: CHECK MANUALLY!
253   git add %s/*.ly
254   xargs git diff HEAD < lsr-unsafe.txt
255
256 ''' % DEST)