Last active
December 10, 2015 06:28
-
-
Save ifduyue/4394658 to your computer and use it in GitHub Desktop.
A small tool to upload a gist.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
''' | |
gist.py | |
~~~~~~~~~ | |
A small tool to upload a gist. | |
:copyright: Copyright (C) 2012 Yue Du <[email protected]> | |
:license: BSD 2-Clause License | |
''' | |
try: | |
from urlfetch import post | |
except ImportError: | |
from requests import post | |
import sys | |
import os | |
import json | |
import optparse | |
import select | |
parser = optparse.OptionParser('python {0} [OPTION]... [FILE]...'.format(sys.argv[0])) | |
parser.add_option('-u', '--user', dest='user', default=None, help='github user') | |
parser.add_option('-p', '--passwd', dest='passwd', default=None, help='github password') | |
parser.add_option('--description', dest='description', default='', help='gist description') | |
parser.add_option('--public', dest='public', action='store_true', default=True, help='create a public gist') | |
parser.add_option('--private', dest='public', action='store_false', help='create a private gist') | |
parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False, help='verbose output') | |
options, args = parser.parse_args() | |
selected = select.select([sys.stdin.fileno()], [], [], 0.1)[0] | |
if len(args) == 0 and not selected: | |
parser.print_help() | |
parser.exit(-1, '\nerror: No files\n') | |
files = {} | |
def adjust_filename(filename): | |
i = 1 | |
hasdot = '.' in filename | |
filename_s = filename.rsplit('.', 1) | |
ret = filename | |
while ret in files: | |
if hasdot: | |
ret = '{1}[{0}].{2}'.format(i, *filename_s) | |
else: | |
ret = '{1}[{0}]'.format(i, filename) | |
i += 1 | |
return ret | |
if selected: | |
files['stdin.txt'] = {'content': sys.stdin.read()} | |
for filepath in args: | |
with open(filepath, 'rb') as f: | |
content = f.read() | |
filename = os.path.basename(filepath) | |
files[adjust_filename(filename)] = {'content': content} | |
data = {'files': files, 'public': options.public} | |
if options.description: | |
data['description'] = options.description | |
postkwargs = {'data': json.dumps(data)} | |
if options.user and options.passwd: | |
postkwargs['auth'] = (options.user, options.passwd) | |
print 'Uploading...' | |
r = post('https://api.github.com/gists', **postkwargs) | |
ret = r.json() if callable(r.json) else r.json | |
if not options.verbose: | |
print ret.get('html_url', r.content) | |
else: | |
import pprint | |
pprint.pprint(ret) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment