blogit.py 12 KB

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