mkhtml.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. #!/usr/bin/env python3
  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-2021 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. import locale
  23. import json
  24. import pathlib
  25. try:
  26. # Python 2 import
  27. from HTMLParser import HTMLParser
  28. except ImportError:
  29. # Python 3 import
  30. from html.parser import HTMLParser
  31. try:
  32. import urlparse
  33. except ImportError:
  34. import urllib.parse as urlparse
  35. if sys.version_info[0] == 2:
  36. PY2 = True
  37. else:
  38. PY2 = False
  39. if not PY2:
  40. unicode = str
  41. def _get_encoding():
  42. encoding = locale.getdefaultlocale()[1]
  43. if not encoding:
  44. encoding = "UTF-8"
  45. return encoding
  46. def decode(bytes_):
  47. """Decode bytes with default locale and return (unicode) string
  48. No-op if parameter is not bytes (assumed unicode string).
  49. :param bytes bytes_: the bytes to decode
  50. """
  51. if isinstance(bytes_, unicode):
  52. return bytes_
  53. if isinstance(bytes_, bytes):
  54. enc = _get_encoding()
  55. return bytes_.decode(enc)
  56. return unicode(bytes_)
  57. html_page_footer_pages_path = (
  58. os.getenv("HTML_PAGE_FOOTER_PAGES_PATH")
  59. if os.getenv("HTML_PAGE_FOOTER_PAGES_PATH")
  60. else ""
  61. )
  62. pgm = sys.argv[1]
  63. src_file = "%s.html" % pgm
  64. tmp_file = "%s.tmp.html" % pgm
  65. trunk_url = "https://github.com/OSGeo/grass/tree/main/"
  66. addons_url = "https://github.com/OSGeo/grass-addons/tree/master/"
  67. header_base = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  68. <html>
  69. <head>
  70. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  71. <title>${PGM} - GRASS GIS Manual</title>
  72. <meta name="Author" content="GRASS Development Team">
  73. <meta name="description" content="${PGM}: ${PGM_DESC}">
  74. <link rel="stylesheet" href="grassdocs.css" type="text/css">
  75. </head>
  76. <body bgcolor="white">
  77. <div id="container">
  78. <a href="index.html"><img src="grass_logo.png" alt="GRASS logo"></a>
  79. <hr class="header">
  80. """
  81. header_nopgm = """<h2>${PGM}</h2>
  82. """
  83. header_pgm = """<h2>NAME</h2>
  84. <em><b>${PGM}</b></em>
  85. """
  86. header_pgm_desc = """<h2>NAME</h2>
  87. <em><b>${PGM}</b></em> - ${PGM_DESC}
  88. """
  89. sourcecode = string.Template(
  90. """<h2>SOURCE CODE</h2>
  91. <p>
  92. Available at:
  93. <a href="${URL_SOURCE}">${PGM} source code</a>
  94. (<a href="${URL_LOG}">history</a>)
  95. </p>
  96. """
  97. )
  98. footer_index = string.Template(
  99. """<hr class="header">
  100. <p>
  101. <a href="index.html">Main index</a> |
  102. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}${INDEXNAME}.html">${INDEXNAMECAP} index</a> |
  103. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}topics.html">Topics index</a> |
  104. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}keywords.html">Keywords index</a> |
  105. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}graphical_index.html">Graphical index</a> |
  106. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}full_index.html">Full index</a>
  107. </p>
  108. <p>
  109. &copy; 2003-${YEAR}
  110. <a href="https://grass.osgeo.org">GRASS Development Team</a>,
  111. GRASS GIS ${GRASS_VERSION} Reference Manual
  112. </p>
  113. </div>
  114. </body>
  115. </html>
  116. """
  117. )
  118. footer_noindex = string.Template(
  119. """<hr class="header">
  120. <p>
  121. <a href="index.html">Main index</a> |
  122. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}topics.html">Topics index</a> |
  123. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}keywords.html">Keywords index</a> |
  124. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}graphical_index.html">Graphical index</a> |
  125. <a href="${HTML_PAGE_FOOTER_PAGES_PATH}full_index.html">Full index</a>
  126. </p>
  127. <p>
  128. &copy; 2003-${YEAR}
  129. <a href="https://grass.osgeo.org">GRASS Development Team</a>,
  130. GRASS GIS ${GRASS_VERSION} Reference Manual
  131. </p>
  132. </div>
  133. </body>
  134. </html>
  135. """
  136. )
  137. def read_file(name):
  138. try:
  139. f = open(name, "rb")
  140. s = f.read()
  141. f.close()
  142. if PY2:
  143. return s
  144. else:
  145. return decode(s)
  146. except IOError:
  147. return ""
  148. def create_toc(src_data):
  149. class MyHTMLParser(HTMLParser):
  150. def __init__(self):
  151. HTMLParser.__init__(self)
  152. self.reset()
  153. self.idx = 1
  154. self.tag_curr = ""
  155. self.tag_last = ""
  156. self.process_text = False
  157. self.data = []
  158. self.tags_allowed = ("h1", "h2", "h3")
  159. self.tags_ignored = "img"
  160. self.text = ""
  161. def handle_starttag(self, tag, attrs):
  162. if tag in self.tags_allowed:
  163. self.process_text = True
  164. self.tag_last = self.tag_curr
  165. self.tag_curr = tag
  166. def handle_endtag(self, tag):
  167. if tag in self.tags_allowed:
  168. self.data.append((tag, "%s_%d" % (tag, self.idx), self.text))
  169. self.idx += 1
  170. self.process_text = False
  171. self.text = ""
  172. self.tag_curr = self.tag_last
  173. def handle_data(self, data):
  174. if not self.process_text:
  175. return
  176. if self.tag_curr in self.tags_allowed or self.tag_curr in self.tags_ignored:
  177. self.text += data
  178. else:
  179. self.text += "<%s>%s</%s>" % (self.tag_curr, data, self.tag_curr)
  180. # instantiate the parser and fed it some HTML
  181. parser = MyHTMLParser()
  182. parser.feed(src_data)
  183. return parser.data
  184. def escape_href(label):
  185. # remove html tags
  186. label = re.sub("<[^<]+?>", "", label)
  187. # fix &nbsp;
  188. label = label.replace("&nbsp;", "")
  189. # fix "
  190. label = label.replace('"', "")
  191. # replace space with underscore + lower
  192. return label.replace(" ", "-").lower()
  193. def write_toc(data):
  194. if not data:
  195. return
  196. fd = sys.stdout
  197. fd.write('<div class="toc">\n')
  198. fd.write('<h4 class="toc">Table of contents</h4>\n')
  199. fd.write('<ul class="toc">\n')
  200. first = True
  201. has_h2 = False
  202. in_h3 = False
  203. indent = 4
  204. for tag, href, text in data:
  205. if tag == "h3" and not in_h3 and has_h2:
  206. fd.write('\n%s<ul class="toc">\n' % (" " * indent))
  207. indent += 4
  208. in_h3 = True
  209. elif not first:
  210. fd.write("</li>\n")
  211. if tag == "h2":
  212. has_h2 = True
  213. if in_h3:
  214. indent -= 4
  215. fd.write("%s</ul></li>\n" % (" " * indent))
  216. in_h3 = False
  217. text = text.replace("\xa0", " ")
  218. fd.write(
  219. '%s<li class="toc"><a href="#%s" class="toc">%s</a>'
  220. % (" " * indent, escape_href(text), text)
  221. )
  222. first = False
  223. fd.write("</li>\n</ul>\n")
  224. fd.write("</div>\n")
  225. def update_toc(data):
  226. ret_data = []
  227. pat = re.compile(r"(<(h[2|3])>)(.+)(</h[2|3]>)")
  228. idx = 1
  229. for line in data.splitlines():
  230. if pat.search(line):
  231. xline = pat.split(line)
  232. line = (
  233. xline[1]
  234. + '<a name="%s">' % escape_href(xline[3])
  235. + xline[3]
  236. + "</a>"
  237. + xline[4]
  238. )
  239. idx += 1
  240. ret_data.append(line)
  241. return "\n".join(ret_data)
  242. def get_addon_path():
  243. """Check if pgm is in the addons list and get addon path
  244. return: pgm path if pgm is addon else None
  245. """
  246. addon_base = os.getenv("GRASS_ADDON_BASE")
  247. if addon_base:
  248. # addons_paths.json is file created during install extension
  249. # check get_addons_paths() function in the g.extension.py file
  250. addons_paths = os.path.join(addon_base, "addons_paths.json")
  251. if os.path.exists(addons_paths):
  252. with open(addons_paths) as f:
  253. addons_paths = json.load(f)
  254. for addon in addons_paths["tree"]:
  255. if pgm == pathlib.Path(addon["path"]).name:
  256. return addon["path"]
  257. # process header
  258. src_data = read_file(src_file)
  259. name = re.search("(<!-- meta page name:)(.*)(-->)", src_data, re.IGNORECASE)
  260. pgm_desc = "GRASS GIS Reference Manual"
  261. if name:
  262. pgm = name.group(2).strip().split("-", 1)[0].strip()
  263. name_desc = re.search(
  264. "(<!-- meta page name description:)(.*)(-->)", src_data, re.IGNORECASE
  265. )
  266. if name_desc:
  267. pgm_desc = name_desc.group(2).strip()
  268. desc = re.search("(<!-- meta page description:)(.*)(-->)", src_data, re.IGNORECASE)
  269. if desc:
  270. pgm = desc.group(2).strip()
  271. header_tmpl = string.Template(header_base + header_nopgm)
  272. else:
  273. if not pgm_desc:
  274. header_tmpl = string.Template(header_base + header_pgm)
  275. else:
  276. header_tmpl = string.Template(header_base + header_pgm_desc)
  277. if not re.search("<html>", src_data, re.IGNORECASE):
  278. tmp_data = read_file(tmp_file)
  279. """
  280. Adjusting keywords html pages paths if add-on html man page
  281. stored on the server
  282. """
  283. if html_page_footer_pages_path:
  284. new_keywords_paths = []
  285. orig_keywords_paths = re.search(
  286. r"<h[1-9]>KEYWORDS</h[1-9]>(.*?)<h[1-9]>",
  287. tmp_data,
  288. re.DOTALL,
  289. )
  290. if orig_keywords_paths:
  291. search_txt = 'href="'
  292. for i in orig_keywords_paths.group(1).split(","):
  293. if search_txt in i:
  294. index = i.index(search_txt) + len(search_txt)
  295. new_keywords_paths.append(
  296. i[:index] + html_page_footer_pages_path + i[index:],
  297. )
  298. if new_keywords_paths:
  299. tmp_data = tmp_data.replace(
  300. orig_keywords_paths.group(1),
  301. ",".join(new_keywords_paths),
  302. )
  303. if not re.search("<html>", tmp_data, re.IGNORECASE):
  304. sys.stdout.write(header_tmpl.substitute(PGM=pgm, PGM_DESC=pgm_desc))
  305. if tmp_data:
  306. for line in tmp_data.splitlines(True):
  307. if not re.search("</body>|</html>", line, re.IGNORECASE):
  308. sys.stdout.write(line)
  309. # create TOC
  310. write_toc(create_toc(src_data))
  311. # process body
  312. sys.stdout.write(update_toc(src_data))
  313. # if </html> is found, suppose a complete html is provided.
  314. # otherwise, generate module class reference:
  315. if re.search("</html>", src_data, re.IGNORECASE):
  316. sys.exit()
  317. index_names = {
  318. "d": "display",
  319. "db": "database",
  320. "g": "general",
  321. "i": "imagery",
  322. "m": "miscellaneous",
  323. "ps": "postscript",
  324. "p": "paint",
  325. "r": "raster",
  326. "r3": "raster3d",
  327. "s": "sites",
  328. "t": "temporal",
  329. "v": "vector",
  330. }
  331. def to_title(name):
  332. """Convert name of command class/family to form suitable for title"""
  333. if name == "raster3d":
  334. return "3D raster"
  335. elif name == "postscript":
  336. return "PostScript"
  337. else:
  338. return name.capitalize()
  339. index_titles = {}
  340. for key, name in index_names.items():
  341. index_titles[key] = to_title(name)
  342. # process footer
  343. index = re.search("(<!-- meta page index:)(.*)(-->)", src_data, re.IGNORECASE)
  344. if index:
  345. index_name = index.group(2).strip()
  346. if "|" in index_name:
  347. index_name, index_name_cap = index_name.split("|", 1)
  348. else:
  349. index_name_cap = to_title(index_name)
  350. else:
  351. mod_class = pgm.split(".", 1)[0]
  352. index_name = index_names.get(mod_class, "")
  353. index_name_cap = index_titles.get(mod_class, "")
  354. grass_version = os.getenv("VERSION_NUMBER", "unknown")
  355. year = os.getenv("VERSION_DATE")
  356. if not year:
  357. year = str(datetime.now().year)
  358. # check the names of scripts to assign the right folder
  359. topdir = os.path.abspath(os.getenv("MODULE_TOPDIR"))
  360. curdir = os.path.abspath(os.path.curdir)
  361. if curdir.startswith(topdir + os.path.sep):
  362. source_url = trunk_url
  363. pgmdir = curdir.replace(topdir, "").lstrip(os.path.sep)
  364. else:
  365. # addons
  366. source_url = addons_url
  367. pgmdir = os.path.sep.join(curdir.split(os.path.sep)[-3:])
  368. url_source = ""
  369. if os.getenv("SOURCE_URL", ""):
  370. addon_path = get_addon_path()
  371. if addon_path:
  372. url_source = urlparse.urljoin(
  373. os.environ["SOURCE_URL"].split("src")[0],
  374. addon_path,
  375. )
  376. else:
  377. url_source = urlparse.urljoin(source_url, pgmdir)
  378. if sys.platform == "win32":
  379. url_source = url_source.replace(os.path.sep, "/")
  380. if index_name:
  381. branches = "branches"
  382. tree = "tree"
  383. commits = "commits"
  384. if branches in url_source:
  385. url_log = url_source.replace(branches, commits)
  386. url_source = url_source.replace(branches, tree)
  387. else:
  388. url_log = url_source.replace(tree, commits)
  389. sys.stdout.write(
  390. sourcecode.substitute(
  391. URL_SOURCE=url_source,
  392. PGM=pgm,
  393. URL_LOG=url_log,
  394. )
  395. )
  396. sys.stdout.write(
  397. footer_index.substitute(
  398. INDEXNAME=index_name,
  399. INDEXNAMECAP=index_name_cap,
  400. YEAR=year,
  401. GRASS_VERSION=grass_version,
  402. HTML_PAGE_FOOTER_PAGES_PATH=html_page_footer_pages_path,
  403. ),
  404. )
  405. else:
  406. sys.stdout.write(
  407. footer_noindex.substitute(
  408. YEAR=year,
  409. GRASS_VERSION=grass_version,
  410. HTML_PAGE_FOOTER_PAGES_PATH=html_page_footer_pages_path,
  411. ),
  412. )