Skip to content

Commit 96f03c1

Browse files
author
Sourcery AI
committed
'Refactored by Sourcery'
1 parent c0b6a22 commit 96f03c1

File tree

8 files changed

+225
-251
lines changed

8 files changed

+225
-251
lines changed

TreeGopher.py

Lines changed: 55 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def populate(parentNode, request):
6868
window.FindElement('-QUERY-').update(request.url())
6969
window.FindElement('-LOADING-').update(visible=True)
7070

71-
if not parentNode in openNodes:
71+
if parentNode not in openNodes:
7272
passes = 0
7373
from_cache = False
7474
try:
@@ -80,25 +80,34 @@ def populate(parentNode, request):
8080
cache[request.url()] = resp
8181
passes += 1
8282
except:
83-
sg.popup("We're sorry!", request.url() + ' could not be fetched. Try again later.')
83+
sg.popup(
84+
"We're sorry!",
85+
f'{request.url()} could not be fetched. Try again later.',
86+
)
8487
if passes == 1:
8588
try:
8689
menu = trim_menu(resp.menu())
8790
passes += 1
8891
except:
89-
sg.popup("We're sorry!", request.url() + ' could not be parsed as a menu for one reason or another.')
92+
sg.popup(
93+
"We're sorry!",
94+
f'{request.url()} could not be parsed as a menu for one reason or another.',
95+
)
9096
if passes == 2:
9197
if from_cache:
92-
gophertree.insert(parentNode, request.url() + ' <cached>', text='- This is a cached menu, double click to go to the live version -', values=[], icon=icons['cache'])
98+
gophertree.insert(
99+
parentNode,
100+
f'{request.url()} <cached>',
101+
text='- This is a cached menu, double click to go to the live version -',
102+
values=[],
103+
icon=icons['cache'],
104+
)
93105
for item in menu:
94-
if not item.request().url() in openNodes:
106+
if item.request().url() not in openNodes:
95107
sub_url = item.request().url()
96108
if item.path.startswith("URL:"):
97109
sub_url = item.path[4:]
98-
if item.type in icons:
99-
icon = icons[item.type]
100-
else:
101-
icon = icons['9']
110+
icon = icons[item.type] if item.type in icons else icons['9']
102111
if item.type == 'i':
103112
gophertree.insert(parentNode, sub_url,
104113
text=item.text, values=[], icon=icon)
@@ -118,17 +127,21 @@ def download_thread(req, dlpath, gui_queue): # This uses Pituophis' Request(
118127
with open(dlpath, "wb") as dl:
119128
remote_file = req.stream().makefile('rb')
120129
while True:
121-
piece = remote_file.read(1024)
122-
if not piece:
130+
if piece := remote_file.read(1024):
131+
dl.write(piece)
132+
else:
123133
break
124-
dl.write(piece)
125134
gui_queue.put(dlpath) # put a message into queue for GUI
126135

127136
history = []
128137

129138
def dlPopup(url):
130-
return sg.popup_get_file('Where to save this file?', 'Download {}'.format(
131-
url), default_path=url.split('/')[-1], save_as=True)
139+
return sg.popup_get_file(
140+
'Where to save this file?',
141+
f'Download {url}',
142+
default_path=url.split('/')[-1],
143+
save_as=True,
144+
)
132145

133146
def go(url):
134147
global gophertree, openNodes, loadedTextURL
@@ -152,19 +165,17 @@ def go(url):
152165
loadedTextURL = req.url()
153166
window.FindElement('-OUTPUT-').update(resp.text())
154167
except:
155-
sg.popup("We're sorry!", req.url() + ' could not be fetched. Try again later.')
168+
sg.popup("We're sorry!", f'{req.url()} could not be fetched. Try again later.')
156169
else:
157170
dlpath = dlPopup(req.url())
158-
if not dlpath is None:
159-
window.FindElement('-DOWNLOADS-').update(value='Downloading {}'.format(dlpath))
171+
if dlpath is not None:
172+
window.FindElement('-DOWNLOADS-').update(value=f'Downloading {dlpath}')
160173
threading.Thread(target=download_thread, args=(req, dlpath, gui_queue), daemon=True).start()
161174

162175
window.FindElement('-LOADING-').update(visible=False)
163176

164177
def plural(x):
165-
if x > 1 or x < 1:
166-
return 's'
167-
return ''
178+
return 's' if x > 1 or x < 1 else ''
168179

169180
previousvalue = None
170181

@@ -185,26 +196,25 @@ def plural(x):
185196
url = url[:-9]
186197
del cache[url]
187198
go(url)
188-
else:
189-
if url.startswith('gopher'):
190-
req = pituophis.parse_url(url)
191-
if req.type == '1':
192-
parentNode = url
193-
if value['-USETREE-']:
194-
populate(parentNode, req)
195-
else:
196-
go(parentNode)
197-
elif req.type == '7':
198-
q = sg.popup_get_text('Search on ' + req.host, '')
199-
if not q is None:
200-
req.query = q
201-
go(req.url())
202-
elif req.type != 'i':
199+
elif url.startswith('gopher'):
200+
req = pituophis.parse_url(url)
201+
if req.type == '1':
202+
parentNode = url
203+
if value['-USETREE-']:
204+
populate(parentNode, req)
205+
else:
206+
go(parentNode)
207+
elif req.type == '7':
208+
q = sg.popup_get_text(f'Search on {req.host}', '')
209+
if q is not None:
210+
req.query = q
203211
go(req.url())
212+
elif req.type != 'i':
213+
go(req.url())
204214

