]> git.donarmstrong.com Git - lilypond.git/blob - scripts/build/extract_texi_filenames.py
Add a -q quiet flag to 'make website' scripts
[lilypond.git] / scripts / build / extract_texi_filenames.py
1 #!@PYTHON@
2 # -*- coding: utf-8 -*-
3 # extract_texi_filenames.py
4
5 # USAGE:  extract_texi_filenames.py [-o OUTDIR] FILES
6 #
7 # -o OUTDIR specifies that output files should rather be written in OUTDIR
8 #
9 # Description:
10 # This script parses the .texi file given and creates a file with the
11 # nodename <=> filename/anchor map.
12 # The idea behind: Unnumbered subsections go into the same file as the
13 # previous numbered section, @translationof gives the original node name,
14 # which is then used for the filename/anchor.
15 #
16 # If this script is run on a file texifile.texi, it produces a file
17 # texifile[.LANG].xref-map with tab-separated entries of the form
18 #        NODE\tFILENAME\tANCHOR
19 # LANG is the document language in case it's not 'en'
20 # Note: The filename does not have any extension appended!
21 # This file should then be used by our texi2html init script to determine
22 # the correct file name and anchor for external refs
23
24 # For translated documentation: cross-references to nodes that exist
25 # only in documentation in English are allowed, that's why the already
26 # generated map file of docs in English is loaded with
27 # --master-map-file option, then the node names that are defined in
28 # the map for the manual in English but not in the translated manual
29 # are added to the map for the translated manual.
30
31
32 import sys
33 import re
34 import os
35 import getopt
36
37 options_list, files = getopt.getopt (sys.argv[1:],'o:s:hI:m:k:q',
38                                      ['output=', 'split=',
39                                       'help', 'include=',
40                                       'master-map-file=',
41                                       'known-missing-files=',
42                                       'quiet'])
43
44 help_text = r"""Usage: %(program_name)s [OPTIONS]... TEXIFILE...
45 Extract files names for texinfo (sub)sections from the texinfo files.
46
47 Options:
48  -h, --help                     print this help
49  -I, --include=DIRECTORY        append DIRECTORY to include search path
50  -m, --master-map-file=FILE     use FILE as master map file
51  -o, --output=DIRECTORY         write .xref-map files to DIRECTORY
52  -s, --split=MODE               split manual according to MODE. Possible values
53                                 are section and custom (default)
54  -k, --known-missing-files      a filename which has a list of files known
55                                 to be missing for this make
56  -q, --quiet                    suppress most messages
57 """
58
59 def help (text):
60     sys.stdout.write ( text)
61     sys.exit (0)
62
63 outdir = '.'
64 split = "custom"
65 include_path = ['.',]
66 master_map_file = ''
67 known_missing_files = []
68 known_missing_files_file = ''
69 suppress_output = False
70 initial_map = {}
71 for opt in options_list:
72     o = opt[0]
73     a = opt[1]
74     if o == '-h' or o == '--help':
75         help (help_text % vars ())
76     if o == '-I' or o == '--include':
77         if os.path.isdir (a):
78             include_path.append (a)
79         else:
80             print 'NOT A DIR from: ', os.getcwd (), a
81     elif o == '-o' or o == '--output':
82         outdir = a
83     elif o == '-s' or o == '--split':
84         split = a
85     elif o == '-m' or o == '--master-map-file':
86         if os.path.isfile (a):
87             master_map_file = a
88     elif o == '--known-missing-files':
89         if os.path.isfile (a):
90             known_missing_files_file = a
91         else:
92             print 'Missing files list file not found: ', a
93     elif o == '-q' or o == '--quiet':
94         suppress_output = True
95     else:
96         raise Exception ('unknown option: ' + o)
97
98 if known_missing_files_file:
99     missing_files = open (known_missing_files_file, 'r')
100     known_missing_files = missing_files.read().splitlines()
101     missing_files.close()
102
103 if not os.path.isdir (outdir):
104     if os.path.exists (outdir):
105         os.unlink (outdir)
106     os.makedirs (outdir)
107
108 include_re = re.compile (r'@include ((?!../lily-).*?\.i?te(xi|ly))$', re.M)
109 whitespaces = re.compile (r'\s+')
110 section_translation_re = re.compile ('^@(node|(?:unnumbered|appendix)\
111 (?:(?:sub){0,2}sec)?|top|chapter|(?:sub){0,2}section|\
112 (?:major|chap|(?:sub){0,2})heading|lydoctitle|translationof) \
113 (.+)$', re.MULTILINE)
114 external_node_re = re.compile (r'\s+@c\s+external.*')
115
116 def expand_includes (m, filename):
117     include_name = m.group (1)
118     filepath = os.path.join (os.path.dirname (filename), include_name)
119     if os.path.exists (filepath):
120         return extract_sections (filepath)[1]
121     else:
122         for directory in include_path:
123             filepath = os.path.join (directory, include_name)
124             if os.path.exists (filepath):
125                 return extract_sections (filepath)[1]
126         if not (include_name in known_missing_files):
127             # Not found
128             print 'No such file: ' + include_name
129             print 'Search path: ' + ':'.join (include_path)
130         return ''
131
132 lang_re = re.compile (r'^@documentlanguage (.+)', re.M)
133
134 def extract_sections (filename):
135     result = ''
136     f = open (filename, 'r')
137     page = f.read ()
138     f.close()
139     # Search document language
140     m = lang_re.search (page)
141     if m and m.group (1) != 'en':
142         lang_suffix = '.' + m.group (1)
143     else:
144         lang_suffix = ''
145     # Replace all includes by their list of sections and extract all sections
146     page = include_re.sub (lambda m: expand_includes (m, filename), page)
147     sections = section_translation_re.findall (page)
148     for sec in sections:
149         result += "@" + sec[0] + " " + sec[1] + "\n"
150     return (lang_suffix, result)
151
152 # Convert a given node name to its proper file name (normalization as
153 # explained in the texinfo manual:
154 # http://www.gnu.org/software/texinfo/manual/texinfo/html_node/HTML-Xref-Node-Name-Expansion.html
155 def texinfo_file_name(title):
156     # exception: The top node is always mapped to index.html
157     if title == "Top":
158         return "index"
159     # File name normalization by texinfo (described in the texinfo manual):
160     # 1/2: letters and numbers are left unchanged
161     # 3/4: multiple, leading and trailing whitespace is removed
162     title = title.strip ();
163     title = whitespaces.sub (' ', title)
164     # 5:   all remaining spaces are converted to '-'
165     # 6:   all other 7- or 8-bit chars are replaced by _xxxx (xxxx=ascii character code)
166     result = ''
167     for index in range(len(title)):
168         char = title[index]
169         if char == ' ': # space -> '-'
170             result += '-'
171         elif ( ('0' <= char and char <= '9' ) or
172                ('A' <= char and char <= 'Z' ) or
173                ('a' <= char and char <= 'z' ) ):  # number or letter
174             result += char
175         else:
176             ccode = ord(char)
177             if ccode <= 0xFFFF:
178                 result += "_%04x" % ccode
179             else:
180                 result += "__%06x" % ccode
181     # 7: if name begins with number, prepend 't_g' (so it starts with a letter)
182     if (result != '') and (ord(result[0]) in range (ord('0'), ord('9'))):
183         result = 't_g' + result
184     return result
185
186 texinfo_re = re.compile (r'@.*?{(.*?)}')
187 def remove_texinfo (title):
188     title = title.replace ('--', '-')
189     return texinfo_re.sub (r'\1', title).strip ()
190
191 def create_texinfo_anchor (title):
192     return texinfo_file_name (remove_texinfo (title))
193
194 unnumbered_re = re.compile (r'unnumbered.+|lydoctitle')
195 file_name_section_level = {
196     'top': 4,
197     'chapter':3,
198     'unnumbered':3,
199     'appendix':3,
200     'section':2,
201     'unnumberedsec':2,
202     'appendixsec':2,
203     'subsection':1,
204     'unnumberedsubsec':1,
205     'appendixsubsec':1,
206     'subsubsection':0,
207     'unnumberedsubsubsec':0,
208     'appendixsubsubsec':0
209 }
210 if split in file_name_section_level:
211     splitting_level = file_name_section_level[split]
212 else:
213     splitting_level = -1
214 def process_sections (filename, lang_suffix, page):
215     sections = section_translation_re.findall (page)
216     basename = os.path.splitext (os.path.basename (filename))[0]
217     p = os.path.join (outdir, basename) + lang_suffix + '.xref-map'
218     if not suppress_output:
219         print 'writing:', p
220     f = open (p, 'w')
221
222     this_title = ''
223     this_filename = 'index'
224     this_anchor = ''
225     this_unnumbered = False
226     had_section = False
227     for sec in sections:
228         if sec[0] == "node":
229             # Write out the cached values to the file and start a new
230             # section:
231             if this_title and this_title != 'Top':
232                     f.write (this_title + "\t" + this_filename + "\t" + this_anchor + "\n")
233             had_section = False
234             this_title = remove_texinfo (sec[1])
235             this_anchor = create_texinfo_anchor (sec[1])
236             # delete entry from master map file
237             if this_title in initial_map:
238                 del initial_map[this_title]
239         elif sec[0] == "translationof":
240             (original_node, external_node) = external_node_re.subn ('', sec[1])
241             original_node = remove_texinfo (original_node)
242             # The following binds the translator to use the
243             # translated node name in cross-references in case
244             # it exists
245             if external_node and original_node in initial_map:
246                 del initial_map[original_node]
247             anchor = create_texinfo_anchor (sec[1])
248             # If @translationof is used, it gives the original
249             # node name, which we use for the anchor and the file
250             # name (if it is a numbered node)
251             this_anchor = anchor
252             if not this_unnumbered:
253                 this_filename = anchor
254             elif original_node in initial_map:
255                 this_filename = initial_map[original_node][2]
256         else:
257             # Some pages might not use a node for every section, so
258             # treat this case here, too: If we already had a section
259             # and encounter another one before the next @node, we
260             # write out the old one and start with the new values
261             if had_section and split != 'node' and this_title:
262                 f.write (this_title + "\t" + this_filename + "\t" + this_anchor + "\n")
263                 this_title = remove_texinfo (sec[1])
264                 this_anchor = create_texinfo_anchor (sec[1])
265             had_section = True
266
267             if split == 'custom':
268                 # unnumbered nodes use the previously used file name,
269                 # only numbered nodes get their own filename! However,
270                 # top-level @unnumbered still get their own file.
271                 this_unnumbered = unnumbered_re.match (sec[0])
272                 if not this_unnumbered:
273                     this_filename = this_anchor
274             elif split == 'node':
275                 this_filename = this_anchor
276             else:
277                 if sec[0] in file_name_section_level and \
278                         file_name_section_level[sec[0]] >= splitting_level:
279                     this_filename = this_anchor
280
281     if this_title and this_title != 'Top':
282         f.write (this_title + "\t" + this_filename + "\t" + this_anchor + "\n")
283
284     for node in initial_map:
285         f.write ("\t".join (initial_map[node]) + "\n")
286     f.close ()
287
288 xref_map_line_re = re.compile (r'(.*?)\t(.*?)\t(.*?)$')
289 if master_map_file:
290     for line in open (master_map_file):
291         m = xref_map_line_re.match (line)
292         if m:
293             initial_map[m.group (1)] = (m.group (1), m.group (2), m.group (3))
294
295 for filename in files:
296     if not suppress_output:
297         print "extract_texi_filenames.py: Processing %s" % filename
298     (lang_suffix, sections) = extract_sections (filename)
299     process_sections (filename, lang_suffix, sections)