Skip to content

Commit 0229a78

Browse files
committed
First pip installable release
Added setup.py MANIFEST.in Added more things to do in TODO.md Refactored gifc to handle more exceptions In update api, change description and file arguements can be used independently Removed the need for config.yml file. Now we extract data from environment variables Create now uses whatever editor you mention amongst [nano, vi, gedit] remove files recognizes when you pass files that are not present
1 parent 46b5cce commit 0229a78

File tree

4 files changed

+99
-35
lines changed

4 files changed

+99
-35
lines changed

MANIFEST.in

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
include README.md

TODO.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,26 @@ else:
136136
print('Creating gist failed')
137137
```
138138
9. - [ ] Get method doesn't work for private gists. May have to use [OAuth](https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/) for that.
139+
11. - [ ] Requests raises exceptions inherited from RequestException that you are not catching. So commands like `r = request.post(....)` can fail on bad internet connections or because other random issues. Catch them like -
140+
```python
141+
except requests.exceptions.RequestException as e: # This is the correct syntax
142+
print e
143+
```
144+
OR
145+
```python
146+
except requests.exceptions.Timeout:
147+
# Maybe set up for a retry, or continue in a retry loop
148+
except requests.exceptions.TooManyRedirects:
149+
# Tell the user their URL was bad and try a different one
150+
except requests.exceptions.RequestException as e:
151+
# catastrophic error. bail.
152+
print e
153+
```
154+
12. Handle FileNotFoundError in creating of gists via file parameter.
139155
10. Instead of using `__file__` as in `foo_config = open(os.path.join(os.path.dirname(__file__),'foo.conf').read()` or ```cwd = os.path.dirname(os.path.abspath(__file__))```, use `pkg_resources` instead. [Help1](http://peak.telecommunity.com/DevCenter/PythonEggs#accessing-package-resources), [Help2](https://setuptools.readthedocs.io/en/latest/pkg_resources.html#resourcemanager-api)
156+
13. Displaying gists in cli
157+
14. Update is still hardcoded with `nano`. Can we open it in system default editor?
158+
15. If no file arguement and description is given in update then open the first file in that gist in interactive mode for editing ?
140159
## It is NOT meant to replace the GUI neither does it attempt to.
141160
142161
## Features we will never have

gifc

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
3-
import argparse
4-
import requests
5-
import yaml
2+
3+
import os
64
import pprint
7-
import subprocess
5+
import argparse
86
import tempfile
9-
import os
7+
import subprocess
8+
9+
import requests
1010

1111
parser = argparse.ArgumentParser(description='Github gists from command line')
1212
sp = parser.add_subparsers(dest='main')
@@ -27,9 +27,9 @@ p2_mutex.add_argument('-i','--interactive', nargs='?', action='store', choices=[
2727
#Update gists
2828
p3 = sp.add_parser('update')
2929
p3.add_argument('gist_id', help='Gist id(sha) of the gist you want to update')
30-
p3.add_argument('-f','--file_name', required=True, help='File name of the file inside the gist you are updating')
30+
p3.add_argument('-f','--file_name', nargs='?', action='store', help='File name of the file inside the gist you are updating')
3131
#parser.add_argument('-nc','--new_content', help='New content string')
32-
p3.add_argument('-cd','--change_description', help='Change the gist description')
32+
p3.add_argument('-cd','--change_description', nargs='?', action='store', help='Change the gist description')
3333
#Delete gists
3434
p4 = sp.add_parser('delete')
3535
p4.add_argument('gist_id', help='Gist id(sha) of the gist you want to delete')
@@ -41,28 +41,17 @@ p5.add_argument('-r', '--remove', nargs='+', required=True, help='File(s) you wa
4141
args = parser.parse_args()
4242

4343
def get_config_details(key):
44-
try:
45-
with open('gist_config.yml', 'r') as f:
46-
config = yaml.safe_load(f)
47-
except:
48-
print('Configuration file not found')
49-
exit()
44+
if key in os.environ:
45+
return os.environ[key]
5046
else:
51-
if config.get(key):
52-
return config[key]
53-
else:
54-
if key == 'TOKEN':
55-
print('User token not found. Please add your token to gist_config.yaml')
56-
exit()
57-
elif key == 'USER_ID':
58-
print('User ID not found. Please add your github user_id to gist_config.yml')
59-
exit()
47+
print('Environment Variable not set. Please set and try again')
48+
exit()
6049

6150
class Color:
62-
red = '\x1b[1;31;40m'
51+
red = '\x1b[1;31;47m'
6352
green = '\x1b[1;32;40m'
6453
yellow = '\x1b[1;33;40m'
65-
white = '\x1b[1;37;40m'
54+
white = '\x1b[1;30;50m'
6655
bold = '\033[1m'
6756
end = '\x1b[0m'
6857

@@ -73,12 +62,12 @@ def pretty_print(gist_list):
7362
print('Gist ID : ', Color.white+gist['Gist ID']+Color.end)
7463
print('><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><')
7564

76-
65+
# Get particular gist https://api.github.com/gists/aa5a315d61ae9438b18d
7766
#Get gists
7867
if args.main == 'get':
7968
number_of_gists = args.number
8069
print('Getting gists...')
81-
user_id = get_config_details('USER_ID')
70+
user_id = get_config_details('GIT_USER_ID')
8271
r = requests.get(f'https://api.github.com/users/{user_id}/gists')
8372
gist_list = []
8473
for gist in r.json()[:number_of_gists]:
@@ -93,7 +82,7 @@ if args.main == 'get':
9382
if args.main == 'create':
9483
#print(args['create'])
9584
gist_file = args.gist_item
96-
header = {"Authorization": f"Bearer {get_config_details('TOKEN')}"}
85+
header = {"Authorization": f"Bearer {get_config_details('GIT_TOKEN')}"}
9786

9887
if args.message:
9988
message = args.message
@@ -119,15 +108,25 @@ if args.main == 'create':
119108
else:
120109
print('Error creating gist. Please use GUI')
121110
else:
111+
try:
112+
check_editor = subprocess.Popen([args.interactive])
113+
check_editor.terminate()
114+
except:
115+
print(Color.red+'Could not open that editor. Please use another.'+Color.end)
116+
exit()
122117
f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
123118
f_name = f.name
124119
f.close()
125-
subprocess.run(['nano', f_name])
120+
subprocess.run([args.interactive, f_name])
126121
with open(f_name) as f:
127122
contents = f.read()
128123

129124
payload = {'description': args.describe, 'public': args.public, 'files':{args.gist_item : {'content': contents}}}
130-
r = requests.post(f"https://api.github.com/gists", headers=header, json=payload)
125+
try:
126+
r = requests.post(f"https://api.github.com/gists", headers=header, json=payload)
127+
except requests.exceptions.RequestException as e:
128+
print(e)
129+
exit()
131130
if r.status_code == 201:
132131
print(r.status_code)
133132
print(r.json()['id'])
@@ -139,7 +138,7 @@ if args.main == 'create':
139138
#Update gists
140139
if args.main == 'update':
141140
gid = args.gist_id
142-
header = {"Authorization": f"Bearer {get_config_details('TOKEN')}"}
141+
header = {"Authorization": f"Bearer {get_config_details('GIT_TOKEN')}"}
143142
payload = dict()
144143
#file content changes
145144
if args.file_name:
@@ -173,7 +172,7 @@ if args.main == 'update':
173172
if args.main == 'delete':
174173
gid = args.gist_id
175174
print(f'Deleting {gid}')
176-
token = get_config_details('TOKEN')
175+
token = get_config_details('GIT_TOKEN')
177176
header = {'Authorization': f'Bearer {token}'}
178177

179178
r = requests.delete(f'https://api.github.com/gists/{gid}', headers=header)
@@ -187,15 +186,18 @@ if args.main == 'remove':
187186
gid = args.gist_id
188187
files = args.remove
189188
pprint.pprint(f'Deleting file(s) {files}')
190-
token = get_config_details('TOKEN')
189+
token = get_config_details('GIT_TOKEN')
191190
header = {'Authorization': f'Bearer {token}'}
192191
#print(files, len(files))
193192
file_del_payload = dict(zip(files,[None]*len(files)))
194193
payload = {"files": file_del_payload}
195-
print(payload)
194+
#print(payload)
196195
r = requests.patch(f'https://api.github.com/gists/{gid}', headers=header, json=payload)
197196
#data vs json when you have to pass "null" as json.
198-
if r.status_code != 200:
197+
if r.status_code == 422:
198+
print('You are trying to delete a file that does not exist. Please try again with correct file.')
199+
exit()
200+
elif r.status_code != 200:
199201
print('Request not completed. Please try the GUI.')
200202
exit()
201203
print('File(s) deleted.')

setup.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from setuptools import setup, find_packages
2+
import sys
3+
4+
if sys.version_info[0] != 3:
5+
raise RuntimeError('Unsupported python version "{0}"'.format(sys.version_info[0]))
6+
7+
try:
8+
with open('README.md') as f:
9+
long_description = f.read()
10+
except:
11+
long_description = 'This is a nifty little tool written in Python to work with GitHub Gists from command line.'
12+
13+
setup(name='gifc',
14+
version='0.1',
15+
description='Github Gists from CLI',
16+
long_description=long_description,
17+
long_description_content_type='text/markdown',
18+
keywords=['gist', 'github', 'cli'],
19+
author='Shantam Raj',
20+
author_email='[email protected]',
21+
url='https://github.com/armsp/gifc',
22+
download_url='',
23+
include_package_data=True,
24+
packages=find_packages('gifc'),
25+
scripts=['gifc'],
26+
license='GNU GPL v3',
27+
install_requires=[
28+
'requests',
29+
],
30+
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
31+
classifiers=[
32+
'Development Status :: 3 - Alpha',
33+
'Intended Audience :: Developers',
34+
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
35+
'Natural Language :: English',
36+
'Programming Language :: Python :: 3.4',
37+
'Programming Language :: Python :: 3.5',
38+
'Programming Language :: Python :: 3.6',
39+
'Programming Language :: Python :: 3.7',
40+
],
41+
zip_safe=False
42+
)

0 commit comments

Comments
 (0)