Skip to content

Instantly share code, notes, and snippets.

@jpmckinney
Last active April 26, 2021 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpmckinney/88c846651ab5411d1ed3a6fe222ce08f to your computer and use it in GitHub Desktop.
Save jpmckinney/88c846651ab5411d1ed3a6fe222ce08f to your computer and use it in GitHub Desktop.
import json
import os
import re
import sys
from textwrap import dedent
tables_replacements = {
'```eval_rst': '',
'```': '',
}
eval_rst_replacements = {
r'.. markdown *::': '',
r'\.\. admonition:: Hint\n *:class: hint': '.. hint::',
r'\.\. admonition:: Note\n *:class: note': '.. note::',
r'\.\. admonition:: Tip\n *:class: tip': '.. tip::',
r'\.\. admonition:: Warning\n *:class: warning': '.. warning::',
}
def tables(matchobj):
content = matchobj.group(1)
for old, new in tables_replacements.items():
content = re.sub(old, new, content)
index = 0
lines = []
for line in content.splitlines():
line = line.strip()
if line.startswith('=='):
if index == 1:
lines.append('-- | - | - | -- | - | -')
index += 1
elif line:
line = f'{line:22}'
lines.append(f'{line[0:2]} | {line[4:5]} | {line[8:9]} | {line[12:14]} | {line[16:17]} | {line[20:-1]}'.strip())
table = '\n'.join(lines)
return f'<div class="disclosure-timing" markdown=1>\n{table}\n</div>'
def eval_rst(matchobj):
content = matchobj.group(1)
for old, new in eval_rst_replacements.items():
content = re.sub(old, new, content)
contents = []
for text in re.split(r'\n *(?=\.\.)', content)[1:]:
text = text.strip()
match = re.search(r'\A\.\. ([^:]+)::(.*)', text)
directive = match.group(1).strip()
arguments = match.group(2).strip()
if directive == 'codelisttable':
directive = 'csv-table'
options = []
body = []
for line in dedent(text[match.end(0):]).splitlines():
line = line.rstrip()
if line.startswith(':'):
options.append(line)
else:
body.append(line)
options = '\n'.join(options)
body = '\n'.join(body)
if body.lstrip().startswith('{'):
body = json.dumps(json.loads(body), ensure_ascii=False, indent=2)
else:
body = dedent(body).lstrip('\n')
parts = [f'```{{{directive}}}']
if arguments:
parts.append(f' {arguments}')
if options or body:
parts.append('\n')
if options:
parts.append(f'{options}')
if options and body:
parts.append('\n\n')
parts.append(f'{body}\n```')
contents.append(''.join(parts))
return '\n\n'.join(contents)
for root, dirs, files in os.walk(sys.argv[1]):
for file in files:
if not file.endswith('.md'):
continue
with open(os.path.join(root, file)) as f:
content = f.read()
content = re.sub(r'<div class="disclosure-timing">(.+?)</div>', tables, content, flags=re.DOTALL)
content = re.sub(r'```(?:{eval-rst}|eval_rst)(.+?)```', eval_rst, content, flags=re.DOTALL)
content = content.replace('\n\n\n', '\n\n')
with open(os.path.join(root, file), 'w') as f:
f.write(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment