Skip to content

Instantly share code, notes, and snippets.

@alghanmi
Created January 25, 2013 08:43
Show Gist options
  • Save alghanmi/4632879 to your computer and use it in GitHub Desktop.
Save alghanmi/4632879 to your computer and use it in GitHub Desktop.
Render a Markdown document using the GitHub markdown API
import argparse
import requests
import simplejson
def gitHubPost(text, mode, context):
"""Send a POST request to GitHub via API """
payload = {'text': text, 'mode':mode}
if context != None:
payload['context'] = context
r = requests.post('https://api.github.com/markdown', data=simplejson.dumps(payload))
if r.status_code == 200:
return r.content
else:
details = ''
for e in res['errors']:
details += '{}.{}: {}.'.format(e['resource'], e['field'], e['code'])
print '[ERROR][HTTP {}] {} - {}'.format(r.status_code, res['message'], details)
return None
'''
Get commandline arguments
'''
parser = argparse.ArgumentParser()
parser.add_argument('file', help='input file name', type=str)
parser.add_argument('-m', '--mode', help='markdown rendering mode. Use markdown for readme file and gfm for comments, issues, etc.', choices=['markdown', 'gfm'], dest='mode', default='markdown')
parser.add_argument('-c', '--context', help='repository context when rendering in gfm mode', nargs=1, dest='context', type=str)
parser.add_argument('-o', '--output', help='output file name', nargs=1, dest='output', type=str)
args = parser.parse_args()
ifile = open(args.file, 'r')
try:
md = ifile.read()
ifile.close()
html = gitHubPost(md, args.mode, args.context)
if args.context != None and args.mode == 'markdown':
print '[ERROR] Can not apply context in {} mode. Remove context or switch to gfm mode.'.format(args.mode)
else:
if args.output != None:
ofile = open(args.output[0], 'w')
ofile.write(html)
ofile.close()
else:
print html
except IOError as e:
print '[ERROR][I/O Exception] Error# {0}: {}'.format(e.errno, e.strerror)
@JohnENoonan
Copy link

Thank you! This is really helpful 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment