blogit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. import markdown2
  39. import argparse
  40. import sys
  41. from distutils import dir_util
  42. import shutil
  43. CONFIG = {
  44. 'content_root': 'content', # where the markdown files are
  45. 'output_to': 'oz123.github.com',
  46. 'templates': 'templates',
  47. 'date_format': '%Y-%m-%d',
  48. 'base_url': 'http://oz123.github.com',
  49. 'http_port': 3030,
  50. 'content_encoding': 'utf-8',
  51. 'author': 'Oz Nahum Tiram'
  52. }
  53. # EDIT THIS PARAMETER TO CHANGE ARCHIVE SIZE
  54. # 0 Means that all the entries will be in the archive
  55. # 10 meas that all the entries except the last 10
  56. ARCHIVE_SIZE = 0
  57. GLOBAL_TEMPLATE_CONTEXT = {
  58. 'media_base': '/media/',
  59. 'media_url': '../media/',
  60. 'site_url': 'http://oz123.github.com',
  61. 'last_build': datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
  62. 'twitter': 'https://twitter.com/#!/OzNTiram',
  63. 'stackoverflow': "http://stackoverflow.com/users/492620/oz123",
  64. 'github': "https://github.com/oz123",
  65. }
  66. KINDS = {
  67. 'writing': {
  68. 'name': 'writing', 'name_plural': 'writings',
  69. },
  70. 'note': {
  71. 'name': 'note', 'name_plural': 'notes',
  72. },
  73. 'link': {
  74. 'name': 'link', 'name_plural': 'links',
  75. },
  76. 'photo': {
  77. 'name': 'photo', 'name_plural': 'photos',
  78. },
  79. 'page': {
  80. 'name': 'page', 'name_plural': 'pages',
  81. },
  82. }
  83. jinja_env = Environment(loader=FileSystemLoader(CONFIG['templates']))
  84. class Tag(object):
  85. def __init__(self, name):
  86. super(Tag, self).__init__()
  87. self.name = name
  88. self.prepare()
  89. self.permalink = GLOBAL_TEMPLATE_CONTEXT["site_url"]
  90. def prepare(self):
  91. _slug = self.name.lower()
  92. _slug = re.sub(r'[;;,. ]', '-', _slug)
  93. self.slug = _slug
  94. class Entry(object):
  95. def __init__(self, path):
  96. super(Entry, self).__init__()
  97. path = path.split('content/')[-1]
  98. self.path = path
  99. self.prepare()
  100. def __str__(self):
  101. return self.path
  102. def __repr__(self):
  103. return self.path
  104. @property
  105. def name(self):
  106. return os.path.splitext(os.path.basename(self.path))[0]
  107. @property
  108. def abspath(self):
  109. return os.path.abspath(os.path.join(CONFIG['content_root'], self.path))
  110. @property
  111. def destination(self):
  112. dest = "%s/%s/index.html" % (KINDS[
  113. self.kind]['name_plural'], self.name)
  114. print dest
  115. return os.path.join(CONFIG['output_to'], dest)
  116. @property
  117. def title(self):
  118. return self.header['title']
  119. @property
  120. def summary_html(self):
  121. return "%s" % markdown2.markdown(self.header['summary'].strip())
  122. @property
  123. def credits_html(self):
  124. return "%s" % markdown2.markdown(self.header['credits'].strip())
  125. @property
  126. def summary_atom(self):
  127. summarya = markdown2.markdown(self.header['summary'].strip())
  128. summarya = re.sub("<p>|</p>", "", summarya)
  129. more = '<a href="%s"> continue reading...</a>' % (self.permalink)
  130. return summarya+more
  131. @property
  132. def published_html(self):
  133. if self.kind in ['link', 'note', 'photo']:
  134. return self.header['published'].strftime("%B %d, %Y %I:%M %p")
  135. return self.header['published'].strftime("%B %d, %Y")
  136. @property
  137. def published_atom(self):
  138. return self.published.strftime("%Y-%m-%dT%H:%M:%SZ")
  139. @property
  140. def atom_id(self):
  141. return "tag:%s,%s:%s" % \
  142. (
  143. self.published.strftime("%Y-%m-%d"),
  144. self.permalink,
  145. GLOBAL_TEMPLATE_CONTEXT["site_url"]
  146. )
  147. @property
  148. def body_html(self):
  149. return markdown2.markdown(self.body, extras=['fenced-code-blocks'])
  150. @property
  151. def permalink(self):
  152. return "/%s/%s" % (KINDS[self.kind]['name_plural'], self.name)
  153. @property
  154. def tags(self):
  155. tags = list()
  156. for t in self.header['tags']:
  157. tags.append(Tag(t))
  158. return tags
  159. def prepare(self):
  160. file = codecs.open(self.abspath, 'r')
  161. header = ['---']
  162. while True:
  163. line = file.readline()
  164. line = line.rstrip()
  165. if not line:
  166. 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 = ''.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. context['entry'] = self
  198. template = jinja_env.get_template("entry.html")
  199. html = template.render(context)
  200. destination = codecs.open(
  201. self.destination, 'w', CONFIG['content_encoding'])
  202. destination.write(html)
  203. destination.close()
  204. return True
  205. class Link(Entry):
  206. def __init__(self, path):
  207. super(Link, self).__init__(path)
  208. @property
  209. def permalink(self):
  210. print "self.url", self.url
  211. raw_input()
  212. return self.url
  213. def entry_factory():
  214. pass
  215. def _sort_entries(entries):
  216. _entries = dict()
  217. sorted_entries = list()
  218. for entry in entries:
  219. _published = entry.header['published'].isoformat()
  220. _entries[_published] = entry
  221. sorted_keys = sorted(_entries.keys())
  222. sorted_keys.reverse()
  223. for key in sorted_keys:
  224. sorted_entries.append(_entries[key])
  225. return sorted_entries
  226. def render_index(entries):
  227. """
  228. this function renders the main page located at index.html
  229. under oz123.github.com
  230. """
  231. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  232. context['entries'] = entries[:10]
  233. template = jinja_env.get_template('entry_index.html')
  234. html = template.render(context)
  235. destination = codecs.open("%s/index.html" % CONFIG[
  236. 'output_to'], 'w', CONFIG['content_encoding'])
  237. destination.write(html)
  238. destination.close()
  239. def render_archive(entries, render_to=None):
  240. """
  241. this function creates the archive page
  242. """
  243. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  244. context['entries'] = entries[ARCHIVE_SIZE:]
  245. template = jinja_env.get_template('archive_index.html')
  246. html = template.render(context)
  247. if not render_to:
  248. render_to = "%s/archive/index.html" % CONFIG['output_to']
  249. dir_util.mkpath("%s/archive" % CONFIG['output_to'])
  250. destination = codecs.open("%s/archive/index.html" % CONFIG[
  251. 'output_to'], 'w', CONFIG['content_encoding'])
  252. destination.write(html)
  253. destination.close()
  254. def render_atom_feed(entries, render_to=None):
  255. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  256. context['entries'] = entries[:10]
  257. template = jinja_env.get_template('atom.xml')
  258. html = template.render(context)
  259. if not render_to:
  260. render_to = "%s/atom.xml" % CONFIG['output_to']
  261. destination = codecs.open(render_to, 'w', CONFIG['content_encoding'])
  262. destination.write(html)
  263. destination.close()
  264. def render_tag_pages(tag_tree):
  265. context = GLOBAL_TEMPLATE_CONTEXT.copy()
  266. for t in tag_tree.items():
  267. context['tag'] = t[1]['tag']
  268. context['entries'] = _sort_entries(t[1]['entries'])
  269. destination = "%s/tags/%s" % (CONFIG['output_to'], context['tag'].slug)
  270. try:
  271. os.makedirs(destination)
  272. except:
  273. pass
  274. template = jinja_env.get_template('tag_index.html')
  275. html = template.render(context)
  276. file = codecs.open("%s/index.html" %
  277. destination, 'w', CONFIG['content_encoding'])
  278. file.write(html)
  279. file.close()
  280. render_atom_feed(context[
  281. 'entries'], render_to="%s/atom.xml" % destination)
  282. def build():
  283. print
  284. print "Rendering website now..."
  285. print
  286. print " entries:"
  287. entries = list()
  288. tags = dict()
  289. for root, dirs, files in os.walk(CONFIG['content_root']):
  290. for fileName in files:
  291. try:
  292. if fileName.endswith('md') or fileName.endswith('markdown'):
  293. entry = Entry(os.path.join(root, fileName))
  294. except Exception, e:
  295. print "Found some problem in: ", fileName
  296. print e
  297. raw_input("Please correct")
  298. sys.exit()
  299. if entry.render():
  300. entries.append(entry)
  301. for tag in entry.tags:
  302. if tag.name not in tags:
  303. tags[tag.name] = {
  304. 'tag': tag,
  305. 'entries': list(),
  306. }
  307. tags[tag.name]['entries'].append(entry)
  308. print " %s" % entry.path
  309. print " :done"
  310. print
  311. print " tag pages & their atom feeds:"
  312. render_tag_pages(tags)
  313. print " :done"
  314. print
  315. print " site wide index"
  316. entries = _sort_entries(entries)
  317. render_index(entries)
  318. print "................done"
  319. print " archive index"
  320. render_archive(entries)
  321. print "................done"
  322. print " site wide atom feeds"
  323. render_atom_feed(entries)
  324. print "...........done"
  325. print
  326. print "All done "
  327. def preview(PREVIEW_ADDR='127.0.1.1', PREVIEW_PORT=11000):
  328. """
  329. launch an HTTP to preview the website
  330. """
  331. import SimpleHTTPServer
  332. import SocketServer
  333. Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
  334. httpd = SocketServer.TCPServer(("", CONFIG['http_port']), Handler)
  335. os.chdir(CONFIG['output_to'])
  336. print "and ready to test at http://127.0.0.1:%d" % CONFIG['http_port']
  337. print "Hit Ctrl+C to exit"
  338. try:
  339. httpd.serve_forever()
  340. except KeyboardInterrupt:
  341. print
  342. print "Shutting Down... Bye!."
  343. print
  344. httpd.server_close()
  345. def publish(GITDIRECTORY=CONFIG['output_to']):
  346. pass
  347. def new_post(GITDIRECTORY=CONFIG['output_to']):
  348. """
  349. This function should create a template for a new post with a title
  350. read from the user input.
  351. Most other fields should be defaults.
  352. """
  353. title = raw_input("Give the title of the post:")
  354. # TODO check there is not : in the title
  355. author = CONFIG['author']
  356. date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
  357. tags = '['+raw_input("Give the tags, separated by ', ':")+']'
  358. published = 'yes'
  359. chronological = 'yes'
  360. kind = 'writing'
  361. summary = ("summary: |\n Type your summary here\nDo not change the "
  362. "indentation"
  363. "to the left\n...\nStart writing your post here!")
  364. # make file name
  365. fname = os.path.join(os.getcwd(), 'content', kind,
  366. datetime.datetime.strftime(datetime.datetime.now(),
  367. '%Y'),
  368. date+'-'+title.replace(' ', '-')+'.markdown')
  369. print fname
  370. def clean(GITDIRECTORY="oz123.github.com"):
  371. directoriestoclean = ["writings", "notes", "links", "tags", "archive"]
  372. os.chdir(GITDIRECTORY)
  373. for directory in directoriestoclean:
  374. shutil.rmtree(directory)
  375. def dist(SOURCEDIR=os.getcwd()+"/content/",
  376. DESTDIR="oz123.github.com/writings_raw/content/"):
  377. """
  378. sync raw files from SOURCE to DEST
  379. """
  380. import subprocess as sp
  381. sp.call(["rsync", "-avP", SOURCEDIR, DESTDIR], shell=False,
  382. cwd=os.getcwd())
  383. if __name__ == '__main__':
  384. parser = argparse.ArgumentParser(
  385. description='blogit - a tool to blog on github.')
  386. parser.add_argument('-b', '--build', action="store_true",
  387. help='convert the markdown files to HTML')
  388. parser.add_argument('-p', '--preview', action="store_true",
  389. help='Launch HTTP server to preview the website')
  390. parser.add_argument('-c', '--clean', action="store_true",
  391. help='clean output files')
  392. parser.add_argument('-n', '--new', action="store_true",
  393. help='create new post')
  394. parser.add_argument('-d', '--dist', action="store_true",
  395. help='sync raw files from SOURCE to DEST')
  396. args = parser.parse_args()
  397. if len(sys.argv) < 2:
  398. parser.print_help()
  399. sys.exit()
  400. if args.clean:
  401. clean()
  402. if args.build:
  403. build()
  404. if args.dist:
  405. dist()
  406. if args.preview:
  407. preview()
  408. if args.new:
  409. new_post()