Skip to content
Myr

build_manpage.py

This file

Path

docs/build_manpage.py

249 lines · 8.7 KiB · Python

Last changed by

Drop the date from the committed man page (#3659)itchynybefore adoption17b87d2

History of this file

Take it

The walk stopped after 200 commits: lines older than fa6a2ff point at it.

website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff

lines 1–67why, one step back
1#!/usr/bin/env python3
2from io import StringIO3from lxml import etree4import markdown5from markdown.extensions import Extension6import re7import sys8import yaml91011# Prevent our markdown parser from trying to help by interpreting things in angle brackets as HTML tags.12class EscapeHtml(Extension):1314 def extendMarkdown(self, md):15 md.preprocessors.deregister('html_block')16 md.inlinePatterns.deregister('html')171819class RoffWalker(object):2021 def __init__(self, tree, output=sys.stdout):22 self.tree = tree23 self.target = output24 self.f = StringIO()2526 def walk(self):27 self._walk(self.tree, parent_tag=None)28 # We don't want to start lines with \. because that can confuse man29 # For lines that start with \., we need to prefix them with \& so it30 # knows not to treat that line as a directive31 data = re.sub(r'^\\\.', r'\&.', self.f.getvalue(), flags=re.MULTILINE)32 self.target.write(data)3334 def _ul_is_special(self, root):35 if len(root) != 1:36 return False37 child = root[0]38 if child.tag != 'li':39 return False40 msg = ''.join(child.itertext()).strip()41 return msg.endswith(':')4243 def _walk_child(self, root):44 if len(root) > 0:45 self._walk(root[0], parent_tag=root.tag)4647 def _write_element(self, root, ensure_newline=True):48 if root.text is not None:49 text = self._sanitize(root.text)50 self.__write_raw(text)51 self._walk_child(root)52 self._write_tail(root, ensure_newline=ensure_newline)5354 def _write_tail(self, root, ensure_newline=False, inline=False):55 if root.tail is not None:56 if inline or root.tail != '\n':57 text = self._sanitize(root.tail)58 if text.endswith('\n'):59 ensure_newline = False60 self.__write_raw(text)61 if ensure_newline:62 self.__write_raw('\n')6364 def _walk(self, root, parent_tag=None):65 last_tag = None66 while root is not None:67 if root.tag == 'h1':

Drop the date from the committed man page (#3659)itchynybefore adoption17b87d2

line 68why, one step back
68 self.__write_cmd('.TH "JQ" "1" "" "" ""')

website: remove unused root path on building website (#3248)itchynybefore adoptionfa6a2ff

lines 69–249why, one step back
69 self.__write_cmd('.SH "NAME"')
70 # TODO: properly parse this71 self.__write_raw(r'\fBjq\fR \- Command\-line JSON processor' +72 "\n")7374 elif root.tag == 'h2':75 self.__write_cmd('.SH "{}"'.format(''.join(76 root.itertext()).strip()))7778 elif root.tag == 'h3':79 text = ''.join(root.itertext()).strip()80 self.__write_cmd('.SS "{}"'.format(self._h3_sanitize(text)))8182 elif root.tag == 'p':83 if last_tag not in ['h2', 'h3'] and parent_tag not in ['li']:84 self.__write_cmd('.P')85 self._write_element(root, ensure_newline=(parent_tag != 'li'))8687 elif root.tag == 'a':88 self._write_element(root, ensure_newline=(parent_tag != 'li'))8990 elif root.tag == 'ul':91 if self._ul_is_special(root):92 li = root[0]93 self.__write_cmd('.TP')94 self._write_element(li)95 next = root.getnext()96 while next is not None and next.tag == 'p':97 if next.getnext() is not None and next.getnext(98 ).tag == 'pre':99 # we don't want to .IP these, because it'll look funny with the code indent100 break101 self.__write_cmd('.IP')102 self._write_element(next)103 root = next104 next = root.getnext()105 else:106 self._walk_child(root)107 self._write_tail(root)108 # A pre tag after the end of a list doesn't want two of the indentation commands109 if root.getnext() is None or root.getnext().tag != 'pre':110 self.__write_cmd('.IP "" 0')111112 elif root.tag == 'li':113 self.__write_cmd(r'.IP "\(bu" 4')114 if root.text is not None and root.text.strip() != '':115 text = self._sanitize(root.text)116 self.__write_raw(text)117 self._walk_child(root)118 self._write_tail(root, ensure_newline=True)119120 elif root.tag == 'strong':121 if root.text is not None:122 text = self._sanitize(root.text)123 self.__write_raw('\\fB{}\\fR'.format(text))124125 self._write_tail(root, inline=True)126127 elif root.tag == 'em':128 if root.text is not None:129 text = self._sanitize(root.text)130 self.__write_raw('\\fI{}\\fR'.format(text))131 self._write_tail(root, inline=True)132133 elif root.tag == 'code':134 if root.text is not None:135 text = self._code_sanitize(root.text)136 self.__write_raw('\\fB{}\\fR'.format(text))137 self._write_tail(root, inline=True)138139 elif root.tag == 'pre':140 self.__write_cmd('.IP "" 4')141 self.__write_cmd('.nf\n') # extra newline for spacing reasons142 next = root143 first = True144 while next is not None and next.tag == 'pre':145 if not first:146 self.__write_raw('\n')147 text = ''.join(next.itertext(with_tail=False))148 self.__write_raw(self._pre_sanitize(text))149 first = False150 root = next151 next = next.getnext()152 self.__write_cmd('.fi')153 self.__write_cmd('.IP "" 0')154155 else:156 self._walk_child(root)157158 last_tag = root.tag159 root = root.getnext()160161 def _base_sanitize(self, text):162 text = re.sub(r'\\', r'\\e', text)163 text = re.sub(r'\.', r'\\.', text)164 text = re.sub("'", r"\'", text)165 text = re.sub('-', r'\-', text)166 return text167168 def _pre_sanitize(self, text):169 return self._base_sanitize(text)170171 def _code_sanitize(self, text):172 text = self._base_sanitize(text)173 text = re.sub(r'\s', ' ', text)174 return text175176 def _h3_sanitize(self, text):177 text = self._base_sanitize(text)178 text = re.sub(' \n|\n ', ' ', text)179 text = re.sub('\n', ' ', text)180 return text181182 def _sanitize(self, text):183 text = self._base_sanitize(text)184 text = re.sub(r'<([^>]+)>', r'\\fI\1\\fR', text)185 text = re.sub(r' +', ' ', text)186 text = re.sub('\n', ' ', text)187 return text188189 def __write_cmd(self, dat):190 print('.', dat, sep='\n', file=self.f)191 pass192193 def __write_raw(self, dat):194 print(dat, sep='', end='', file=self.f)195 pass196197198def load_yml_file(fn):199 with open(fn) as f:200 return yaml.safe_load(f)201202203def dedent_body(body):204 lines = [re.sub(r'^ (\S)', r'\1', l) for l in body.split('\n')]205 return '\n'.join(lines)206207208def convert_manual_to_markdown():209 f = StringIO()210 manual = load_yml_file("content/manual/dev/manual.yml")211 f.write(manual.get('manpage_intro', '\n'))212 f.write(dedent_body(manual.get('body', '\n')))213 for section in manual.get('sections', []):214 f.write('## {}\n'.format(section.get('title', '').upper()))215 f.write(dedent_body(section.get('body', '\n')))216 f.write('\n')217 for entry in section.get('entries', []):218 f.write('### {}\n'.format(entry.get('title', '')))219 f.write(dedent_body(entry.get('body', '\n')))220 f.write('\n')221 if entry.get('examples') is not None:222 f.write("~~~~\n")223 first = True224 for example in entry.get('examples'):225 if not first:226 f.write('\n')227 f.write("jq '{}'\n".format(example.get('program', '')))228 f.write(" {}\n".format(example.get('input', '')))229 output = [str(x) for x in example.get('output', [])]230 f.write("=> {}\n".format(', '.join(output)))231 first = False232 f.write("~~~~\n")233 f.write('\n')234 f.write(manual.get('manpage_epilogue', ''))235 return f.getvalue()236237238# Convert manual.yml to our special markdown format239markdown_data = convert_manual_to_markdown()240241# Convert markdown to html242html_data = markdown.markdown(markdown_data,243 extensions=[EscapeHtml(), 'fenced_code'])244245# Parse the html into a tree so we can walk it246tr = etree.HTML(html_data, etree.HTMLParser())247248# Convert the markdown to ROFF249RoffWalker(tr).walk()