Debian Codegraph @

libs/zziplib/zziplib-src/docs/dbk2man.py

raw
1 #! /usr/bin/python3
2
3 """ Converts an xml-file with docbook elements into troff manual pages.
4 The conversion uses etree expecting <refentry> elements in the input.
5 The output goes to a multiple files in manX/* subdirectories.
6 """
7
8 __author__ = "Guido U. Draheim"
9
10 import logging
11 import os.path
12 import re
13 import collections
14 import xml.etree.ElementTree as ET
15
16 logg = logging.getLogger("dbk2man")
17
18 def decodes(text):
19 if not text: return text
20 try:
21 return text.decode("utf-8")
22 except:
23 try:
24 return text.decode("latin-1")
25 except:
26 return str(text)
27
28 def esc(text):
29 text = decodes(text)
30 text = text.replace(".", "\\&.")
31 text = text.replace("-", "\\-")
32 return text
33 def unescape(text):
34 text = decodes(text)
35 text = text.replace('&lt;', '<')
36 text = text.replace('&gt;', '>')
37 text = text.replace('&quot;', '"')
38 text = text.replace('&amp;', '&')
39 return text
40 def htm(text):
41 text = decodes(text)
42 text = text.replace('&', '&amp;')
43 text = text.replace('<', '&lt;')
44 text = text.replace('>', '&gt;')
45 text = text.replace('"', '&quot;')
46 return text
47 def mailhref(text):
48 return re.sub("<([^<>]*@[^<>]*)>",
49 lambda x: '&lt;<a href="mailto:%s">%s</a>&gt;' % (x.group(1), x.group(1)),
50 text)
51
52 OverviewEntry = collections.namedtuple("OverviewEntry", ["manpage", "manvolnum", "refpurpose"])
53
54 def parse_docbook(filename):
55 tree = ET.parse(filename)
56 return tree.getroot()
57
58 def dbk2(man, filenames, subdirectory = "."):
59 for filename in filenames:
60 root = parse_docbook(filename)
61 overview = docbook2(man, root, subdirectory)
62 overview2(man, overview, subdirectory, filename)
63
64 def docbook2(man, root, subdirectory = "."):
65 if root.tag != "reference":
66 logg.warning("no <reference> found, not a docbook file?")
67 logg.warning("found <%s> instead", root.tag)
68 overview = {}
69 title = ""
70 for refentry in root:
71 if refentry.tag == 'title':
72 title = refentry.text
73 continue
74 if refentry.tag != 'refentry':
75 logg.warning("no <refentry> list found, not a docbook file?")
76 logg.warning("found <%s> instead", refentry.tag)
77 continue
78 overviewref = refentry2(man, refentry, subdirectory, title)
79 for filename, overviewentry in overviewref.items():
80 overview[filename] = overviewentry
81 return overview
82
83 def refentryinfo2(man, refentry, title):
84 date, productname, manvolnum, refentrytitle = "", "", "", ""
85 section = refentry.find("refentryinfo")
86 if section is not None:
87 found = section.find("date")
88 if found is not None: date = found.text
89 found = section.find("productname")
90 if found is not None: productname = found.text
91 section = refentry.find("refmeta")
92 if section is not None:
93 found = section.find("refentrytitle")
94 if found is not None: refentrytitle = found.text
95 found = section.find("manvolnum")
96 if found is not None: manvolnum = found.text
97 if man:
98 header = []
99 if refentrytitle:
100 header += [ refentrytitle ]
101 if manvolnum:
102 header += [ manvolnum ]
103 if date:
104 header += [ date ]
105 if productname:
106 header += [ productname ]
107 if title:
108 header += [ title ]
109 if not header:
110 logg.warning("no <refmeta> found")
111 return ""
112 text = '.TH ' + " ".join([ '"%s"' % esc(part) for part in header])
113 return text + "\n"
114 else:
115 text = "<html><head><title>"
116 if productname or title:
117 text += "%s: " % htm(productname or title)
118 text += htm(refentrytitle)
119 if manvolnum:
120 text += "(%s)" % htm(manvolnum)
121 text += "</title>"
122 text += "\n" + '<meta name="product" content="%s" />' % htm(productname or title)
123 text += "\n" + '<meta name="refentry" content="%s" />' % htm(refentrytitle)
124 text += "\n" + '<meta name="manvolnum" content="%s" />' % htm(manvolnum)
125 text += "\n" + '<meta name="date" content="%s" />' % htm(date)
126 return text + "\n</head><body>\n"
127
128 def refentrytitle2(man, refentry, title = ""):
129 refentrytitle = ""
130 section = refentry.find("refmeta")
131 if section is not None:
132 found = section.find("refentrytitle")
133 if found is not None: refentrytitle = found.text
134 refentries = [ refentrytitle ]
135 refpurpose = ""
136 section = refentry.find("refnamediv")
137 if section is not None:
138 found = section.find("refpurpose")
139 if found is not None: refpurpose = found.text
140 for found in section.findall("refname"):
141 refname = found.text
142 if refname not in refentries:
143 refentries.append(refname)
144 if not refentrytitle:
145 logg.warning("no <refentrytitle> found")
146 return ""
147 elif man:
148 text = '.SH "NAME"' + "\n"
149 text += "" + esc(", ".join(refentries))
150 text += " " + esc("-")
151 text += " " + esc(refpurpose)
152 return text + "\n"
153 else:
154 text = '<h3>Name</h3>' + "\n"
155 text += "<p>" + htm(", ".join(refentries))
156 text += " " + htm("-")
157 text += " " + htm(refpurpose)
158 text += "</p>"
159 return text + "\n"
160
161 def refsynopsisdiv2(man, refentry, title = ""):
162 refsynopsisdiv = refentry.find("refsynopsisdiv")
163 if refsynopsisdiv is None:
164 logg.warning("no <resynopsisdiv> found")
165 return ""
166 if man:
167 return refsynopsisdiv2man(refsynopsisdiv, title)
168 else:
169 return refsynopsisdiv2htm(refsynopsisdiv, title)
170
171 def refsynopsisdiv2man(refsynopsisdiv, title = ""):
172 text = '.SH "SYNOPSIS"' + "\n"
173 text += ".sp\n"
174 text += ".nf\n"
175 for funcsynopsis in refsynopsisdiv.findall("funcsynopsis"):
176 funcsynopsisinfo = ""
177 found = funcsynopsis.find("funcsynopsisinfo")
178 if found is not None: funcsynopsisinfo = found.text
179 if funcsynopsisinfo:
180 for info in funcsynopsisinfo.split("\n"):
181 text += '.B "%s"' % esc(info)
182 text += "\n"
183 text += ".sp" + "\n"
184 else:
185 logg.debug("no <funcsynopsisinfo> found")
186 logg.debug("\n%s", ET.tostring(funcsynopsis))
187 funcs = 0
188 for funcprototype in funcsynopsis.findall("funcprototype"):
189 item = ET.tostring(funcprototype)
190 item = decodes(item)
191 item = item.replace("<funcprototype>","")
192 item = item.replace("</funcprototype>","")
193 if False:
194 item = item.replace("\n", " ")
195 item = item.replace("<funcdef>","")
196 item = item.replace("</funcdef>","")
197 item = item.replace("<paramdef>",'<def>')
198 item = item.replace("</paramdef>",'<def>')
199 items = item.split("<def>")
200 text += '.BI %s' % " ".join(['"%s"' % part for part in items if part])
201 else:
202 item = item.replace("<funcdef>","")
203 item = re.sub(r"([_\w]+)</funcdef>", lambda x: "\\fI%s\\fR" % x.group(1), item)
204 item = item.replace("<paramdef>",'')
205 item = item.replace("</paramdef>",'')
206 text += item
207 text += "\n"
208 funcs += 1
209 if not funcs:
210 logg.warning("no <funcprototype> found")
211 logg.warning("\n%s", ET.tostring(funcsynopsis))
212 text += ".fi" + "\n"
213 text += ".sp" + "\n"
214 return text
215
216 def refsynopsisdiv2htm(refsynopsisdiv, title = ""):
217 text = '<h3>Synopsis</h3>' + "\n"
218 text += '<pre>' + "\n"
219 for funcsynopsis in refsynopsisdiv.findall("funcsynopsis"):
220 funcsynopsisinfo = ""
221 found = funcsynopsis.find("funcsynopsisinfo")
222 if found is not None: funcsynopsisinfo = found.text
223 if funcsynopsisinfo:
224 for info in funcsynopsisinfo.split("\n"):
225 text += '<b>%s</b>' % htm(info)
226 text += "\n"
227 text += "\n"
228 else:
229 logg.debug("no <funcsynopsisinfo> found")
230 logg.debug("\n%s", ET.tostring(funcsynopsis))
231 funcs = 0
232 for funcprototype in funcsynopsis.findall("funcprototype"):
233 item = ET.tostring(funcprototype)
234 item = decodes(item)
235 item = item.replace("<funcprototype>","")
236 item = item.replace("</funcprototype>","")
237 item = item.replace("<funcdef>","")
238 item = re.sub(r"([_\w]+)</funcdef>", lambda x: "<b>%s</b>" % x.group(1), item)
239 item = item.replace("<paramdef>",'')
240 item = item.replace("</paramdef>",'')
241 text += item
242 text += "\n"
243 funcs += 1
244 if not funcs:
245 logg.warning("no <funcprototype> found")
246 logg.warning("\n%s", ET.tostring(funcsynopsis))
247 text += "</pre>" + "\n"
248 return text
249
250 def refsections2(man, refentry, title = ""):
251 text = ""
252 for refsect in refentry.findall("refsect1"):
253 if man:
254 text += refsect2man(refsect, title)
255 text += ".sp\n"
256 else:
257 text += refsect2htm(refsect, title)
258 return text
259
260
261 def refsect2man(refsect, title = ""):
262 text = ""
263 head = refsect.find("title")
264 if head is not None:
265 text += '.SH "%s"' % (esc(head.text.upper()))
266 text += "\n"
267 for para in list(refsect):
268 if para.tag == 'title':
269 continue
270 if para.tag == 'para':
271 text += para2man(para) + "\n"
272 text += ".sp\n"
273 continue
274 if para.tag == 'itemizedlist':
275 for item in list(para):
276 text += para2man(item) + "\n"
277 text += ".sp\n"
278 continue
279 logg.warning("unknown para <%s>", para.tag)
280 return text
281
282 def refsect2htm(refsect, title = ""):
283 text = ""
284 head = refsect.find("title")
285 if head is not None:
286 text += '<h3>%s</h3>' % htm(head.text)
287 text += "\n"
288 for para in list(refsect):
289 if para.tag == 'title':
290 continue
291 if para.tag == 'para':
292 text += "<p>" + para2htm(para)
293 text += "</p>" + "\n"
294 continue
295 if para.tag == 'itemizedlist':
296 text += "<ul>" + "\n"
297 for item in list(para):
298 text += "<li><p>" + para2htm(item)
299 text += "</p></li>" + "\n"
300 text += "</ul>" + "\n"
301 continue
302 logg.warning("unknown para <%s>", para.tag)
303 return text
304
305 def para2man(para):
306 item = unescape(ET.tostring(para))
307 item = decodes(item)
308 item = item.replace("\n", " ")
309 item = item.replace(" ", " ")
310 item = item.replace(" ", " ")
311 item = item.replace(" ", " ")
312 item = item.replace(" ", " ")
313 item = item.replace("<listitem>", "")
314 item = item.replace("</listitem>", "")
315 item = item.replace("<para>", "")
316 item = item.replace("</para>", "")
317 item = item.replace("<function>", "\\fI")
318 item = item.replace("</function>", "\\fP")
319 item = item.replace("<literal>", "\\fI")
320 item = item.replace("</literal>", "\\fP")
321 return item
322
323 def para2htm(para):
324 item = unescape(ET.tostring(para))
325 item = decodes(item)
326 item = item.replace("\n", " ")
327 item = item.replace(" ", " ")
328 item = item.replace(" ", " ")
329 item = item.replace(" ", " ")
330 item = item.replace(" ", " ")
331 item = item.replace("<listitem>", "")
332 item = item.replace("</listitem>", "")
333 item = item.replace("<para>", "")
334 item = item.replace("</para>", "")
335 item = item.replace("<function>", "<em><code>")
336 item = item.replace("</function>", "</code></em>")
337 item = item.replace("<literal>", "<code>")
338 item = item.replace("</literal>", "</code>")
339 item = mailhref(item)
340 return item
341
342 def styleinfo2(man):
343 if man:
344 styles = []
345 styles += [ ".ie \\n(.g .ds Aq \\(aq" ]
346 styles += [ ".el .ds Aq " ] # http://bugs.debian.org/507673
347 styles += [ ".nh" ] # disable hyphenation
348 styles += [ ".ad l" ] # align left, no justification
349 return "".join([ "%s\n" % part for part in styles ])
350 else:
351 return ""
352
353 def refends2(man):
354 if man:
355 return ""
356 else:
357 return "</body></html>" + "\n"
358
359 def refentry2(man, refentry, subdirectory = ".", title = ""):
360 if refentry.tag != "refentry":
361 logg.warning("no <refentry> found, not a docbook file?")
362 logg.warning("found <%s> instead", refentry.tag)
363 text = ""
364 text += refentryinfo2(man, refentry, title)
365 text += styleinfo2(man)
366 text += refentrytitle2(man, refentry, title)
367 text += refsynopsisdiv2(man, refentry)
368 text += refsections2(man, refentry)
369 text += refends2(man)
370
371 ### write the files
372 refentrytitle = ""
373 manvolnum = "3"
374 section = refentry.find("refmeta")
375 if section is not None:
376 found = section.find("refentrytitle")
377 if found is not None: refentrytitle = found.text
378 found = section.find("manvolnum")
379 if found is not None: manvolnum = found.text
380 #
381 refpurpose = ""
382 section = refentry.find("refnamediv")
383 if section is None:
384 logg.warning("no <refnamediv> found in <refentry> for '%s', bad docbook?", refentrytitle)
385 if not refentrytitle: raise Exception("not even a refentrytitle")
386 manpages = [ refentrytitle ]
387 else:
388 manpages = [ refname.text for refname in section.findall("refname") ]
389 found = section.find("refpurpose")
390 if found is not None: refpurpose = found.text
391 #
392 overview = {}
393 if man:
394 written = 0
395 for manpage in manpages:
396 if not refentrytitle:
397 refentrytitle = manpage
398 filename = "%s/man%s/%s.%s" % (subdirectory, manvolnum, manpage, manvolnum)
399 if manpage != refentrytitle:
400 manpagetext = ".so man%s/%s.%s\n" % (manvolnum, refentrytitle, manvolnum)
401 writefile(filename, manpagetext)
402 else:
403 manpagetext = text
404 writefile(filename, manpagetext)
405 written += 1
406 overview[filename] = OverviewEntry(manpage, manvolnum, refpurpose)
407 if not written:
408 manpage = refentrytitle
409 filename = "%s/man%s/%s.%s" % (subdirectory, manvolnum, manpage, manvolnum)
410 writefile(filename, manpagetext)
411 overview[filename] = OverviewEntry(manpage, manvolnum, refpurpose)
412 else:
413 manpage = refentrytitle
414 filename = "%s/%s.%s.%s" % (subdirectory, manpage, manvolnum, "html")
415 writefile(filename, text)
416 overview[filename] = OverviewEntry(manpage, manvolnum, refpurpose)
417 #
418 return overview
419
420 def splitname(filename):
421 base = os.path.basename(filename)
422 name, ext = os.path.splitext(base)
423 return name
424
425 def overview2(man, overview, subdirectory, docbook_filename):
426 if not man:
427 overview2htm(overview, subdirectory, docbook_filename)
428
429 def overview2htm(overview, subdirectory, docbook_filename):
430 basename = splitname(docbook_filename)
431 text = "<html><head><title>%s %s</title>\n" % (htm(basename), htm("overview"))
432 text += "</head><body>\n"
433 text += "<h3>%s %s</h3>\n" % (htm(basename), htm("overview"))
434 text += "<ul>\n"
435 for filename in sorted(overview):
436 entry = overview[filename]
437 subdir_filename = os.path.basename(filename)
438 text += '<li><a href="%s">%s</a> - %s</li>' % (subdir_filename, entry.manpage, htm(entry.refpurpose))
439 text += "\n"
440 text += "</ul>\n"
441 text += "</body></html>\n"
442 filename = "%s/%s.%s" % (subdirectory, basename, "html")
443 writefile(filename, text)
444
445 def writefile(filename, manpagetext):
446 dirname = os.path.dirname(filename)
447 if not os.path.isdir(dirname):
448 logg.debug("mkdir %s", dirname)
449 os.makedirs(dirname)
450 with open(filename, "w") as f:
451 f.write(manpagetext)
452 logg.debug("written %s [%s]", filename, manpagetext.split("\n", 1)[0])
453
454 if __name__ == "__main__":
455 from optparse import OptionParser
456 _o = OptionParser("%prog [options] docbookfiles...")
457 _o.add_option("-o","--into", metavar="DIR", default=".",
458 help="specify base directory for output [%default]")
459 _o.add_option("-t","--make", metavar="DIR", default="man",
460 help="make 'man'/'html' output pages [%default]")
461 _o.add_option("-v","--verbose", action="count", default=0,
462 help="increase logging level [%default]")
463 opt, args = _o.parse_args()
464 logging.basicConfig(level = max(0, logging.WARNING - 10 * opt.verbose))
465 # ensure commandline is compatible with "xmlto -o DIR TYPE INPUTFILE"
466 make = opt.make
467 if args and args[0] in ("man", "html"):
468 make = args[0]
469 args = args[1:]
470 dbk2(make == 'man', args, opt.into)