-
Notifications
You must be signed in to change notification settings - Fork 73
/
gist.py
executable file
·149 lines (126 loc) · 4.81 KB
/
gist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#!/usr/bin/env python
"""
Python script to post a Gist of a file from
a common/shared computer. Prompts for auth
interactively.
This is largely based on Soren Bleikertz' simple
example at:
<http://bleikertz.com/blog/gist_python.html>
##################
Copyright 2015 Jason Antman <[email protected]> <http://www.jasonantman.com>
Free for any use provided that patches are submitted back to me.
The latest version of this script can be found at:
<https://github.com/jantman/misc-scripts/blob/master/gist.py>
CHANGELOG:
2015-02-05 jantman:
- initial script
2015-04-15 jantman:
- catch error on ssl import and disable no_verify option
"""
import httplib
import urllib
import re
import os.path
from optparse import OptionParser
import platform
import sys
import json
import logging
from copy import deepcopy
FORMAT = "[%(levelname)s %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(level=logging.ERROR, format=FORMAT)
logger = logging.getLogger(__name__)
try:
from ssl import _create_unverified_context
have_ssl = True
except ImportError:
logger.error("ERROR - could not import ssl._create_unverified_context; unable to disable SSL cert verification")
have_ssl = False
def debug_response(response):
logger.debug("Response status {s}".format(s=response.status))
logger.debug("Response: {d}".format(d=response.read()))
logger.debug("Headers: \n{h}".format(
h='\n'.join(['{k}: {v}\n'.format(k=i[0], v=i[1]) for i in response.getheaders()])
))
def gist_write(name, content, token=None, prefix=False, no_verify=False):
if prefix:
name = '{n}_{name}'.format(n=platform.node(), name=name)
logger.debug("Setting name to: {n}".format(n=name))
data = {
'public': False,
'files': {
name: {
'content': content
}
}
}
# data debug
d = deepcopy(data)
if len(d['files'][name]['content']) > 800:
tmp = d['files'][name]['content']
d['files'][name]['content'] = tmp[:200] + "\n...\n" + tmp[-200:]
logger.debug("POST data: {d}".format(d=d))
headers = {'User-Agent': 'https://github.com/jantman/misc-scripts/blob/master/gist.py'}
if token is not None:
headers['Authorization'] = 'token {t}'.format(t=token)
logger.debug("Setting Authorization header to: {h}".format(h=headers['Authorization']))
if no_verify:
conn = httplib.HTTPSConnection("api.github.com", context=_create_unverified_context())
else:
conn = httplib.HTTPSConnection("api.github.com")
logger.debug("Opened connection to https://api.github.com")
logger.debug("POSTing to /gists")
conn.request("POST", "/gists", json.dumps(data), headers)
response = conn.getresponse()
debug_response(response)
if response.status == 201:
data = response.read()
conn.close()
try:
d = json.loads(data)
return(d['html_url'])
except:
pass
logger.error("Got 201 status but no JSON response")
logger.debug("Response: \n{d}".format(d=data))
h = response.getheaders()
for header in h:
if header[0] == 'location':
url = header[1].replace('api.github.com/gists/', 'gist.github.com/')
return url
return ''
logger.error("ERROR - got response code {s}".format(s=response.status))
conn.close()
raise SystemExit(1)
usage = 'USAGE: gist.py [options] filename'
parser = OptionParser(usage=usage)
parser.add_option('-d', '--description', dest='description', action='store',
type=str, help='Gist description')
parser.add_option('-p', '--prefix', dest='prefix', action='store_false',
default=True,
help='prefix gist filename with hostname')
parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
help='verbose output')
parser.add_option('-V', '--no-verify', dest='no_verify', action='store_true',
default=False, help='do not verify SSL')
(options, args) = parser.parse_args()
if options.verbose:
logger.setLevel(logging.DEBUG)
if options.no_verify and not have_ssl:
logger.error("ERROR: could not import ssl._create_unverified_context; therefore unable to disable SSL cert verification")
raise SystemExit(1)
if len(args) < 1:
sys.stderr.write(usage + "\n")
raise SystemExit(1)
if not os.path.exists(args[0]):
logger.error("ERROR: {f} does not exist".format(f=args[0]))
raise SystemExit(1)
token = raw_input("GitHub API Token: ").strip()
if token == '':
logger.error("ERROR: empty token")
raise SystemExit(1)
with open(args[0], 'r') as fh:
content = fh.read()
name = args[0]
url = gist_write(name, content, token=token, prefix=options.prefix, no_verify=options.no_verify)
logger.info("Created: {u}".format(u=url))