1
0

blogit.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8
  3. # Copyleft (C) 2010 Mir Nazim <hello@mirnazim.org>
  4. #
  5. # Everyone is permitted to copy and distribute verbatim or modified
  6. # copies of this license document, and changing it is allowed as long
  7. # as the name is changed.
  8. #
  9. # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  10. #
  11. # 0. You just DO WHATEVER THE FUCK YOU WANT TO. (IT'S SLOPPY CODE ANYWAY)
  12. #
  13. # WARANTIES:
  14. # 0. Are you kidding me?
  15. # 1. Seriously, Are you fucking kidding me?
  16. # 2. If anything goes wrong, sue the "The Empire".
  17. import os
  18. import re
  19. import datetime
  20. import yaml # in debian python-yaml
  21. from StringIO import StringIO
  22. import codecs
  23. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  24. import markdown2
  25. import argparse
  26. import sys
  27. from distutils import dir_util
  28. import pdb
  29. CONFIG = {
  30. 'content_root': 'content', # where the markdown files are
  31. 'output_to': 'oz123.github.com',
  32. 'templates': 'templates',
  33. 'date_format': '%Y-%m-%d',
  34. 'base_url': 'oz123.github.com',
  35. 'http_port': 3030,
  36. 'content_encoding': 'utf-8',
  37. }
  38. GLOBAL_TEMPLATE_CONTEXT = {
  39. 'media_base': '/media/',
  40. 'media_url': '../media/',
  41. 'site_url' : 'oz123.github.com',
  42. 'last_build' : datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
  43. 'twitter' : 'https://twitter.com/#!/OzNTiram',
  44. 'stackoverflow': "http://stackoverflow.com/users/492620/oz123",
  45. 'github' : "https://github.com/oz123",
  46. 'side_bar': """
  47. <div id="nav">
  48. <div><img src="/media/img/me.png"></div>
  49. <a title="Home" href="/">home</a>
  50. <a title="About" class="about" href="/about.html">about</a>
  51. <a title="Archive" class="archive" href="/archive">archive</a>
  52. <a title="Atom feeds" href="/atom.xml">atom</a>
  53. <a title="Twitter" href="https://twitter.com/#!/OzNTiram">twitter</a>
  54. <a title="Stackoverflow" href="http://stackoverflow.com/users/492620/oz123">stackoverflow</a>
  55. <a title="Github" href="https://github.com/oz123">github</a>
  56. </div>
  57. """
  58. }
  59. KINDS = {
  60. 'writing': {
  61. 'name': 'writing', 'name_plural': 'writings',
  62. },
  63. 'note': {
  64. 'name': 'note', 'name_plural': 'notes',
  65. },
  66. 'link': {
  67. 'name': 'link', 'name_plural': 'links',
  68. },
  69. 'photo': {
  70. 'name': 'photo', 'name_plural': 'photos',
  71. },
  72. 'page': {
  73. 'name': 'page', 'name_plural': 'pages',
  74. },
  75. }
  76. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  77. class Tag(object):
  78. def __init__(self, name):
  79. super(Tag, self).__init__()
  80. self.name = name
  81. self.prepare()
  82. self.permalink = "oz123.github.com"
  83. def prepare(self):
  84. _slug = self.name.lower()
  85. _slug = re.sub(r'[;;,. ]', '-', _slug)
  86. self.slug = _slug
  87. class Entry(object):
  88. def __init__(self, path):
  89. super(Entry, self).__init__()
  90. path = path.split('content/')[-1]
  91. self.path = path
  92. self.prepare()
  93. def __str__(self):
  94. return self.path
  95. def __repr__(self):
  96. return self.path
  97. @property
  98. def name(self):
  99. return os.path.splitext(os.path.basename(self.path))[0]
  100. @property
  101. def abspath(self):
  102. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  103. @property
  104. def destination(self):
  105. dest = "%s/%s/index.html" % (KINDS[self.kind]['name_plural'], self.name)
  106. print dest
  107. return os.path.join(CONFIG['output_to'], dest)
  108. @property
  109. def title(self):
  110. return self.header['title']
  111. @property
  112. def summary_html(self):
  113. return "%s" % markdown2.markdown(self.header['summary'].strip())
  114. @property
  115. def credits_html(self):
  116. return "%s" % markdown2.markdown(self.header['credits'].strip())
  117. @property
  118. def summary_atom(self):
  119. summarya=markdown2.markdown(self.header['summary'].strip())
  120. summarya=re.sub("<p>|</p>","",summarya)
  121. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  122. return summarya+more
  123. @property
  124. def published_html(self):
  125. if self.kind in ['link', 'note', 'photo']:
  126. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  127. return self.header['published'].strftime("%B %d, %Y")
  128. @property
  129. def published_atom(self):
  130. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  131. @property
  132. def atom_id(self):
  133. return "tag:oz123.github.com,%s:%s" % \
  134. (
  135. self.published.strftime("%Y-%m-%d"),
  136. self.permalink,
  137. )
  138. @property
  139. def body_html(self):
  140. return markdown2.markdown(self.body, extras=['code-color'])
  141. @property
  142. def permalink(self):
  143. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  144. @property
  145. def tags(self):
  146. tags = list()
  147. for t in self.header['tags']:
  148. tags.append(Tag(t))
  149. return tags
  150. def prepare(self):
  151. file = codecs.open(self.abspath, 'r')
  152. header = ['---']
  153. while True:
  154. line = file.readline()
  155. line = line.rstrip()
  156. if not line: break
  157. header.append(line)
  158. self.header = yaml.load(StringIO('\n'.join(header)))
  159. for h in self.header.items():
  160. if h:
  161. try:
  162. setattr(self, h[0], h[1])
  163. except:
  164. pass
  165. body = list()
  166. for line in file.readlines():
  167. body.append(line)
  168. self.body = '\n'.join(body)
  169. file.close()
  170. if self.kind == 'link':
  171. from urlparse import urlparse
  172. self.domain_name = urlparse(self.url).netloc
  173. elif self.kind == 'photo':
  174. pass
  175. elif self.kind == 'note':
  176. pass
  177. elif self.kind == 'writing':
  178. pass
  179. def render(self):
  180. if not self.header['public']:
  181. return False
  182. try:
  183. os.makedirs(os.path.dirname(self.destination))
  184. except:
  185. pass
  186. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  187. print "context"
  188. print context
  189. context['entry'] = self
  190. print "entry", context['entry']
  191. template = jinja_env.get_template("entry.html")
  192. print "template" , template
  193. #print dir(template)
  194. #raw_input()
  195. html = template.render(context)
  196. print "in render", self.destination
  197. destination = codecs.open(self.destination, 'w', CONFIG['content_encoding'])
  198. destination.write(html)
  199. destination.close()
  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['output_to'], 'w', CONFIG['content_encoding'])
  232. destination.write(html)
  233. destination.close()
  234. def render_archive(entries, render_to=None):
  235. """
  236. this function creates the archive page
  237. """
  238. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  239. context['entries'] = entries[10:]
  240. template = jinja_env.get_template('archive_index.html')
  241. html = template.render(context)
  242. if not render_to:
  243. render_to = "%s/archive/index.html" % CONFIG['output_to']
  244. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  245. destination = codecs.open("%s/archive/index.html" % CONFIG['output_to'], 'w', CONFIG['content_encoding'])
  246. destination.write(html)
  247. destination.close()
  248. def render_atom_feed(entries, render_to=None):
  249. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  250. context['entries'] = entries[:10]
  251. template = jinja_env.get_template('atom.xml')
  252. html = template.render(context)
  253. if not render_to:
  254. render_to = "%s/atom.xml" % CONFIG['output_to']
  255. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  256. destination.write(html)
  257. destination.close()
  258. def render_tag_pages(tag_tree):
  259. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  260. for t in tag_tree.items():
  261. context['tag'] = t[1]['tag']
  262. context['entries'] = _sort_entries(t[1]['entries'])
  263. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  264. try:
  265. os.makedirs(destination)
  266. except:
  267. pass
  268. template = jinja_env.get_template('tag_index.html')
  269. html = template.render(context)
  270. file = codecs.open("%s/index.html" % destination, 'w', CONFIG['content_encoding'])
  271. file.write(html)
  272. file.close()
  273. #print " tags/%s" % (context['tag'].slug, )
  274. render_atom_feed(context['entries'], render_to="%s/atom.xml" % destination)
  275. def build():
  276. print
  277. print "Rendering website now..."
  278. print
  279. print " entries:"
  280. entries = list()
  281. tags = dict()
  282. for root, dirs, files in os.walk(CONFIG['content_root']):
  283. for file in files:
  284. entry = Entry(os.path.join(root, file))
  285. if entry.render():
  286. entries.append(entry)
  287. for tag in entry.tags:
  288. if not tags.has_key(tag.name):
  289. tags[tag.name] = {
  290. 'tag': tag,
  291. 'entries': list(),
  292. }
  293. tags[tag.name]['entries'].append(entry)
  294. print " %s" % entry.path
  295. print " :done"
  296. print
  297. print " tag pages & their atom feeds:"
  298. render_tag_pages(tags)
  299. print " :done"
  300. print
  301. print " site wide index"
  302. entries = _sort_entries(entries)
  303. #render_index(_sort_entries(entries))
  304. render_index(entries)
  305. print "................done"
  306. print " archive index"
  307. render_archive(entries)
  308. print "................done"
  309. print " site wide atom feeds"
  310. #render_atom_feed(_sort_entries(entries))
  311. render_atom_feed(entries)
  312. print "...........done"
  313. print
  314. print "All done "
  315. def preview(PREVIEW_ADDR = '127.0.1.1',PREVIEW_PORT = 11000):
  316. """
  317. launch an HTTP to preview the website
  318. """
  319. import SimpleHTTPServer
  320. import SocketServer
  321. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  322. httpd = SocketServer.TCPServer(("", CONFIG['http_port']), Handler)
  323. os.chdir(CONFIG['output_to'])
  324. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  325. print "Hit Ctrl+C to exit"
  326. try:
  327. httpd.serve_forever()
  328. except KeyboardInterrupt:
  329. print
  330. print "Shutting Down... Bye!."
  331. print
  332. httpd.server_close()
  333. def publish(GITDIRECTORY="oz123.github.com"):
  334. pass
  335. if __name__== '__main__':
  336. parser = argparse.ArgumentParser(description='blogit - a tool blog on github.')
  337. parser.add_argument('-b','--build', action="store_true",
  338. help='convert the markdown files to HTML')
  339. parser.add_argument('-p','--preview', action="store_true",
  340. help='Launch HTTP server to preview the website')
  341. args = parser.parse_args()
  342. if len(sys.argv) < 2 :
  343. parser.print_help()
  344. sys.exit()
  345. #import pdb; pdb.set_trace()
  346. if args.build:
  347. #pdb.set_trace()
  348. build()
  349. if args.preview:
  350. preview()