From 2a21a37ab41d013dac8d5e6f636d5dc9a98c2d15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alin=20Tr=C4=83istaru?= Date: Wed, 3 May 2017 21:08:26 +0300 Subject: [PATCH] code cleanup --- scripts/debug.py | 9 ++++---- scripts/distro.py | 19 +++++++---------- scripts/gen.py | 8 +++---- scripts/grub.py | 31 ++++++++++++--------------- scripts/imager.py | 48 +++++++++++++++--------------------------- scripts/iso.py | 17 ++++----------- scripts/persistence.py | 4 +--- scripts/qemu.py | 33 ++++++++++++----------------- scripts/syslinux.py | 7 +++--- scripts/udisks.py | 17 ++++----------- scripts/usb.py | 32 ++++++++++++---------------- 11 files changed, 87 insertions(+), 138 deletions(-) diff --git a/scripts/debug.py b/scripts/debug.py index 2e6339c..3a3805c 100644 --- a/scripts/debug.py +++ b/scripts/debug.py @@ -1,5 +1,4 @@ import os -import platform import inspect from . import config @@ -8,8 +7,8 @@ try: except: try: from .colorama import init as colorama_init, Fore, Back, Style - except: - pass + except Exception as e: + raise e finally: try: colorama_init(autoreset=True) @@ -38,7 +37,8 @@ def fnCall(): Prints filename:line:function for parent and grandparent. """ - if not config.debug: return + if not config.debug: + return print(colors.OKGREEN + colors.BOLD + "=== DEBUG === | %s:%d:%s() called from %s:%d:%s()" % ( inspect.stack()[1][1].split(os.sep)[-1], @@ -48,4 +48,3 @@ def fnCall(): inspect.stack()[2][2], inspect.stack()[2][3], )+colors.RESET) - diff --git a/scripts/distro.py b/scripts/distro.py index aa1c265..0456a95 100644 --- a/scripts/distro.py +++ b/scripts/distro.py @@ -7,7 +7,6 @@ # under the terms of GNU General Public License, v.2 or above import os -import string import platform import re from .iso import * @@ -32,7 +31,7 @@ def distro(iso_cfg_ext_dir, iso_link): if name.endswith(('.cfg', '.CFG', '.txt', '.TXT', '.lst')): try: # errors='ignore' is required as some files also contain non utf character - string = open(os.path.join(path, name), errors='ignore').read() + string = open(os.path.join(path, name), errors='ignore').read() except IOError: return "Read Error." else: @@ -143,15 +142,13 @@ def distro(iso_cfg_ext_dir, iso_link): if distro: return distro # FIXME: See the below comments. - ''' - else: - # FIXME: The idea of detecting as generic is to work like a unetbootin if other methods fails. - # This simply extracts distro to root of the USB and install syslinux on isolinux.bin directory. - # All works fine but unable to boot the distro successfully. Also, see the generic section from - # syslinux, update_cfg and install_distro modules. - if self.isolinux_bin_exist(): - return "generic" - ''' +# else: +# # FIXME: The idea of detecting as generic is to work like a unetbootin if other methods fails. +# # This simply extracts distro to root of the USB and install syslinux on isolinux.bin directory. +# # All works fine but unable to boot the distro successfully. Also, see the generic section from +# # syslinux, update_cfg and install_distro modules. +# if self.isolinux_bin_exist(): +# return "generic" else: return None diff --git a/scripts/gen.py b/scripts/gen.py index 9a7fc8e..6c12966 100644 --- a/scripts/gen.py +++ b/scripts/gen.py @@ -243,17 +243,17 @@ def read_input_yes(): return False -def strings(filename, min=4): +def strings(filename, _min=4): with open(filename, errors="ignore") as f: result = "" for c in f.read(): if c in string.printable: result += c continue - if len(result) >= min: + if len(result) >= _min: yield result result = "" - if len(result) >= min: # catch result at EOF + if len(result) >= _min: # catch result at EOF yield result @@ -392,7 +392,7 @@ def write_to_file(filepath, text): Simple function to write a text file :param filepath: Path to file :param text: Text to be written on to file - :return: + :return: """ with open(filepath, 'w') as f: f.write(text.strip()) diff --git a/scripts/grub.py b/scripts/grub.py index b13d66e..ff7ba5a 100644 --- a/scripts/grub.py +++ b/scripts/grub.py @@ -147,19 +147,16 @@ def grub_custom_menu(mbus_grub_cfg_path, distro): if distro in ['sgrubd2', 'raw_iso']: grub_raw_iso(mbus_grub_cfg_path) - ''' - with open(mbus_grub_cfg_path, 'a') as f: - f.write("#start " + iso.iso_basename(config.image_path) + "\n") - f.write(grub_raw_iso()) - f.write("#end " + iso.iso_basename(config.image_path) + "\n") - - - elif iso_size_mb < 750.0: - grub_raw_iso(mbus_grub_cfg_path) - ''' +# with open(mbus_grub_cfg_path, 'a') as f: +# f.write("#start " + iso.iso_basename(config.image_path) + "\n") +# f.write(grub_raw_iso()) +# f.write("#end " + iso.iso_basename(config.image_path) + "\n") +# +# +# elif iso_size_mb < 750.0: +# grub_raw_iso(mbus_grub_cfg_path) else: - return False @@ -207,10 +204,10 @@ def extract_kernel_line(search_text, match_line, isolinux_dir): """ Function to check if kernel/linux line present in isolinux.cfg file is valid. If valid, then convert them in to grub accepted format - :param search_text: Type of text is to be searched. Typically kernel or linux + :param search_text: Type of text is to be searched. Typically kernel or linux :param match_line: Line containing kernel ot linux from isolinux supported .cfg files :param isolinux_dir: Path to isolinux directory of an ISO - :return: Valid grub2 accepted kernel/linux line after conversion. If nothing found return ''. + :return: Valid grub2 accepted kernel/linux line after conversion. If nothing found return ''. """ kernel_line = '' @@ -250,8 +247,8 @@ def extract_kernel_line(search_text, match_line, isolinux_dir): def iso2grub2(iso_dir): """ Function to convert syslinux configuration to grub2 accepted configuration format. Features implemented are similar - to that of grub2 'loopback.cfg'. This 'loopback.cfg' file can be later on caled directly from grub2. The main - advantage of this function is to generate the 'loopback.cfg' file automatically without manual involvement. + to that of grub2 'loopback.cfg'. This 'loopback.cfg' file can be later on caled directly from grub2. The main + advantage of this function is to generate the 'loopback.cfg' file automatically without manual involvement. :param iso_dir: Path to distro install directory for looping through '.cfg' files. :param file_out: Path to 'loopback.cfg' file. By default it is set to root of distro install directory. :return: @@ -308,7 +305,7 @@ def iso2grub2(iso_dir): for _lines in kernel_text: kernel_line = extract_kernel_line(_lines[0][1], _lines[0][0], iso_bin_dir) - if kernel_line is '': + if kernel_line == '': continue else: break @@ -322,7 +319,7 @@ def iso2grub2(iso_dir): for _lines in initrd_text: initrd_line = extract_kernel_line(_lines[0][1], _lines[0][0], iso_bin_dir) - if initrd_line is '': + if initrd_line == '': continue else: break diff --git a/scripts/imager.py b/scripts/imager.py index d69c29e..c0dc652 100644 --- a/scripts/imager.py +++ b/scripts/imager.py @@ -12,9 +12,7 @@ import subprocess import collections import platform import signal -from PyQt5 import QtGui from PyQt5 import QtWidgets -from PyQt5 import QtCore from .gui.ui_multibootusb import Ui_MainWindow from .gen import * from . import iso @@ -28,15 +26,14 @@ if platform.system() == "Windows": def dd_linux(): import time - input = "if=" + config.image_path + _input = "if=" + config.image_path in_file_size = float(os.path.getsize(config.image_path)) - output = "of=" + config.usb_disk + _output = "of=" + config.usb_disk os.system("umount " + config.usb_disk + "1") - command = ['dd', input, output, "bs=1M", "oflag=sync"] + command = ['dd', _input, _output, "bs=1M", "oflag=sync"] log("Executing ==> " + " ".join(command)) dd_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) - # bar = progressbar.ProgressBar(redirect_stdout=True) pbar = progressbar.ProgressBar( maxval=100, widgets=[ @@ -73,10 +70,10 @@ def dd_win(): windd = resource_path(os.path.join("data", "tools", "dd", "dd.exe")) if os.path.exists(resource_path(os.path.join("data", "tools", "dd", "dd.exe"))): log("dd exist") - input = "if=" + config.image_path + _input = "if=" + config.image_path in_file_size = float(os.path.getsize(config.image_path) / 1024 / 1024) - output = "of=\\\.\\" + config.usb_disk - command = [windd, input, output, "bs=1M", "--progress"] + _output = "of=\\\.\\" + config.usb_disk + command = [windd, _input, _output, "bs=1M", "--progress"] log("Executing ==> " + " ".join(command)) dd_process = subprocess.Popen(command, universal_newlines=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False) @@ -127,19 +124,8 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow): self.ui.imager_iso_size.setText("ISO Size: " + self.iso_size + " MB") log("ISO Size is " + self.iso_size + " MB") -# def onImagerComboChange(self): -# config.imager_usb_disk = str(self.ui.comboBox_2.currentText()) -# if bool(config.imager_usb_disk): -# self.ui.imager_disk_label.setText(self.imager_usb_detail(config.imager_usb_disk, partition=0).usb_type) -# self.ui.imager_total_size.setText(usb.bytes2human(int(self.imager_usb_detail(config.imager_usb_disk, partition=0).total_size))) -# -# if platform.system() == "Linux": -# self.ui.label_imager_uuid.setText("Disk Model:") -# self.ui.imager_uuid.setText(str(self.imager_usb_detail(config.imager_usb_disk, partition=0).model)) -# else: -# self.ui.imager_uuid.setText(self.imager_usb_detail(config.imager_usb_disk, partition=0).model) - - def imager_list_usb(self, partition=1): + @staticmethod + def imager_list_usb(partition=1): """ Function to detect whole USB disk. It uses lsblk package on Linux. :param partition: What to return. By default partition is set. @@ -148,7 +134,7 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow): disk = [] if platform.system() == "Linux": output = subprocess.check_output("lsblk -i", shell=True) - if not partition == 1: + if partition != 1: for line in output.splitlines(): line = line.split() if (line[2].strip()) == b'1' and (line[5].strip()) == b'disk': @@ -159,15 +145,15 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow): if (line[2].strip()) == b'1' and line[5].strip() == b'part': disk.append(str("/dev/" + str(line[0].strip()[2:]))) else: - if partition == 1 or not partition == 1: - oFS = win32com.client.Dispatch("Scripting.FileSystemObject") - oDrives = oFS.Drives - for drive in oDrives: - if drive.DriveType == 1 and drive.IsReady: - disk.append(drive) + oFS = win32com.client.Dispatch("Scripting.FileSystemObject") + oDrives = oFS.Drives + for drive in oDrives: + if drive.DriveType == 1 and drive.IsReady: + disk.append(drive) return disk - def imager_usb_detail(self, usb_disk, partition=1): + @staticmethod + def imager_usb_detail(usb_disk, partition=1): """ Function to detect details of USB disk using lsblk :param usb_disk: path to usb disk @@ -180,7 +166,7 @@ class Imager(QtWidgets.QMainWindow, Ui_MainWindow): output = subprocess.check_output("lsblk -ib " + usb_disk, shell=True) for line in output.splitlines(): line = line.split() - if not partition == 1: + if partition != 1: if line[2].strip() == b'1' and line[5].strip() == b'disk': total_size = line[3] if not total_size: diff --git a/scripts/iso.py b/scripts/iso.py index f670467..d660db4 100644 --- a/scripts/iso.py +++ b/scripts/iso.py @@ -10,7 +10,6 @@ import sys import os import string -import platform import re from .gen import * from .isodump3 import ISO9660 @@ -56,11 +55,7 @@ def isolinux_bin_exist(iso_link): """ if os.path.exists(iso_link): iso_file_list = _7zip.list_iso(iso_link) - if any("isolinux.bin" in s.lower() for s in iso_file_list): - return True - else: - return False - + return bool(any("isolinux.bin" in s.lower() for s in iso_file_list)) def iso_size(iso_link): @@ -74,10 +69,7 @@ def is_bootable(iso_link): """ iso9660fs = ISO9660(iso_link) isBootable = iso9660fs.checkISOBootable() - if isBootable: - return True - else: - return False + return bool(isBootable) def isolinux_bin_dir(iso_link): @@ -162,14 +154,14 @@ def isolinux_version(isolinux_bin_path): return str(number) -def iso_extract_file(iso_link, dest_dir, filter): +def iso_extract_file(iso_link, dest_dir, _filter): """ Extract the specific file(s) from an ISO :param dest_dir: Path to destination directory. :param filter: Filter to extract particular file(s) :return: Extract file(s) to destination. """ - _7zip.extract_iso(iso_link, dest_dir, filter) + _7zip.extract_iso(iso_link, dest_dir, _filter) def extract_cfg_file(iso_link): @@ -232,4 +224,3 @@ if __name__ == '__main__': iso_extract_full(iso_path, 'test') iso_extract_file(iso_path, 'test', 'isolinux.bin') log(isolinux_version(test_iso_bin_path)) - diff --git a/scripts/persistence.py b/scripts/persistence.py index 01bb6b0..7ea8290 100644 --- a/scripts/persistence.py +++ b/scripts/persistence.py @@ -6,7 +6,6 @@ # Licence: This file is a part of multibootusb package. You can redistribute it or modify # under the terms of GNU General Public License, v.2 or above -import sys import os import platform import tarfile @@ -92,7 +91,7 @@ def create_persistence(): if subprocess.call(persistence_dd_cmd, shell=True) == 0: gen.log("\nSuccessfully created persistence file...\n") - if not config.distro == 'fedora': + if config.distro != 'fedora': gen.log('Applying filesystem to persistence file...') config.status_text = 'Applying filesystem to persistence file. Please wait...' gen.log('Executing ==> ' + persistence_mkfs_cmd) @@ -111,4 +110,3 @@ def extract_file(file_path, install_dir): tar = tarfile.open(file_path, "r:bz2") tar.extractall(install_dir) tar.close() - diff --git a/scripts/qemu.py b/scripts/qemu.py index 717b25c..44231af 100644 --- a/scripts/qemu.py +++ b/scripts/qemu.py @@ -11,7 +11,6 @@ import os import subprocess import platform -from .admin import adminCmd from PyQt5 import QtWidgets from .gui.ui_multibootusb import Ui_MainWindow from .gen import * @@ -27,7 +26,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow): QtWidgets.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) - + def on_Qemu_Boot_iso_Click(self): """ Main function to boot a selected ISO. @@ -102,9 +101,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow): cmd = qemu + ' -hda ' + qemu_usb_disk + ram + ' -vga std' try: log('Executing ==> ' + cmd) - # adminCmd([qemu, '-hda', usb_disk[:-1], '-m', ram, '-vga std'], gui=True) subprocess.Popen(cmd, shell=True) - # adminCmd(qemu_cmd, gui=True) except: QtWidgets.QMessageBox.information(self, 'Error...', 'Error booting USB\n\nUnable to start QEMU.') @@ -133,8 +130,9 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow): return None else: return selected_ram - - def check_qemu_exist(self): + + @staticmethod + def check_qemu_exist(): """ Check if QEMU is available on host system. :return: path to QEMU program or None otherwise. @@ -150,7 +148,7 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow): elif platform.system() == "Windows": qemu = resource_path(os.path.join("data", "tools", "qemu", "qemu-system-x86_64.exe")) log(qemu) - + if qemu: log("QEMU: using " + qemu) else: @@ -158,24 +156,21 @@ class Qemu(QtWidgets.QMainWindow, Ui_MainWindow): return qemu - - def get_physical_disk_number(self, usb_disk): + @staticmethod + def get_physical_disk_number(usb_disk): """ Get the physical disk number as detected ny Windows. :param usb_disk: USB disk (Like F:) :return: Disk number. """ import wmi - c = wmi.WMI () - for physical_disk in c.Win32_DiskDrive (): - for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"): - for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"): + c = wmi.WMI() + for physical_disk in c.Win32_DiskDrive(): + for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"): + for logical_disk in partition.associators("Win32_LogicalDiskToPartition"): if logical_disk.Caption == usb_disk: - """ - log physical_disk.Caption - log partition.Caption - log logical_disk.Caption - """ +# log physical_disk.Caption +# log partition.Caption +# log logical_disk.Caption log("Physical Device Number is " + partition.Caption[6:-14]) return str(partition.Caption[6:-14]) - diff --git a/scripts/syslinux.py b/scripts/syslinux.py index 9bd6722..b9fab3d 100644 --- a/scripts/syslinux.py +++ b/scripts/syslinux.py @@ -7,7 +7,6 @@ # under the terms of GNU General Public License, v.2 or above import os -import sys import subprocess import platform from .gen import * @@ -39,7 +38,7 @@ def set_boot_flag(usb_disk): return False -def syslinux_default(usb_disk, version=4): +def syslinux_default(usb_disk): """ Install Syslinux of a selected drive :param usb_disk: '/dev/sdx' on linux and 'E:' on Windows @@ -152,7 +151,7 @@ def syslinux_distro_dir(usb_disk, iso_link, distro): if platform.system() == "Linux": syslinux_path = os.path.join(multibootusb_host_dir(), "syslinux", "bin", "syslinux") + config.syslinux_version if os.access(syslinux_path, os.X_OK) is False: - subprocess.call('chmod +x ' + syslinux_path, shell=True) == 0 + subprocess.call('chmod +x ' + syslinux_path, shell=True) sys_cmd = syslinux_path + option + quote(distro_syslinux_install_dir) + ' ' + usb_disk dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1' log("Executing ==> " + sys_cmd) @@ -194,7 +193,7 @@ def syslinux_distro_dir(usb_disk, iso_link, distro): ext_cmd = syslinux_path + " --install " + distro_syslinux_install_dir dd_cmd = 'dd if=' + usb_disk + ' ' + 'of=' + quote(distro_sys_install_bs) + ' count=1' if os.access(syslinux_path, os.X_OK) is False: - subprocess.call('chmod +x ' + syslinux_path, shell=True) == 0 + subprocess.call('chmod +x ' + syslinux_path, shell=True) log("Executing ==> " + ext_cmd) if subprocess.call(ext_cmd, shell=True) == 0: log("\nSyslinux install on distro directory is successful...\n") diff --git a/scripts/udisks.py b/scripts/udisks.py index e02ec59..d1538df 100644 --- a/scripts/udisks.py +++ b/scripts/udisks.py @@ -11,7 +11,8 @@ __copyright__ = '2010, Kovid Goyal ' __docformat__ = 'restructuredtext en' # from __future__ import print_function -import os, re +import os +import re def node_mountpoint(node): @@ -133,16 +134,6 @@ class UDisks2(object): def mount(self, device_node_path): d = self.device(device_node_path) - -# euid = os.environ['SUDO_UID'] -# egid = os.environ['SUDO_GID'] -# -# if euid and egid: -# user, group = int(euid), int(egid) -# else: -# user, group = os.getuid(), os.getgid() -# -# mount_options = ['rw', 'noexec', 'nosuid', 'nodev', 'uid=%d' % user, 'gid=%d' % group] mount_options = ['rw', 'noexec', 'nosuid', 'nodev'] try: @@ -158,8 +149,8 @@ class UDisks2(object): mp = node_mountpoint(str(device_node_path)) if mp is None: raise - finally: - return mp + + return mp def unmount(self, device_node_path): d = self.device(device_node_path) diff --git a/scripts/usb.py b/scripts/usb.py index 2848778..6786de1 100644 --- a/scripts/usb.py +++ b/scripts/usb.py @@ -84,7 +84,7 @@ def disk_usage(mount_path): raise NotImplementedError("Platform not supported.") -def list_devices(partition=1, fixed=False): +def list_devices(fixed=False): """ List inserted USB devices. :return: USB devices as list. @@ -97,7 +97,7 @@ def list_devices(partition=1, fixed=False): try: import pyudev except Exception as e: - gen.log('Pydev is not installed on host system. Using the inbuilt one.') + gen.log('PyUdev is not installed on host system, using built-in.') from . import pyudev context = pyudev.Context() @@ -209,12 +209,9 @@ def details_udev(usb_disk_part): import pyudev except: from . import pyudev - """ - Try with PyUdev to get the details of USB disks. - This is the easiest and reliable method to find USB details. - Also, it is a standalone package and no dependencies are required. - """ - # gen.log "Using PyUdev for detecting USB details..." +# Try with PyUdev to get the details of USB disks. +# This is the easiest and reliable method to find USB details. +# Also, it is a standalone package and no dependencies are required. context = pyudev.Context() try: device = pyudev.Device.from_device_file(context, usb_disk_part) @@ -280,7 +277,7 @@ def details_udisks2(usb_disk_part): device = bd.Get('org.freedesktop.UDisks2.Block', 'Device', dbus_interface='org.freedesktop.DBus.Properties') device = bytearray(device).replace(b'\x00', b'').decode('utf-8') uuid = bd.Get('org.freedesktop.UDisks2.Block', 'IdUUID', dbus_interface='org.freedesktop.DBus.Properties') - file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties') + file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties') mount_point = bd.Get('org.freedesktop.UDisks2.Filesystem', 'MountPoints', dbus_interface='org.freedesktop.DBus.Properties') if mount_point: # mount_point = str(bytearray(mount_point[0]).decode('utf-8').replace(b'\x00', b'')) @@ -367,18 +364,17 @@ def win_disk_details(disk_drive): size_total = shutil.disk_usage(mount_point)[0] size_used = shutil.disk_usage(mount_point)[1] size_free = shutil.disk_usage(mount_point)[2] - ''' + # The below code works only from vista and above. I have removed it as many people reported that the software # was not working under windows xp. Even then, it is significantly slow if 'All Drives' option is checked. # Removing the code doesn't affect the functionality as it is only used to find vendor id and model of the drive. - c = wmi.WMI() - for physical_disk in c.Win32_DiskDrive(InterfaceType="USB"): - for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"): - for logical_disk in partition.associators("Win32_LogicalDiskToPartition"): - if logical_disk.Caption == disk_drive: - vendor = (physical_disk.PNPDeviceID.split('&VEN_'))[1].split('&PROD_')[0] - model = (physical_disk.PNPDeviceID.split('&PROD_'))[1].split('&REV_')[0] - ''' +# c = wmi.WMI() +# for physical_disk in c.Win32_DiskDrive(InterfaceType="USB"): +# for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"): +# for logical_disk in partition.associators("Win32_LogicalDiskToPartition"): +# if logical_disk.Caption == disk_drive: +# vendor = (physical_disk.PNPDeviceID.split('&VEN_'))[1].split('&PROD_')[0] +# model = (physical_disk.PNPDeviceID.split('&PROD_'))[1].split('&REV_')[0] return {'uuid': uuid, 'file_system': file_system, 'label': label, 'mount_point': mount_point, 'size_total': size_total, 'size_used': size_used, 'size_free': size_free,