Improving code for Python 3

Signed-off-by: Dimitris Zlatanidis <d.zlatanidis@gmail.com>
This commit is contained in:
Dimitris Zlatanidis 2020-01-18 13:50:02 +01:00
parent 41ba3586e1
commit 2a42b77527
2 changed files with 53 additions and 96 deletions

View file

@ -52,7 +52,7 @@ class BuildPackage:
self.msg = Msg() self.msg = Msg()
self._SOURCES = self.meta.SBo_SOURCES self._SOURCES = self.meta.SBo_SOURCES
self.prgnam = self.script[:-7] self.prgnam = self.script[:-7]
self.log_file = "build_{0}_log".format(self.prgnam) self.log_file = f"build_{self.prgnam}_log"
self.sbo_logs = self.meta.log_path + "sbo/" self.sbo_logs = self.meta.log_path + "sbo/"
self.build_logs = self.sbo_logs + "build_logs/" self.build_logs = self.sbo_logs + "build_logs/"
self.start_log_time = time.strftime("%H:%M:%S") self.start_log_time = time.strftime("%H:%M:%S")
@ -94,27 +94,21 @@ class BuildPackage:
shutil.copy2(src, self.path + self.prgnam) shutil.copy2(src, self.path + self.prgnam)
os.chdir(self.path + self.prgnam) os.chdir(self.path + self.prgnam)
# change permissions # change permissions
subprocess.call("chmod +x {0}.SlackBuild".format(self.prgnam), subprocess.call(f"chmod +x {self.prgnam}.SlackBuild", shell=True)
shell=True)
pass_var = self._pass_variable() pass_var = self._pass_variable()
if self.meta.sbo_build_log in ["on", "ON"]: if self.meta.sbo_build_log in ["on", "ON"]:
if os.path.isfile(self.build_logs + self.log_file): if os.path.isfile(self.build_logs + self.log_file):
os.remove(self.build_logs + self.log_file) os.remove(self.build_logs + self.log_file)
# start log write # start log write
log_head(self.build_logs, self.log_file, self.start_log_time) log_head(self.build_logs, self.log_file, self.start_log_time)
subprocess.Popen("{0} ./{1}.SlackBuild 2>&1 | tee -a " subprocess.Popen(f"{' '.join(pass_var)} ./{self.prgnam}.SlackBuild 2>&1 | tee -a "
"{2}{3}".format(" ".join(pass_var), f"{self.build_logs}{self.log_file}", shell=True, stdout=sys.stdout).communicate()
self.prgnam, self.build_logs,
self.log_file), shell=True,
stdout=sys.stdout).communicate()
sum_time = build_time(self.start_time) sum_time = build_time(self.start_time)
# write end in log file # write end in log file
log_end(self.build_logs, self.log_file, sum_time) log_end(self.build_logs, self.log_file, sum_time)
print("Total build time for the package {0} : {1}\n".format( print(f"Total build time for the package {self.prgnam} : {sum_time}\n")
self.prgnam, sum_time))
else: else:
subprocess.call("{0} ./{1}.SlackBuild".format( subprocess.call(f"{' '.join(pass_ver)} ./{self.prgnam}.SlackBuild", shell=True)
" ".join(pass_var), self.prgnam), shell=True)
os.chdir(self.path) os.chdir(self.path)
except KeyboardInterrupt: # (OSError, IOError): except KeyboardInterrupt: # (OSError, IOError):
self.msg.pkg_not_found("\n", self.prgnam, "Wrong file", "\n") self.msg.pkg_not_found("\n", self.prgnam, "Wrong file", "\n")
@ -141,7 +135,7 @@ class BuildPackage:
""" """
if self.meta.makeflags in ["on", "ON"]: if self.meta.makeflags in ["on", "ON"]:
cpus = multiprocessing.cpu_count() cpus = multiprocessing.cpu_count()
os.environ["MAKEFLAGS"] = "-j{0}".format(cpus) os.environ["MAKEFLAGS"] = f"-j{cpus}"
def _pass_variable(self): def _pass_variable(self):
"""Return enviroment variables """Return enviroment variables
@ -150,7 +144,7 @@ class BuildPackage:
for var in os.environ.keys(): for var in os.environ.keys():
expVAR = var.split("_") expVAR = var.split("_")
if expVAR[0] == self.prgnam.upper() and expVAR[1] != "PATH": if expVAR[0] == self.prgnam.upper() and expVAR[1] != "PATH":
pass_var.append("{0}={1}".format(expVAR[1], os.environ[var])) pass_var.append(f"{expVAR[1]}={os.environ[var]}")
return pass_var return pass_var
def _delete_sbo_tar_gz(self): def _delete_sbo_tar_gz(self):
@ -188,7 +182,7 @@ def log_end(path, log_file, sum_time):
log.seek(2) log.seek(2)
log.write("#" * 79 + "\n\n") log.write("#" * 79 + "\n\n")
log.write("Time : " + time.strftime("%H:%M:%S") + "\n") log.write("Time : " + time.strftime("%H:%M:%S") + "\n")
log.write("Total build time : {0}\n".format(sum_time)) log.write(f"Total build time : {sum_time}\n")
log.write(" " * 38 + "E N D\n\n") log.write(" " * 38 + "E N D\n\n")
log.write("#" * 79 + "\n\n") log.write("#" * 79 + "\n\n")
log.close() log.close()
@ -204,11 +198,9 @@ def build_time(start_time):
elif diff_time > 59.99 and diff_time <= 3599.99: elif diff_time > 59.99 and diff_time <= 3599.99:
sum_time = round(diff_time / 60, 2) sum_time = round(diff_time / 60, 2)
sum_time_list = re.findall(r"\d+", str(sum_time)) sum_time_list = re.findall(r"\d+", str(sum_time))
sum_time = ("{0} Min {1} Sec".format(sum_time_list[0], sum_time = (f"{sum_time_list[0]} Min {sum_time_list[1]} Sec")
sum_time_list[1]))
elif diff_time > 3599.99: elif diff_time > 3599.99:
sum_time = round(diff_time / 3600, 2) sum_time = round(diff_time / 3600, 2)
sum_time_list = re.findall(r"\d+", str(sum_time)) sum_time_list = re.findall(r"\d+", str(sum_time))
sum_time = ("{0} Hours {1} Min".format(sum_time_list[0], sum_time = (f"{sum_time_list[0]} Hours {sum_time_list[1]} Min")
sum_time_list[1]))
return sum_time return sum_time

