Skip to content

Instantly share code, notes, and snippets.

@atheriel

atheriel/newpost.py

Created Feb 12, 2014
Embed
What would you like to do?
A simple program for generating new posts and pages for Pelican.
#!/usr/bin/env python
__doc__ = '''
Create a new post/page.
Usage:
newpost.py <title> [--page] [-t <tag>...]
newpost.py -h | --help | --version
Options:
--page Create a 'page' as opposed to a 'post'.
-t, --tags Specify the tags for the page/post.
-v, --version Show version information and exit.
-h, --help Show this help and exit.
'''
template = '''{title}
{title_underline}
:date: {date}
:tags: {tags}
:author: {author}
'''
import os
import sys
import os.path
import datetime
from docopt import docopt
import pelicanconf # To get the blog author
def main():
args = docopt(__doc__)
today = datetime.date.today()
# Locate the blog directory and check that ``content`` exists
cwd = os.path.dirname(os.path.realpath(__file__))
assert os.path.exists(cwd + '/content')
# Generate a file from title + date in the blog's content directory
if not args['--page']:
filename = os.path.join(cwd, 'content/{0}-{1}.rst'.format(today, args['<title>'].lower().replace(' ', '-').replace('.', '')))
else:
if not os.path.exists(cwd + '/content/pages'):
os.mkdir(cwd + '/content/pages')
filename = os.path.join(cwd, 'content/pages/{0}.rst'.format(args['<title>'].lower().replace(' ', '-').replace('.', '')))
if os.path.exists(filename):
print('Error: A file for that title already exists.')
sys.exit(1)
with open(filename, 'w') as f:
f.write(template.format(
title = args['<title>'],
title_underline = '#' * len(args['<title>']),
tags = ', '.join([t.lower() for t in args['<tag>']]) if args['<tag>'] is not None else '',
date = today,
author = pelicanconf.AUTHOR,
))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment