Skip to content

Instantly share code, notes, and snippets.

@ayushkumarshah
Created June 6, 2020 09:23
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 ayushkumarshah/333b21b8c0268381cf690d8f1c6e75bb to your computer and use it in GitHub Desktop.
Save ayushkumarshah/333b21b8c0268381cf690d8f1c6e75bb to your computer and use it in GitHub Desktop.
import argparse
import os, glob
parser = argparse.ArgumentParser()
def dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
# Add the arguments to the parser
parser.add_argument(
"-s", "--source", required=True, type=dir_path, help="Source directory"
)
parser.add_argument(
"-t", "--target", required=True, type=dir_path, help="Target directory"
)
args = parser.parse_args()
source, target = args.source, args.target
for filename in glob.glob(os.path.join(source, "*.md")):
print(filename)
f = open(filename, "r").read()
lines = f.splitlines()
first, rest = lines[:10], lines[10:]
fixed_first = ["---", "layout: post"]
for line in first:
for key in ["Title:", "Date:", "Summary:"]:
if line.startswith(key):
line = line.replace(key, key.lower())
if key == "Date:":
if not filename.startswith("20"):
date = line[6 : 6 + 10] + "-"
else:
date = ""
if line.startswith("Authors:"):
line = line.replace("Authors:", "author:")
if line.startswith("Slug:"):
continue
if line.startswith("Tags:"):
line = line.replace("Tags: ", "tags: [") + "]"
if line.startswith("Category:"):
line = line.replace("Category: ", "categories: [") + "]"
if line.startswith("Status:"):
line = line.replace(line, "---")
fixed_first.append(line)
rest_new = []
for line in rest:
line = line.replace("/images/", "/assets/img/sample/")
line = line.replace("{.img-center}", "")
rest_new.append(line)
with open(
os.path.join(target, "{}{}".format(date, filename[filename.rindex("/") + 1 :])),
"w",
) as f:
f.writelines(l + "\n" for l in fixed_first + rest_new)
print("Files written to {} directory".format(target))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment