mkhtml.py 9.9 KB

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