forked from bobuk/addmeto.cc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblogit
executable file
·365 lines (314 loc) · 11.1 KB
/
blogit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env python3
import sys
sys.path.insert(0, 'libs/')
import os
import json
from datetime import datetime, timedelta
import re
import pystache
import baker
import markdown2 as markdown
from pyatom import AtomFeed
current_date = datetime.now().strftime('%Y-%m-%d')
daydelta = timedelta(days=1)
def loadConfigs(path=os.getcwd()):
fname = os.path.join(path, 'config.json')
if not os.path.isfile(fname):
return None
return json.load(open(fname))
config = loadConfigs()
def saveto(fres):
dname = os.path.dirname(fres)
try:
os.makedirs(dname)
except:
pass
return open(fres, 'w')
def tags_cludge(tag):
tag = "<small>#" + tag.group(1) + "</small>"
return tag
def makeHtml(inbound):
res = []
for line in inbound.split('\n'):
line = line.strip()
if line.startswith('>>') and line.endswith('<<'):
line = line[2:-2].strip()
if line.startswith('!['):
# inline image!
tp, url = line[2:-1].split('](')
if tp == 'center':
line = '<div style="text-align: center"><img src="' + \
url + \
'" style="float: none" /></div>'
else:
raise Error('Unknown inline')
res.append(line)
res = '\n'.join(res)
res = markdown.markdown(res)
res = re.sub('\{(\w+)\}', tags_cludge, res)
return res
class Index(dict):
def __init__(self, filename=None, ro=False, *args, **kwds):
self.filename = filename if filename else config['local']['index']
self.ro = ro
if os.path.isfile(self.filename):
self.load(self.filename)
dict.__init__(self, *args, **kwds)
if 'idx' not in self:
self['idx'] = []
def load(self, fd):
try:
return self.update(json.load(open(fd, 'r')))
except Exception:
pass
def sync(self):
'Write dict to disk'
if self.ro:
return
with saveto(self.filename) as fl:
json.dump(self, fl, ensure_ascii=False, indent=True)
def close(self):
self.sync()
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
class Entry:
def __init__(self, page, empty=False):
self.is_index = False
post_path = config['local']['posts']
self.fullpath = os.path.join(post_path, page)
if '.' not in self.fullpath:
self.fullpath = self.fullpath + '.md'
self.page = page
self.title = None
self.cdate = os.path.getmtime(self.fullpath)
self.fdate = self.cdate
if not empty and os.path.isfile(self.fullpath):
self.load()
def parse(self):
pass
def load(self):
self.content = open(self.fullpath).read()
self.parse()
class MarkDownEntry(Entry):
def parse(self):
if self.content.startswith('---'):
headers, rest = self.content[3:].split('---', 1)
self.headers = {}
for key, value in (line.strip().split(': ', 1)
for line in headers.split('\n')
if not line.startswith('#') and ':' in line):
self.headers[key.lower()] = value
self.content = rest
if 'title' in self.headers:
self.title = self.headers['title']
if 'date' in self.headers:
self.fdate = self.headers['date']
elif self.content.startswith('# '):
title, rest = self.content.split('\n', 1)
hashmash, self.title = title.split(' ', 1)
self.content = rest
else:
title, rest = self.content.split('\n', 1)
self.title = title
self.content = rest
self.draft = 'draft' in self.title or 'DRAFT' in self.title
self.content = makeHtml(self.content)
self.result = os.path.join(config['local']['results']['posts'],
self.page, 'index.html')
self.permalink = config['site'] + config['local']['results']['site'] + self.page
def do(self, template):
return self.do_to(template, self.result)
def do_to(self, template, fpath):
res = pystache.render(open(template, 'r').read(),
{
'conf': config, 'title': self.title,
'cdate': self.cdate, 'fdate': self.fdate,
'content': self.content.replace('\n', ' '), 'permalink': self.permalink
})
with saveto(fpath) as fl:
fl.write(res)
class Archive:
def __init__(self, idx):
self.idx = idx
self.results = os.path.join(config['local']['results']['archive'], 'index.html')
def do(self, template):
items = []
for x in reversed(self.idx['idx']):
if 'draft' in self.idx[x] and self.idx[x]['draft']:
continue
items.append({
'fname': self.idx[x]['permalink'],
'subtitle': self.idx[x]['title'],
})
res = pystache.render(open(template, 'r').read(),
{
'conf': config,
'title': 'Archive',
'items': items,
'permalink': config['site'] + '/archive'
})
with saveto(self.results) as fl:
fl.write(res)
class RSS:
def __init__(self, idx):
self.idx = idx
self.results = os.path.join(config['local']['results']['feed'])
def do(self):
feed = AtomFeed(title=config['title'],
feed_url=config['site'] + "feed",
url=config['site'][:-1] if config['site'].endswith('/') else config['site'],
author=config['author'])
for x in list(reversed(self.idx['idx']))[:10]:
if 'draft' in self.idx[x] and self.idx[x]['draft']:
continue
page = MarkDownEntry(x)
feed.add(title=self.idx[x]['title'],
content=page.content,
content_type="html",
author=config['author'],
url=self.idx[x]['permalink'],
updated=datetime.fromtimestamp(self.idx[x]['cdate'])
)
with saveto(self.results) as fl:
fl.write(feed.to_string())
@baker.command(
shortopts={
"overwrite": "o",
"edit": "e"},
params={"page": "page name",
"overwrite": "overwrite page even if exists",
"edit": "open text editor if page created"}
)
def entry(page=current_date, overwrite=False, edit=False):
"""create and edit new blog entry"""
path = config['local']['posts']
if page == 'yesterday':
page = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
elif page == 'tomorrow':
page = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
fullpath = os.path.join(path, page + '.md')
if os.path.isfile(fullpath):
if not overwrite and not edit:
sys.stderr.write('File %s already exists.\n' % fullpath)
return
else:
with saveto(fullpath) as fl:
fl.write('# Title\n\n-----\n\n## Для всех\n## На грани\n## Для гиков\n## Разное\n\n')
if edit:
os.system(config['local']['editor'] % fullpath)
else:
sys.stdout.write(fullpath + '\n')
return
@baker.command
def show(page=current_date):
"""print out page"""
if '.' in page:
page = page.rsplit('.', 1)[0]
entry = MarkDownEntry(page)
if entry:
sys.stdout.write(entry.content.replace('\n', ' '))
return
@baker.command(
shortopts={"page": "p",
"force": "f"},
params={"page": "page name",
"force": "force regen page"}
)
def gen(page=current_date, force=False):
"""generate a static .html for a page"""
if '.' in page:
page = page.rsplit('.', 1)[0]
fpath = os.path.join(config['local']['posts'], page + '.md')
if not force:
with Index(ro=True) as idx:
if page in idx and os.path.getmtime(fpath) <= idx[page]['cdate']:
return
entry = MarkDownEntry(page)
if entry.draft:
sys.stdout.write('Page ' + page + ' drafted.\n')
else:
with Index(ro=True) as idx:
if page not in idx['idx']:
entry.is_index = True
else:
last = None
for x in reversed(idx['idx']):
if 'draft' not in idx[x] or idx[x]['draft'] == False:
last = x
break
if last == page:
entry.is_index = True
entry.do(config['local']['templates']['post'])
sys.stdout.write('File %s writen\n' % entry.result)
if entry.is_index:
entry.do_to(config['local']['templates']['post'],
config['local']['results']['path'] + 'index.html')
sys.stdout.write('Page ' + page + ' also is index\n')
with Index() as idx:
idx[page] = dict(
permalink=entry.permalink,
title=entry.title,
cdate=entry.cdate,
fdate=entry.fdate,
draft=entry.draft,
)
if page not in idx['idx']:
idx['idx'].append(page)
@baker.command
def archive():
'''regen /arhive page'''
f = Archive(Index(ro=True))
f.do(config['local']['templates']['archive'])
sys.stdout.write('Archive ' + f.results + ' saved\n')
@baker.command
def feed():
'''regen /feed page'''
f = RSS(Index(ro=True))
f.do()
sys.stdout.write('Atom feed ' + f.results + ' saved\n')
@baker.command(
shortopts={
"wipe": "w",
"force": "f",
"noindex": "n",
"andsync": "s"},
params={"wipe": "wipe out current index",
"force": "force regen pages",
"noindex": "do not regen feed and archives",
"andsync": "execute `sync` command right after finish"}
)
def regen(wipe=False, force=False, noindex=False, andsync=False):
"""regenerate index and all pages"""
if wipe:
with Index() as idx:
idx['idx'] = []
for item in os.listdir(config['local']['posts']):
gen(page=item, force=force)
if not noindex:
archive()
feed()
if andsync:
sync()
@baker.command
def sync():
"""syncronize results tree with s3 server"""
cwd = os.getcwd()
os.chdir(config['local']['results']['path'])
os.system("s3cmd --no-preserve --recursive --exclude=feed sync * " + config['s3']['bucket'])
os.system("s3cmd --no-preserve -m 'text/xml' put feed " + config['s3']['bucket'])
os.chdir(cwd)
@baker.command
def server(port=8000):
"""run a local http server in results tree"""
cwd = os.getcwd()
os.chdir(config['local']['results']['path'])
import http.server
import socketserver
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", port), Handler)
print("serving at port", port)
httpd.serve_forever()
os.chdir(cwd)
baker.run()