blogit.py 13 KB

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