mkhtml.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: Builds manual pages
  5. # AUTHOR(S): Markus Neteler
  6. # Glynn Clements
  7. # Martin Landa <landa.martin gmail.com>
  8. # PURPOSE: Create HTML manual page snippets
  9. # COPYRIGHT: (C) 2007-2014 by Glynn Clements
  10. # and the GRASS Development Team
  11. #
  12. # This program is free software under the GNU General
  13. # Public License (>=v2). Read the file COPYING that
  14. # comes with GRASS for details.
  15. #
  16. #############################################################################
  17. import sys
  18. import os
  19. import string
  20. import re
  21. from datetime import datetime
  22. from HTMLParser import HTMLParser
  23. import urlparse
  24. pgm = sys.argv[1]
  25. src_file = "%s.html" % pgm
  26. tmp_file = "%s.tmp.html" % pgm
  27. source_url = "https://trac.osgeo.org/grass/browser/grass/branches/releasebranch_7_0/"
  28. header_base = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  29. <html>
  30. <head>
  31. <title>GRASS GIS Manual: ${PGM}</title>
  32. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  33. <link rel="stylesheet" href="grassdocs.css" type="text/css">
  34. </head>
  35. <body bgcolor="white">
  36. <div id="container">
  37. <a href="index.html"><img src="grass_logo.png" alt="GRASS logo"></a>
  38. <hr class="header">
  39. """
  40. header_nopgm = """<h2>${PGM}</h2>
  41. """
  42. header_pgm = """<h2>NAME</h2>
  43. <em><b>${PGM}</b></em>
  44. """
  45. header_pgm_desc = """<h2>NAME</h2>
  46. <em><b>${PGM}</b></em> - ${PGM_DESC}
  47. """
  48. sourcecode = string.Template(
  49. """<h2>SOURCE CODE</h2>
  50. <p>Available at: <a href="${URL_SOURCE}">${PGM} source code</a> (<a href="${URL_LOG}">history</a>)</p>
  51. """
  52. )
  53. footer_index = string.Template(
  54. """<hr class="header">
  55. <p>
  56. <a href="index.html">Main index</a> |
  57. <a href="${INDEXNAME}.html">${INDEXNAMECAP} index</a> |
  58. <a href="topics.html">Topics index</a> |
  59. <a href="keywords.html">Keywords index</a> |
  60. <a href="full_index.html">Full index</a>
  61. </p>
  62. <p>
  63. &copy; 2003-${YEAR}
  64. <a href="http://grass.osgeo.org">GRASS Development Team</a>,
  65. GRASS GIS ${GRASS_VERSION} Reference Manual
  66. </p>
  67. </div>
  68. </body>
  69. </html>
  70. """)
  71. footer_noindex = string.Template(
  72. """<hr class="header">
  73. <p>
  74. <a href="index.html">Main index</a> |
  75. <a href="topics.html">Topics index</a> |
  76. <a href="keywords.html">Keywords index</a> |
  77. <a href="full_index.html">Full index</a>
  78. </p>
  79. <p>
  80. &copy; 2003-${YEAR}
  81. <a href="http://grass.osgeo.org">GRASS Development Team</a>,
  82. GRASS GIS ${GRASS_VERSION} Reference Manual
  83. </p>
  84. </div>
  85. </body>
  86. </html>
  87. """)
  88. def read_file(name):
  89. try:
  90. f = open(name, 'rb')
  91. s = f.read()
  92. f.close()
  93. return s
  94. except IOError:
  95. return ""
  96. def create_toc(src_data):
  97. class MyHTMLParser(HTMLParser):
  98. def __init__(self):
  99. self.reset()
  100. self.idx = 1
  101. self.tag_curr = ''
  102. self.tag_last = ''
  103. self.process_text = False
  104. self.data = []
  105. self.tags_allowed = ('h1', 'h2', 'h3')
  106. self.tags_ignored = ('img')
  107. self.text = ''
  108. def handle_starttag(self, tag, attrs):
  109. if tag in self.tags_allowed:
  110. self.process_text = True
  111. self.tag_last = self.tag_curr
  112. self.tag_curr = tag
  113. def handle_endtag(self, tag):
  114. if tag in self.tags_allowed:
  115. self.data.append((tag, '%s_%d' % (tag, self.idx),
  116. self.text))
  117. self.idx += 1
  118. self.process_text = False
  119. self.text = ''
  120. self.tag_curr = self.tag_last
  121. def handle_data(self, data):
  122. if not self.process_text:
  123. return
  124. if self.tag_curr in self.tags_allowed or self.tag_curr in self.tags_ignored:
  125. self.text += data
  126. else:
  127. self.text += '<%s>%s</%s>' % (self.tag_curr, data, self.tag_curr)
  128. # instantiate the parser and fed it some HTML
  129. parser = MyHTMLParser()
  130. parser.feed(src_data)
  131. return parser.data
  132. def escape_href(label):
  133. # remove html tags
  134. label = re.sub('<[^<]+?>', '', label)
  135. # fix &nbsp;
  136. label = label.replace('&nbsp;', '')
  137. # fix "
  138. label = label.replace('"', '')
  139. # replace space with underscore + lower
  140. return label.replace(' ', '-').lower()
  141. def write_toc(data):
  142. if not data:
  143. return
  144. fd = sys.stdout
  145. fd.write('<div class="toc">\n')
  146. fd.write('<h4 class="toc">Table of contents</h4>\n')
  147. fd.write('<ul class="toc">\n')
  148. first = True
  149. has_h2 = False
  150. in_h3 = False
  151. indent = 4
  152. for tag, href, text in data:
  153. if tag == 'h3' and not in_h3 and has_h2:
  154. fd.write('\n%s<ul class="toc">\n' % (' ' * indent))
  155. indent += 4
  156. in_h3 = True
  157. elif not first:
  158. fd.write('</li>\n')
  159. if tag == 'h2':
  160. has_h2 = True
  161. if in_h3:
  162. indent -= 4
  163. fd.write('%s</ul></li>\n' % (' ' * indent))
  164. in_h3 = False
  165. fd.write('%s<li class="toc"><a href="#%s" class="toc">%s</a>' % \
  166. (' ' * indent, escape_href(text), text))
  167. first = False
  168. fd.write('</li>\n</ul>\n')
  169. fd.write('</div>\n')
  170. def update_toc(data):
  171. ret_data = []
  172. pat = re.compile(r'(<(h[2|3])>)(.+)(</h[2|3]>)')
  173. idx = 1
  174. for line in data.splitlines():
  175. if pat.search(line):
  176. xline = pat.split(line)
  177. line = xline[1] + '<a name="%s">' % escape_href(xline[3]) + xline[3] + '</a>' + xline[4]
  178. idx += 1
  179. ret_data.append(line)
  180. return '\n'.join(ret_data)
  181. # process header
  182. src_data = read_file(src_file)
  183. name = re.search('(<!-- meta page name:)(.*)(-->)', src_data, re.IGNORECASE)
  184. pgm_desc = None
  185. if name:
  186. pgm = name.group(2).strip().split('-', 1)[0].strip()
  187. name_desc = re.search('(<!-- meta page name description:)(.*)(-->)', src_data, re.IGNORECASE)
  188. if name_desc:
  189. pgm_desc = name_desc.group(2).strip()
  190. desc = re.search('(<!-- meta page description:)(.*)(-->)', src_data,
  191. re.IGNORECASE)
  192. if desc:
  193. pgm = desc.group(2).strip()
  194. header_tmpl = string.Template(header_base + header_nopgm)
  195. else:
  196. if not pgm_desc:
  197. header_tmpl = string.Template(header_base + header_pgm)
  198. else:
  199. header_tmpl = string.Template(header_base + header_pgm_desc)
  200. if not re.search('<html>', src_data, re.IGNORECASE):
  201. tmp_data = read_file(tmp_file)
  202. if not re.search('<html>', tmp_data, re.IGNORECASE):
  203. sys.stdout.write(header_tmpl.substitute(PGM=pgm, PGM_DESC=pgm_desc))
  204. if tmp_data:
  205. for line in tmp_data.splitlines(True):
  206. if not re.search('</body>|</html>', line, re.IGNORECASE):
  207. sys.stdout.write(line)
  208. # create TOC
  209. write_toc(create_toc(src_data))
  210. # process body
  211. sys.stdout.write(update_toc(src_data))
  212. # if </html> is found, suppose a complete html is provided.
  213. # otherwise, generate module class reference:
  214. if re.search('</html>', src_data, re.IGNORECASE):
  215. sys.exit()
  216. index_names = {
  217. 'd' : 'display',
  218. 'db': 'database',
  219. 'g' : 'general',
  220. 'i' : 'imagery',
  221. 'm' : 'misc',
  222. 'ps': 'postscript',
  223. 'p' : 'paint',
  224. 'r' : 'raster',
  225. 'r3': 'raster3d',
  226. 's' : 'sites',
  227. 't' : 'temporal',
  228. 'v' : 'vector'
  229. }
  230. def to_title(name):
  231. """Convert name of command class/family to form suitable for title"""
  232. return name.capitalize()
  233. index_titles = {}
  234. for key, name in index_names.iteritems():
  235. if key == 'r3':
  236. index_titles[key] = '3D raster'
  237. else:
  238. index_titles[key] = to_title(name)
  239. # process footer
  240. index = re.search('(<!-- meta page index:)(.*)(-->)', src_data, re.IGNORECASE)
  241. if index:
  242. index_name = index.group(2).strip()
  243. if '|' in index_name:
  244. index_name, index_name_cap = index_name.split('|', 1)
  245. else:
  246. index_name_cap = index_name
  247. else:
  248. mod_class = pgm.split('.', 1)[0]
  249. index_name = index_names.get(mod_class, '')
  250. index_name_cap = index_titles.get(mod_class, '')
  251. grass_version = os.getenv("VERSION_NUMBER", "unknown")
  252. year = os.getenv("VERSION_DATE")
  253. if not year:
  254. year = str(datetime.now().year)
  255. # check the names of scripts to assign the right folder
  256. topdir = os.path.abspath(os.getenv("MODULE_TOPDIR"))
  257. curdir = os.path.abspath(os.path.curdir)
  258. pgmdir = curdir.replace(topdir, '').lstrip('/')
  259. url_source = urlparse.urljoin(source_url, pgmdir)
  260. if index_name:
  261. sys.stdout.write(sourcecode.substitute(URL_SOURCE=url_source, PGM=pgm,
  262. URL_LOG=url_source.replace('browser', 'log')))
  263. sys.stdout.write(footer_index.substitute(INDEXNAME=index_name,
  264. INDEXNAMECAP=index_name_cap,
  265. YEAR=year, GRASS_VERSION=grass_version))
  266. else:
  267. sys.stdout.write(footer_noindex.substitute(YEAR=year,
  268. GRASS_VERSION=grass_version))