Skip to content

Instantly share code, notes, and snippets.

@mseri
Created June 2, 2015 14:44
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 mseri/269144eab2a2bfead64d to your computer and use it in GitHub Desktop.
Save mseri/269144eab2a2bfead64d to your computer and use it in GitHub Desktop.
Generates a stub for a markdown pelican article.
#!/usr/bin/env python3
"""Generates a stub for a markdown pelican article."""
import click
from datetime import datetime
from os import listdir
TEMPLATE = """Id: {aid}
Title: {title}
Date: {date}
Modified: {date}
Tags: {tags}
Category: Blog
Slug: {title_slug}
Authors: Marcello Seri
Status: draft
"""
# TODO: make this dynamic or customisable
FILENAME = "{aid:02d}-{title_slug}.md"
# TODO: make this dynamic or customisable
BLOG_FOLDER = # Here goes the path to your pelican blog's raw content
######################################################################
## Courtesy of http://flask.pocoo.org/snippets/5/
## Generating Slugs - by Armin Ronacher
import re
from unidecode import unidecode
## pylint: disable=C0103
## Investigate if r'[\s\W]+' is fine too
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
def slugify(text, delim='-'):
"""Generates an ASCII-only slug."""
result = []
for word in _punct_re.split(text.lower()):
result.extend(unidecode(word).split())
return str(delim.join(result))
######################################################################
def int_or_zero(string):
"""Casts a string to an int and returns the casted integer value.
In case of ValueError it returns 0."""
value = 0
try:
value = int(string)
except ValueError:
pass
return value
@click.command()
@click.argument("title")
@click.option("--save",
is_flag=True,
help="Saves the file in the blog content folder.")
@click.option("--verbose",
is_flag=True,
help="In combination with --save prints the full file path.")
def process(title, save, verbose):
"""Generates a stub for a markdown pelican article."""
# TODO: Add optional tags option.
template_dict = {"title": title, "tags": ""}
# Generates the id by elaborating the list of article filenames
# These are of the form {aid}-{title_slug}.md
filelist = listdir(BLOG_FOLDER)
template_dict["aid"] = 1 + max(int_or_zero(filename[:2])
for filename in filelist)
template_dict["date"] = datetime.now().isoformat()
template_dict["title_slug"] = slugify(title)
content = TEMPLATE.format(**template_dict)
if save:
filename = "{}/{}".format(BLOG_FOLDER, FILENAME.format(**template_dict))
with open(filename, "w") as f:
f.write(content)
if verbose:
print("Stub written to: {}".format(filename))
else:
print(content)
if __name__ == '__main__':
#pylint: disable=E1120
process()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment