Skip to content

Instantly share code, notes, and snippets.

@jpmckinney
Last active April 26, 2021 16:53
Show Gist options
  • 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
replacements = {
r'.. markdown *::': '',
r'\.\. admonition:: Hint\n *:class: hint': '.. hint::',
r'\.\. admonition:: Note\n *:class: note': '.. note::',
r'\.\. admonition:: Warning\n *:class: warning': '.. warning::',
}
def repl(matchobj):
content = matchobj.group(1)
for old, new in 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'```{eval-rst}(.+?)```', repl, 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