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
Provenance
- Commit
e5414e6- Tree
4b935be- Author
itchyny <itchyny@cybozu.co.jp>- Committer
GitHub <noreply@github.com>- Parent
fd9da66
3 files changed+239 added−219 removed
modified:docs/build_manpage.py+191 added-178 removed
6 unmodified lines7 import re8 import sys9 import yaml10 11+12 # Prevent our markdown parser from trying to help by interpreting things in angle brackets as HTML tags.13 class EscapeHtml(Extension):13- def extendMarkdown(self, md, md_globals):14- del md.preprocessors['html_block']15- del md.inlinePatterns['html']14 15+ def extendMarkdown(self, md, md_globals):16+ del md.preprocessors['html_block']17+ del md.inlinePatterns['html']18+19+20 class RoffWalker(object):18- def __init__(self, tree, output=sys.stdout):19- self.tree = tree20- self.target = output21- self.f = StringIO()21 23- 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()26 31- 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)34 40- 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(':')43 44- 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)47 51- 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)54 61- 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')64 70- 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")75 73- 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()))79 77- 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)))83 82- 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'))88 103- 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')110 111- 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)118 116- 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))123 118- 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)125 124- 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)131 130- 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)137 146- 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')153 149- last_tag = root.tag150- root = root.getnext()154+ else:155+ self._walk_child(root)156 152- 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()159 159- 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 text166 162- 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)169 167- 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 text174 173- 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 text180 180- 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 text187 184- 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+ pass191 192+ def __write_raw(self, dat):193+ print(dat, sep='', end='', file=self.f)194+ pass195+196+197 def 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)200 201+202 def 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)205 206+207 def 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()235 236+237 # Convert manual.yml to our special markdown format238 markdown_data = convert_manual_to_markdown()239 240 # Convert markdown to html229-html_data = markdown.markdown(markdown_data, extensions=[EscapeHtml(), 'fenced_code'])241+html_data = markdown.markdown(markdown_data,242+ extensions=[EscapeHtml(), 'fenced_code'])243 244 # Parse the html into a tree so we can walk it245 tr = etree.HTML(html_data, etree.HTMLParser())246 2 unmodified linesmodified:docs/build_mantests.py+9 added-9 removed
1 #!/usr/bin/env python32 import yaml3 4 with 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 lines9 import shutil10 import yaml11 12 env = Environment(13- loader=FileSystemLoader('templates'),14- autoescape=select_autoescape(['html.j2']),13+ loader=FileSystemLoader('templates'),14+ autoescape=select_autoescape(['html.j2']),15 )16 17+18 def 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)21 22+23 env.filters['search_id'] = lambda input: input.replace(r'`', '')24 env.filters['section_id'] = lambda input: re.sub(r"[^a-zA-Z0-9_]", '', input)25 env.filters['entry_id'] = lambda input: re.sub(r"[ `]", '', input)26 env.filters['markdownify'] = lambda input: Markup(markdown(input))27 env.filters['no_paragraph'] = lambda input: Markup(re.sub(r"</?p>", '', input))28 27-env.globals['unique_id'] = contextfunction(lambda ctx: str(next(ctx['unique_ctr'])))29+env.globals['unique_id'] = contextfunction(30+ lambda ctx: str(next(ctx['unique_ctr'])))31 29-32 env.globals.update(load_yml_file('site.yml'))33 32-34 env.globals['navigation'] = ['tutorial', 'download', 'manual']35 36+37 def 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 + '/'47 46- 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')50 49- template_name = re.sub(r".yml$", '.html.j2', base)51+ template_name = re.sub(r".yml$", '.html.j2', base)52 51- 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')61 62 63 def 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)72 73+74 copy_public_files()75 76 for fn in glob.glob('content/**/*.yml', recursive=True):70- generate_file(env, fn)77+ generate_file(env, fn)