Create script to convert markdown posts to Org format
This commit is contained in:
parent
3d452d5640
commit
49961a3007
58
_posts/_md-to-org.py
Executable file
58
_posts/_md-to-org.py
Executable file
@ -0,0 +1,58 @@
|
||||
#! /usr/bin/env python3
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
RENAME_REGEX = re.compile(r'\.(markdown|md)')
|
||||
FRONT_MATTER_REGEX = re.compile(r'^---\n([\s\S]+?)\n---', re.MULTILINE)
|
||||
|
||||
def convert(filename):
|
||||
org_filename = re.sub(RENAME_REGEX, '.org', filename)
|
||||
|
||||
with open(filename) as md_file:
|
||||
markdown = md_file.read()
|
||||
|
||||
filename = re.sub(RENAME_REGEX, '', filename)
|
||||
|
||||
# Get the front matter
|
||||
m = re.match(FRONT_MATTER_REGEX, markdown)
|
||||
if not m:
|
||||
print(f'No front matter found in {filename}')
|
||||
|
||||
return
|
||||
|
||||
front_matter = m.groups()[0]
|
||||
markdown = markdown[len(front_matter) + 10:]
|
||||
front_matter = yaml.load(front_matter)
|
||||
|
||||
markdown = '\n'.join(' ' + line if line else '' for line in markdown.split('\n'))
|
||||
|
||||
tags = ''
|
||||
permalink = ''
|
||||
date = front_matter['date'].isoformat().replace('T', ' ')
|
||||
|
||||
if 'tags' in front_matter:
|
||||
tags = ' :' + ':'.join(front_matter['tags']) + ':'
|
||||
|
||||
if 'permalink' in front_matter:
|
||||
permalink = f' :PERMALINK: {front_matter["permalink"]}\n'
|
||||
|
||||
markdown = markdown.replace('`', '~')
|
||||
|
||||
org_content = f'''* {front_matter['title']}{tags}
|
||||
CLOSED: [{date}]
|
||||
:PROPERTIES:
|
||||
:EXPORT_FILENAME: {filename}
|
||||
{permalink} :END:
|
||||
|
||||
{markdown}'''
|
||||
|
||||
with open(org_filename, 'w') as org_file:
|
||||
org_file.write(org_content)
|
||||
|
||||
if __name__ == '__main__':
|
||||
for filename in sys.argv[1:]:
|
||||
convert(filename)
|
Loading…
Reference in New Issue
Block a user