Refactory of the code

Rewrote some part of the code in a more pythonic way and made the code follow the PEP8 style guide
This commit is contained in:
Domenico 2022-08-31 16:23:33 +02:00 committed by GitHub
parent 709ab25ba8
commit 069a5f04db
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -24,6 +24,7 @@ from rich.progress import (
from config import * from config import *
class Utils: class Utils:
def __init__(self) -> None: def __init__(self) -> None:
self.aur_pkgs = {} self.aur_pkgs = {}
@ -49,16 +50,14 @@ class Utils:
if len(res) > 0: if len(res) > 0:
output = ARCH_URL.format( output = ARCH_URL.format(
repo = res[0]["repo"], repo=res[0]["repo"],
arch = res[0]["arch"], arch=res[0]["arch"],
pkg = res[0]["pkgname"] pkg=res[0]["pkgname"]
) )
return output return output
aur_matches = {} aur_matches = {pkg: self.aur_pkgs[pkg]
for pkg in self.aur_pkgs: for pkg in self.aur_pkgs if pkg.startswith(pkg_name)}
if pkg.startswith(pkg_name):
aur_matches[pkg] = self.aur_pkgs[pkg]
if len(aur_matches) == 1: if len(aur_matches) == 1:
output = os.path.join(AUR_URL, list(aur_matches.values())[0]) output = os.path.join(AUR_URL, list(aur_matches.values())[0])
@ -66,53 +65,43 @@ class Utils:
elif len(aur_matches) > 1: elif len(aur_matches) > 1:
choices = list(aur_matches.keys()) choices = list(aur_matches.keys())
choices.append("None of the above") choices.append("None of the above")
s = self.user_select("Multiple Packages were found. Please select which one to use", choices) s = self.user_select(
"Multiple Packages were found. Please select which one to use", choices)
if s != "None of the above": if s != "None of the above":
output = os.path.join(AUR_URL, aur_matches[s]) output = os.path.join(AUR_URL, aur_matches[s])
return output return output
def user_select(self, que, choices): def user_select(self, que, choices):
print() print(f"\n{que}")
print(que)
q = [inquirer.List('a', message=">>", choices=choices)] q = [inquirer.List('a', message=">>", choices=choices)]
return inquirer.prompt(q)["a"] return inquirer.prompt(q)["a"]
def user_text(self, que): def user_text(self, que):
print() print(f"\n{que}")
print(que)
q = [inquirer.Text('a', message=">>")] q = [inquirer.Text('a', message=">>")]
return inquirer.prompt(q)["a"] return inquirer.prompt(q)["a"]
def user_confirm(self, que, y_otp="Yes", n_opt="No"): def user_confirm(self, que, y_otp="Yes", n_opt="No"):
ans = self.user_select(que, [y_otp, n_opt]) ans = self.user_select(que, [y_otp, n_opt])
if ans == y_otp: return ans == y_otp
return True
else:
return False
def user_path(self, que, required=False): def user_path(self, que, required=False):
while True: while True:
print() print(f"\n{que}")
print(que)
q = [inquirer.Text('a', message=">>")] q = [inquirer.Text('a', message=">>")]
p = inquirer.prompt(q)["a"] p = inquirer.prompt(q)["a"]
if not p: if not p:
if required: if required:
print("This field is required.") print("This field is required.")
continue continue
else: p = None
p = None break
break
if os.path.exists(p): if os.path.exists(p):
break break
print("File does not exist. Please try again.") print("File does not exist. Please try again.\n")
print()
return p return p
@ -122,24 +111,24 @@ class Utils:
x = re.findall('href="(.*tar.zst)"', txt) x = re.findall('href="(.*tar.zst)"', txt)
for i in x: for i in x:
name = urllib.parse.unquote(i, encoding='utf-8', errors='replace').replace(".pkg.tar.zst", "") name = urllib.parse.unquote(
i, encoding='utf-8', errors='replace').replace(".pkg.tar.zst", "")
self.aur_pkgs[name] = i self.aur_pkgs[name] = i
def download(self, url, dest, name): def download(self, url, dest, name):
progress = self.new_progress() progress = self.new_progress()
with progress: with progress:
print(f"Downloading {name}...") print(f"Downloading {name}...")
task_id = progress.add_task("download", filename=" ", start=False) task_id = progress.add_task("download", filename=" ", start=False)
response = urlopen(url) response = urlopen(url)
progress.update(task_id, total=int(response.info()["Content-length"])) progress.update(task_id, total=int(
response.info()["Content-length"]))
with open(dest, "wb") as dest_file: with open(dest, "wb") as dest_file:
progress.start_task(task_id) progress.start_task(task_id)
for data in iter(partial(response.read, 32768), b""): for data in iter(partial(response.read, 32768), b""):
dest_file.write(data) dest_file.write(data)
progress.update(task_id, advance=len(data)) progress.update(task_id, advance=len(data))
def extract_zst(self, zst_file, out_path): def extract_zst(self, zst_file, out_path):
zst_file = Path(zst_file).expanduser() zst_file = Path(zst_file).expanduser()
out_path = Path(out_path).expanduser().resolve() out_path = Path(out_path).expanduser().resolve()
@ -153,8 +142,7 @@ class Utils:
z.extractall(out_path) z.extractall(out_path)
def validate_desktop_file(self, file_path): def validate_desktop_file(self, file_path):
out = self.run_cmd(f"desktop-file-validate {file_path}", True) if out := self.run_cmd(f"desktop-file-validate {file_path}", True):
if out:
return False, out return False, out
else: else:
return True, None return True, None
@ -173,7 +161,8 @@ class Utils:
subprocess.run(shlex.split(cmd)) subprocess.run(shlex.split(cmd))
def set_icon_desktop_file(self, desktop_file, icon_name): def set_icon_desktop_file(self, desktop_file, icon_name):
self.run_cmd(f"desktop-file-edit {desktop_file} --set-icon={icon_name}") self.run_cmd(
f"desktop-file-edit {desktop_file} --set-icon={icon_name}")
def make_executable(self, file_path): def make_executable(self, file_path):
self.run_cmd(f"chmod +x {file_path}") self.run_cmd(f"chmod +x {file_path}")
@ -194,9 +183,4 @@ class Utils:
return pkgs return pkgs
def max_len(self, lst): def max_len(self, lst):
max1 = len(lst[0]) return max(len(i) for i in lst)
for i in lst:
if(len(i) > max1):
max1 = len(i)
return max1