Donate to support Ukraine's independence.

25 Dec'13

Creating shortcut function in Fabric to create a Pelican draft

I migrated from Wordpress to Pelican few month ago and so far I was satisfied with it, mainly because my demands to the blogging platform are far lower than one might imagine. But as atrue engineer, I always strive to eliminate any duplication in code or in actions.

For this reason I’ve created one more Fabric function that creates a draft for me, properly setting the date and slug for me:

drafts_path = 'content/drafts/'

def draft(title):
    from datetime import date
    from time import strftime, gmtime
    from unidecode import unidecode
    import re
    from subprocess import call

    today_iso =
    now_iso = strftime("%Y-%m-%d %H:%M", gmtime())
    file_slug = unidecode(title.decode('utf-8')).lower()
    file_slug = re.sub("\s+", "-", file_slug)
    file_slug = re.sub("[-]+", "-", file_slug).lstrip('-')
    file_name = "%s-%s.rst" % (today_iso, file_slug)
    file_path = "%s%s" % (drafts_path, file_name)
    if not os.path.exists(file_path):
        draft_fd = open(file_path, "w+")
        print(title, file=draft_fd)
        print('='*len(title), file=draft_fd)
        print('', file=draft_fd)
        print(':date: %s' % now_iso, file=draft_fd)
        print(':slug: %s' % file_slug, file=draft_fd)
        print(':status: draft', file=draft_fd)
        print('', file=draft_fd)
        print("WARNING: file already exists")
    call(['editor', file_path])