Skip to content

Commit 096f0ac

Browse files
author
lucasgit13
committed
cleanning some code
1 parent 429c5bb commit 096f0ac

File tree

1 file changed

+53
-70
lines changed

1 file changed

+53
-70
lines changed

Get-Dir-Github-Repo/get.py

Lines changed: 53 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,43 @@
44
import sys
55
import os
66
import subprocess
7+
from itertools import product
78

89
__version__ = "1.1"
910

1011

1112
# This will attempt to import the modules required for the script run
1213
# if fail to import it will try to install
13-
modules = ['requests']
14+
modules = ["requests"]
1415

1516
try:
1617
import requests
1718
except:
18-
print('Attempting to install the requirements...')
19+
print("Attempting to install the requirements...")
1920

2021
try:
2122
for module in modules:
22-
subprocess.run(['python', '-m', 'pip', 'install', module],
23-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
23+
subprocess.run(
24+
["python", "-m", "pip", "install", module],
25+
stdout=subprocess.DEVNULL,
26+
stderr=subprocess.DEVNULL,
27+
)
2428
import requests
25-
print('Requirements was successful installed!')
29+
30+
print("Requirements was successful installed!")
2631
except:
2732
try:
2833
for module in modules:
29-
subprocess.run(['python3', '-m', 'pip', 'install', module],
30-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
34+
subprocess.run(
35+
["python3", "-m", "pip", "install", module],
36+
stdout=subprocess.DEVNULL,
37+
stderr=subprocess.DEVNULL,
38+
)
3139
import requests
32-
print('Requirements was successful installed!')
40+
41+
print("Requirements was successful installed!")
3342
except:
34-
sys.exit('Could not install requirements :(')
43+
sys.exit("Could not install requirements :(")
3544

3645

3746
### Comandline arguments ###
@@ -78,13 +87,14 @@
7887

7988
### Functions ###
8089
def check_url(url):
81-
"""
82-
Check if the given url is valid and to ensure that get real repository information.
83-
"""
90+
if not "https://github.com/" in url:
91+
sys.exit("The url must to be a valid and public Github repository.")
92+
8493
if url[-1] == "/":
8594
url = url[:-1]
95+
8696
try:
87-
r = requests.head(url, timeout=30)
97+
r = requests.get(url, timeout=30)
8898
except requests.ConnectionError as e:
8999
print(
90100
"OOPS!! Connection Error. Make sure you are connected to Internet. Technical Details given below.\n"
@@ -98,45 +108,9 @@ def check_url(url):
98108
sys.exit(str(e))
99109
except KeyboardInterrupt:
100110
sys.exit("Someone closed the program")
101-
else:
102-
if r.status_code == 404:
103-
sys.exit(
104-
"404: Verify internet connection or check if the url is correct")
105111

106-
if not "https://github.com/" in url:
107-
sys.exit("Not a Github repo")
108-
109-
user = url.split("/")[3]
110-
repo = url.split("/")[4]
111-
repo_api = f"https://api.github.com/repos/{user}/{repo}/contents"
112-
113-
try:
114-
r2 = requests.get(repo_api, timeout=30)
115-
j = r2.json()
116-
117-
if r2.status_code != 200:
118-
if r2.headers["content-type"] == "application/json; charset=utf-8":
119-
message = r.json()["message"]
120-
if type(message) == dict:
121-
sys.exit(f"server: {message}")
122-
123-
count = 0
124-
for token in range(0, len(j)):
125-
t = j[token]["type"]
126-
if t != "dir":
127-
count += 1
128-
if count == 0:
129-
sys.exit(f"No files found in {url}")
130-
131-
else:
132-
return 0
133-
except requests.exceptions.RequestException:
134-
sys.exit(
135-
"Make sure you are provided a valid link and make sure you are connected to Internet."
136-
)
137-
138-
139-
### End of functions ###
112+
if r.status_code == 404:
113+
sys.exit(f"404 Client Error: Not Found for url: {url}")
140114

141115

142116
def Get(url):
@@ -150,7 +124,7 @@ def Get(url):
150124
try:
151125
sp = url.split("/")
152126
if len(sp) > 5:
153-
for _ in range(0, 7):
127+
for _ in range(7):
154128
sp.pop(0)
155129
path = "/".join(sp)
156130

@@ -160,22 +134,25 @@ def Get(url):
160134
api_url = f"https://api.github.com/repos/{user}/{repo}/contents/{path}"
161135
else:
162136
api_url = f"https://api.github.com/repos/{user}/{repo}/contents"
137+
163138
if api_url:
164139
try:
165140
r = requests.get(api_url, timeout=30)
166-
r1 = r.status_code
167-
if r1 != 200:
141+
code = r.status_code
142+
143+
if code == 403:
168144
if r.headers["content-type"] == "application/json; charset=utf-8":
169-
if type(r.json()) == dict:
170-
message = r.json()["message"]
171-
if type(message) == dict:
172-
sys.exit(f"server: {message}")
173-
else:
174-
sys.exit(f"{r1}: invalid url: {url}.")
175-
except requests.exceptions.RequestException:
176-
sys.exit(f"error: invalid url: {url}.")
177-
except:
178-
sys.exit(f"error: invalid url: {url}.")
145+
if "message" in r.json():
146+
sys.exit("You reached requests limit, try again later!")
147+
if code == 404:
148+
sys.exit(f"error: {code}")
149+
except requests.exceptions.RequestException as e:
150+
sys.exit(f"error:\n{e}")
151+
else:
152+
sys.exit(f"error: could not extract information about repo: {url}.")
153+
except Exception as e:
154+
print(e)
155+
sys.exit(f"error: could not extract information about repo: {url}.")
179156
else:
180157
return {"api_url": api_url, "repo": repo, "path": path}
181158

@@ -192,10 +169,6 @@ def search_pattern(obj, pattern_list):
192169

193170

194171
def include(obj, pattern_list):
195-
"""
196-
Receives a list of dictionaries and a glob pattern list and it returns back a list
197-
with the files that match with each pattern and variable with the amount of matches.
198-
"""
199172
include_list = []
200173
matches = 0
201174

@@ -256,6 +229,18 @@ def fetch(obj):
256229
exclude_list = args.exclude
257230
directory = ""
258231

232+
if include_list and exclude_list:
233+
# Check if the glob patttern given to -I and -E
234+
# was the same, if it is exit with an error
235+
globs = list(product(include_list, exclude_list))
236+
for token in range(len(globs)):
237+
i = globs[token][0]
238+
e = globs[token][1]
239+
240+
if i == e:
241+
print(f"-I and -E cannot share same glob pattern: {i}")
242+
sys.exit(0)
243+
259244
if output:
260245
directory = output
261246
else:
@@ -293,7 +278,6 @@ def fetch(obj):
293278

294279
if matches != 0:
295280
obj = obj_
296-
del obj_
297281
print(f"{matches} matches found to include")
298282
else:
299283
sys.exit(f"no matches for {include_list}")
@@ -303,7 +287,6 @@ def fetch(obj):
303287
if matches:
304288
obj_ = exclude(obj, exclude_list, matches)
305289
obj = obj_
306-
del obj_
307290
else:
308291
print(f"{matches} matches found to ignore")
309292

0 commit comments

Comments
 (0)