Skip to content

Instantly share code, notes, and snippets.

@gnarula
Last active December 16, 2015 05:08
Show Gist options
  • Save gnarula/5381884 to your computer and use it in GitHub Desktop.
Save gnarula/5381884 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
import argparse
import base64
import getpass
import json
import os
import urllib
import urllib2
import sys
CLIENT_ID = '3ac8e677057dd16c52ab'
CLIENT_SECRET = 'f13de5368cbe1acf4a843b96a3ff3b0bf0883f37'
def main():
parser = argparse.ArgumentParser(description="A script to creat gists from the terminal")
parser.add_argument('gistname', help="Filename for the gist.")
parser.add_argument('file', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="File to read from. If not mentioned input from STDIN will be accepted")
parser.add_argument('-p', '--protected', action='store_true', default=False, help="Make Gist Protected")
args = parser.parse_args()
checkConfig(args)
def checkConfig(args):
if not os.path.exists(os.path.expanduser('~/.gistit')):
setup()
createGist(args)
def setup():
print "It appears that you're running this script for the first time. Please take a while to configure it"
username = raw_input("Github Username: ")
password = getpass.getpass("Password (won't be echoed): ")
# try to login
data = {'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'scopes': 'gist'}
auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
result = makeRequest('authorizations', data, auth)
if 'token' in result:
print "Login Successfull"
f = open(os.path.expanduser('~/.gistit'), 'w')
f.write(result['token'])
f.close()
else:
print "Token not received"
sys.exit(1)
def createGist(args):
token = fetchToken()
public = not args.protected
postGist(args.gistname, args.file.read(), public, token)
def postGist(filename, content, public, token):
data = {'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'public': public, 'files': {filename: {'content': content}}}
result = makeRequest('gists?access_token=%s' % token, data)
print "Gist Created. %s URL: %s" % (filename, result['html_url'])
def fetchToken():
with open(os.path.expanduser('~/.gistit')) as f:
return str(f.readline())
def makeRequest(endpoint, data, auth=None):
url = 'https://api.github.com/%s' % endpoint
req = urllib2.Request(url, json.dumps(data))
if auth:
req.add_header("Authorization", "Basic %s" % auth)
try:
response = urllib2.urlopen(req)
except urllib2.HTTPError as err:
if err.code == 401:
print "Authentication failed"
sys.exit(1)
print "HTTPError: %s" % err
sys.exit(1)
return json.load(response)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment