forked from OSGeo/grass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
g.html2man.py
executable file
·60 lines (48 loc) · 1.3 KB
/
g.html2man.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3
from pathlib import Path
import sys
import re
from ghtml import HTMLParser
from ggroff import Formatter
from io import StringIO
entities = {"nbsp": " ", "bull": "*"}
# Remove ToC
def fix(content):
if isinstance(content, tuple):
tag, attrs, body = content
if tag == "div" and ("class", "toc") in attrs:
return None
return (tag, attrs, fix(body))
if isinstance(content, list):
return [fixed for item in content for fixed in [fix(item)] if fixed is not None]
return content
def main():
# parse HTML
infile = sys.argv[1]
inf = open(infile)
p = HTMLParser(entities)
for n, line in enumerate(inf):
try:
p.feed(line)
except Exception as err:
sys.stderr.write(
"%s:%d:0: Error (%s): %s\n" % (infile, n + 1, repr(err), line)
)
sys.exit(1)
p.close()
inf.close()
# generate groff
sf = StringIO()
f = Formatter(infile, sf)
f.pp(fix(p.data))
s = sf.getvalue()
sf.close()
# strip excess whitespace
blank_re = re.compile("[ \t\n]*\n([ \t]*\n)*")
s = blank_re.sub("\n", s)
s = s.lstrip()
# write groff
s = s.encode("UTF-8")
Path(sys.argv[2]).write_bytes(s)
if __name__ == "__main__":
main()