-
Notifications
You must be signed in to change notification settings - Fork 3
/
gifc
executable file
·245 lines (225 loc) · 9.79 KB
/
gifc
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Gifc is a tool written in Python to work with GitHub Gists from command line.
# Copyright (C) 2018 Shantam Raj
# This code is licensed under GNU GPLv3 license. See LICENSE.md for details
import os
import pprint
import argparse
import tempfile
import subprocess
import requests
parser = argparse.ArgumentParser(description='Github gists from command line')
sp = parser.add_subparsers(dest='main')
sp.required = True
#Get gists
p1 = sp.add_parser('get')
p1.add_argument('number', help='Get <number> gists and their descriptions', type=int)
#Create gists
p2 = sp.add_parser('create')
p2.add_argument('gist_item', help='Gist full file name')
p2.add_argument('-d', '--describe', required=True, help='Gist description')
p2.add_argument('-p','--public', help='Make a public gist', default='false')
p2_mutex = p2.add_mutually_exclusive_group()
p2_mutex.add_argument('-m','--message', help='Gist contents from cli as string')
p2_mutex.add_argument('-f','--file', help='Gist contents from a local file')
p2_mutex.add_argument('-i','--interactive', nargs='?', action='store', choices=['vi', 'nano', 'gedit'], help='Create contents of the gist right now from an editor')
#Update gists
p3 = sp.add_parser('update')
p3.add_argument('gist_id', help='Gist id(sha) of the gist you want to update')
p3.add_argument('-f','--file_name', nargs='?', action='store', help='File name of the file inside the gist you are updating')
p3.add_argument('-i', '--interactive', nargs='?', action='store', choices=['vi', 'nano', 'gedit'], help='Edit contents of the gist in an editor')
p3.add_argument('-cd','--change_description', nargs='?', action='store', help='Change the gist description')
#Delete gists
p4 = sp.add_parser('delete')
p4.add_argument('gist_id', help='Gist id(sha) of the gist you want to delete')
#Delete files
p5 = sp.add_parser('remove')
p5.add_argument('gist_id', help='Gist id(sha) of the gist you want to remove files from')
p5.add_argument('-r', '--remove', nargs='+', required=True, help='File(s) you want to remove from a gist')
args = parser.parse_args()
def get_config_details(key):
if key in os.environ:
return os.environ[key]
else:
print('Environment Variable not set. Please set and try again')
exit()
class Color:
red = '\033[91m' #1;31;47m '\033[91m'
green = '\x1b[1;32;40m'
yellow = '\x1b[1;33;40m'
white = '\x1b[1;30;50m'
orange = '\33[93m'
bold = '\033[1m'
end = '\x1b[0m'
def pretty_print(gist_list):
for gist in gist_list:
print('Description: ', Color.bold+Color.red+gist['Description']+Color.end)
print('Files : ', gist['Files'])
print('Gist ID : ', Color.orange+gist['Gist ID']+Color.end)
print(''.center(os.get_terminal_size(1)[0], '~'))
# Get particular gist https://api.github.com/gists/aa5a315d61ae9438b18d
#Get gists
if args.main == 'get':
number_of_gists = args.number
print('Getting gists...')
user_id = get_config_details('GIT_USER_ID')
r = requests.get('https://api.github.com/users/{}/gists'.format(user_id))
gist_list = []
for gist in r.json()[:number_of_gists]:
gist_id = gist['id']
gist_description = gist['description']
gist_files = [file_ for file_ in gist['files'].keys()]
gist_list.append({'Description': gist_description,'Gist ID': gist_id, 'Files': gist_files})
pretty_print(gist_list)
# Create gists
if args.main == 'create':
#print(args['create'])
gist_file = args.gist_item
header = {"Authorization": f"Bearer {get_config_details('GIT_TOKEN')}"}
if args.message:
message = args.message
payload = {'description': args.describe, 'public': args.public, 'files':{args.gist_item : {'content': message}}}
#print(payload)
r = requests.post(f"https://api.github.com/gists", headers=header, json=payload)
#print(r.status_code)
if r.status_code == 201:
print(r.json()['id'])
print('Gist successfully created')
else:
print('Error creating gist. Please use GUI')
elif args.file: #Fails if the location of the file is wrong i.e file doesn't exist
file_ = args.file
with open(file_, 'r') as f:
f2s = f.read()
payload = {'description': args.describe, 'public': args.public, 'files':{args.gist_item : {'content': f2s}}}
r = requests.post(f"https://api.github.com/gists", headers=header, json=payload)
#print(r.status_code)
if r.status_code == 201:
print(r.json()['id'])
print('Gist successfully created')
else:
print('Error creating gist. Please use GUI')
else:
try:
check_editor = subprocess.Popen([args.interactive])
check_editor.terminate()
except:
print(Color.red+'Could not open that editor. Please use another.'+Color.end)
exit()
f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
f_name = f.name
f.close()
subprocess.run([args.interactive, f_name])
with open(f_name) as f:
contents = f.read()
payload = {'description': args.describe, 'public': args.public, 'files':{args.gist_item : {'content': contents}}}
try:
r = requests.post(f"https://api.github.com/gists", headers=header, json=payload)
except requests.exceptions.RequestException as e:
print(e)
exit()
if r.status_code == 201:
#print(r.status_code)
print(r.json()['id'])
print('Gist successfully created')
else:
print('Creating gist failed')
#Update gists
if args.main == 'update':
if not args.file_name and not args.interactive and not args.change_description:
parser.error('Please provide either file to edit, a description change or an editor for interactive mode')
gid = args.gist_id
header = {"Authorization": f"Bearer {get_config_details('GIT_TOKEN')}"}
payload = dict()
#file content changes
if args.file_name:
r = requests.get('https://api.github.com/gists/{}'.format(gid))
if r.status_code != 200:
print('Error getting gist contents for interactive mode')
exit()
f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
n = f.name
content = r.json()['files'][args.file_name]['content']
f.write(content)
f.close()
subprocess.run(['nano', n])
with open(n, 'r') as f:
new_content = f.read()
payload['files'] = {args.file_name :{'content': new_content}}
os.remove(n)
else:
if args.interactive:
get_gist = requests.get('https://api.github.com/gists/{}'.format(gid))
gist_files = get_gist.json()['files']
if len(gist_files) > 1:
print(Color.red+'There are multiple files in this gist'+Color.end)
file_content_dict = dict()
for gist_file_name, gist_file_meta in gist_files.items():
f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
n = f.name
content = gist_file_meta['content']
f.write(content)
f.close()
subprocess.run([args.interactive, n])
with open(n, 'r') as f:
new_content = f.read()
file_content_dict[gist_file_name] = {'content': new_content}
os.remove(n)
payload['files'] = file_content_dict
#gist description changes
if args.change_description:
payload['description'] = args.change_description
r = requests.patch('https://api.github.com/gists/{}'.format(gid), headers=header, json=payload)
#print(r.status_code)
if r.status_code == 200:
print("Gist successfully updated")
else:
print("Gist failed to update. Please use GUI.")
#Delete files or gists
if args.main == 'delete':
gid = args.gist_id
user_input = input(Color.red+Color.bold+"Are you sure you want to delete {} ? Y/N\n".format(gid)+Color.end)
if user_input.lower() not in ('y', 'n'):
print("Please enter either y or n")
print(Color.red+"Aborting"+Color.end)
exit()
if user_input.lower() != 'y':
print(Color.red+"Aborting"+Color.end)
exit()
print('Deleting {}'.format(gid))
token = get_config_details('GIT_TOKEN')
header = {'Authorization': 'Bearer {}'.format(token)}
r = requests.delete('https://api.github.com/gists/{}'.format(gid), headers=header)
#print(r.status_code)
if r.status_code != 204:
print('Request not completed. Maybe the gist_id is incorrect. Please try the GUI.')
exit()
print('Gist deleted.')
if args.main == 'remove':
gid = args.gist_id
files = args.remove
user_input = input(Color.red+Color.bold+"Are you sure you want to delete {} ? Y/N\n".format(files)+Color.end)
if user_input.lower() not in ('y', 'n'):
print("Please enter either y or n")
print(Color.red+"Aborting"+Color.end)
exit()
if user_input.lower() != 'y':
print(Color.red+"Aborting"+Color.end)
exit()
pprint.pprint('Deleting file(s) {}'.format(files))
token = get_config_details('GIT_TOKEN')
header = {'Authorization': 'Bearer {}'.format(token)}
#print(files, len(files))
file_del_payload = dict(zip(files,[None]*len(files)))
payload = {"files": file_del_payload}
#print(payload)
r = requests.patch('https://api.github.com/gists/{}'.format(gid), headers=header, json=payload)
#data vs json when you have to pass "null" as json.
if r.status_code == 422:
print('You are trying to delete a file that does not exist. Please try again with correct file.')
exit()
elif r.status_code != 200:
print('Request not completed. Please try the GUI.')
exit()
print('File(s) deleted.')