blogit.py 13 KB

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