Created
May 4, 2012 11:37
-
-
Save maksbotan/2594284 to your computer and use it in GitHub Desktop.
This file contains 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 | |
import json, urllib2, base64 | |
from xdg import BaseDirectory as basedir | |
from argparse import ArgumentParser | |
import os.path, sys, getpass | |
class AuthError(Exception): pass | |
def pgist_request_helper(uri, data, basic_auth="", auth_token=""): | |
json_req = json.dumps(data, encoding="utf-8") | |
if auth_token: | |
uri = "{}?access_token={}".format(uri, auth_token) | |
req = urllib2.Request(uri, data=json_req) | |
req.add_header("Content-Type", "application/json; charset=utf-8") | |
if basic_auth: | |
req.add_header("Authorization", "Basic {}".format( | |
base64.b64encode(basic_auth))) | |
#Errors from the following are caught by calling code | |
response = urllib2.urlopen(req) | |
json_resp = json.load(response, encoding="utf-8") | |
return json_resp | |
def pgist_save_config(config): | |
conf_dir = basedir.save_config_path("pgist") | |
json.dump(config, open(os.path.join(conf_dir, "pgist.conf"), "w"), indent=4) | |
def pgist_load_config(): | |
config = {} | |
for config_dir in basedir.load_config_paths("pgist"): | |
config.update(json.load(open(os.path.join(config_dir, "pgist.conf")))) | |
return config | |
def pgist_initialize_config(config): | |
print("You are about to get access token for Github Gist service") | |
print("Please note, your username and password won't be saved") | |
username = raw_input("Please enter your Github username: ") | |
password = getpass.getpass("Please enter your Github password: ") | |
basic_auth = "{}:{}".format(username, password) | |
data = {"scopes": ["gist"], "note": "pgist client"} | |
try: | |
response = pgist_request_helper( | |
"https://api.github.com/authorizations", | |
data, | |
basic_auth=basic_auth) | |
except urllib2.HTTPError as e: | |
print("Something went wrong while requesting auth token: {} {}".format(e.code, e.reason)) | |
raise AuthError() | |
except ValueError: | |
print("Something went wrong while requesting auth token") | |
raise AuthError() | |
config["auth_token"] = response["token"] | |
pgist_save_config(config) | |
def pgist_handle_auth(): | |
config = pgist_load_config() | |
if not config: | |
pgist_initialize_config(config) | |
return config["auth_token"] | |
def pgist_post(filenames, private=False, auth=False, | |
description="", extension=""): | |
if extension and not extension.startswith("."): | |
extension = "."+extension | |
data = {"public": not private, "files":{}} | |
if description: | |
data["description"] = description | |
for filename in filenames: | |
try: | |
data["files"][os.path.basename(filename)+extension] = { | |
"content": open(filename, "rb").read() | |
} | |
except IOError as e: | |
print("File '{}' cannot be loaded: {}.".format(filename, e.strerror)) | |
if not data["files"]: | |
print("No files can be loaded, exit.") | |
return 1 | |
if auth: | |
try: | |
auth_token = pgist_handle_auth() | |
except AuthError: | |
return 1 | |
else: | |
auth_token = "" | |
try: | |
json_resp = pgist_request_helper( | |
"https://api.github.com/gists", | |
data, | |
auth_token=auth_token) | |
except urllib2.HTTPError as e: | |
print("Could not paste: {} {}.".format(e.code, e.reason)) | |
return 1 | |
except ValueError: | |
print("GitHub response cannot be parsed, exit.") | |
return 1 | |
print(json_resp['html_url']) | |
return 0 | |
if __name__ == '__main__': | |
parser = ArgumentParser( | |
description="Console interface to Github Gist service") | |
parser.add_argument("filenames", metavar="file", nargs="+", | |
help="Files to paste") | |
parser.add_argument("-p", "--private", action="store_true", | |
help="Create private paste") | |
parser.add_argument("-a", "--auth", action="store_true", | |
help="Use authentication") | |
parser.add_argument("-d", "--description", | |
help="Description for the paste") | |
parser.add_argument("-x", "--extension", default="", | |
help="Add this extension to all file names") | |
args = parser.parse_args() | |
sys.exit(pgist_post(**args.__dict__)) | |
# vim: set ft=python |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment