Switch to ruff linting

This commit is contained in:
2Shirt 2023-03-19 18:47:46 -07:00
parent dad1d3e7f9
commit e00920f24a
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C
33 changed files with 66 additions and 68 deletions

View file

@ -6,13 +6,12 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
import wk # noqa: E402
# Classes
REBOOT_STR = wk.std.color_string('Reboot', 'YELLOW')
class MenuEntry():
# pylint: disable=too-few-public-methods
"""Simple class to allow cleaner code below."""
def __init__(self, name, function=None, selected=True, **kwargs):
self.name = name
@ -96,5 +95,5 @@ if __name__ == '__main__':
wk.std.abort()
except SystemExit:
raise
except: #pylint: disable=bare-except
except: # noqa: E722
wk.std.major_exception()

View file

@ -6,12 +6,11 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
import wk # noqa: E402
# Classes
class MenuEntry():
# pylint: disable=too-few-public-methods
"""Simple class to allow cleaner code below."""
def __init__(self, name, function=None, selected=True, **kwargs):
self.name = name
@ -163,5 +162,5 @@ if __name__ == '__main__':
wk.std.abort()
except SystemExit:
raise
except: #pylint: disable=bare-except
except: # noqa: E722
wk.std.major_exception()

View file

@ -6,7 +6,7 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
import wk # noqa: E402
if __name__ == '__main__':
@ -16,5 +16,5 @@ if __name__ == '__main__':
wk.std.abort()
except SystemExit:
raise
except: #pylint: disable=bare-except
except: # noqa: E722
wk.std.major_exception()

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3
"""WizardKit: ddrescue TUI"""
# pylint: disable=invalid-name
# vim: sts=2 sw=2 ts=2
from docopt import docopt
@ -20,5 +19,5 @@ if __name__ == '__main__':
wk.clone.ddrescue.main()
except SystemExit:
raise
except: #pylint: disable=bare-except
except: # noqa: E722
wk.std.major_exception()

View file

