Skip to content

Instantly share code, notes, and snippets.

@ehuss

ehuss/1to2.py Secret

Last active February 28, 2019 05:38
Show Gist options
  • Save ehuss/b2a647eb69aa8f57bc4fb397656dfac1 to your computer and use it in GitHub Desktop.
Save ehuss/b2a647eb69aa8f57bc4fb397656dfac1 to your computer and use it in GitHub Desktop.
mdbook 0.1 to 0.2
import os
import re
import sys
LINK_PATTERN = r'(?m)^(\[[^]]+\]: )([^\n]*)()'
LINK_PATTERN2 = r'(\[[^]]+\]\()([^)]*)(\))'
def repl(match, parts, filename):
link = match.group(2)
if link.startswith('http'):
return match.group(0)
if not link.startswith('#'):
# Don't fixup links to outside documents.
if not link.startswith('..'):
link = link.replace('.html', '.md')
if parts:
link = os.path.relpath(link, '/'.join(parts))
# print('orig=%r new=%r parts=%r' % (match.group(2), link, parts))
return match.group(1) + link + match.group(3)
def process(path, parts):
print(path)
contents = open(path).read()
filename = os.path.basename(path)
for pattern in [LINK_PATTERN, LINK_PATTERN2]:
contents = re.sub(pattern, lambda x: repl(x, parts, filename), contents)
open(path, 'w').write(contents)
def main(start):
for (dirpath, dirnames, filenames) in os.walk(start):
relative = os.path.relpath(dirpath, start)
if relative == '.':
parts = []
else:
parts = relative.split(os.path.sep)
for filename in filenames:
if os.path.splitext(filename)[1] == '.md':
process(os.path.join(dirpath, filename), parts)
if __name__ == '__main__':
main(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment