Mercurial > public > pelican-blog
comparison __bgn/import_blogophile.py @ 2:b7be75ff95b0
Created a script to convert my Blogofile posts to Pelican.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Wed, 29 Jan 2014 21:32:04 -0600 |
parents | |
children | c3115da3ff73 |
comparison
equal
deleted
inserted
replaced
1:64edb34396b6 | 2:b7be75ff95b0 |
---|---|
1 #!/usr/bin/env python | |
2 """ | |
3 A simple script to convert my Blogofile restructured text posts into the format | |
4 expected by Pelican. | |
5 | |
6 """ | |
7 # Copyright (C) 2014 by Brian Neal. | |
8 # | |
9 # Permission is hereby granted, free of charge, to any person obtaining a copy | |
10 # of this software and associated documentation files (the "Software"), to deal | |
11 # in the Software without restriction, including without limitation the rights | |
12 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
13 # copies of the Software, and to permit persons to whom the Software is | |
14 # furnished to do so, subject to the following conditions: | |
15 # | |
16 # The above copyright notice and this permission notice shall be included in | |
17 # all copies or substantial portions of the Software. | |
18 # | |
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
25 # THE SOFTWARE. | |
26 | |
27 import datetime | |
28 import os | |
29 import re | |
30 import time | |
31 | |
32 | |
33 SRC_DIR = os.path.expanduser('~/coding/python/virtualenvs/blogofile/blog/_posts') | |
34 DST_DIR = os.path.expanduser('~/coding/python/venvs/blog/blog-pelican/content') | |
35 | |
36 TITLE_RE = re.compile(r'^title: (?P<title>.*)$') | |
37 DATE_RE = re.compile(r'^date: (?P<year>\d{4})/' | |
38 r'(?P<month>\d{1,2})/' | |
39 r'(?P<day>\d{1,2})\s*' | |
40 r'(?P<time>\d{2}:\d{2}:\d{2})\s*$') | |
41 CAT_RE = re.compile(r'^categories: (?P<cats>.*)$') | |
42 | |
43 PELICAN_FMT = """\ | |
44 {title} | |
45 {title_underline} | |
46 | |
47 :date: {date} | |
48 :category: coding | |
49 :tags: {tags} | |
50 :slug: {slug} | |
51 :author: Brian Neal | |
52 | |
53 {content} | |
54 """ | |
55 | |
56 | |
57 class ConvertError(Exception): | |
58 """Exception class for the conversion process""" | |
59 | |
60 | |
61 def slugify(s): | |
62 """Return a slug from the string s. | |
63 | |
64 This code must match what Blogofile was doing in order to keep the URLs the | |
65 same. In this case I had customized Blogfile's functionality based on a tip | |
66 by Mike Bayer: http://techspot.zzzeek.org/2010/12/06/my-blogofile-hacks/ | |
67 | |
68 """ | |
69 slug = s.lower() | |
70 | |
71 # convert ellipses to spaces | |
72 slug = re.sub(r'\.{2,}', ' ', slug) | |
73 | |
74 # flatten everything non alpha or . into a single - | |
75 slug = re.sub(r'[^0-9a-zA-Z\.]+', '-', slug) | |
76 | |
77 # trim off leading/trailing - | |
78 slug = re.sub(r'^-+|-+$', '', slug) | |
79 return slug | |
80 | |
81 | |
82 def convert(src, dst): | |
83 """Convert Blogofile to Pelican.""" | |
84 print '{} -> {}'.format(src, dst) | |
85 meta, content = parse_input(src) | |
86 write_output(meta, content, dst) | |
87 | |
88 | |
89 def parse_input(src): | |
90 """Parse input Blogofile .rst input. | |
91 | |
92 Returns a 2-tuple: | |
93 meta - dictionary of Blogofile metadata | |
94 content - blog post body as a string | |
95 | |
96 """ | |
97 with open(src, 'r') as fp: | |
98 lines = fp.readlines() | |
99 | |
100 # Find meta block | |
101 for i, line in enumerate(lines): | |
102 if line == '---\n': | |
103 meta_start = i | |
104 break | |
105 else: | |
106 raise ConvertError("Can't find start of meta block") | |
107 | |
108 for i, line in enumerate(lines[meta_start + 1 :]): | |
109 if line == '---\n': | |
110 meta_end = meta_start + 1 + i | |
111 break | |
112 else: | |
113 raise ConvertError("Can't find end of meta block") | |
114 | |
115 meta_lines = lines[meta_start + 1 : meta_end] | |
116 meta = {} | |
117 for line in meta_lines: | |
118 m = TITLE_RE.match(line) | |
119 if m: | |
120 meta['title'] = m.group('title').strip() | |
121 continue | |
122 m = DATE_RE.match(line) | |
123 if m: | |
124 year = int(m.group('year')) | |
125 month = int(m.group('month')) | |
126 day = int(m.group('day')) | |
127 t = time.strptime(m.group('time'), '%H:%M:%S') | |
128 meta['date'] = datetime.datetime.combine( | |
129 datetime.date(year, month, day), | |
130 datetime.time(t.tm_hour, t.tm_min, t.tm_sec)) | |
131 continue | |
132 m = CAT_RE.match(line) | |
133 if m: | |
134 meta['categories'] = m.group('cats').replace(' ', '').split(',') | |
135 continue | |
136 | |
137 for k in ['title', 'date', 'categories']: | |
138 if k not in meta: | |
139 raise ConvertError("Missing {} in metadata".format(k)) | |
140 | |
141 content = ''.join(lines[meta_end + 1:]).strip() | |
142 return meta, content | |
143 | |
144 | |
145 def write_output(meta, content, dst): | |
146 """Create the Pelican style .rst file from the Blogofile metadata and | |
147 content. Output is written to the file specified by dst. | |
148 | |
149 """ | |
150 title = meta['title'] | |
151 date = meta['date'].strftime('%Y-%m-%d %H:%M') | |
152 tags = ', '.join(meta['categories']) | |
153 slug = slugify(title) | |
154 | |
155 post = PELICAN_FMT.format(title=title, | |
156 title_underline='#'*len(title), | |
157 date=date, | |
158 tags=tags, | |
159 slug=slug, | |
160 content=content) | |
161 | |
162 with open(dst, 'w') as fp: | |
163 fp.write(post) | |
164 | |
165 | |
166 if __name__ == '__main__': | |
167 for name in os.listdir(SRC_DIR): | |
168 if name.endswith('.rst'): | |
169 src = os.path.join(SRC_DIR, name) | |
170 dst = os.path.join(DST_DIR, name) | |
171 | |
172 try: | |
173 convert(src, dst) | |
174 except ConvertError as ex: | |
175 print "Error converting {}: {}".format(name, ex) |