soli-mdbook/outline_to_mdbook.py

58 lines
2.3 KiB
Python

"""
A script to take a folder of markdown files (created by an outline export) and convert it into a folder
of markdown files in the correct format for mdbook.
"""
import os
import subprocess
import re
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
def outline_to_mdbook(input_path, output_path):
summary_lines = []
if not os.path.exists(output_path):
os.mkdir(output_path)
for root, dirs, files in os.walk(input_path):
path = root.split(os.sep)
for file in files:
rel_path = os.path.relpath(root, input_path)
new_rel_dir = rel_path.replace(" ", "-")
new_dir = os.path.join(output_path, new_rel_dir).replace(" ", "-")
file_path = os.path.join(root, file)
if file.endswith(".md"):
new_file = file.replace(" ", "-")
new_file = new_file.replace("%2F", "-")
new_file = new_file.replace(".md", "")
new_file = re.sub('[^A-Za-z0-9\-]+', '', new_file)
new_file = new_file.replace("--", "-")
if new_file.startswith("-"):
new_file = new_file[1:]
if new_file.endswith("-"):
new_file = new_file[:-1]
new_file += ".md"
else:
new_file = file
new_path = os.path.join(new_dir, new_file)
if not os.path.exists(new_dir):
os.makedirs(new_dir)
# copy over the file
subprocess.call(["cp", file_path, new_path])
if file.endswith(".md"):
new_rel_path = os.path.join(new_rel_dir, new_file)
summary_line = "- [{old_name}](./{new_rel_path})".format(
old_name=file.replace(".md", ""),
new_rel_path=new_rel_path
)
summary_lines.append(summary_line)
# finallly write summary file
summary_file_path = os.path.join(output_path, "SUMMARY-base.md")
with open(summary_file_path, 'w') as f:
for line in summary_lines:
f.writelines(line + "\n")
if __name__ == "__main__":
input_path = os.path.join(PROJECT_PATH, "export")
output_path = os.path.join(PROJECT_PATH, "src")
outline_to_mdbook(input_path, output_path)