Skip to content

Instantly share code, notes, and snippets.

@skhaz
Last active December 16, 2019 15:42
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 skhaz/8ee7bc487e2a2f7df3eef71c298d6f2a to your computer and use it in GitHub Desktop.
Save skhaz/8ee7bc487e2a2f7df3eef71c298d6f2a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import re
import functools
import itertools
from pathlib import Path
import click
from jinja2 import Environment, BaseLoader, Template
try:
import ujson as json
except ImportError:
import json
jinja2_env = Environment(loader=BaseLoader(), trim_blocks=True)
base = Template('''---
title: {{ title }}
tags: [""]
draft: false
---
{{ content }}
''')
tags = '''
<img src="{{ filename }}" alt="{{ title }}">
---
<audio controls>
<source src="{{ filename }}" type="{{ mimetype }}">
</audio>
---
<video controls>
<source src="{{ filename }}" type="{{ mimetype }}">
</video>
'''.split(
'---'
)
templates = {
key: f'{{% include base %}}\n{value}'
for key, value in dict(
image=tags[0],
audio=tags[1],
video=tags[2],
).items()
}
residuous = (Path.cwd() / 'residuous.txt').read_text().splitlines()
def render(context):
content = context['content']
del context['content']
[r for r in residuous if (content := content.replace(r, ''))]
kind, _ = context['mimetype'].split('/')
template = templates[kind]
result = jinja2_env.from_string(template).render(base=base, content=content, **context)
filepath = Path.cwd() / f'{context["guid"]}.md'
filepath.write_text(result)
@click.command()
@click.option('-d', '--directory', required=True)
def run(directory):
path = Path(directory).resolve()
if not path.exists():
return
files = {p for p in path.glob('*.json')} or [path]
[
*map(
render,
itertools.chain(
*map(
lambda f: json.loads(f.read_text()),
files,
)
),
)
]
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment