Improving code for Python 3

Signed-off-by: Dimitris Zlatanidis <d.zlatanidis@gmail.com>
This commit is contained in:
Dimitris Zlatanidis 2020-01-11 14:12:21 +01:00
parent 8e341f918c
commit 72a7a77250
6 changed files with 51 additions and 66 deletions

View file

@ -36,6 +36,10 @@ class Config:
def __init__(self):
self.config_file = "/etc/slpkg/slpkg.conf"
self.meta = _meta_
self.green = _meta_.color["GREEN"]
self.red = _meta_.color["RED"]
self.cyan = _meta_.color["CYAN"]
self.endc = _meta_.color["ENDC"]
def view(self):
"""View slpkg config file
@ -70,25 +74,20 @@ class Config:
read_conf = Utils().read_file(self.config_file)
for line in read_conf.splitlines():
if not line.startswith("#") and line.split("=")[0] in conf_args:
print("{0}".format(line))
print(line)
else:
print("{0}{1}{2}".format(self.meta.color["CYAN"], line,
self.meta.color["ENDC"]))
print() # new line at end
print(f"{self.cyan}{line}{self.endc}", end="\n")
def edit(self):
"""Edit configuration file
"""
subprocess.call("{0} {1}".format(self.meta.editor,
self.config_file), shell=True)
subprocess.call(f"{self.meta.editor} {self.config_file}", shell=True)
def reset(self):
"""Reset slpkg.conf file with default values
"""
shutil.copy2(self.config_file + ".orig", self.config_file)
if filecmp.cmp(self.config_file + ".orig", self.config_file):
print("{0}The reset was done{1}".format(
self.meta.color["GREEN"], self.meta.color["ENDC"]))
print(f"{self.green}The reset was done{self.endc}")
else:
print("{0}Reset failed{1}".format(self.meta.color["RED"],
self.meta.color["ENDC"]))
print(f"{self.red}Reset failed{self.endc}")

View file

@ -38,20 +38,17 @@ class PkgDesc:
self.paint = paint
self.meta = _meta_
self.msg = Msg()
self.COLOR = ""
self.lib = ""
color_text = {
self.color = {
"red": self.meta.color["RED"],
"green": self.meta.color["GREEN"],
"yellow": self.meta.color["YELLOW"],
"cyan": self.meta.color["CYAN"],
"grey": self.meta.color["GREY"],
"": ""
}
self.COLOR = color_text[self.paint]
}[self.paint]
if self.repo in self.meta.repositories and self.repo != "sbo":
self.lib = self.meta.lib_path + "{0}_repo/PACKAGES.TXT".format(
self.repo)
self.lib = f"{self.meta.lib_path}{self.repo}_repo/PACKAGES.TXT"
def view(self):
"""Print package description by repository
@ -69,8 +66,7 @@ class PkgDesc:
if count == 11:
break
if description:
print("{0}{1}{2}".format(self.COLOR, description,
self.meta.color["ENDC"]))
print(f"{self.color}{description}{self.meta.color['ENDC']}")
else:
self.msg.pkg_not_found("", self.name, "No matching", "\n")
raise SystemExit(1)

View file

@ -42,6 +42,9 @@ class Download:
self.repo = repo
self.file_name = ""
self.meta = _meta_
self.green = _meta_.color["GREEN"]
self.red = _meta_.color["RED"]
self.endc = _meta_.color["ENDC"]
self.msg = Msg()
self.dir_prefix = ""
self.downder = self.meta.downder
@ -61,24 +64,13 @@ class Download:
self._make_tarfile(self.file_name, source_dir)
self._check_certificate()
print("\n[{0}/{1}][ {2}Download{3} ] --> {4}\n".format(
dwn_count, len(self.url), self.meta.color["GREEN"],
self.meta.color["ENDC"],
self.file_name))
print(f"\n[{dwn_count}/{len(self.url)}][ {self.green}Download{self.endc} ] --> {self.file_name}\n")
if self.downder in ["wget"]:
subprocess.call("{0} {1} {2}{3} {4}".format(
self.downder, self.downder_options,
self.dir_prefix, self.path, dwn),
shell=True)
subprocess.call(f"{self.downder} {self.downder_options} {self.dir_prefix}{self.path} {dwn}", shell=True)
if self.downder in ["aria2c"]:
subprocess.call("{0} {1} {2}{3} {4}".format(
self.downder, self.downder_options,
self.dir_prefix, self.path[:-1], dwn),
shell=True)
subprocess.call(f"{self.downder} {self.downder_options} {self.dir_prefix}{self.path[:-1]} {dwn}", shell=True)
elif self.downder in ["curl", "http"]:
subprocess.call("{0} {1} {2}{3} {4}".format(
self.downder, self.downder_options,
self.path, self.file_name, dwn), shell=True)
subprocess.call(f"{self.downder} {self.downder_options} {self.path}{self.file_name} {dwn}", shell=True)
self._check_if_downloaded()
dwn_count += 1
@ -102,9 +94,7 @@ class Download:
if not os.path.isfile(self.path + self.file_name):
print()
self.msg.template(78)
print("| Download '{0}' file [ {1}FAILED{2} ]".format(
self.file_name, self.meta.color["RED"],
self.meta.color["ENDC"]))
print(f"| Download '{self.file_name}' file [ {self.red}FAILED{self.endc} ]")
self.msg.template(78)
print()
if not self.msg.answer() in ["y", "Y"]:
@ -118,10 +108,9 @@ class Download:
certificate = (' --no-check-certificate --header="Cookie: '
'oraclelicense=accept-securebackup-cookie"')
self.msg.template(78)
print("| '{0}' need to go ahead downloading".format(
certificate[:23].strip()))
print(f"| '{certificate[:23].strip()}' need to go ahead downloading")
self.msg.template(78)
print()
self.downder_options += certificate
if not self.msg.answer() in ["y", "Y"]:
raise SystemExit()
raise SystemExit()

View file

@ -26,6 +26,12 @@ import os
import subprocess
# class ImportErrorGraphEasy(Exception):
# def __init__(self, GraphEasyImportError):
# Exception.__init__(self, "graph-easy required")
# self.GraphEasyImportError = GraphEasyImportError
class Graph:
"""Drawing dependencies diagram
"""
@ -46,13 +52,10 @@ class Graph:
try:
import pygraphviz as pgv
except ImportError:
graph_easy, comma = "", ""
if (self.image == "ascii" and
not os.path.isfile("/usr/bin/graph-easy")):
comma = ","
graph_easy = " graph-easy"
print("Require 'pygraphviz{0}{1}': Install with 'slpkg -s sbo "
"pygraphviz{1}'".format(comma, graph_easy))
if self.image == "ascii" and not os.path.isfile("/usr/bin/graph-easy"):
print("Require 'grap_easy': Install with 'slpkg -s sbo graph-easy'")
else:
print("Require 'pygraphviz: Install with 'slpkg -s sbo pygraphviz'")
raise SystemExit()
if self.image != "ascii":
self.check_file()
@ -91,12 +94,12 @@ class Graph:
"graph-easy'")
self.remove_dot()
raise SystemExit()
subprocess.call("graph-easy {0}.dot".format(self.image), shell=True)
subprocess.call(f"graph-easy {self.image}.dot", shell=True)
self.remove_dot()
raise SystemExit()
def remove_dot(self):
"""Remove .dot files
"""
if os.path.isfile("{0}.dot".format(self.image)):
os.remove("{0}.dot".format(self.image))
if os.path.isfile(f"{self.image}.dot"):
os.remove(f"{self.image}.dot")

View file

@ -39,11 +39,11 @@ def pkg_checksum(binary, repo):
elif repo == "slpkg":
CHECKSUMS_md5 = URL(_meta_.CHECKSUMS_link).reading()
else:
lib = "{0}{1}_repo/CHECKSUMS.md5".format(_meta_.lib_path, repo)
lib = f"{_meta_.lib_path}{repo}_repo/CHECKSUMS.md5"
f = open(lib, "r")
CHECKSUMS_md5 = f.read()
f.close()
for line in CHECKSUMS_md5.splitlines():
if line.endswith("/{0}".format(binary)):
if line.endswith(f"/{binary}"):
md5 = line.split()[0]
return md5

View file

@ -36,6 +36,10 @@ class PackageHealth:
def __init__(self, mode):
self.mode = mode
self.meta = _meta_
self.green = _meta_.color["GREEN"]
self.red = _meta_.color["RED"]
self.yellow = _meta_.color["YELLOW"]
self.endc = _meta_.color["ENDC"]
self.msg = Msg()
self.pkg_path = _meta_.pkg_path
self.installed = []
@ -56,9 +60,7 @@ class PackageHealth:
"/incoming/" not in line):
if not os.path.isfile(r"/" + line):
self.cn += 1
print("Not installed: {0}/{1}{2} --> {3}".format(
self.meta.color["RED"], line, self.meta.color["ENDC"],
pkg))
print(f"Not installed: {self.red}/{line}{self.endc} --> {pkg}")
elif not self.mode:
print(line)
except IOError:
@ -76,7 +78,7 @@ class PackageHealth:
with open(self.pkg_path + pkg, "r") as fopen:
for line in fopen:
if "\0" in line:
print("Null: {0}").format(line)
print(f"Null: {line}")
break
self.cf += 1 # count all files
self.lf += 1 # count each package files
@ -90,18 +92,14 @@ class PackageHealth:
print()
per = int(round((float(self.cf) / (self.cf + self.cn)) * 100))
if per > 90:
color = self.meta.color["GREEN"]
color = self.green
elif per < 90 and per > 60:
color = self.meta.color["YELLOW"]
color = self.yellow
elif per < 60:
color = self.meta.color["RED"]
health = "{0}{1}%{2}".format(color, str(per), self.meta.color["ENDC"])
color = self.red
health = f"{color}{str(per)}%{self.endc}"
self.msg.template(78)
print("| {0}{1}{2}{3}{4}".format(
"Total files", " " * 7, "Not installed", " " * 40, "Health"))
self.msg.template(78)
print("| {0}{1}{2}{3}{4:>4}".format(
self.cf, " " * (18-len(str(self.cf))),
self.cn, " " * (55-len(str(self.cn))),
health))
print(f"| Total files{' ' * 7}Not installed{' ' * 40}Health")
self.msg.template(78)
print(f"| {self.cf}{' ' * (18-len(str(self.cf)))}{self.cn}{' ' * (55-len(str(self.cn)))}{health:>4}")
self.msg.template(78)