Skip to content

Instantly share code, notes, and snippets.

@iainhouston
Last active March 30, 2022 03:24
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 iainhouston/cb9917add871c7dd40409068045c28b2 to your computer and use it in GitHub Desktop.
Save iainhouston/cb9917add871c7dd40409068045c28b2 to your computer and use it in GitHub Desktop.
This is (probably yet another) Python script to create a new post in your Jekyll blog
#!/usr/bin/env python3
# makepost.py
'''
Program to create a Jekyll _post file in the correct format
and populated with essential frontmatter
'''
import os, re, sys, argparse
from datetime import date, time, datetime
# blogcats allows you to limit the categories of new posts in your blog
# list elements are separated by a comma, or a semicolon
known_categories = re.split(r'[;,]\s*', os.environ['blogcats']) if ('blogcats' in os.environ) else ['Blog']
version='%(prog)s 0.2'
parser = argparse.ArgumentParser(description='Create a new Jekyll blog post', epilog=" You can provide zero or more '--category' arguments (default='Blog') but, if supplied, each one is restricted to a value in your 'blogcats' environment variable CSV list. Ω If you do not supply a '--blogpath' argument, %(prog)s will look for a 'blogpath' environment variable.")
parser.add_argument('title', type=str, action='store',
help='The title of the blog post')
parser.add_argument('-b', '--blogpath', type=str, action='store',
help='Path to your Jekyll blog _post files')
parser.add_argument('-c', '--category', type=str, action='append', dest='categories',
choices=known_categories, default=["Blog"],
help="A category for the new post's front matter.")
parser.add_argument('-n', '--no_output', action='store_true',
help="Don't write a file for the post. 'False' by default.")
parser.add_argument('-V', '-v', '--version', action='version', version=version)
args = parser.parse_args()
# If a blogpath argument is provided, it overrides the envoronment variable
# of the same name. If neither esists, then we really cannot carry on!
if args.blogpath:
blogpath = args.blogpath
else:
if 'blogpath' in os.environ:
blogpath = os.environ['blogpath']
else:
parser.print_help()
print('{0}: error: Neither -b/--blogpath nor environment blogpath supplied.'.format(parser.prog))
sys.exit(1)
# Sanitiise the title argument to make it a suitable file name
pat = re.compile(r'([a-z,A-Z,0-9]+)')
filename = '_'.join(pat.findall(args.title))
# Jekyll likes its posts to be named just so
filedate = datetime.now().date()
filepath = '{0}/{1}-{2}.markdown'.format(blogpath,filedate,filename)
# Jekyll likes its front matter just so.
# Jekyll can use this to ensure correct sorting of posts
filetime = datetime.now().time().strftime('%H-%M-%S')
contents = r"""---
title: {title}
date: {filedate} {filetime}
layout: post
categories: {categories}
---
{title}
===============
Replace this text with your text about {title}""".format(title=args.title, filedate=filedate, filetime=filetime,categories=(args.categories if args.categories else '[]'))
if not args.no_output:
with open(filepath, 'w') as file:
print('Creating a new blog post file at: \n{0}'.format(filepath))
file.write(contents)
else:
print('===================================')
print('No post written: "--no_output=True"')
print('===================================')
print(contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment