comparison tools/new_post.py @ 11:75a003a548c4

Added a script to create a new post by answering questions.
author Brian Neal <bgneal@gmail.com>
date Sun, 02 Feb 2014 13:07:15 -0600
parents
children
comparison
equal deleted inserted replaced
10:6c03ca07a16d 11:75a003a548c4
1 """A script to help create new blog posts by asking the user some questions and
2 then creating a new .rst file accordingly.
3
4 """
5 import datetime
6 import os
7 import pwd
8 import re
9 import subprocess
10
11
12 POST = """\
13 {title}
14 {title_under}
15
16 :date: {date}
17 :tags: {tags}
18 :slug: {slug}
19 :author: {author}
20
21 """
22
23
24 def slugify(s):
25 """Return a slug from the string s."""
26
27 slug = s.lower()
28
29 # convert ellipses to spaces
30 slug = re.sub(r'\.{2,}', ' ', slug)
31
32 # flatten everything non alpha or . into a single -
33 slug = re.sub(r'[^0-9a-zA-Z\.]+', '-', slug)
34
35 # trim off leading/trailing -
36 slug = re.sub(r'^-+|-+$', '', slug)
37 return slug
38
39
40 def main():
41
42 title = raw_input("Blog title: ")
43 title_under = '#' * len(title)
44
45 # Usually takes me about an hour to write a blog post:
46 anticipated_date = datetime.datetime.now() + datetime.timedelta(hours=1)
47 default_date = anticipated_date.strftime('%Y-%m-%d %H:%M')
48 date_str = raw_input("Publish date [{}]: ".format(default_date))
49 date_str = date_str if date_str else default_date
50
51 tags = raw_input("Tags (comma separated): ")
52
53 default_slug = slugify(title)
54 slug = raw_input("Slug [{}]: ".format(default_slug))
55 slug = slug if slug else default_slug
56
57 # Author; yes I could just hardcode my name here... ;)
58 user = os.environ.get('USER', '')
59 if user:
60 user = pwd.getpwnam(user)[4].split(',')[0]
61
62 default_author = user
63 author = raw_input('Author [{}]: '.format(default_author))
64 author = author if author else default_author
65
66 post = POST.format(title=title, title_under=title_under, date=date_str,
67 tags=tags, slug=slug, author=author)
68
69 # Create a file for the new post.
70 # This is all specific to my convention of put posts under a category
71 # directory and having the first 3 characters in the filename be a number
72 # (000-999).
73 category = raw_input('Category [Coding]: ')
74 category = category if category else 'Coding'
75
76 post_dir = os.path.join('content', category)
77 posts = sorted(os.listdir(post_dir))
78 if posts:
79 last_post_num = int(posts[-1][:3])
80 num = last_post_num + 1
81 else:
82 num = 0
83
84 new_name = '{num:03}-{slug}.rst'.format(num=num, slug=slug)
85 new_path = os.path.join('content', category, new_name)
86
87 # Write file:
88 with open(new_path, 'w') as fp:
89 fp.write(post)
90
91 # Launch editor if set
92 editor = os.environ.get('VISUAL', os.environ.get('EDITOR'))
93 if editor:
94 subprocess.call([editor, new_path])
95
96
97 if __name__ == '__main__':
98 main()