gist_directive.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. try:
  2. from urllib.request import urlopen
  3. except ImportError:
  4. from urllib import urlopen
  5. import os
  6. import io
  7. from docutils.parsers.rst import directives
  8. from pelican.rstdirectives import Pygments
  9. def fetch(gid, filename, typ):
  10. if not os.path.exists('.gists'):
  11. os.mkdir('.gists')
  12. key = os.path.join('.gists', ("%s/%s/%s" % (typ, gid, filename)).replace('/', ';'))
  13. if os.path.isfile(key):
  14. print('LOAD-CACHED:', key)
  15. return io.open(key, encoding='utf8').read()
  16. else:
  17. if typ == 'gist':
  18. url = 'https://gist.githubusercontent.com/%s/raw/%s' % (gid, filename)
  19. elif typ == 'github':
  20. url = 'https://raw.githubusercontent.com/%s/%s' % (gid, filename)
  21. else:
  22. raise RuntimeError(typ)
  23. print('FETCHING:', url)
  24. fp = urlopen(url)
  25. if fp.getcode() != 200:
  26. print('FAILED TO FETCH:', url)
  27. print(' status code:', fp.getcode())
  28. print(' response:')
  29. try:
  30. print(fp.read())
  31. finally:
  32. raise SystemExit()
  33. data = fp.read()
  34. with open(key, 'wb') as fh:
  35. fh.write(data)
  36. return data.decode('utf8')
  37. class Gist(Pygments):
  38. """ Embed Github Gist Snippets in rst text
  39. GIST_ID and FILENAME are required.
  40. Usage:
  41. .. gist:: GIST_ID FILENAME
  42. """
  43. required_arguments = 1
  44. optional_arguments = 2
  45. has_content = False
  46. gist_type = 'gist'
  47. def run(self):
  48. gist = self.arguments[0]
  49. filename = self.arguments[1] if len(self.arguments) > 1 else ''
  50. language = self.arguments[2] if len(self.arguments) > 2 else None
  51. self.arguments = [language]
  52. self.content = fetch(gist, filename, self.gist_type).splitlines()
  53. return super(Gist, self).run()
  54. class Github(Gist):
  55. gist_type = 'github'
  56. def register():
  57. directives.register_directive('gist', Gist)
  58. directives.register_directive('github', Github)