Skip to content
Myr

docs: Fix coding style of Python scripts using YAPF (#2606)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by itchyny · committed by GitHub · parent fd9da66 · Browse files · 3 files+239 added−219 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+239 added−219 removed

  • other:+239 added−219 removed

3 files+239 added−219 removed

modified:docs/build_manpage.py+191 added-178 removed
6 unmodified lines
7import re8import sys9import yaml101112# Prevent our markdown parser from trying to help by interpreting things in angle brackets as HTML tags.13class EscapeHtml(Extension):13 def extendMarkdown(self, md, md_globals):14 del md.preprocessors['html_block']15 del md.inlinePatterns['html']1415 def extendMarkdown(self, md, md_globals):16 del md.preprocessors['html_block']17 del md.inlinePatterns['html']181920class RoffWalker(object):18 def __init__(self, tree, output=sys.stdout):19 self.tree = tree20 self.target = output21 self.f = StringIO()2123 def walk(self):24 self._walk(self.tree, parent_tag=None)25 # We don't want to start lines with \. because that can confuse man26 # For lines that start with \., we need to prefix them with \& so it27 # knows not to treat that line as a directive28 data = re.sub(r'^\\\.', r'\&.', self.f.getvalue(), flags=re.MULTILINE)29 self.target.write(data)22 def __init__(self, tree, output=sys.stdout):23 self.tree = tree24 self.target = output25 self.f = StringIO()2631 def _ul_is_special(self, root):32 if len(root) != 1:33 return False34 child = root[0]35 if child.tag != 'li':36 return False37 msg = ''.join(child.itertext()).strip()38 return msg.endswith(':')27 def walk(self):28 self._walk(self.tree, parent_tag=None)29 # We don't want to start lines with \. because that can confuse man30 # For lines that start with \., we need to prefix them with \& so it31 # knows not to treat that line as a directive32 data = re.sub(r'^\\\.', r'\&.', self.f.getvalue(), flags=re.MULTILINE)33 self.target.write(data)3440 def _walk_child(self, root):41 if len(root) > 0:42 self._walk(root[0], parent_tag=root.tag)35 def _ul_is_special(self, root):36 if len(root) != 1:37 return False38 child = root[0]39 if child.tag != 'li':40 return False41 msg = ''.join(child.itertext()).strip()42 return msg.endswith(':')4344 def _write_element(self, root, ensure_newline=True):45 if root.text is not None:46 text = self._sanitize(root.text)47 self.__write_raw(text)48 self._walk_child(root)49 self._write_tail(root, ensure_newline=ensure_newline)44 def _walk_child(self, root):45 if len(root) > 0:46 self._walk(root[0], parent_tag=root.tag)4751 def _write_tail(self, root, ensure_newline=False, inline=False):52 if root.tail is not None:53 if inline or root.tail != '\n':54 text = self._sanitize(root.tail)55 if text.endswith('\n'):56 ensure_newline = False57 self.__write_raw(text)58 if ensure_newline:59 self.__write_raw('\n')48 def _write_element(self, root, ensure_newline=True):49 if root.text is not None:50 text = self._sanitize(root.text)51 self.__write_raw(text)52 self._walk_child(root)53 self._write_tail(root, ensure_newline=ensure_newline)5461 def _walk(self, root, parent_tag=None):62 last_tag = None63 while root is not None:64 if root.tag == 'h1':65 self.__write_cmd('.TH "JQ" "1" "{}" "" ""'.format(date.today().strftime('%B %Y')))66 self.__write_cmd('.SH "NAME"')67 # TODO: properly parse this68 self.__write_raw(r'\fBjq\fR \- Command\-line JSON processor' + "\n")55 def _write_tail(self, root, ensure_newline=False, inline=False):56 if root.tail is not None:57 if inline or root.tail != '\n':58 text = self._sanitize(root.tail)59 if text.endswith('\n'):60 ensure_newline = False61 self.__write_raw(text)62 if ensure_newline:63 self.__write_raw('\n')6470 elif root.tag == 'h2':71 self.__write_cmd('.SH "{}"'.format(''.join(root.itertext()).strip()))65 def _walk(self, root, parent_tag=None):66 last_tag = None67 while root is not None:68 if root.tag == 'h1':69 self.__write_cmd('.TH "JQ" "1" "{}" "" ""'.format(70 date.today().strftime('%B %Y')))71 self.__write_cmd('.SH "NAME"')72 # TODO: properly parse this73 self.__write_raw(r'\fBjq\fR \- Command\-line JSON processor' +74 "\n")7573 elif root.tag == 'h3':74 text = ''.join(root.itertext()).strip()75 self.__write_cmd('.SS "{}"'.format(self._h3_sanitize(text)))76 elif root.tag == 'h2':77 self.__write_cmd('.SH "{}"'.format(''.join(78 root.itertext()).strip()))7977 elif root.tag == 'p':78 if last_tag not in ['h2', 'h3'] and parent_tag not in ['li']:79 self.__write_cmd('.P')80 self._write_element(root, ensure_newline=(parent_tag != 'li'))80 elif root.tag == 'h3':81 text = ''.join(root.itertext()).strip()82 self.__write_cmd('.SS "{}"'.format(self._h3_sanitize(text)))8382 elif root.tag == 'ul':83 if self._ul_is_special(root):84 li = root[0]85 self.__write_cmd('.TP')86 self._write_element(li)87 next = root.getnext()88 while next is not None and next.tag == 'p':89 if next.getnext() is not None and next.getnext().tag == 'pre':90 # we don't want to .IP these, because it'll look funny with the code indent91 break92 self.__write_cmd('.IP')93 self._write_element(next)94 root = next95 next = root.getnext()96 else:97 self._walk_child(root)98 self._write_tail(root)99 # A pre tag after the end of a list doesn't want two of the indentation commands100 if root.getnext() is None or root.getnext().tag != 'pre':101 self.__write_cmd('.IP "" 0')84 elif root.tag == 'p':85 if last_tag not in ['h2', 'h3'] and parent_tag not in ['li']:86 self.__write_cmd('.P')87 self._write_element(root, ensure_newline=(parent_tag != 'li'))88103 elif root.tag == 'li':104 self.__write_cmd(r'.IP "\(bu" 4')105 if root.text is not None and root.text.strip() != '':106 text = self._sanitize(root.text)107 self.__write_raw(text)108 self._walk_child(root)109 self._write_tail(root, ensure_newline=True)89 elif root.tag == 'ul':90 if self._ul_is_special(root):91 li = root[0]92 self.__write_cmd('.TP')93 self._write_element(li)94 next = root.getnext()95 while next is not None and next.tag == 'p':96 if next.getnext() is not None and next.getnext(97 ).tag == 'pre':98 # we don't want to .IP these, because it'll look funny with the code indent99 break100 self.__write_cmd('.IP')101 self._write_element(next)102 root = next103 next = root.getnext()104 else:105 self._walk_child(root)106 self._write_tail(root)107 # A pre tag after the end of a list doesn't want two of the indentation commands108 if root.getnext() is None or root.getnext().tag != 'pre':109 self.__write_cmd('.IP "" 0')110111 elif root.tag == 'strong':112 if root.text is not None:113 text = self._sanitize(root.text)114 self.__write_raw('\\fB{}\\fR'.format(text))111 elif root.tag == 'li':112 self.__write_cmd(r'.IP "\(bu" 4')113 if root.text is not None and root.text.strip() != '':114 text = self._sanitize(root.text)115 self.__write_raw(text)116 self._walk_child(root)117 self._write_tail(root, ensure_newline=True)118116 self._write_tail(root, inline=True)119 elif root.tag == 'strong':120 if root.text is not None:121 text = self._sanitize(root.text)122 self.__write_raw('\\fB{}\\fR'.format(text))123118 elif root.tag == 'em':119 if root.text is not None:120 text = self._sanitize(root.text)121 self.__write_raw('\\fI{}\\fR'.format(text))122 self._write_tail(root, inline=True)124 self._write_tail(root, inline=True)125124 elif root.tag == 'code':125 if root.text is not None:126 text = self._code_sanitize(root.text)127 self.__write_raw('\\fB{}\\fR'.format(text))128 self._write_tail(root, inline=True)126 elif root.tag == 'em':127 if root.text is not None:128 text = self._sanitize(root.text)129 self.__write_raw('\\fI{}\\fR'.format(text))130 self._write_tail(root, inline=True)131130 elif root.tag == 'pre':131 self.__write_cmd('.IP "" 4')132 self.__write_cmd('.nf\n') # extra newline for spacing reasons133 next = root134 first = True135 while next is not None and next.tag == 'pre':136 if not first:137 self.__write_raw('\n')138 text = ''.join(next.itertext(with_tail=False))139 self.__write_raw(self._pre_sanitize(text))140 first = False141 root = next142 next = next.getnext()143 self.__write_cmd('.fi')144 self.__write_cmd('.IP "" 0')132 elif root.tag == 'code':133 if root.text is not None:134 text = self._code_sanitize(root.text)135 self.__write_raw('\\fB{}\\fR'.format(text))136 self._write_tail(root, inline=True)137146 else:147 self._walk_child(root)138 elif root.tag == 'pre':139 self.__write_cmd('.IP "" 4')140 self.__write_cmd('.nf\n') # extra newline for spacing reasons141 next = root142 first = True143 while next is not None and next.tag == 'pre':144 if not first:145 self.__write_raw('\n')146 text = ''.join(next.itertext(with_tail=False))147 self.__write_raw(self._pre_sanitize(text))148 first = False149 root = next150 next = next.getnext()151 self.__write_cmd('.fi')152 self.__write_cmd('.IP "" 0')153149 last_tag = root.tag150 root = root.getnext()154 else:155 self._walk_child(root)156152 def _base_sanitize(self, text):153 text = re.sub(r'\\', r'\\e', text)154 text = re.sub(r'\.', r'\\.', text)155 text = re.sub("'", r"\'", text)156 text = re.sub('-', r'\-', text)157 return text157 last_tag = root.tag158 root = root.getnext()159159 def _pre_sanitize(self, text):160 return self._base_sanitize(text)160 def _base_sanitize(self, text):161 text = re.sub(r'\\', r'\\e', text)162 text = re.sub(r'\.', r'\\.', text)163 text = re.sub("'", r"\'", text)164 text = re.sub('-', r'\-', text)165 return text166162 def _code_sanitize(self, text):163 text = self._base_sanitize(text)164 text = re.sub(r'\s', ' ', text)165 return text167 def _pre_sanitize(self, text):168 return self._base_sanitize(text)169167 def _h3_sanitize(self, text):168 text = self._base_sanitize(text)169 text = re.sub(' \n|\n ', ' ', text)170 text = re.sub('\n', ' ', text)171 return text170 def _code_sanitize(self, text):171 text = self._base_sanitize(text)172 text = re.sub(r'\s', ' ', text)173 return text174173 def _sanitize(self, text):174 text = self._base_sanitize(text)175 text = re.sub(r'<([^>]+)>', r'\\fI\1\\fR', text)176 text = re.sub(r' +', ' ', text)177 text = re.sub('\n', ' ', text)178 return text175 def _h3_sanitize(self, text):176 text = self._base_sanitize(text)177 text = re.sub(' \n|\n ', ' ', text)178 text = re.sub('\n', ' ', text)179 return text180180 def __write_cmd(self, dat):181 print('.', dat, sep='\n', file=self.f)182 pass181 def _sanitize(self, text):182 text = self._base_sanitize(text)183 text = re.sub(r'<([^>]+)>', r'\\fI\1\\fR', text)184 text = re.sub(r' +', ' ', text)185 text = re.sub('\n', ' ', text)186 return text187184 def __write_raw(self, dat):185 print(dat, sep='', end='', file=self.f)186 pass188 def __write_cmd(self, dat):189 print('.', dat, sep='\n', file=self.f)190 pass191192 def __write_raw(self, dat):193 print(dat, sep='', end='', file=self.f)194 pass195196197def load_yml_file(fn):189 with open(fn) as f:190 return yaml.safe_load(f)198 with open(fn) as f:199 return yaml.safe_load(f)200201202def dedent_body(body):193 lines = [re.sub(r'^ (\S)', r'\1', l) for l in body.split('\n')]194 return '\n'.join(lines)203 lines = [re.sub(r'^ (\S)', r'\1', l) for l in body.split('\n')]204 return '\n'.join(lines)205206207def convert_manual_to_markdown():197 f = StringIO()198 manual = load_yml_file("content/manual/manual.yml")199 f.write(manual.get('manpage_intro', '\n'))200 f.write(dedent_body(manual.get('body', '\n')))201 for section in manual.get('sections', []):202 f.write('## {}\n'.format(section.get('title', '').upper()))203 f.write(dedent_body(section.get('body', '\n')))204 f.write('\n')205 for entry in section.get('entries', []):206 f.write('### {}\n'.format(entry.get('title', '')))207 f.write(dedent_body(entry.get('body', '\n')))208 f.write('\n')209 if entry.get('examples') is not None:210 f.write("~~~~\n")211 first = True212 for example in entry.get('examples'):213 if not first:208 f = StringIO()209 manual = load_yml_file("content/manual/manual.yml")210 f.write(manual.get('manpage_intro', '\n'))211 f.write(dedent_body(manual.get('body', '\n')))212 for section in manual.get('sections', []):213 f.write('## {}\n'.format(section.get('title', '').upper()))214 f.write(dedent_body(section.get('body', '\n')))215 f.write('\n')216 for entry in section.get('entries', []):217 f.write('### {}\n'.format(entry.get('title', '')))218 f.write(dedent_body(entry.get('body', '\n')))219 f.write('\n')220 if entry.get('examples') is not None:221 f.write("~~~~\n")222 first = True223 for example in entry.get('examples'):224 if not first:225 f.write('\n')215 f.write("jq '{}'\n".format(example.get('program', '')))216 f.write(" {}\n".format(example.get('input', '')))217 output = [str(x) for x in example.get('output', [])]218 f.write("=> {}\n".format(', '.join(output)))219 first = False220 f.write("~~~~\n")221 f.write('\n')222 f.write(manual.get('manpage_epilogue', ''))223 return f.getvalue()226 f.write("jq '{}'\n".format(example.get('program', '')))227 f.write(" {}\n".format(example.get('input', '')))228 output = [str(x) for x in example.get('output', [])]229 f.write("=> {}\n".format(', '.join(output)))230 first = False231 f.write("~~~~\n")232 f.write('\n')233 f.write(manual.get('manpage_epilogue', ''))234 return f.getvalue()235236237# Convert manual.yml to our special markdown format238markdown_data = convert_manual_to_markdown()239240# Convert markdown to html229html_data = markdown.markdown(markdown_data, extensions=[EscapeHtml(), 'fenced_code'])241html_data = markdown.markdown(markdown_data,242 extensions=[EscapeHtml(), 'fenced_code'])243244# Parse the html into a tree so we can walk it245tr = etree.HTML(html_data, etree.HTMLParser())246
2 unmodified lines
modified:docs/build_mantests.py+9 added-9 removed
1#!/usr/bin/env python32import yaml34with open("content/manual/manual.yml") as f:5 manual = yaml.safe_load(f)6 for section in manual.get('sections', []):7 for entry in section.get('entries', []):8 for example in entry.get('examples', []):9 print(example.get('program', '').replace('\n', ' '))10 print(example.get('input', ''))11 for s in example.get('output', []):12 print(s)13 print('')5 manual = yaml.safe_load(f)6 for section in manual.get('sections', []):7 for entry in section.get('entries', []):8 for example in entry.get('examples', []):9 print(example.get('program', '').replace('\n', ' '))10 print(example.get('input', ''))11 for s in example.get('output', []):12 print(s)13 print('')
modified:docs/build_website.py+39 added-32 removed
8 unmodified lines
9import shutil10import yaml1112env = Environment(13 loader=FileSystemLoader('templates'),14 autoescape=select_autoescape(['html.j2']),13 loader=FileSystemLoader('templates'),14 autoescape=select_autoescape(['html.j2']),15)161718def load_yml_file(fn):18 with open(fn) as f:19 return yaml.safe_load(f)19 with open(fn) as f:20 return yaml.safe_load(f)212223env.filters['search_id'] = lambda input: input.replace(r'`', '')24env.filters['section_id'] = lambda input: re.sub(r"[^a-zA-Z0-9_]", '', input)25env.filters['entry_id'] = lambda input: re.sub(r"[ `]", '', input)26env.filters['markdownify'] = lambda input: Markup(markdown(input))27env.filters['no_paragraph'] = lambda input: Markup(re.sub(r"</?p>", '', input))2827env.globals['unique_id'] = contextfunction(lambda ctx: str(next(ctx['unique_ctr'])))29env.globals['unique_id'] = contextfunction(30 lambda ctx: str(next(ctx['unique_ctr'])))312932env.globals.update(load_yml_file('site.yml'))333234env.globals['navigation'] = ['tutorial', 'download', 'manual']353637def generate_file(env, fname='content/1.tutorial/default.yml'):36 path, base = os.path.split(fname)37 path = os.path.relpath(path, 'content')38 if path == '.':39 path = ''40 slug = 'index'41 permalink = ''42 else:43 slug = os.path.basename(path)44 permalink = path + '/'38 path, base = os.path.split(fname)39 path = os.path.relpath(path, 'content')40 if path == '.':41 path = ''42 slug = 'index'43 permalink = ''44 else:45 slug = os.path.basename(path)46 permalink = path + '/'4746 output_dir = os.path.join('output', path)47 output_path = os.path.join(output_dir, 'index.html')48 output_dir = os.path.join('output', path)49 output_path = os.path.join(output_dir, 'index.html')5049 template_name = re.sub(r".yml$", '.html.j2', base)51 template_name = re.sub(r".yml$", '.html.j2', base)5251 ctx = load_yml_file(fname)52 ctx.update(unique_ctr=itertools.count(1), permalink=permalink, slug=slug, navitem=path)53 os.makedirs(output_dir, exist_ok=True)54 env.get_template(template_name).stream(ctx).dump(output_path, encoding='utf-8')53 ctx = load_yml_file(fname)54 ctx.update(unique_ctr=itertools.count(1),55 permalink=permalink,56 slug=slug,57 navitem=path)58 os.makedirs(output_dir, exist_ok=True)59 env.get_template(template_name).stream(ctx).dump(output_path,60 encoding='utf-8')616263def copy_public_files(root=''):58 for f in os.scandir(os.path.join('public', root)):59 src = os.path.join(root, f.name)60 dst = os.path.join('output', src)61 if f.is_dir():62 os.makedirs(dst, exist_ok=True)63 copy_public_files(src)64 else:65 shutil.copyfile(f.path, dst)64 for f in os.scandir(os.path.join('public', root)):65 src = os.path.join(root, f.name)66 dst = os.path.join('output', src)67 if f.is_dir():68 os.makedirs(dst, exist_ok=True)69 copy_public_files(src)70 else:71 shutil.copyfile(f.path, dst)727374copy_public_files()7576for fn in glob.glob('content/**/*.yml', recursive=True):70 generate_file(env, fn)77 generate_file(env, fn)