blogit.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. # Note about Summary
  18. # has to be 1 line, no '\n' allowed!
  19. """
  20. Summary: |
  21. some summary ...
  22. """
  23. """
  24. Everything the Header can't have ":" in it, you can't have title
  25. with ":" it makes markdown breark!
  26. """
  27. import os
  28. import re
  29. import datetime
  30. import yaml # in debian python-yaml
  31. from StringIO import StringIO
  32. import codecs
  33. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  34. import markdown2
  35. import argparse
  36. import sys
  37. from distutils import dir_util
  38. import pdb
  39. CONFIG = {
  40. 'content_root': 'content', # where the markdown files are
  41. 'output_to': 'oz123.github.com',
  42. 'templates': 'templates',
  43. 'date_format': '%Y-%m-%d',
  44. 'base_url': 'oz123.github.com',
  45. 'http_port': 3030,
  46. 'content_encoding': 'utf-8',
  47. }
  48. GLOBAL_TEMPLATE_CONTEXT = {
  49. 'media_base': '/media/',
  50. 'media_url': '../media/',
  51. 'site_url' : 'oz123.github.com',
  52. 'last_build' : datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
  53. 'twitter' : 'https://twitter.com/#!/OzNTiram',
  54. 'stackoverflow': "http://stackoverflow.com/users/492620/oz123",
  55. 'github' : "https://github.com/oz123",
  56. 'side_bar': """
  57. <div id="nav">
  58. <div><img src="/media/img/me.png"></div>
  59. <a title="Home" href="/">home</a>
  60. <a title="About" class="about" href="/about.html">about</a>
  61. <a title="Archive" class="archive" href="/archive">archive</a>
  62. <a title="Atom feeds" href="/atom.xml">atom</a>
  63. <a title="Twitter" href="https://twitter.com/#!/OzNTiram">twitter</a>
  64. <a title="Stackoverflow" href="http://stackoverflow.com/users/492620/oz123">stackoverflow</a>
  65. <a title="Github" href="https://github.com/oz123">github</a>
  66. </div>
  67. """
  68. }
  69. KINDS = {
  70. 'writing': {
  71. 'name': 'writing', 'name_plural': 'writings',
  72. },
  73. 'note': {
  74. 'name': 'note', 'name_plural': 'notes',
  75. },
  76. 'link': {
  77. 'name': 'link', 'name_plural': 'links',
  78. },
  79. 'photo': {
  80. 'name': 'photo', 'name_plural': 'photos',
  81. },
  82. 'page': {
  83. 'name': 'page', 'name_plural': 'pages',
  84. },
  85. }
  86. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  87. class Tag(object):
  88. def __init__(self, name):
  89. super(Tag, self).__init__()
  90. self.name = name
  91. self.prepare()
  92. self.permalink = "oz123.github.com"
  93. def prepare(self):
  94. _slug = self.name.lower()
  95. _slug = re.sub(r'[;;,. ]', '-', _slug)
  96. self.slug = _slug
  97. class Entry(object):
  98. def __init__(self, path):
  99. super(Entry, self).__init__()
  100. path = path.split('content/')[-1]
  101. self.path = path
  102. self.prepare()
  103. def __str__(self):
  104. return self.path
  105. def __repr__(self):
  106. return self.path
  107. @property
  108. def name(self):
  109. return os.path.splitext(os.path.basename(self.path))[0]
  110. @property
  111. def abspath(self):
  112. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  113. @property
  114. def destination(self):
  115. dest = "%s/%s/index.html" % (KINDS[self.kind]['name_plural'], self.name)
  116. print dest
  117. return os.path.join(CONFIG['output_to'], dest)
  118. @property
  119. def title(self):
  120. return self.header['title']
  121. @property
  122. def summary_html(self):
  123. return "%s" % markdown2.markdown(self.header['summary'].strip())
  124. @property
  125. def credits_html(self):
  126. return "%s" % markdown2.markdown(self.header['credits'].strip())
  127. @property
  128. def summary_atom(self):
  129. summarya=markdown2.markdown(self.header['summary'].strip())
  130. summarya=re.sub("<p>|</p>","",summarya)
  131. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  132. return summarya+more
  133. @property
  134. def published_html(self):
  135. if self.kind in ['link', 'note', 'photo']:
  136. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  137. return self.header['published'].strftime("%B %d, %Y")
  138. @property
  139. def published_atom(self):
  140. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  141. @property
  142. def atom_id(self):
  143. return "tag:oz123.github.com,%s:%s" % \
  144. (
  145. self.published.strftime("%Y-%m-%d"),
  146. self.permalink,
  147. )
  148. @property
  149. def body_html(self):
  150. return markdown2.markdown(self.body, extras=['code-color'])
  151. @property
  152. def permalink(self):
  153. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  154. @property
  155. def tags(self):
  156. tags = list()
  157. for t in self.header['tags']:
  158. tags.append(Tag(t))
  159. return tags
  160. def prepare(self):
  161. file = codecs.open(self.abspath, 'r')
  162. header = ['---']
  163. while True:
  164. line = file.readline()
  165. line = line.rstrip()
  166. if not line: break
  167. header.append(line)
  168. self.header = yaml.load(StringIO('\n'.join(header)))
  169. for h in self.header.items():
  170. if h:
  171. try:
  172. setattr(self, h[0], h[1])
  173. except:
  174. pass
  175. body = list()
  176. for line in file.readlines():
  177. body.append(line)
  178. self.body = '\n'.join(body)
  179. file.close()
  180. if self.kind == 'link':
  181. from urlparse import urlparse
  182. self.domain_name = urlparse(self.url).netloc
  183. elif self.kind == 'photo':
  184. pass
  185. elif self.kind == 'note':
  186. pass
  187. elif self.kind == 'writing':
  188. pass
  189. def render(self):
  190. if not self.header['public']:
  191. return False
  192. try:
  193. os.makedirs(os.path.dirname(self.destination))
  194. except:
  195. pass
  196. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  197. print "context"
  198. print context
  199. context['entry'] = self
  200. print "entry", context['entry']
  201. template = jinja_env.get_template("entry.html")
  202. print "template" , template
  203. #print dir(template)
  204. #raw_input()
  205. html = template.render(context)
  206. print "in render", self.destination
  207. destination = codecs.open(self.destination, 'w', CONFIG['content_encoding'])
  208. destination.write(html)
  209. destination.close()
  210. return True
  211. class Link(Entry):
  212. def __init__(self, path):
  213. super(Link, self).__init__(path)
  214. @property
  215. def permalink(self):
  216. print "self.url", self.url
  217. raw_input()
  218. return self.url
  219. def entry_factory():
  220. pass
  221. def _sort_entries(entries):
  222. _entries = dict()
  223. sorted_entries = list()
  224. for entry in entries:
  225. _published = entry.header['published'].isoformat()
  226. _entries[_published] = entry
  227. sorted_keys = sorted(_entries.keys())
  228. sorted_keys.reverse()
  229. for key in sorted_keys:
  230. sorted_entries.append(_entries[key])
  231. return sorted_entries
  232. def render_index(entries):
  233. """
  234. this function renders the main page located at index.html
  235. under oz123.github.com
  236. """
  237. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  238. context['entries'] = entries[:10]
  239. template = jinja_env.get_template('entry_index.html')
  240. html = template.render(context)
  241. destination = codecs.open("%s/index.html" % CONFIG['output_to'], 'w', CONFIG['content_encoding'])
  242. destination.write(html)
  243. destination.close()
  244. def render_archive(entries, render_to=None):
  245. """
  246. this function creates the archive page
  247. """
  248. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  249. context['entries'] = entries[10:]
  250. template = jinja_env.get_template('archive_index.html')
  251. html = template.render(context)
  252. if not render_to:
  253. render_to = "%s/archive/index.html" % CONFIG['output_to']
  254. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  255. destination = codecs.open("%s/archive/index.html" % CONFIG['output_to'], 'w', CONFIG['content_encoding'])
  256. destination.write(html)
  257. destination.close()
  258. def render_atom_feed(entries, render_to=None):
  259. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  260. context['entries'] = entries[:10]
  261. template = jinja_env.get_template('atom.xml')
  262. html = template.render(context)
  263. if not render_to:
  264. render_to = "%s/atom.xml" % CONFIG['output_to']
  265. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  266. destination.write(html)
  267. destination.close()
  268. def render_tag_pages(tag_tree):
  269. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  270. for t in tag_tree.items():
  271. context['tag'] = t[1]['tag']
  272. context['entries'] = _sort_entries(t[1]['entries'])
  273. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  274. try:
  275. os.makedirs(destination)
  276. except:
  277. pass
  278. template = jinja_env.get_template('tag_index.html')
  279. html = template.render(context)
  280. file = codecs.open("%s/index.html" % destination, 'w', CONFIG['content_encoding'])
  281. file.write(html)
  282. file.close()
  283. #print " tags/%s" % (context['tag'].slug, )
  284. render_atom_feed(context['entries'], render_to="%s/atom.xml" % destination)
  285. def build():
  286. print
  287. print "Rendering website now..."
  288. print
  289. print " entries:"
  290. entries = list()
  291. tags = dict()
  292. for root, dirs, files in os.walk(CONFIG['content_root']):
  293. for fileName in files:
  294. try:
  295. entry = Entry(os.path.join(root, fileName))
  296. except Exception, e:
  297. print "Found some problem in: ", fileName
  298. print e
  299. raw_input("Please correct")
  300. sys.exit()
  301. if entry.render():
  302. entries.append(entry)
  303. for tag in entry.tags:
  304. if not tags.has_key(tag.name):
  305. tags[tag.name] = {
  306. 'tag': tag,
  307. 'entries': list(),
  308. }
  309. tags[tag.name]['entries'].append(entry)
  310. print " %s" % entry.path
  311. print " :done"
  312. print
  313. print " tag pages & their atom feeds:"
  314. render_tag_pages(tags)
  315. print " :done"
  316. print
  317. print " site wide index"
  318. entries = _sort_entries(entries)
  319. #render_index(_sort_entries(entries))
  320. render_index(entries)
  321. print "................done"
  322. print " archive index"
  323. render_archive(entries)
  324. print "................done"
  325. print " site wide atom feeds"
  326. #render_atom_feed(_sort_entries(entries))
  327. render_atom_feed(entries)
  328. print "...........done"
  329. print
  330. print "All done "
  331. def preview(PREVIEW_ADDR = '127.0.1.1',PREVIEW_PORT = 11000):
  332. """
  333. launch an HTTP to preview the website
  334. """
  335. import SimpleHTTPServer
  336. import SocketServer
  337. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  338. httpd = SocketServer.TCPServer(("", CONFIG['http_port']), Handler)
  339. os.chdir(CONFIG['output_to'])
  340. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  341. print "Hit Ctrl+C to exit"
  342. try:
  343. httpd.serve_forever()
  344. except KeyboardInterrupt:
  345. print
  346. print "Shutting Down... Bye!."
  347. print
  348. httpd.server_close()
  349. def publish(GITDIRECTORY="oz123.github.com"):
  350. pass
  351. if __name__== '__main__':
  352. parser = argparse.ArgumentParser(description='blogit - a tool blog on github.')
  353. parser.add_argument('-b','--build', action="store_true",
  354. help='convert the markdown files to HTML')
  355. parser.add_argument('-p','--preview', action="store_true",
  356. help='Launch HTTP server to preview the website')
  357. args = parser.parse_args()
  358. if len(sys.argv) < 2 :
  359. parser.print_help()
  360. sys.exit()
  361. #import pdb; pdb.set_trace()
  362. if args.build:
  363. #pdb.set_trace()
  364. build()
  365. if args.preview:
  366. preview()