blogit.py 14 KB

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