blogit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. #!/usr/bin/env python
  2. # Copyright (C) 2013 Oz Nahum <nahumoz@gmail.com>
  3. #
  4. # Everyone is permitted to copy and distribute verbatim or modified
  5. # copies of this license document, and changing it is allowed as long
  6. # as the name is changed.
  7. #
  8. # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  9. #
  10. # 0. You just DO WHATEVER THE FUCK YOU WANT TO. (IT'S SLOPPY CODE ANYWAY)
  11. #
  12. # WARANTIES:
  13. # 0. Are you kidding me?
  14. # 1. Seriously, Are you fucking kidding me?
  15. # 2. If anything goes wrong, sue the "The Empire".
  16. # Note about Summary
  17. # has to be 1 line, no '\n' allowed!
  18. """
  19. Summary: |
  20. some summary ...
  21. Your post
  22. """
  23. """
  24. Everything the Header can't have ":" or "..." in it, you can't have title
  25. with ":" it makes markdown break!
  26. """
  27. """
  28. The content directory can contain only mardown or txt files, no images
  29. allowed!
  30. """
  31. import os
  32. import re
  33. import datetime
  34. import yaml # in debian python-yaml
  35. from StringIO import StringIO
  36. import codecs
  37. from jinja2 import Environment, FileSystemLoader # in debian python-jinja2
  38. try:
  39. import markdown2
  40. except ImportError:
  41. import markdown as markdown2
  42. import argparse
  43. import sys
  44. from distutils import dir_util
  45. import shutil
  46. CONFIG = {
  47. 'content_root': 'content', # where the markdown files are
  48. 'output_to': 'oz123.github.com',
  49. 'templates': 'templates',
  50. 'date_format': '%Y-%m-%d',
  51. 'base_url': 'http://oz123.github.com',
  52. 'http_port': 3030,
  53. 'content_encoding': 'utf-8',
  54. 'author': 'Oz Nahum Tiram'
  55. }
  56. # EDIT THIS PARAMETER TO CHANGE ARCHIVE SIZE
  57. # 0 Means that all the entries will be in the archive
  58. # 10 meas that all the entries except the last 10
  59. ARCHIVE_SIZE = 0
  60. GLOBAL_TEMPLATE_CONTEXT = {
  61. 'media_base': '/media/',
  62. 'media_url': '../media/',
  63. 'site_url': 'http://oz123.github.com',
  64. 'last_build': datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
  65. 'twitter': 'https://twitter.com/#!/OzNTiram',
  66. 'stackoverflow': "http://stackoverflow.com/users/492620/oz123",
  67. 'github': "https://github.com/oz123",
  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 = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  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[
  116. self.kind]['name_plural'], self.name)
  117. print dest
  118. return os.path.join(CONFIG['output_to'], dest)
  119. @property
  120. def title(self):
  121. return self.header['title']
  122. @property
  123. def summary_html(self):
  124. return "%s" % markdown2.markdown(self.header['summary'].strip())
  125. @property
  126. def credits_html(self):
  127. return "%s" % markdown2.markdown(self.header['credits'].strip())
  128. @property
  129. def summary_atom(self):
  130. summarya = markdown2.markdown(self.header['summary'].strip())
  131. summarya = re.sub("<p>|</p>", "", summarya)
  132. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  133. return summarya+more
  134. @property
  135. def published_html(self):
  136. if self.kind in ['link', 'note', 'photo']:
  137. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  138. return self.header['published'].strftime("%B %d, %Y")
  139. @property
  140. def published_atom(self):
  141. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  142. @property
  143. def atom_id(self):
  144. return "tag:%s,%s:%s" % \
  145. (
  146. self.published.strftime("%Y-%m-%d"),
  147. self.permalink,
  148. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  149. )
  150. @property
  151. def body_html(self):
  152. return markdown2.markdown(self.body) # , extras=['code-color'])
  153. @property
  154. def permalink(self):
  155. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  156. @property
  157. def tags(self):
  158. tags = list()
  159. for t in self.header['tags']:
  160. tags.append(Tag(t))
  161. return tags
  162. def prepare(self):
  163. file = codecs.open(self.abspath, 'r')
  164. header = ['---']
  165. while True:
  166. line = file.readline()
  167. line = line.rstrip()
  168. if not line:
  169. break
  170. header.append(line)
  171. self.header = yaml.load(StringIO('\n'.join(header)))
  172. for h in self.header.items():
  173. if h:
  174. try:
  175. setattr(self, h[0], h[1])
  176. except:
  177. pass
  178. body = list()
  179. for line in file.readlines():
  180. body.append(line)
  181. self.body = ''.join(body)
  182. file.close()
  183. if self.kind == 'link':
  184. from urlparse import urlparse
  185. self.domain_name = urlparse(self.url).netloc
  186. elif self.kind == 'photo':
  187. pass
  188. elif self.kind == 'note':
  189. pass
  190. elif self.kind == 'writing':
  191. pass
  192. def render(self):
  193. if not self.header['public']:
  194. return False
  195. try:
  196. os.makedirs(os.path.dirname(self.destination))
  197. except:
  198. pass
  199. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  200. context['entry'] = self
  201. template = jinja_env.get_template("entry.html")
  202. html = template.render(context)
  203. destination = codecs.open(
  204. self.destination, 'w', CONFIG['content_encoding'])
  205. destination.write(html)
  206. destination.close()
  207. return True
  208. class Link(Entry):
  209. def __init__(self, path):
  210. super(Link, self).__init__(path)
  211. @property
  212. def permalink(self):
  213. print "self.url", self.url
  214. raw_input()
  215. return self.url
  216. def entry_factory():
  217. pass
  218. def _sort_entries(entries):
  219. _entries = dict()
  220. sorted_entries = list()
  221. for entry in entries:
  222. _published = entry.header['published'].isoformat()
  223. _entries[_published] = entry
  224. sorted_keys = sorted(_entries.keys())
  225. sorted_keys.reverse()
  226. for key in sorted_keys:
  227. sorted_entries.append(_entries[key])
  228. return sorted_entries
  229. def render_index(entries):
  230. """
  231. this function renders the main page located at index.html
  232. under oz123.github.com
  233. """
  234. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  235. context['entries'] = entries[:10]
  236. template = jinja_env.get_template('entry_index.html')
  237. html = template.render(context)
  238. destination = codecs.open("%s/index.html" % CONFIG[
  239. 'output_to'], 'w', CONFIG['content_encoding'])
  240. destination.write(html)
  241. destination.close()
  242. def render_archive(entries, render_to=None):
  243. """
  244. this function creates the archive page
  245. """
  246. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  247. context['entries'] = entries[ARCHIVE_SIZE:]
  248. template = jinja_env.get_template('archive_index.html')
  249. html = template.render(context)
  250. if not render_to:
  251. render_to = "%s/archive/index.html" % CONFIG['output_to']
  252. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  253. destination = codecs.open("%s/archive/index.html" % CONFIG[
  254. 'output_to'], 'w', CONFIG['content_encoding'])
  255. destination.write(html)
  256. destination.close()
  257. def render_atom_feed(entries, render_to=None):
  258. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  259. context['entries'] = entries[:10]
  260. template = jinja_env.get_template('atom.xml')
  261. html = template.render(context)
  262. if not render_to:
  263. render_to = "%s/atom.xml" % CONFIG['output_to']
  264. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  265. destination.write(html)
  266. destination.close()
  267. def render_tag_pages(tag_tree):
  268. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  269. for t in tag_tree.items():
  270. context['tag'] = t[1]['tag']
  271. context['entries'] = _sort_entries(t[1]['entries'])
  272. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  273. try:
  274. os.makedirs(destination)
  275. except:
  276. pass
  277. template = jinja_env.get_template('tag_index.html')
  278. html = template.render(context)
  279. file = codecs.open("%s/index.html" %
  280. destination, 'w', CONFIG['content_encoding'])
  281. file.write(html)
  282. file.close()
  283. render_atom_feed(context[
  284. '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. if fileName.endswith('md') or fileName.endswith('markdown'):
  296. entry = Entry(os.path.join(root, fileName))
  297. except Exception, e:
  298. print "Found some problem in: ", fileName
  299. print e
  300. raw_input("Please correct")
  301. sys.exit()
  302. if entry.render():
  303. entries.append(entry)
  304. for tag in entry.tags:
  305. if tag.name not in tags:
  306. tags[tag.name] = {
  307. 'tag': tag,
  308. 'entries': list(),
  309. }
  310. tags[tag.name]['entries'].append(entry)
  311. print " %s" % entry.path
  312. print " :done"
  313. print
  314. print " tag pages & their atom feeds:"
  315. render_tag_pages(tags)
  316. print " :done"
  317. print
  318. print " site wide index"
  319. entries = _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(entries)
  327. print "...........done"
  328. print
  329. print "All done "
  330. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  331. """
  332. launch an HTTP to preview the website
  333. """
  334. import SimpleHTTPServer
  335. import SocketServer
  336. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  337. httpd = SocketServer.TCPServer(("", CONFIG['http_port']), Handler)
  338. os.chdir(CONFIG['output_to'])
  339. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  340. print "Hit Ctrl+C to exit"
  341. try:
  342. httpd.serve_forever()
  343. except KeyboardInterrupt:
  344. print
  345. print "Shutting Down... Bye!."
  346. print
  347. httpd.server_close()
  348. def publish(GITDIRECTORY=CONFIG['output_to']):
  349. pass
  350. def new_post(GITDIRECTORY=CONFIG['output_to']):
  351. """
  352. This function should create a template for a new post with a title
  353. read from the user input.
  354. Most other fields should be defaults.
  355. """
  356. title = raw_input("Give the title of the post:")
  357. # TODO check there is not : in the title
  358. author = CONFIG['author']
  359. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  360. tags = '['+raw_input("Give the tags, separated by ', ':")+']'
  361. published = 'yes'
  362. chronological = 'yes'
  363. kind = 'writing'
  364. summary = ("summary: |\n Type your summary here\nDo not change the "
  365. "indentation"
  366. "to the left\n...\nStart writing your post here!")
  367. # make file name
  368. fname = os.path.join(os.getcwd(), 'content', kind,
  369. datetime.datetime.strftime(datetime.datetime.now(),
  370. '%Y'),
  371. date+'-'+title.replace(' ', '-')+'.markdown')
  372. print fname
  373. def clean(GITDIRECTORY="oz123.github.com"):
  374. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  375. os.chdir(GITDIRECTORY)
  376. for directory in directoriestoclean:
  377. shutil.rmtree(directory)
  378. def dist(SOURCEDIR=os.getcwd()+"/content/",
  379. DESTDIR="oz123.github.com/writings_raw/content/"):
  380. """
  381. sync raw files from SOURCE to DEST
  382. """
  383. import subprocess as sp
  384. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  385. cwd=os.getcwd())
  386. if __name__ == '__main__':
  387. parser = argparse.ArgumentParser(
  388. description='blogit - a tool to blog on github.')
  389. parser.add_argument('-b', '--build', action="store_true",
  390. help='convert the markdown files to HTML')
  391. parser.add_argument('-p', '--preview', action="store_true",
  392. help='Launch HTTP server to preview the website')
  393. parser.add_argument('-c', '--clean', action="store_true",
  394. help='clean output files')
  395. parser.add_argument('-n', '--new', action="store_true",
  396. help='create new post')
  397. parser.add_argument('-d', '--dist', action="store_true",
  398. help='sync raw files from SOURCE to DEST')
  399. args = parser.parse_args()
  400. if len(sys.argv) < 2:
  401. parser.print_help()
  402. sys.exit()
  403. if args.clean:
  404. clean()
  405. if args.build:
  406. build()
  407. if args.dist:
  408. dist()
  409. if args.preview:
  410. preview()
  411. if args.new:
  412. new_post()