EngineeringFantasy

Fabric Entry Creation

Wednesday, 11 December 2013

So, in my attempts to create a functioning static blog generator using pelican, I've been using fabric to create my entries so that I can easily sort them according to their dates.

Here's the code:

def make_entry(title='default'):
    today = datetime.datetime.today()
    slug = title.lower().strip().replace(' ', '-')
    f_create = "content/{}_{:0>2}_{:0>2}_{}.rst".format(today.year, today.month, today.day, slug)
    with open(f_create, 'w') as w:
        with open('template.txt', 'r') as r:
            s = r.read().format(title=title,
                                hashes='#' * len(title),
                                year=today.year,
                                month=today.month,
                                day=today.day,
                                hour=today.hour,
                                minute=today.minute,
                                slug=slug)
            w.write(s)
            print("File created -> " + f_create)

Now, when I was doing this, I initally used the datetime.date class, but that did not have the hour and the minute attributes in the class. I also did not want to bother with slug creation, so I got that build in too.

I tried to get all the template string inside the function, but later on decided to refactor it out to a template.txt, which I can more easily use and change:

{title}
{hashes}

:date: {year}-{month}-{day} {hour}:{minute}
:tags:
:category:
:slug: {slug}
:author: Nafiul Islam

#Post goes here

The great thing about fabric is how easy it makes writing command line arguments. So, if I wanted to create a file with say {year}_{month}_{day}_{title}, I'd just do this:

fab make_entry:'My awesome title here'

Now that is awesome! :D