Skip to content

Instantly share code, notes, and snippets.

@etng
Created September 26, 2017 03:01
Show Gist options
  • Save etng/0abf62a6e4ddabb59b34dced39aafada to your computer and use it in GitHub Desktop.
Save etng/0abf62a6e4ddabb59b34dced39aafada to your computer and use it in GitHub Desktop.
published from yibombp.local
#!/usr/bin/env python
'''
# Create a Github Gist with a simple Python script
## usage
* save this file as ~/gist.py
* and call it like this:
* create new gist with filenames
~/gist.py full_path_to_your_file1 full_path_to_your_file2 full_path_to_your_file3
* upldate last gist with filenames
~/gist.py l[ast] a.py b.py c.py
* create new gist with rest filenames
~/gist.py n[ew] a.py b.py c.py
~/gist.py c[reate] a.py b.py c.py
* then we can get a gist with all the files
## dependencies
pip install requests
## uninstall
rm ~/gist.py
## remove secret_file
rm ~/.gist.pass
rm ~/.gist.last
## used api
https://developer.github.com/v3/gists/
'''
import os
import requests
import sys
import json
import platform
node_name = platform.node()
secret_file = os.path.expanduser('~/.gist.pass')
last_file = os.path.expanduser('~/.gist.last')
try:
username, password, public = map(lambda _:_.strip(), open(secret_file, 'r').readlines()[:3])
except:
while True:
username = raw_input('please input username:')
if username:
break
while True:
password = raw_input('please input password:').strip()
if password:
break
while True:
public = raw_input('please input public or not: yes/no/y/n').strip()
if public:
break
with open(secret_file, 'wb') as f:
f.write("\n".join([username, password, public]))
files = {}
if len(sys.argv) < 2:
print 'should have at least one file'
sys.exit(1)
filenames = sys.argv[1:]
gist_id = ''
if filenames and not os.path.exists(filenames[0]):
gist_id = filenames.pop(0)
if gist_id in ('c', 'create', 'n', 'new'):
gist_id = ''
elif gist_id in ('l', 'last'):
try:
gist_id = open(last_file, 'r').read()
except:
pass
for filename in filenames:
content = open(filename, 'r').read()
name = os.path.basename(filename)
files[name] = {
'content': content,
}
payload = json.dumps({
'description': 'published from {}'.format(node_name),
'public': public.lower().startswith('y'),
'files': files,
})
auth = requests.auth.HTTPBasicAuth(username, password)
if gist_id:
r = requests.patch(
'https://api.github.com/gists/{}'.format(gist_id),
data=payload,
auth=auth,
)
else:
r = requests.post(
'https://api.github.com/gists',
data=payload,
auth=auth,
)
result = r.json()
with open(last_file, 'wb') as f:
f.write(result.get('id', ''))
print(result.get('message', ''))
print(result.get('html_url', ''))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment