blogit.py 15 KB

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