blogit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #!/usr/bin/env python
  2. # ============================================================================
  3. # Blogit.py is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License, version 3
  5. # as published by the Free Software Foundation;
  6. #
  7. # Blogit.py is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with Blogit.py; if not, write to the Free Software
  14. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  15. # ============================================================================
  16. # Copyright (C) 2013 Oz Nahum Tiram <nahumoz@gmail.com>
  17. # ============================================================================
  18. # Note about Summary
  19. # has to be 1 line, no '\n' allowed!
  20. """
  21. Summary: |
  22. some summary ...
  23. Your post
  24. """
  25. """
  26. Everything the Header can't have ":" or "..." in it, you can't have title
  27. with ":" it makes markdown break!
  28. """
  29. """
  30. The content directory can contain only mardown or txt files, no images
  31. allowed!
  32. """
  33. import os
  34. import re
  35. import datetime
  36. import argparse
  37. import sys
  38. from distutils import dir_util
  39. import shutil
  40. from StringIO import StringIO
  41. import codecs
  42. from conf import CONFIG, ARCHIVE_SIZE, GLOBAL_TEMPLATE_CONTEXT, KINDS
  43. import subprocess as sp
  44. try:
  45. import yaml # in debian python-yaml
  46. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  47. except ImportError, e:
  48. print e
  49. print "On Debian based system you can install the dependencies with: "
  50. print "apt-get install python-yaml python-jinja2"
  51. sys.exit(1)
  52. try:
  53. import markdown2
  54. renderer = 'md2'
  55. except ImportError, e:
  56. try:
  57. import markdown
  58. renderer = 'md1'
  59. except ImportError, e:
  60. print e
  61. print "try: sudo pip install markdown2"
  62. sys.exit(1)
  63. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  64. class Tag(object):
  65. def __init__(self, name):
  66. super(Tag, self).__init__()
  67. self.name = name
  68. self.prepare()
  69. self.permalink = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  70. def prepare(self):
  71. _slug = self.name.lower()
  72. _slug = re.sub(r'[;;,. ]', '-', _slug)
  73. self.slug = _slug
  74. class Entry(object):
  75. def __init__(self, path):
  76. super(Entry, self).__init__()
  77. path = path.split('content/')[-1]
  78. self.path = path
  79. self.prepare()
  80. def __str__(self):
  81. return self.path
  82. def __repr__(self):
  83. return self.path
  84. @property
  85. def name(self):
  86. return os.path.splitext(os.path.basename(self.path))[0]
  87. @property
  88. def abspath(self):
  89. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  90. @property
  91. def destination(self):
  92. dest = "%s/%s/index.html" % (KINDS[
  93. self.kind]['name_plural'], self.name)
  94. print dest
  95. return os.path.join(CONFIG['output_to'], dest)
  96. @property
  97. def title(self):
  98. return self.header['title']
  99. @property
  100. def summary_html(self):
  101. return "%s" % markdown2.markdown(self.header['summary'].strip())
  102. @property
  103. def credits_html(self):
  104. return "%s" % markdown2.markdown(self.header['credits'].strip())
  105. @property
  106. def summary_atom(self):
  107. summarya = markdown2.markdown(self.header['summary'].strip())
  108. summarya = re.sub("<p>|</p>", "", summarya)
  109. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  110. return summarya+more
  111. @property
  112. def published_html(self):
  113. if self.kind in ['link', 'note', 'photo']:
  114. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  115. return self.header['published'].strftime("%B %d, %Y")
  116. @property
  117. def published_atom(self):
  118. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  119. @property
  120. def atom_id(self):
  121. return "tag:%s,%s:%s" % \
  122. (
  123. self.published.strftime("%Y-%m-%d"),
  124. self.permalink,
  125. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  126. )
  127. @property
  128. def body_html(self):
  129. if renderer == 'md2':
  130. return markdown2.markdown(self.body, extras=['fenced-code-blocks',
  131. 'hilite'])
  132. if renderer == 'md1':
  133. return markdown.markdown(self.body,
  134. extensions=['fenced_code',
  135. 'codehilite(linenums=False)'])
  136. @property
  137. def permalink(self):
  138. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  139. @property
  140. def tags(self):
  141. tags = list()
  142. for t in self.header['tags']:
  143. tags.append(Tag(t))
  144. return tags
  145. def prepare(self):
  146. file = codecs.open(self.abspath, 'r')
  147. header = ['---']
  148. while True:
  149. line = file.readline()
  150. line = line.rstrip()
  151. if not line:
  152. break
  153. header.append(line)
  154. self.header = yaml.load(StringIO('\n'.join(header)))
  155. for h in self.header.items():
  156. if h:
  157. try:
  158. setattr(self, h[0], h[1])
  159. except:
  160. pass
  161. body = list()
  162. for line in file.readlines():
  163. body.append(line)
  164. self.body = ''.join(body)
  165. file.close()
  166. if self.kind == 'link':
  167. from urlparse import urlparse
  168. self.domain_name = urlparse(self.url).netloc
  169. elif self.kind == 'photo':
  170. pass
  171. elif self.kind == 'note':
  172. pass
  173. elif self.kind == 'writing':
  174. pass
  175. def render(self):
  176. if not self.header['public']:
  177. return False
  178. try:
  179. os.makedirs(os.path.dirname(self.destination))
  180. except:
  181. pass
  182. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  183. context['entry'] = self
  184. # this is redundant ! every time we render entry we get_template?
  185. # todo: make template class property !
  186. template = jinja_env.get_template("entry.html")
  187. try:
  188. html = template.render(context)
  189. except Exception, e:
  190. print context
  191. print self.path
  192. print e
  193. sys.exit()
  194. destination = codecs.open(
  195. self.destination, 'w', CONFIG['content_encoding'])
  196. destination.write(html)
  197. destination.close()
  198. # before returning write log to csv
  199. # file name, date first seen, date rendered
  200. # self.path , date-first-seen, if rendered datetime.now
  201. return True
  202. class Link(Entry):
  203. def __init__(self, path):
  204. super(Link, self).__init__(path)
  205. @property
  206. def permalink(self):
  207. print "self.url", self.url
  208. raw_input()
  209. return self.url
  210. def entry_factory():
  211. pass
  212. def _sort_entries(entries):
  213. _entries = dict()
  214. sorted_entries = list()
  215. for entry in entries:
  216. _published = entry.header['published'].isoformat()
  217. _entries[_published] = entry
  218. sorted_keys = sorted(_entries.keys())
  219. sorted_keys.reverse()
  220. for key in sorted_keys:
  221. sorted_entries.append(_entries[key])
  222. return sorted_entries
  223. def render_index(entries):
  224. """
  225. this function renders the main page located at index.html
  226. under oz123.github.com
  227. """
  228. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  229. context['entries'] = entries[:10]
  230. template = jinja_env.get_template('entry_index.html')
  231. html = template.render(context)
  232. destination = codecs.open("%s/index.html" % CONFIG[
  233. 'output_to'], 'w', CONFIG['content_encoding'])
  234. destination.write(html)
  235. destination.close()
  236. def render_archive(entries, render_to=None):
  237. """
  238. this function creates the archive page
  239. """
  240. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  241. context['entries'] = entries[ARCHIVE_SIZE:]
  242. template = jinja_env.get_template('archive_index.html')
  243. html = template.render(context)
  244. if not render_to:
  245. render_to = "%s/archive/index.html" % CONFIG['output_to']
  246. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  247. destination = codecs.open("%s/archive/index.html" % CONFIG[
  248. 'output_to'], 'w', CONFIG['content_encoding'])
  249. destination.write(html)
  250. destination.close()
  251. def render_atom_feed(entries, render_to=None):
  252. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  253. context['entries'] = entries[:10]
  254. template = jinja_env.get_template('atom.xml')
  255. html = template.render(context)
  256. if not render_to:
  257. render_to = "%s/atom.xml" % CONFIG['output_to']
  258. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  259. destination.write(html)
  260. destination.close()
  261. def render_tag_pages(tag_tree):
  262. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  263. for t in tag_tree.items():
  264. context['tag'] = t[1]['tag']
  265. context['entries'] = _sort_entries(t[1]['entries'])
  266. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  267. try:
  268. os.makedirs(destination)
  269. except:
  270. pass
  271. template = jinja_env.get_template('tag_index.html')
  272. html = template.render(context)
  273. file = codecs.open("%s/index.html" %
  274. destination, 'w', CONFIG['content_encoding'])
  275. file.write(html)
  276. file.close()
  277. render_atom_feed(context[
  278. 'entries'], render_to="%s/atom.xml" % destination)
  279. def build():
  280. print
  281. print "Rendering website now..."
  282. print
  283. print " entries:"
  284. entries = list()
  285. tags = dict()
  286. for root, dirs, files in os.walk(CONFIG['content_root']):
  287. for fileName in files:
  288. try:
  289. if fileName.endswith('md') or fileName.endswith('markdown'):
  290. entry = Entry(os.path.join(root, fileName))
  291. except Exception, e:
  292. print "Found some problem in: ", entry.path
  293. print e
  294. print "Please correct this problem ..."
  295. sys.exit()
  296. if entry.render():
  297. entries.append(entry)
  298. for tag in entry.tags:
  299. if tag.name not in tags:
  300. tags[tag.name] = {
  301. 'tag': tag,
  302. 'entries': list(),
  303. }
  304. tags[tag.name]['entries'].append(entry)
  305. print " %s" % entry.path
  306. print " :done"
  307. print
  308. print " tag pages & their atom feeds:"
  309. render_tag_pages(tags)
  310. print " :done"
  311. print
  312. print " site wide index"
  313. entries = _sort_entries(entries)
  314. render_index(entries)
  315. print "................done"
  316. print " archive index"
  317. render_archive(entries)
  318. print "................done"
  319. print " site wide atom feeds"
  320. render_atom_feed(entries)
  321. print "...........done"
  322. print
  323. print "All done "
  324. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  325. """
  326. launch an HTTP to preview the website
  327. """
  328. import SimpleHTTPServer
  329. import SocketServer
  330. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  331. httpd = SocketServer.TCPServer(("", CONFIG['http_port']), Handler)
  332. os.chdir(CONFIG['output_to'])
  333. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  334. print "Hit Ctrl+C to exit"
  335. try:
  336. httpd.serve_forever()
  337. except KeyboardInterrupt:
  338. print
  339. print "Shutting Down... Bye!."
  340. print
  341. httpd.server_close()
  342. def publish(GITDIRECTORY=CONFIG['output_to']):
  343. sp.call('git push', cwd=GITDIRECTORY, shell=True)
  344. def new_post(GITDIRECTORY=CONFIG['output_to'],
  345. kind=KINDS['writing']):
  346. """
  347. This function should create a template for a new post with a title
  348. read from the user input.
  349. Most other fields should be defaults.
  350. """
  351. title = raw_input("Give the title of the post: ")
  352. while ':' in title:
  353. title = raw_input("Give the title of the post (':' not allowed): ")
  354. author = CONFIG['author']
  355. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  356. tags = '['+raw_input("Give the tags, separated by ', ':")+']'
  357. published = 'yes'
  358. chronological = 'yes'
  359. summary = ("summary: |\n Type your summary here.\n Do not change the "
  360. "indentation"
  361. "to the left\n ...\n\nStart writing your post here!")
  362. # make file name
  363. fname = os.path.join(os.getcwd(), 'content', kind['name_plural'],
  364. datetime.datetime.strftime(datetime.datetime.now(),
  365. '%Y'),
  366. date+'-'+title.replace(' ', '-')+'.markdown')
  367. with open(fname, 'w') as npost:
  368. npost.write('title: %s\n' % title)
  369. npost.write('author: %s\n' % author)
  370. npost.write('published: %s\n' % date)
  371. npost.write('tags: %s\n' % tags)
  372. npost.write('public: %s\n' % published)
  373. npost.write('chronological: %s\n' % chronological)
  374. npost.write('kind: %s\n' % kind['name'])
  375. npost.write('%s' % summary)
  376. os.system('%s %s' % (CONFIG['editor'], fname))
  377. def clean(GITDIRECTORY=CONFIG['output_to']):
  378. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  379. os.chdir(GITDIRECTORY)
  380. for directory in directoriestoclean:
  381. shutil.rmtree(directory)
  382. def dist(SOURCEDIR=os.getcwd()+"/content/",
  383. DESTDIR=CONFIG['raw_content']):
  384. """
  385. sync raw files from SOURCE to DEST
  386. """
  387. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  388. cwd=os.getcwd())
  389. if __name__ == '__main__':
  390. parser = argparse.ArgumentParser(
  391. description='blogit - a tool to blog on github.')
  392. parser.add_argument('-b', '--build', action="store_true",
  393. help='convert the markdown files to HTML')
  394. parser.add_argument('-p', '--preview', action="store_true",
  395. help='Launch HTTP server to preview the website')
  396. parser.add_argument('-c', '--clean', action="store_true",
  397. help='clean output files')
  398. parser.add_argument('-n', '--new', action="store_true",
  399. help='create new post')
  400. parser.add_argument('-d', '--dist', action="store_true",
  401. help='sync raw files from SOURCE to DEST')
  402. parser.add_argument('--publish', action="store_true",
  403. help='push built HTML to git upstream')
  404. args = parser.parse_args()
  405. if len(sys.argv) < 2:
  406. parser.print_help()
  407. sys.exit()
  408. if args.clean:
  409. clean()
  410. if args.build:
  411. build()
  412. if args.dist:
  413. dist()
  414. if args.preview:
  415. preview()
  416. if args.new:
  417. new_post()
  418. if args.publish:
  419. publish()