mkhtml.py 14 KB

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