Skip to content

Instantly share code, notes, and snippets.

@husjon
Last active March 31, 2018 10:38
Show Gist options
  • Save husjon/064799ff960980fabaa809c85d66b4ee to your computer and use it in GitHub Desktop.
Save husjon/064799ff960980fabaa809c85d66b4ee to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import argparse
import collections
import json
import os
import requests
token_env_name = 'GIST_TOKEN'
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--public', action="store_true",
help='Tags the gist as public')
parser.add_argument('-d', '--description',
help='Adds a description to the gist')
parser.add_argument('-t', '--token',
help=f'GitHub token (can also be set via the {token_env_name} environment token)')
parser.add_argument('file', nargs='+',
help='File to upload to GitHub gists')
parser.add_argument('-f', '--filename',
help='Set filename of gist (only when uploading single gist)')
args = parser.parse_args()
if not args.token and token_env_name not in os.environ.keys():
print('[!] Token missing.\n')
parser.print_help()
exit(1)
gist_token = args.token or os.environ[token_env_name]
gist_availability = args.public
gist_files = args.file
gist_filename = args.filename
def file_content(gist_file):
with open(gist_file, 'r') as f:
gist_content = {"content": f.read().replace(gist_token, '<private_token>')}
return gist_content
def main():
global gist_filename
data = {
"description": args.description if args.description else "",
"public": gist_availability,
"files": collections.OrderedDict()
}
if len(gist_files) == 1:
gist_file = gist_files[0]
gist_filename = gist_filename if gist_filename else gist_file
data['files'][gist_filename] = file_content(gist_file)
else:
for gist_file in gist_files:
data['files'][gist_file] = file_content(gist_file)
headers = {'Authorization': f'token {gist_token}'}
res = requests.post('https://api.github.com/gists', data=json.dumps(data), headers=headers)
if res and res.status_code == 201:
availability = 'Public' if gist_availability else 'Private'
snippet_url = res.json()['html_url']
print(f'[+] {availability} Gist created: {snippet_url}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment