general py3 changes, regex fixes

py3_forced
idziubenko 3 years ago
parent 57df4358f0
commit f30a4133f0

@ -119,7 +119,7 @@ def progressCopyFile(source, dest):
bufsize = (100 - (size % 100) + size) / 100
with open(source, 'rb') as infile:
with open(dest, 'w') as outfile:
for i in xrange(1, 101):
for i in range(1, 101):
outfile.write(infile.read(bufsize))
yield i
@ -430,7 +430,7 @@ class Distributive():
def rndString(self):
"""Get random string with len 8 char"""
return "".join([choice(string.ascii_letters + string.digits)
for i in xrange(0, 8)])
for i in range(0, 8)])
def _getSquashNum(self, reMatch):
if reMatch.groups()[1] and reMatch.groups()[1].isdigit():
@ -848,7 +848,7 @@ class FormatProcess(process):
self._label = label
self.purpose = purpose
self.compression = compression
super(FormatProcess, self).__init__(*self.format_command())
super().__init__(*self.format_command())
def format_command(self):
cmd = getProgPath(self.format_util)
@ -1877,7 +1877,7 @@ class FlashDistributive(PartitionDistributive):
raise DistributiveError(
_("Failed to remove %s") % fn)
else:
super(FlashDistributive, self).performFormat()
super().performFormat()
def getType(self):
return _("USB flash %s") % self.partition
@ -1910,7 +1910,7 @@ class FlashDistributive(PartitionDistributive):
d = DirectoryDistributive(mp)
d.no_unmount = True
return d
return super(FlashDistributive, self).convertToDirectory()
return super().convertToDirectory()
def releaseChild(self, child):
"""Umount child Directory distributive"""
@ -1976,7 +1976,7 @@ class LayeredDistributive(Distributive):
:param image_file: образ оригинала
:param parent: родительский дистрибутив
"""
super(LayeredDistributive, self).__init__(parent=parent)
super().__init__(parent=parent)
self.mdirectory = mdirectory
self.diff_directory = diff_directory
self.workdir = "%s-work" % self.diff_directory

@ -685,7 +685,7 @@ class Install(MethodsInterface):
"""
"""Get random string with len 8 char"""
return "".join([choice(string.ascii_letters + string.digits)
for i in xrange(0, 8)])
for i in range(0, 8)])
def _getFreeDirectory(self, directory):
"""

@ -516,7 +516,7 @@ class currentUsers(migrate):
"""Current users"""
def __init__(self):
super(currentUsers, self).__init__('/')
super().__init__('/')
def addUsers(self, *users_passwd):
"""Added users and groups to current system"""

@ -99,7 +99,7 @@ class ResolutionVariable(VideoVariable):
"""
Check resolution format 1234x567
"""
if not re.match(r'^\d+x\d+(-\d+(@\d+)?)?$', value):
if not re.match('^\d+x\d+(-\d+(@\d+)?)?$', value):
raise VariableError(
_("Wrong resolution {resolution} {example}").format(
resolution=value,

@ -132,7 +132,7 @@ class VariableOsAudioData(ReadonlyTableVariable):
def get(self, hr=HumanReadable.No):
# /proc/asound/card*/pcm*p/info
data = readFile('/proc/asound/cards')
cards = re.findall(r'^\s*(\d+).*\s-\s(.+)\n\s+\S.* at .*$',
cards = re.findall('^\s*(\d+).*\s-\s(.+)\n\s+\S.* at .*$',
data, re.M)
if cards:
return list(self.generate_cards(cards))
@ -209,12 +209,12 @@ class VariableOsAudioHw(Variable):
def get_deprecated(self):
asound_data = readFile('/etc/asound.conf')
default_card_re = re.compile(r'defaults.ctl.card\s+(\d+)')
default_card_re = re.compile('defaults.ctl.card\s+(\d+)')
entry = default_card_re.search(asound_data)
if entry and entry.groups()[0] in self.Get('os_audio_id'):
return "%s,0" % entry.groups()[0]
default_card_re = re.compile(
r'pcm.!default {[^}]+card\s+(\d+)[^}]+device\s+(\d+)[^}]+}')
'pcm.!default {[^}]+card\s+(\d+)[^}]+device\s+(\d+)[^}]+}')
entry = default_card_re.search(asound_data)
if entry:
entry = "%s,%s" % entry.groups()

@ -43,16 +43,16 @@ class SizeHelper(VariableInterface):
def set(self, value):
# convert table from value to MB
sizeMap = {r'kB': Sizes.kB,
r'K': Sizes.K,
r'M': Sizes.M,
r'Mb': Sizes.Mb,
r'G': Sizes.G,
r'Gb': Sizes.Gb,
r'T': Sizes.T,
r'Tb': Sizes.Tb}
sizeMap = {'kB': Sizes.kB,
'K': Sizes.K,
'M': Sizes.M,
'Mb': Sizes.Mb,
'G': Sizes.G,
'Gb': Sizes.Gb,
'T': Sizes.T,
'Tb': Sizes.Tb}
value = value.strip()
reSizeValue = re.compile(r'^(\d+)\s*(%s)?' % r"|".join(sizeMap.keys()))
reSizeValue = re.compile('^(\d+)\s*(%s)?' % "|".join(sizeMap.keys()))
res = reSizeValue.search(value)
if not res:
return "0"
@ -147,7 +147,7 @@ class VariableClAutopartitionDeviceData(ReadonlyTableVariable):
'cl_autopartition_device_size',
'cl_autopartition_device_name']
re_raid = re.compile(r"raid[1-9]")
re_raid = re.compile("raid[1-9]")
def get(self, hr=HumanReadable.No):
def generator():
@ -287,7 +287,7 @@ class VariableClAutopartitionDevice(AutopartitionHelper, Variable):
"""
Проверить схемы RAID, чтобы исключить базирование их на lvm
"""
typecheck = re.compile(r"lvm.*raid")
typecheck = re.compile("lvm.*raid")
for dev, fulltype in self.ZipVars("os_device_dev",
"os_device_fulltype"):
if dev in valuelist:
@ -783,7 +783,7 @@ class VariableClAutopartitionDiskSize(DiskFilter, ReadonlyVariable):
field = "disk_size"
def get(self):
return [str(x) for x in super(VariableClAutopartitionDiskSize, self).get()]
return [str(x) for x in super().get()]
def humanReadable(self):
return [humanreadableSize(x) for x in self.Get()]
@ -1027,7 +1027,7 @@ class VariableClAutopartitionBindPath(FieldValue, ReadonlyVariable):
column = 0
def get(self):
return list(super(VariableClAutopartitionBindPath, self).get())
return list(super().get())
class VariableClAutopartitionBindMountpoint(FieldValue, ReadonlyVariable):
"""
@ -1038,4 +1038,4 @@ class VariableClAutopartitionBindMountpoint(FieldValue, ReadonlyVariable):
column = 1
def get(self):
return list(super(VariableClAutopartitionBindMountpoint, self).get())
return list(super().get())

@ -45,8 +45,8 @@ setLocalTranslate('cl_install3', sys.modules[__name__])
class DeviceHelper(VariableInterface):
rePassDevice = re.compile(r"^/block/(?!%s)" % r"|".join([r'sr', r'fd',
r'ram', r'loop']))
rePassDevice = re.compile("^/block/(?!%s)" % "|".join(['sr', 'fd',
'ram', 'loop']))
def getBlockDevices(self):
"""Get interest devices from sys block path"""
@ -58,7 +58,7 @@ class DeviceHelper(VariableInterface):
Using for sort. (Example: sda2 ("sda",2), md5p1 ("md",5,"p",1)
"""
return [int(x) if x.isdigit() else x for x in re.findall(r'\d+|\D+', dev)]
return [int(x) if x.isdigit() else x for x in re.findall('\d+|\D+', dev)]
def mapUdevProperty(self, var, prop, default):
"""Get each element from var through udev [prop]"""
@ -162,7 +162,7 @@ class VariableOsDeviceDev(DeviceHelper, ReadonlyVariable):
Disk devices
"""
type = "list"
re_disk_raid = re.compile(r"^disk-.*-raid\d+$", re.I)
re_disk_raid = re.compile("^disk-.*-raid\d+$", re.I)
def init(self):
pass
@ -512,7 +512,7 @@ class VariableOsDiskDev(DeviceHelper, ReadonlyVariable):
def get(self):
# получить блочные утсройства, в списке устройства с таблицей раздела
# разделены '/'
re_parent = re.compile(r"^/block/[^/]+")
re_parent = re.compile("^/block/[^/]+")
disks = self.getBlockDevices()
parents = {re_parent.search(x).group()
for x in disks if x.count("/") > 2}
@ -584,8 +584,8 @@ class VariableOsDiskType(ReadonlyVariable):
List type (lvm,raid,partition,disk)
"""
type = "list"
re_raid = re.compile(r"-raid\d+$")
re_raid_partition = re.compile(r"-raid\d+-partition$")
re_raid = re.compile("-raid\d+$")
re_raid_partition = re.compile("-raid\d+-partition$")
def get(self):
"""Get partition scheme"""
@ -1167,7 +1167,7 @@ class VariableOsLocationDest(LocationHelper, Variable):
##########################
# detect efi specifing
##########################
reEfi = re.compile(r"/u?efi", re.I)
reEfi = re.compile("/u?efi", re.I)
if any(reEfi.search(x) for x in value):
if self.Get('cl_client_type') == 'gui':
raise VariableError(
@ -2009,7 +2009,7 @@ class VariableOsInstallUefi(LocationHelper, Variable):
opt = ["--uefi"]
metavalue = "EFI"
re_not0_raid = re.compile(r"-raid[1-9]")
re_not0_raid = re.compile("-raid[1-9]")
def init(self):
self.label = _("UEFI boot")

@ -42,21 +42,21 @@ setLocalTranslate('cl_install3', sys.modules[__name__])
class DistroRepository(Linux):
contentCache = {}
marches = [r'i686', r'x86_64']
marches = ['i686', 'x86_64']
extensiton = [r'iso', r'tar.bz2', r'tar.gz', r'tar.7z', r'tar.lzma']
extensiton = ['iso', 'tar.bz2', 'tar.gz', 'tar.7z', 'tar.lzma']
reDistName = re.compile(r"""
reDistName = re.compile("""
^.*/(?P<os_linux_shortname>%(name)s)
-(?P<os_linux_ver>%(ver)s)
(?:-(?P<serial_id>%(ser)s))?
-(?P<os_arch_machine>%(march)s)
.(?P<ext>%(ext)s)$""" %
{r'name': r"[a-z0-9]+",
r'ver': r"(\d+\.)*\d+",
r'ser': r"\d+",
r'march': r"|".join(marches),
r'ext': r"|".join(extensiton)
{'name': "[a-z0-9]+",
'ver': r"(\d+\.)*\d+",
'ser': r"\d+",
'march': "|".join(marches),
'ext': "|".join(extensiton)
}, re.X)
def _getDistrInfo(self, filename):
@ -71,9 +71,9 @@ class DistroRepository(Linux):
distdic = match.groupdict()
distdic["os_linux_build"] = ""
if "os_linux_ver" in distdic:
if re.match(r"^\d{8}$", distdic["os_linux_ver"]):
distdic[r"os_linux_build"] = distdic["os_linux_ver"]
distdic[r"os_linux_ver"] = ""
if re.match("^\d{8}$", distdic["os_linux_ver"]):
distdic["os_linux_build"] = distdic["os_linux_ver"]
distdic["os_linux_ver"] = ""
return distdic
def getImage(self, scratch, rootType, imagePath, march=None,
@ -99,7 +99,7 @@ class DistroRepository(Linux):
return sorted(list(set([x.groupdict()['name'] for x in distros])))
def opcompareByString(self, buf):
if buf:
reOp = re.compile(r"^(!=|=|==|<=|>=|>|<)?(\d+.*)$")
reOp = re.compile("^(!=|=|==|<=|>=|>|<)?(\d+.*)$")
res = reOp.search(buf)
if res:
return ({'!=': operator.ne,
@ -245,15 +245,15 @@ class DistroRepository(Linux):
def getBestStage(self, dirs, march=None, hardened=None):
"""Get latest stage by march"""
if march:
march = {r'x86_64': r'amd64'}.get(march, march)
march = {'x86_64': 'amd64'}.get(march, march)
else:
march = r"[^-]+"
march = "[^-]+"
if hardened is None:
hardened = r"(?:-hardened)?"
hardened = "(?:-hardened)?"
elif hardened is True:
hardened = r"-hardened"
hardened = "-hardened"
elif hardened is False:
hardened = r""
hardened = ""
reStage = re.compile(r'^.*/stage3-%s%s-(\d+)\.tar\.bz2$' %
(march, hardened), re.S)
return self._findLatestFile(dirs, reStage, lambda x: x.groups()[0])

@ -142,10 +142,10 @@ class VariableOsInstallKernelConfig(ReadonlyVariable):
makefile_path = path.join(distr_path, kernel_src, "Makefile")
# get version from Makefile
re_makefile = re.compile(r"^VERSION = (\S+)\n"
r"PATCHLEVEL = (\S+)\n"
r"SUBLEVEL = (\S+)\n"
r"EXTRAVERSION = (\S*)\n", re.M)
re_makefile = re.compile("^VERSION = (\S+)\n"
"PATCHLEVEL = (\S+)\n"
"SUBLEVEL = (\S+)\n"
"EXTRAVERSION = (\S*)\n", re.M)
if path.exists(makefile_path):
with open(makefile_path) as f:
match = re_makefile.search(f.read(200))
@ -332,7 +332,7 @@ class KernelHelper(VariableInterface):
Helper for kernel variables
"""
reFindVer = re.compile(
r"(?<=version )(\d+\.?\d*\.?\d*\.?\d*)([^\d* ])*(\d*)")
"(?<=version )(\d+\.?\d*\.?\d*\.?\d*)([^\d* ])*(\d*)")
def getFilesByType(self, pathname, descr):
"""Get files from "pathname" has "descr" in descriptions"""
@ -348,7 +348,7 @@ class KernelHelper(VariableInterface):
def getInitrd(self, arch, shortname, chroot, kernel, suffix="",
notsuffix=""):
"""Get initrd for kernel"""
reInitrdVer = re.compile(r"(initrd|initramfs)-(.+?)(-install)?$", re.S)
reInitrdVer = re.compile("(initrd|initramfs)-(.+?)(-install)?$", re.S)
def initrd_version_by_name(filename):
resInitrdVer = reInitrdVer.search(filename)

@ -855,7 +855,7 @@ class VariableOsInstallNetDnsSearch(NetHelper, Variable):
return False
def set(self, value):
return " ".join(re.split(r'[; ,]', value))
return " ".join(re.split('[; ,]', value))
def get(self):
"""Get current name servers"""
@ -882,7 +882,7 @@ class VariableOsInstallNetDns(VariableOsInstallNetDnsSearch):
self.help = _("domain name server (comma-separated)")
def set(self, value):
return " ".join(re.split(r'[; ,]', value))
return " ".join(re.split('[; ,]', value))
def get(self):
dnsIps = (x for x

@ -69,7 +69,7 @@ class GrubHelper(VariableInterface):
Получить пароль из конфигурационного файла grub
"""
data = readFile(self.grub_passwd_file)
reRootPwd = re.compile(r"password_pbkdf2 root (\S+)")
reRootPwd = re.compile("password_pbkdf2 root (\S+)")
pwd = reRootPwd.search(data)
if pwd:
return pwd.group(1)
@ -712,7 +712,7 @@ class VariableOsNvidiaMask(ReadonlyVariable):
nvidiacards = [x for x in process(lsPciProg, "-d", vendor, "-n")
if " %s: " % category in x]
cardsid = [x.groups()[0] for x
in [re.search(r"[0-9a-fA-F]{4}:([0-9a-fA-F]{4})", y) for y in nvidiacards] if x]
in [re.search("[0-9a-fA-F]{4}:([0-9a-fA-F]{4})", y) for y in nvidiacards] if x]
if not cardsid:
return set()
return set(cardsid)
@ -737,7 +737,7 @@ class VariableOsNvidiaMask(ReadonlyVariable):
eclassdata = readFile(nvidiaeclass)
reBlock = re.compile(
r"if has \$\{nvidia_gpu\}\s+\\([^;]+);\s*then(.*?)fi", re.S)
reMask = re.compile(r'>=x11-drivers/nvidia-drivers[^"]+')
reMask = re.compile('>=x11-drivers/nvidia-drivers[^"]+')
masks = []
for block in reBlock.findall(eclassdata):
nvidia_ids, mask_data = block
@ -954,7 +954,7 @@ class VariableOsInstallGrubTerminal(Variable):
if getValueFromConfig(grubDefault, 'GRUB_TERMINAL') == 'console':
return 'console'
grubCfg = '/boot/grub/grub.cfg'
if re.search(r'^terminal_output\s*console', readFile(grubCfg), re.M):
if re.search('^terminal_output\s*console', readFile(grubCfg), re.M):
return 'console'
return 'gfxterm'

@ -72,12 +72,12 @@ class install_data(module_install_data.install_data):
data_files = []
data_files += [('/etc/init.d', [('data/calculate',0755)]),
('/usr/bin',[('bin/xautologin',0755)]),
data_files += [('/etc/init.d', [('data/calculate',0o755)]),
('/usr/bin',[('bin/xautologin',0o755)]),
('/usr/share/calculate/doc', ['data/handbook-en.html',
'data/handbook-ru.html']),
('/usr/libexec/calculate', [('data/cl-video-install', 0755)]),
('/bin',[('bin/bashlogin',0755)])]
('/usr/libexec/calculate', [('data/cl-video-install', 0o755)]),
('/bin',[('bin/bashlogin',0o755)])]
packages = [
"calculate."+str('.'.join(root.split(os.sep)[1:]))

Loading…
Cancel
Save