Categories: 3d printing (14) arcade cabinet (6) arduino (2) backup (4) blogofile (4) dns (8) mailbox alert (62) making (12) projects (116) RAID (4) rants (24) raspberry pi (2) site (26) ultimaker (4)

Small script to create Blogofile posts

2012-08-04 | Permalink

I’ve written a very small Python 3 script to initialize Blogofile posts;

It generates a post number, prompts for a title, automatically sets the date, and adds an empty categories field.

It uses the basic simple-blog conventions, but the script should be easy enough to change to your setup.

Not very useful (yet?), but it makes starting a post just that tiny bit easier.

#!/usr/bin/python3

#
# Simple helper tool to create blog entries.
#

import datetime
import os
import re

EDITOR='<editor here>' # I use 'geany -l7'
BLOG_ENTRY_PATH='<(sub)directory of _posts here>'

def find_next_number(path):
    '''Reads the directory, and returns the first available post number'''
    all_post_numbers = []
    all_files = os.listdir(path)
    p = re.compile('^([0-9]+)\s+')
    for filename in all_files:
        match = p.match(filename)
        if match:
            all_post_numbers.append(int(match.group(1)))
    all_post_numbers.sort()
    return all_post_numbers[-1] + 1;

def prompt_for_title():
    return input('Post title: ')

def get_new_date():
    now = datetime.datetime.now()
    return now.strftime('%Y/%m/%d %H:%M:%S')

class Post:
    def __init__(self, path, number, title, date_str):
        self.path = path
        self.number = number
        self.title = title
        self.date_str = date_str

    def get_filename(self):
        filename = '%03d - %s.markdown' % (self.number, self.title)
        return os.path.join(self.path, filename)

    def create_file(self):
        with open(self.get_filename(), 'w') as out_f:
            out_f.write('---\n')
            out_f.write('title: ' + self.title + '\n')
            out_f.write('date: ' + self.date_str + '\n')
            out_f.write('categories: \n')
            out_f.write('---\n')
            out_f.write('\n')

number = find_next_number(BLOG_ENTRY_PATH)
title = prompt_for_title()
date = get_new_date()
post = Post(BLOG_ENTRY_PATH, number, title, date)
print(post.get_filename())
post.create_file()
os.system('%s "%s"&' % (EDITOR, post.get_filename()))