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