From a22fa0abbdc502048386ab8abe2dfdbca45050a7 Mon Sep 17 00:00:00 2001 From: mutantmonkey Date: Mon, 22 May 2017 22:06:51 -0700 Subject: [PATCH] Remove gist.py and pastee.py --- gist.py | 153 --------------------------------------------- pastee.py | 184 ------------------------------------------------------ 2 files changed, 337 deletions(-) delete mode 100755 gist.py delete mode 100755 pastee.py diff --git a/gist.py b/gist.py deleted file mode 100755 index cc0a4c2..0000000 --- a/gist.py +++ /dev/null @@ -1,153 +0,0 @@ -#!/usr/bin/env python3 -""" -Python command line client for gist.github.com - -Based on Chris Wanstrath's ruby gist client: - http://github.com/defunkt/gist/tree/master - -Basic usage: - cat file.txt | pygist - pygist file1 file2 file3 file4 - pygist -p file1 - echo 'hello world' | pygist -a - pygist -g 1234 > something.txt - -""" -__author__ = 'Matt Kemp ' -__version__ = 'pygist 2.0 3/5/11' -__license__ = """ -Copyright (c) 2011 Matt Kemp - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -""" - -import os -import sys -import subprocess - -from argparse import ArgumentParser, RawDescriptionHelpFormatter -from urllib.request import urlopen -from urllib.parse import urlencode - -site = 'https://gist.github.com/gists' - -def get_gh_login(): - cmd = subprocess.getoutput('which git') - if not cmd: - return - - user = subprocess.getoutput('{0} config --global github.user'.format(cmd)) - token = subprocess.getoutput('{0} config --global github.token'.format(cmd)) - - return user, token - -def gen_request(files, private, anon, description): - i = 0 - data = {} - - if not anon: - user, token = get_gh_login() - if all((user, token)): - data['login'] = user - data['token'] = token - - if private: - data['private'] = 'on' - - if description: - data['description'] = description - - for filename in files: - i += 1 - if filename is sys.stdin: - filename = '' - extension = '' - contents = sys.stdin.read() - else: - if not os.path.isfile(filename): - print("'{0}' does not exist or is not a regular file".format(filename)) - sys.exit() - extension = os.path.splitext(filename)[1] - with open(filename) as file: - contents = file.read() - - data['file_ext[gistfile{0:d}]'.format(i)] = extension - data['file_name[gistfile{0:d}]'.format(i)] = os.path.basename(filename) - data['file_contents[gistfile{0:d}]'.format(i)] = contents - - - return urlencode(data).encode('utf8') - -def get_gist(id): - url = 'https://gist.github.com/%s.txt' % id - with urlopen(url) as info: - data = info.read() - sys.stdout.write(data.decode('utf8')) - -def copy_paste(url): - cmd = None - if sys.platform == 'darwin': - cmd = cmd or subprocess.getoutput('which pbcopy') - cmd = cmd or subprocess.getoutput('which xclip') - if cmd: - output = subprocess.Popen(cmd, stdin=subprocess.PIPE) - output.stdin.write(url) - output.stdin.close() - return True - else: - return False - -def main(): - parser = ArgumentParser(description=__doc__, - formatter_class=RawDescriptionHelpFormatter) - parser.add_argument('-v', '--version', action='version', version=__version__) - parser.add_argument('-g', dest='gist_id', - help='retreive a paste identified by the gist id') - parser.add_argument('-d', dest='description', - help='description of the gist') - parser.add_argument('-p', dest='private', action='store_true', - help='set for private gist') - parser.add_argument('-a', dest='anon', action='store_true', - help='set for anonymous gist') - parser.add_argument('file', nargs='*', help='file to paste to gist') - args = parser.parse_args() - - if args.gist_id: - get_gist(args.gist_id) - sys.exit() - - if sys.stdin.isatty() and not args.file: - parser.print_help() - sys.exit(1) - - if len(args.file) < 1: - data = gen_request([sys.stdin], args.private, args.anon, args.description) - else: - data = gen_request(args.file, args.private, args.anon, args.description) - - with urlopen(site, data) as info: - url = info.geturl() - - if copy_paste(url.encode('utf8')): - print('{0} | copied to clipboard successfully.'.format(url)) - else: - print('{0}'.format(url)) - -if __name__ == '__main__': - main() diff --git a/pastee.py b/pastee.py deleted file mode 100755 index 9099e78..0000000 --- a/pastee.py +++ /dev/null @@ -1,184 +0,0 @@ -#!/usr/bin/python2 -import httplib -import optparse -import os -import sys -import threading -import urllib -import urlparse - - -__version__ = (0, 1, 0) - -PASTEE_URL = "https://pastee.org" -DEFAULT_LEXER = "text" -DEFAULT_TTL = 30 # days - - -class Paste: - """Class representing a paste that has been submitted.""" - def __init__(self, content, lexer, url): - """Constructor. - - Args: - content: paste content - lexer: lexer used for this paste - url: URL to access the paste - """ - self.content = content - self.lexer = lexer - self.url = url - - def __unicode__(self): - return self.url - - def __str__(self): - return str(self.__unicode__) - - -class PasteClient: - """Pasting client for a Pastee application. - - Instances of this class can be used to programmatically create new pastes on - an installation of Pastee (https://pastee.org). - - This class is thread-safe. - """ - def __init__(self, url=PASTEE_URL): - """Constructor. - - Args: - url: URL to Pastee installation (defaults to https://pastee.org) - """ - parse = urlparse.urlsplit(url) - self._scheme = parse[0] - self._netloc = parse[1] - self._lock = threading.Semaphore() - - def paste(self, content, lexer=None, ttl=None, key=None): - """Create a new paste. - - Args: - content: string of text to paste - lexer: lexer to use (defaults to text) - ttl: time-to-live in days (defaults to 30) - key: encrypt paste with this key; if not specified, paste is not - encrypted - - Returns: - Paste object - """ - if lexer is None: - lexer = DEFAULT_LEXER - if ttl is None: - ttl = DEFAULT_TTL - - if self._scheme == "https": - self._conn = httplib.HTTPSConnection(self._netloc) - else: - self._conn = httplib.HTTPConnection(self._netloc) - - headers = {"Content-type": "application/x-www-form-urlencoded", - "Accept": "text/plain"} - params = {"lexer": lexer, - "content": content, - "ttl": int(ttl * 86400)} - if key is not None: - params["encrypt"] = "checked" - params["key"] = key - - self._lock.acquire() - self._conn.request("POST", "/submit", urllib.urlencode(params), headers) - response = self._conn.getresponse() - self._lock.release() - return self._make_paste(response, content, lexer) - - def paste_file(self, filename, lexer=None, ttl=None, key=None): - """Create a new paste from a file. - - Args: - filename: path to file - lexer: lexer to use (defaults to extension of the file or text) - ttl: time-to-live in days (defaults to 30) - key: encrypt paste with this key; if not specified, paste is not - encrypted - - Returns: - Paste object - """ - _, ext = os.path.splitext(filename) - if lexer is None and ext: - lexer = ext[1:] # remove leading period first - # TODO(ms): need exception handling here - fd = open(filename, "r") - content = fd.read() - fd.close() - return self.paste(content, lexer=lexer, ttl=ttl, key=key) - - def _make_paste(self, response, content, lexer): - for (key, value) in response.getheaders(): - if key.lower() == "location": - return self._clean_url(value) - return Paste(content, lexer, self._clean_url(value)) - - def _clean_url(self, url): - p = urlparse.urlsplit(url) - scheme = p[0] - netloc_split = p[1].split(":") - hostname = netloc_split[0] - if len(netloc_split) > 1: - port = int(netloc_split[1]) - else: - port = scheme == "https" and 443 or 80 - path = p[2] - port_str = "" - if port != 80 and scheme == "http": - port_str = ":%d" % port - elif port != 443 and scheme == "https": - port_str = ":%d" % port - return "%s://%s%s%s" % (scheme, hostname, port_str, path) - - -def die_with_error(message): - """Print a message and exit with exit code 1. - - Args: - message: message to print before exiting - """ - print "error: %s" % message - sys.exit(1) - - -def main(): - parser = optparse.OptionParser() - parser.add_option("-l", "--lexer", dest="lexer", metavar="LEXERNAME", - help=("Force use of a particular lexer (i.e. c, py). " - "This defaults to the extension of the supplied " - "filenames, or 'text' if pasting from stdin.")) - parser.add_option("-t", "--ttl", dest="ttl", metavar="DAYS", - help=("Number of days before the paste will expire.")) - parser.add_option("-k", "--key", dest="key", metavar="PASSPHRASE", - help=("Encrypt pastes with this key.")) - (options, filenames) = parser.parse_args() - lexer = options.lexer - key = options.key - try: - ttl = float(options.ttl) - except ValueError: - die_with_error("floating point number must be passed for TTL") - except TypeError: - ttl = None - - client = PasteClient() - - if filenames: - # paste from multiple files - for filename in filenames: - print client.paste_file(filename, lexer=lexer, ttl=ttl, key=key) - else: - # paste from stdin - print client.paste(sys.stdin.read(), lexer=lexer, ttl=ttl, key=key) - - -if __name__ == "__main__": - main() -- 2.51.2