205-
window.FindElement('-LOADING-').update(visible=False)
206-
else:
207-
os.startfile(url)
215+
window.FindElement('-LOADING-').update(visible=False)
216+
else:
217+
os.startfile(url)
208218
previousvalue = value
209219
elif event == 'Go':
210220
go(value['-QUERY-'].rstrip())
@@ -223,7 +233,7 @@ def plural(x):
223233
pyperclip.copy(loadedTextURL)
224234
elif event == 'Save...':
225235
dlpath = dlPopup(loadedTextURL)
226-
if not dlpath is None:
236+
if dlpath is not None:
227237
with open(dlpath, 'w') as f:
228238
f.write(value['-OUTPUT-'])
229239

@@ -236,7 +246,11 @@ def plural(x):
236246
# if message received from queue, display the message in the Window
237247
if message:
238248
window.FindElement('-DOWNLOADS-').update(value='')
239-
if sg.popup_yes_no('Finished downloading {}. Would you like to open the downloaded file?'.format(message)):
249+
if sg.popup_yes_no(
250+
f'Finished downloading {message}. Would you like to open the downloaded file?'
251+
):
240252
os.startfile(message)
241-
window.FindElement('-CACHE-').update(value='{} menu{} in cache.'.format(len(cache), plural(len(cache))))
253+
window.FindElement('-CACHE-').update(
254+
value=f'{len(cache)} menu{plural(len(cache))} in cache.'
255+
)
242256
window.close()

build/lib/pituophis/__init__.py