View file

@ -45,6 +45,12 @@ class PackageManager:
def __init__(self, binary): def __init__(self, binary):
self.binary = binary self.binary = binary
self.meta = _meta_ self.meta = _meta_
self.green = _meta_.color["GREEN"]
self.red = _meta_.color["RED"]
self.yellow = _meta_.color["YELLOW"]
self.cyan = _meta_.color["CYAN"]
self.grey = _meta_.color["GREY"]
self.endc = _meta_.color["ENDC"]
self.msg = Msg() self.msg = Msg()
self.skip = [] self.skip = []
self.size = 0 self.size = 0
@ -56,8 +62,7 @@ class PackageManager:
""" """
for pkg in self.binary: for pkg in self.binary:
try: try:
subprocess.call("installpkg {0} {1}".format(flag, pkg), subprocess.call(f"installpkg {flag} {pkg}", shell=True)
shell=True)
check = pkg[:-4].split("/")[-1] check = pkg[:-4].split("/")[-1]
if os.path.isfile(self.meta.pkg_path + check): if os.path.isfile(self.meta.pkg_path + check):
print("Completed!\n") print("Completed!\n")
@ -72,8 +77,7 @@ class PackageManager:
""" """
for pkg in self.binary: for pkg in self.binary:
try: try:
subprocess.call("upgradepkg {0} {1}".format(flag, pkg), subprocess.call(f"upgradepkg {flag} {pkg}", shell=True)
shell=True)
check = pkg[:-4].split("/")[-1] check = pkg[:-4].split("/")[-1]
if os.path.isfile(self.meta.pkg_path + check): if os.path.isfile(self.meta.pkg_path + check):
print("Completed!\n") print("Completed!\n")
@ -183,8 +187,7 @@ class PackageManager:
for pkg in self.binary: for pkg in self.binary:
name = GetFromInstalled(pkg).name() name = GetFromInstalled(pkg).name()
ver = GetFromInstalled(pkg).version() ver = GetFromInstalled(pkg).version()
package = find_package("{0}{1}{2}".format( package = find_package(f"{name}{ver}{self.meta.sp}", self.meta.pkg_path)
name, ver, self.meta.sp), self.meta.pkg_path)
if pkg and name == pkg: if pkg and name == pkg:
removed.append(pkg) removed.append(pkg)
packages.append(package[0]) packages.append(package[0])
@ -197,14 +200,12 @@ class PackageManager:
"""View packages before removed """View packages before removed
""" """
print("\nPackages with name matching [ {0}{1}{2} ]\n".format( print("\nPackages with name matching [ {0}{1}{2} ]\n".format(
self.meta.color["CYAN"], ", ".join(self.binary), self.cyan, ", ".join(self.binary), self.endc))
self.meta.color["ENDC"]))
removed, packages = self._get_removed() removed, packages = self._get_removed()
if packages and "--checklist" in self.extra: if packages and "--checklist" in self.extra:
removed = [] removed = []
text = "Press 'spacebar' to unchoose packages from the remove" text = "Press 'spacebar' to unchoose packages from the remove"
backtitle = "{0} {1}".format(self.meta.__all__, backtitle = f"{self.meta.__all__} {self.meta.__version__}"
self.meta.__version__)
status = True status = True
pkgs = DialogUtil(packages, text, " Remove ", backtitle, pkgs = DialogUtil(packages, text, " Remove ", backtitle,
status).checklist() status).checklist()
@ -215,16 +216,14 @@ class PackageManager:
else: else:
for rmv, pkg in zip(removed, packages): for rmv, pkg in zip(removed, packages):
self._sizes(pkg) self._sizes(pkg)
print("[ {0}delete{1} ] --> [ {2} ] - {3}".format( print(f"[ {self.red}delete{self.endc} ] --> [ {self.file_size} ] - {pkg}")
self.meta.color["RED"], self.meta.color["ENDC"],
self.file_size, pkg))
self._calc_sizes() self._calc_sizes()
self._remove_summary() self._remove_summary()
if "--third-party" in self.extra: if "--third-party" in self.extra:
print("\n") print("\n")
self.msg.template(78) self.msg.template(78)
print(("| {0}{1}*** WARNING ***{2}").format( print(("| {0}{1}*** WARNING ***{2}").format(
" " * 27, self.meta.color["RED"], self.meta.color["ENDC"])) " " * 27, self.red, self.endc))
print("| Before you use third-party option, be sure you have" print("| Before you use third-party option, be sure you have"
" updated the packages \n| lists. Run the command" " updated the packages \n| lists. Run the command"
" 'slpkg update' and 'slpkg -c slack --upgrade'") " 'slpkg update' and 'slpkg -c slack --upgrade'")
@ -248,8 +247,7 @@ class PackageManager:
print("\nRemoved summary") print("\nRemoved summary")
print("=" * 79) print("=" * 79)
print("{0}Size of removed packages {1} {2}.{3}".format( print("{0}Size of removed packages {1} {2}.{3}".format(
self.meta.color["GREY"], round(self.size, 2), self.unit, self.grey, round(self.size, 2), self.unit, self.endc))
self.meta.color["ENDC"]))
def _view_deps(self, path, package): def _view_deps(self, path, package):
"""View dependencies before remove """View dependencies before remove
@ -267,8 +265,7 @@ class PackageManager:
if "--checklist" in self.extra: if "--checklist" in self.extra:
deps, dependencies = [], [] deps, dependencies = [], []
text = "Found dependencies for the package {0}".format(package) text = "Found dependencies for the package {0}".format(package)
backtitle = "{0} {1}".format(self.meta.__all__, backtitle = f"{self.meta.__all__} {self.meta.__version__}"
self.meta.__version__)
status = True status = True
deps = DialogUtil(packages, text, " Remove ", backtitle, deps = DialogUtil(packages, text, " Remove ", backtitle,
status).checklist() status).checklist()
@ -278,19 +275,16 @@ class PackageManager:
else: else:
print() # new line at start print() # new line at start
self.msg.template(78) self.msg.template(78)
print("| Found dependencies for the package {0}:".format( print(f"| Found dependencies for the package {package}:")
package))
self.msg.template(78) self.msg.template(78)
for pkg in packages: for pkg in packages:
find = find_package(pkg + self.meta.sp, self.meta.pkg_path) find = find_package(pkg + self.meta.sp, self.meta.pkg_path)
self._sizes(find[0]) self._sizes(find[0])
print("| {0}{1}{2}".format(self.meta.color["RED"], pkg, print(f"| {self.red}{pkg}{self.endc}")
self.meta.color["ENDC"]))
self.msg.template(78) self.msg.template(78)
self._calc_sizes() self._calc_sizes()
print("| {0}Size of removed dependencies {1} {2}{3}".format( print("| {0}Size of removed dependencies {1} {2}{3}".format(
self.meta.color["GREY"], round(self.size, 2), self.unit, self.grey, round(self.size, 2), self.unit, self.endc))
self.meta.color["ENDC"]))
self.msg.template(78) self.msg.template(78)
return dependencies return dependencies
@ -298,8 +292,7 @@ class PackageManager:
"""removepkg Slackware command """removepkg Slackware command
""" """
try: try:
subprocess.call("removepkg {0} {1}".format(self.flag, package), subprocess.call(f"removepkg {self.flag} {package}", shell=True)
shell=True)
if os.path.isfile(self.dep_path + package): if os.path.isfile(self.dep_path + package):
os.remove(self.dep_path + package) # remove log os.remove(self.dep_path + package) # remove log
except subprocess.CalledProcessError as er: except subprocess.CalledProcessError as er:
@ -354,17 +347,14 @@ class PackageManager:
deps = Utils().read_file(self.dep_path + pkg) deps = Utils().read_file(self.dep_path + pkg)
for rmv in removes: for rmv in removes:
if GetFromInstalled(rmv).name() and rmv in deps.split(): if GetFromInstalled(rmv).name() and rmv in deps.split():
pkg_dep.append( pkg_dep.append(f"{rmv} is dependency of the package --> {pkg}")
"{0} is dependency of the package --> {1}".format(
rmv, pkg))
package.append(pkg) package.append(pkg)
dependency.append(rmv) dependency.append(rmv)
if package: if package:
if "--checklist" in self.extra: if "--checklist" in self.extra:
text = ("Press 'spacebar' to choose packages for the" text = ("Press 'spacebar' to choose packages for the"
" remove exception") " remove exception")
backtitle = "{0} {1}".format(self.meta.__all__, backtitle = f"{self.meta.__all__} {self.meta.__version__}"
self.meta.__version__)
status = False status = False
choose = DialogUtil(pkg_dep, text, " !!! WARNING !!! ", choose = DialogUtil(pkg_dep, text, " !!! WARNING !!! ",
backtitle, status).checklist() backtitle, status).checklist()
@ -373,15 +363,11 @@ class PackageManager:
else: else:
self.msg.template(78) self.msg.template(78)
print("| {0}{1}{2}".format( print("| {0}{1}{2}".format(
self.meta.color["RED"], " " * 30 + "!!! WARNING !!!", self.red, " " * 30 + "!!! WARNING !!!", self.endc))
self.meta.color["ENDC"]))
self.msg.template(78) self.msg.template(78)
for p, d in zip(package, dependency): for p, d in zip(package, dependency):
print("| {0}{1}{2} is dependency of the package --> " print(f"| {self.yellow}{d}{self.endc} is dependency of the package --> "
"{3}{4}{5}".format(self.meta.color["YELLOW"], d, f"{self.green}{p}{self.endc}")
self.meta.color["ENDC"],
self.meta.color["GREEN"], p,
self.meta.color["ENDC"]))
self.msg.template(78) self.msg.template(78)
self._skip_remove() self._skip_remove()
@ -393,13 +379,13 @@ class PackageManager:
msg_pkg = "package" msg_pkg = "package"
if len(removes) > 1: if len(removes) > 1:
msg_pkg = "packages" msg_pkg = "packages"
print("| Total {0} {1} removed".format(len(removes), msg_pkg)) print(f"| Total {len(removes)} {msg_pkg} removed")
self.msg.template(78) self.msg.template(78)
for pkg in removes: for pkg in removes:
if not GetFromInstalled(pkg).name(): if not GetFromInstalled(pkg).name():
print("| Package {0} removed".format(pkg)) print(f"| Package {pkg} removed")
else: else:
print("| Package {0} not found".format(pkg)) print(f"| Package {pkg} not found")
self.msg.template(78) self.msg.template(78)
print() # new line at end print() # new line at end
@ -410,8 +396,7 @@ class PackageManager:
pkg_cache, match_cache = "", "" pkg_cache, match_cache = "", ""
slack_packages, slack_names = slackware_repository() slack_packages, slack_names = slackware_repository()
print("\nPackages with matching name [ {0}{1}{2} ]\n".format( print("\nPackages with matching name [ {0}{1}{2} ]\n".format(
self.meta.color["CYAN"], ", ".join(self.binary), self.cyan, ", ".join(self.binary), self.endc))
self.meta.color["ENDC"]))
for pkg in self.binary: for pkg in self.binary:
for match in find_package("", self.meta.pkg_path): for match in find_package("", self.meta.pkg_path):
pkg_cache = pkg pkg_cache = pkg
@ -434,9 +419,7 @@ class PackageManager:
for pkgs in packages: for pkgs in packages:
matching += 1 matching += 1
self._sizes(pkgs) self._sizes(pkgs)
print("[ {0}installed{1} ] [ {2} ] - {3}".format( print(f"[ {self.green}installed{self.endc} ] [ {self.file_size} ] - {pkgs}")
self.meta.color["GREEN"], self.meta.color["ENDC"],
self.file_size, pkgs))
if matching == 0: if matching == 0:
message = "Can't find" message = "Can't find"
self.msg.pkg_not_found("", ", ".join(self.binary), message, "\n") self.msg.pkg_not_found("", ", ".join(self.binary), message, "\n")
@ -446,10 +429,9 @@ class PackageManager:
print("\nFound summary") print("\nFound summary")
print("=" * 79) print("=" * 79)
print("{0}Total found {1} matching packages.{2}".format( print("{0}Total found {1} matching packages.{2}".format(
self.meta.color["GREY"], matching, self.meta.color["ENDC"])) self.grey, matching, self.endc))
print("{0}Size of installed packages {1} {2}.{3}\n".format( print("{0}Size of installed packages {1} {2}.{3}\n".format(
self.meta.color["GREY"], round(self.size, 2), self.unit, self.grey, round(self.size, 2), self.unit, self.endc))
self.meta.color["ENDC"]))
def _sizes(self, package): def _sizes(self, package):
"""Package size summary """Package size summary
@ -472,8 +454,7 @@ class PackageManager:
for pkg in self.binary: for pkg in self.binary:
name = GetFromInstalled(pkg).name() name = GetFromInstalled(pkg).name()
ver = GetFromInstalled(pkg).version() ver = GetFromInstalled(pkg).version()
find = find_package("{0}{1}{2}".format(name, ver, self.meta.sp), find = find_package(f"{name}{ver}{self.meta.sp}", self.meta.pkg_path)
self.meta.pkg_path)
if find: if find:
package = Utils().read_file( package = Utils().read_file(
self.meta.pkg_path + "".join(find)) self.meta.pkg_path + "".join(find))
@ -501,28 +482,16 @@ class PackageManager:
print() print()
for pkg in sorted(pkg_list): for pkg in sorted(pkg_list):
pkg = self._splitting_packages(pkg, repo, name) pkg = self._splitting_packages(pkg, repo, name)
if installed: if installed and repo:
if repo == "sbo": if pkg in all_installed_names:
if pkg in all_installed_names: pkg = f"{self.green}{pkg}{self.endc}"
pkg = ("{0}{1}{2}".format(self.meta.color["GREEN"],
pkg,
self.meta.color["ENDC"]))
else:
if pkg in all_installed_names:
pkg = ("{0}{1}{2}".format(self.meta.color["GREEN"],
pkg,
self.meta.color["ENDC"]))
if INDEX: if INDEX:
index += 1 index += 1
pkg = self.list_color_tag(pkg) pkg = self.list_color_tag(pkg)
print("{0}{1}:{2} {3}".format( print(f"{self.grey}{index}:{self.endc} {pkg}")
self.meta.color["GREY"], index,
self.meta.color["ENDC"], pkg))
if index == page: if index == page:
read = input("\nPress {0}Enter{1} to " read = input(f"\nPress {self.cyan}Enter{self.endc} to continue... ")
"continue... ".format(
self.meta.color["CYAN"],
self.meta.color["ENDC"]))
if read in ["Q", "q"]: if read in ["Q", "q"]:
break break
print() # new line after page print() # new line after page
@ -567,14 +536,11 @@ class PackageManager:
packages = "" packages = ""
if repo == "sbo": if repo == "sbo":
if (os.path.isfile( if (os.path.isfile(
self.meta.lib_path + "{0}_repo/SLACKBUILDS.TXT".format( self.meta.lib_path + f"{repo}_repo/SLACKBUILDS.TXT")):
repo))): packages = Utils().read_file(self.meta.lib_path + f"{repo}_repo/SLACKBUILDS.TXT")
packages = Utils().read_file(self.meta.lib_path + "{0}_repo/"
"SLACKBUILDS.TXT".format(repo))
else: else:
if (os.path.isfile( if (os.path.isfile(
self.meta.lib_path + "{0}_repo/PACKAGES.TXT".format( self.meta.lib_path + f"{repo}_repo/PACKAGES.TXT")):
repo))):
packages = Utils().read_file(self.meta.lib_path + "{0}_repo/" packages = Utils().read_file(self.meta.lib_path + "{0}_repo/"
"PACKAGES.TXT".format(repo)) "PACKAGES.TXT".format(repo))
return packages return packages
@ -587,8 +553,7 @@ class PackageManager:
if pkg.endswith(".txz") or pkg.endswith(".tgz"): if pkg.endswith(".txz") or pkg.endswith(".tgz"):
find = pkg[:-4] find = pkg[:-4]
if find_package(find, self.meta.pkg_path): if find_package(find, self.meta.pkg_path):
pkg = "{0}{1}{2}".format(self.meta.color["GREEN"], pkg, pkg = f"{self.green}{pkg}{self.endc}"
self.meta.color["ENDC"])
return pkg return pkg
def list_of_installed(self, repo, name): def list_of_installed(self, repo, name):