@ -10,7 +10,7 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
import wk # noqa: E402
wk.std.print_colored(
(wk.cfg.main.KIT_NAME_FULL, ': ', 'Debug Console'),
('GREEN', None, 'YELLOW'),

View file

@ -6,6 +6,6 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
import wk # noqa: E402
wk.os.win.export_bitlocker_info()

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3
"""WizardKit: Hardware Diagnostics"""
# pylint: disable=invalid-name
# vim: sts=2 sw=2 ts=2
from docopt import docopt
@ -20,5 +19,5 @@ if __name__ == '__main__':
wk.hw.diags.main()
except SystemExit:
raise
except: #pylint: disable=bare-except
except: # noqa: E722
wk.std.major_exception()

View file

@ -6,8 +6,8 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
from wk.cfg.net import SDIO_SERVER # pylint: disable=wrong-import-position
import wk # noqa: E402
from wk.cfg.net import SDIO_SERVER # noqa: E402
# STATIC VARIABLES
MOUNT_EXCEPTIONS = (
@ -70,7 +70,9 @@ def use_network_sdio():
if __name__ == '__main__':
wk.std.set_title(f'{wk.cfg.main.KIT_NAME_FULL}: Snappy Driver Installer Origin Launcher')
wk.std.set_title(
f'{wk.cfg.main.KIT_NAME_FULL}: Snappy Driver Installer Origin Launcher',
)
log_dir = wk.log.format_log_path(tool=True).parent
USE_NETWORK = False

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3
"""WizardKit: Mount Backup Shares"""
# pylint: disable=invalid-name
# vim: sts=2 sw=2 ts=2
import wk

18
scripts/pyproject.toml Normal file
View file

@ -0,0 +1,18 @@
[tool.ruff.per-file-ignores]
# Init files
"wk/__init__.py" = ["F401"]
"wk/cfg/__init__.py" = ["F401"]
"wk/clone/__init__.py" = ["F401"]
"wk/hw/__init__.py" = ["F401"]
"wk/kit/__init__.py" = ["F401"]
"wk/os/__init__.py" = ["F401"]
"wk/repairs/__init__.py" = ["F401"]
"wk/setup/__init__.py" = ["F401"]
# Long lines
"wk/borrowed/acpi.py" = ["E501", "F841"]
"wk/cfg/ddrescue.py" = ["E501"]
"wk/cfg/hw.py" = ["E501"]
"wk/cfg/launchers.py" = ["E501"]
"wk/cfg/setup.py" = ["E501"]
"wk/cfg/sources.py" = ["E501"]

View file

@ -1,5 +1,4 @@
"""WizardKit: Config - ddrescue"""
# pylint: disable=line-too-long
# vim: sts=2 sw=2 ts=2
from collections import OrderedDict

View file

@ -1,5 +1,4 @@
"""WizardKit: Config - Hardware"""
# pylint: disable=line-too-long
# vim: sts=2 sw=2 ts=2
import re

View file

@ -1,5 +1,4 @@
"""WizardKit: Config - Launchers (Windows)"""
# pylint: disable=line-too-long
# vim: sts=2 sw=2 ts=2
LAUNCHERS = {

View file

@ -1,5 +1,4 @@
"""WizardKit: Config - Setup"""
# pylint: disable=line-too-long
# vim: sts=2 sw=2 ts=2
@ -31,7 +30,6 @@ REG_CHROME_UBLOCK_ORIGIN = {
},
}
REG_WINDOWS_EXPLORER = {
# pylint: disable=line-too-long
'HKLM': {
# Disable Location Tracking
r'Software\Microsoft\Windows NT\CurrentVersion\Sensor\Overrides\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}': (

View file

@ -1,5 +1,4 @@
"""WizardKit: Config - Tool Sources"""
# pylint: disable=line-too-long
# vim: sts=2 sw=2 ts=2

View file

@ -1,5 +1,4 @@
"""WizardKit: ddrescue TUI"""
# pylint: disable=too-many-lines
# vim: sts=2 sw=2 ts=2
import atexit
@ -127,7 +126,6 @@ TIMEZONE = pytz.timezone(cfg.main.LINUX_TIME_ZONE)
# Classes
class BlockPair():
"""Object for tracking source to dest recovery data."""
# pylint: disable=too-many-instance-attributes
def __init__(self, source, destination, model, working_dir):
"""Initialize BlockPair()
@ -336,7 +334,6 @@ class BlockPair():
class State():
# pylint: disable=too-many-public-methods
"""Object for tracking hardware diagnostic data."""
def __init__(self):
self.block_pairs = []
@ -706,7 +703,6 @@ class State():
return sum(pair.size for pair in self.block_pairs)
def init_recovery(self, docopt_args):
# pylint: disable=too-many-branches
"""Select source/dest and set env."""
std.clear_screen()
source_parts = []
@ -1896,7 +1892,6 @@ def source_or_destination_changed(state):
def main():
# pylint: disable=too-many-branches
"""Main function for ddrescue TUI."""
args = docopt(DOCSTRING)
log.update_log_path(dest_name='ddrescue-TUI', timestamp=True)
@ -2038,7 +2033,6 @@ def mount_raw_image_macos(path):
def run_ddrescue(state, block_pair, pass_name, settings, dry_run=True):
# pylint: disable=too-many-statements
"""Run ddrescue using passed settings."""
cmd = build_ddrescue_cmd(block_pair, pass_name, settings)
poweroff_source_after_idle = True
@ -2186,7 +2180,6 @@ def run_ddrescue(state, block_pair, pass_name, settings, dry_run=True):
def run_recovery(state, main_menu, settings_menu, dry_run=True):
# pylint: disable=too-many-branches
"""Run recovery passes."""
atexit.register(state.save_debug_reports)
attempted_recovery = False

View file

@ -1,11 +1,9 @@
"""WizardKit: Debug Functions"""
# pylint: disable=invalid-name
# vim: sts=2 sw=2 ts=2
# Classes
class Debug():
# pylint: disable=too-few-public-methods
"""Object used when dumping debug data."""
def method(self):
"""Dummy method used to identify functions vs data."""

View file

@ -21,7 +21,6 @@ LOG = logging.getLogger(__name__)
# Classes
class NonBlockingStreamReader():
"""Class to allow non-blocking reads from a stream."""
# pylint: disable=too-few-public-methods
# Credits:
## https://gist.github.com/EyalAr/7915597
## https://stackoverflow.com/a/4896288
@ -200,7 +199,6 @@ def popen_program(cmd, minimized=False, pipe=False, shell=False, **kwargs):
shell=shell,
**kwargs)
try:
# pylint: disable=consider-using-with
proc = subprocess.Popen(**cmd_kwargs)
except FileNotFoundError:
LOG.error('Command not found: %s', cmd)
@ -212,7 +210,6 @@ def popen_program(cmd, minimized=False, pipe=False, shell=False, **kwargs):
def run_program(cmd, check=True, pipe=True, shell=False, **kwargs):
# pylint: disable=subprocess-run-check
"""Run program and return a subprocess.CompletedProcess object."""
LOG.debug(
'cmd: %s, check: %s, pipe: %s, shell: %s',

View file

@ -325,7 +325,6 @@ class State():
# Functions
def build_menu(cli_mode=False, quick_mode=False) -> std.Menu:
# pylint: disable=too-many-branches
"""Build main menu, returns wk.std.Menu."""
menu = std.Menu(title=None)
@ -377,7 +376,6 @@ def build_menu(cli_mode=False, quick_mode=False) -> std.Menu:
def cpu_stress_tests(state, test_objects, test_mode=False) -> None:
# pylint: disable=too-many-statements
"""CPU & cooling check using Prime95 and Sysbench."""
LOG.info('CPU Test (Prime95)')
aborted = False
@ -508,7 +506,6 @@ def cpu_stress_tests(state, test_objects, test_mode=False) -> None:
def disk_attribute_check(state, test_objects, test_mode=False) -> None:
# pylint: disable=unused-argument
"""Disk attribute check."""
LOG.info('Disk Attribute Check')
for test in test_objects:
@ -587,7 +584,6 @@ def disk_io_benchmark(
def disk_self_test(state, test_objects, test_mode=False) -> None:
# pylint: disable=unused-argument
"""Disk self-test if available."""
LOG.info('Disk Self-Test(s)')
aborted = False
@ -749,7 +745,6 @@ def disk_surface_scan(state, test_objects, test_mode=False) -> None:
def main() -> None:
# pylint: disable=too-many-branches
"""Main function for hardware diagnostics."""
args = docopt(DOCSTRING)
log.update_log_path(dest_name='Hardware-Diagnostics', timestamp=True)

View file

@ -33,7 +33,6 @@ WK_LABEL_REGEX = re.compile(
# Classes
@dataclass(**DATACLASS_DECORATOR_KWARGS)
class Disk:
# pylint: disable=too-many-instance-attributes
"""Object for tracking disk specific data."""
attributes: dict[Any, dict] = field(init=False, default_factory=dict)
bus: str = field(init=False)

View file

@ -121,7 +121,6 @@ class Sensors():
self, out_path, alt_max=None,
exit_on_thermal_limit=True, temp_labels=None,
thermal_action=None) -> None:
# pylint: disable=too-many-arguments
"""Write report to path every second until stopped.
thermal_action is a cmd to run if ThermalLimitReachedError is caught.
@ -182,7 +181,6 @@ class Sensors():
self, out_path, alt_max=None,
exit_on_thermal_limit=True, temp_labels=None,
thermal_action=None) -> None:
# pylint: disable=too-many-arguments
"""Start background thread to save report to file.
thermal_action is a cmd to run if ThermalLimitReachedError is caught.
@ -315,7 +313,11 @@ def get_sensor_data_linux() -> dict[Any, Any]:
## current temp is labeled xxxx_input
for source, labels in sources.items():
for label, temp in labels.items():
if label.startswith('fan') or label.startswith('in') or label.startswith('curr'):
if (
label.startswith('fan')
or label.startswith('in')
or label.startswith('curr')
):
# Skip fan RPMs and voltages
continue
if 'input' in label:

View file

@ -8,7 +8,6 @@ from wk.cfg.python import DATACLASS_DECORATOR_KWARGS
@dataclass(**DATACLASS_DECORATOR_KWARGS)
class Test:
# pylint: disable=too-many-instance-attributes
"""Object for tracking test specific data."""
dev: Any
label: str

View file

@ -209,7 +209,11 @@ def download_fastcopy():
def download_furmark():
"""Download FurMark."""
installer = download_to_temp('FurMark_Setup.exe', SOURCES['FurMark'], referer=SOURCES['FurMark'])
installer = download_to_temp(
'FurMark_Setup.exe',
SOURCES['FurMark'],
referer=SOURCES['FurMark'],
)
out_path = BIN_DIR.joinpath('FurMark')
tmp_path = TMP_DIR.joinpath('FurMarkInstall')
run_program([installer, f'/DIR={tmp_path}', '/SILENT'])

View file

@ -55,13 +55,23 @@ def download_file(out_path, source_url, as_new=False, overwrite=False, referer=N
# Request download
with requests.Session() as session:
try:
response = session.get(source_url, allow_redirects=True, headers=headers, stream=True)
except requests.RequestException as _err:
response = session.get(
source_url,
allow_redirects=True,
headers=headers,
stream=True,
)
except requests.RequestException:
try:
sleep(1)
response = session.get(source_url, allow_redirects=True, headers=headers, stream=True)
except requests.RequestException as _err2:
download_failed = _err2
response = session.get(
source_url,
allow_redirects=True,
headers=headers,
stream=True,
)
except requests.RequestException as _err:
download_failed = _err
else:
if not response.ok:
download_failed = response

View file

@ -88,7 +88,6 @@ def apply_image(part_path, image_path, hide_macos_boot=True):
def build_ufd():
# pylint: disable=too-many-statements
"""Build UFD using selected sources."""
args = docopt(DOCSTRING)
if args['--debug']:

View file

@ -41,7 +41,6 @@ def enable_debug_mode():
def format_log_path(
log_dir=None, log_name=None, timestamp=False,
kit=False, tool=False, append=False):
# pylint: disable=too-many-arguments
"""Format path based on args passed, returns pathlib.Path obj."""
log_path = pathlib.Path(
f'{log_dir if log_dir else DEFAULT_LOG_DIR}/'

View file

@ -178,7 +178,6 @@ def mount(source, mount_point=None, read_write=False):
def mount_volumes(device_path=None, read_write=False, scan_corestorage=False):
# pylint: disable=too-many-branches
"""Mount all detected volumes.
NOTE: If device_path is specified then only volumes

View file

@ -354,7 +354,6 @@ def show_alert_box(message, title=None):
# Registry Functions
def reg_delete_key(hive, key, recurse=False):
# pylint: disable=raise-missing-from
"""Delete a key from the registry.
NOTE: If recurse is False then it will only work on empty keys.
@ -518,7 +517,6 @@ def reg_write_settings(settings):
def reg_set_value(hive, key, name, data, data_type, option=None):
# pylint: disable=too-many-arguments
"""Set value for hive/key."""
access = winreg.KEY_WRITE
data_type = reg_get_data_type(data_type)
@ -702,7 +700,7 @@ def start_service(service_name):
run_program(cmd, check=False)
# Verify service was started
if not get_service_status(service_name) in ('running', 'start_pending'):
if get_service_status(service_name) not in ('running', 'start_pending'):
raise GenericError(f'Failed to start service {service_name}')

View file

@ -1,5 +1,4 @@
"""WizardKit: Repairs - Windows"""
# pylint: disable=too-many-lines
# vim: sts=2 sw=2 ts=2
import atexit
@ -548,7 +547,12 @@ def set_log_path():
# Ignore and use default values
update_log_path(dest_name='Auto Repairs', timestamp=True)
else:
update_log_path(dest_name=log_path, keep_history=False, timestamp=False, append=True)
update_log_path(
dest_name=log_path,
keep_history=False,
timestamp=False,
append=True,
)
def show_main_menu(base_menus, menus, presets, title):

View file

@ -1,5 +1,4 @@
"""WizardKit: Setup - Windows"""
# pylint: disable=too-many-lines
# vim: sts=2 sw=2 ts=2
import configparser

View file

@ -1,5 +1,4 @@
"""WizardKit: Standard Functions"""
# pylint: disable=too-many-lines
# vim: sts=2 sw=2 ts=2
import inspect
@ -134,7 +133,6 @@ class Menu():
def _get_display_name(
self, name, details,
index=None, no_checkboxes=True, setting_item=False):
# pylint: disable=too-many-arguments
"""Format display name based on details and args, returns str."""
disabled = details.get('Disabled', False)
if setting_item and not details['Selected']:
@ -400,7 +398,6 @@ class Menu():
class TryAndPrint():
# pylint: disable=too-many-instance-attributes
"""Object used to standardize running functions and returning the result.
The errors and warning attributes are used to allow fine-tuned results
@ -521,7 +518,6 @@ class TryAndPrint():
def run(
self, message, function, *args,
catch_all=None, msg_good=None, verbose=None, **kwargs):
# pylint: disable=catching-non-exception
"""Run a function and print the results, returns results as dict.
If catch_all is True then (nearly) all exceptions will be caught.

View file

@ -203,7 +203,6 @@ def prep_file(path):
def resize_pane(pane_id=None, width=None, height=None, **kwargs):
# pylint: disable=unused-argument
"""Resize current or target pane.
NOTE: kwargs is only here to make calling this function easier

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3
"""WizardKit: Debug Launcher"""
# pylint: disable=invalid-name
# vim: sts=2 sw=2 ts=2
import os
@ -10,7 +9,7 @@ import sys
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
import wk # pylint: disable=wrong-import-position
import wk # noqa: E402
# STATIC VARIABLES