Lines changed: 38 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,11 @@ def url(self):
149149
"""
150150
protocol = 'gopher'
151151
path = self.path
152-
query = ''
153-
if not (self.query == ''):
154-
query = '%09' + self.query
152+
query = f'%09{self.query}' if self.query != '' else ''
155153
hst = self.host
156-
if not self.port == 70:
157-
hst += ':{}'.format(self.port)
158-
return '{}://{}/{}{}{}'.format(protocol, hst, self.type, path, query)
154+
if self.port != 70:
155+
hst += f':{self.port}'
156+
return f'{protocol}://{hst}/{self.type}{path}{query}'
159157

160158

161159
class Item:
@@ -227,8 +225,7 @@ def parse_menu(source):
227225
line) > 4: # discard Gopher+ and other naughty stuff
228226
line = line[:-1]
229227
line = '\t'.join(line)
230-
matches = re.match(r'^(.)(.*)\t(.*)\t(.*)\t(.*)', line)
231-
if matches:
228+
if matches := re.match(r'^(.)(.*)\t(.*)\t(.*)\t(.*)', line):
232229
item.type = matches[1]
233230
item.text = matches[2]
234231
item.path = matches[3]
@@ -251,12 +248,12 @@ def parse_url(url):
251248
up = urlparse(url)
252249

253250
if up.scheme == '':
254-
up = urlparse('gopher://' + url)
251+
up = urlparse(f'gopher://{url}')
255252

256253
req.path = up.path
257254
if up.query:
258-
req.path += '?{}'.format(up.query) # NOT to be confused with actual gopher queries, which use %09
259-
# this just combines them back into one string
255+
req.path += f'?{up.query}'
256+
# this just combines them back into one string
260257
req.host = up.hostname
261258
req.port = up.port
262259
if up.port is None:
@@ -347,7 +344,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70',
347344
if not path.startswith('URL:'):
348345
# fix relative path
349346
if not path.startswith('/'):
350-
path = realpath(gophermap_dir + '/' + path)
347+
path = realpath(f'{gophermap_dir}/{path}')
351348

352349
# globbing
353350
if '*' in path:
@@ -387,10 +384,12 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70',
387384
while '' in splt:
388385
splt.remove('')
389386
s.text = splt[len(splt) - 1]
390-
if os.path.exists(file + '/gophertag'):
391-
s.text = ''.join(list(open(
392-
file + '/gophertag'))).replace(
393-
'\r\n', '').replace('\n', '')
387+
if os.path.exists(f'{file}/gophertag'):
388+
s.text = (
389+
''.join(list(open(f'{file}/gophertag')))
390+
.replace('\r\n', '')
391+
.replace('\n', '')
392+
)
394393
s.path = file.replace(pub_dir, '/', 1)
395394
s.path = re.sub(r'/{2}', r'/', s.path)
396395
s.host = host
@@ -399,15 +398,12 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70',
399398
s.path = ''
400399
s.host = ''
401400
s.port = '0'
402-
if s.type == '1':
403-
d = 0
404-
else:
405-
d = 1
406-
if not s.path.endswith('gophermap'):
407-
if not s.path.endswith(
408-
'gophertag'):
409-
listing.append(
410-
[file, s, s.text, d])
401+
d = 0 if s.type == '1' else 1
402+
if not s.path.endswith(
403+
'gophermap'
404+
) and not s.path.endswith('gophertag'):
405+
listing.append(
406+
[file, s, s.text, d])
411407

412408
listing = natsorted(listing,
413409
key=itemgetter(0))
@@ -416,8 +412,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70',
416412
listing = natsorted(listing,
417413
key=itemgetter(3))
418414

419-
for item in listing:
420-
new_menu.append(item[1])
415+
new_menu.extend(item[1] for item in listing)
421416
else:
422417
new_menu.append(errors['403_glob'])
423418

@@ -438,10 +433,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70',
438433
mime = mimetypes.guess_type(
439434
pub_dir + path)[0]
440435
if mime is None: # is directory or binary
441-
if os.path.isdir(file):
442-
s.type = '1'
443-
else:
444-
s.type = '9'
436+
s.type = '1' if os.path.isdir(file) else '9'
445437
else:
446438
for sw in mime_starts_with.keys():
447439
if mime.startswith(sw):
@@ -450,7 +442,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70',
450442

451443
new_menu.append(item.source())
452444
else:
453-
item = 'i' + item + '\t\t\t0'
445+
item = f'i{item}' + '\t\t\t0'
454446
new_menu.append(item)
455447
return new_menu
456448

@@ -492,32 +484,25 @@ def handle(request):
492484
if os.path.isdir(res_path):
493485
# is directory
494486
if os.path.exists(res_path):
495-
if os.path.isfile(res_path + '/gophermap'):
496-
in_file = open(res_path + '/gophermap', "r+")
497-
gmap = in_file.read()
498-
in_file.close()
499-
menu = parse_gophermap(source=gmap,
500-
def_host=request.host,
501-
def_port=request.advertised_port,
502-
gophermap_dir=request.path,
503-
pub_dir=pub_dir)
487+
if os.path.isfile(f'{res_path}/gophermap'):
488+
with open(f'{res_path}/gophermap', "r+") as in_file:
489+
gmap = in_file.read()
504490
else:
505491
gmap = '?*\t\r\n'
506-
menu = parse_gophermap(source=gmap,
507-
def_host=request.host,
508-
def_port=request.advertised_port,
509-
gophermap_dir=request.path,
510-
pub_dir=pub_dir)
511-
return menu
492+
return parse_gophermap(
493+
source=gmap,
494+
def_host=request.host,
495+
def_port=request.advertised_port,
496+
gophermap_dir=request.path,
497+
pub_dir=pub_dir,
498+
)
512499
elif os.path.isfile(res_path):
513-
in_file = open(res_path, "rb")
514-
data = in_file.read()
515-
in_file.close()
500+
with open(res_path, "rb") as in_file:
501+
data = in_file.read()
516502
return data
517503

518504
if request.alt_handler:
519-
alt = request.alt_handler(request)
520-
if alt:
505+
if alt := request.alt_handler(request):
521506
return alt
522507

523508
e = errors['404']
@@ -536,7 +521,7 @@ def serve(host="127.0.0.1", port=70, advertised_port=None,
536521
"""
537522
if pub_dir is None or pub_dir == '':
538523
pub_dir = '.'
539-
print('Gopher server is now running on', host + ':' + str(port) + '.')
524+
print('Gopher server is now running on', f'{host}:{str(port)}.')
540525

541526
class GopherProtocol(asyncio.Protocol):
542527
def connection_made(self, transport):

examples/catenifer.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,9 @@ def go(url, itype=''):
2929
# req.type = '1' parse_url() now does this in Pituophis 1.0
3030
if itype == '7':
3131
req.type = itype
32-
print(bold('URL: ' + req.url()))
33-
if req.type == '7':
34-
if req.query == '':
35-
req.query = input(bold('Search term: '))
32+
print(bold(f'URL: {req.url()}'))
33+
if req.type == '7' and req.query == '':
34+
req.query = input(bold('Search term: '))
3635
if req.type in compatibleTypes:
3736
resp = req.get()
3837
if req.type in menuTypes:
@@ -42,13 +41,13 @@ def go(url, itype=''):
4241
text = typeIcons['9']
4342
if selector.type in typeIcons:
4443
text = typeIcons[selector.type]
45-
text = text + ' ' + selector.text
44+
text = f'{text} {selector.text}'
4645
if selector.type not in noLinkTypes:
4746
items += 1
4847
requests[items] = selector.request()
49-
text = text + ' (' + requests[items].url() + ') ' + bold('[#' + str(items) + ']')
48+
text = f"{text} ({requests[items].url()}) {bold(f'[#{items}]')}"
5049
if selector.path.startswith('URL:'):
51-
text = text + ' (' + selector.path.split('URL:')[1] + ')'
50+
text = f'{text} (' + selector.path.split('URL:')[1] + ')'
5251
print(text)
5352
elif req.type == '0':
5453
print(resp.text())

0 commit comments

Comments
 (0)