Skip to content

Commit

Permalink
Random cleanups by @ThomasWaldmann (#1879)
Browse files Browse the repository at this point in the history
* fix PEP8 E721

do not compare types, for exact checks use `is` / `is not`, for instance checks use `isinstance()`

* remove redundant parentheses

* fix SiteWorker.run for empty job queue

local variable job is not assigned if queue was empty
when calling .run(), but it is used in exception handler.

* remove unreachable code in parse_diff_lines

* bug fix for unreachable code in is_worker_running

the code intended to check if *any* worker is running for
any site was *unreachable*.

this caused false negative results for site=None.

* check_failed_response: remove outdated part of docstring

* pull request template: fix relative path to LICENSE.txt

* fix typos

* use logger.warning, .warn is deprecated
  • Loading branch information
ThomasWaldmann authored Jan 9, 2024
1 parent 1f06235 commit 675010e
Show file tree
Hide file tree
Showing 17 changed files with 42 additions and 45 deletions.
2 changes: 1 addition & 1 deletion .github/ISSUE_TEMPLATE/bug_form.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: "Bug Report Form"
description: "Report a bug or a similiar issue."
description: "Report a bug or a similar issue."
body:
- type: markdown
attributes:
Expand Down
4 changes: 2 additions & 2 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: Bug Report
about: Report a bug or a similiar issue - the classic way
about: Report a bug or a similar issue - the classic way
title: ''
labels: ''
assignees: ''
Expand All @@ -18,7 +18,7 @@ If you want to suggest a feature or have any other question, please use our
#### Description

<!-- Description
Please decribe your issue and its context in a clear and concise way.
Please describe your issue and its context in a clear and concise way.
Please try to reproduce the issue and provide the steps to reproduce it.
-->

Expand Down
2 changes: 1 addition & 1 deletion .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
- [ ] All new and existing tests passed.


*I provide my contribution under the terms of the [license](./../../LICENSE.txt) of this repository and I affirm the [Developer Certificate of Origin][dco].*
*I provide my contribution under the terms of the [license](./../LICENSE.txt) of this repository and I affirm the [Developer Certificate of Origin][dco].*

[dco]: https://developercertificate.org/

Expand Down
4 changes: 2 additions & 2 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@
@nox.parametrize("borgbackup", supported_borgbackup_versions)
def run_tests(session, borgbackup):
# install borgbackup
if (sys.platform == 'darwin'):
if sys.platform == 'darwin':
# in macOS there's currently no fuse package which works with borgbackup directly
session.install(f"borgbackup=={borgbackup}")
elif (borgbackup == "1.1.18"):
elif borgbackup == "1.1.18":
# borgbackup 1.1.18 doesn't support pyfuse3
session.install("llfuse")
session.install(f"borgbackup[llfuse]=={borgbackup}")
Expand Down
18 changes: 9 additions & 9 deletions package/fix_app_qt_folder_names_for_codesign.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ def create_symlink(folder: Path) -> None:
"""Create the appropriate symlink in the MacOS folder
pointing to the Resources folder.
"""
sibbling = Path(str(folder).replace("MacOS", ""))
sibling = Path(str(folder).replace("MacOS", ""))

# PyQt6/Qt/qml/QtQml/Models.2
root = str(sibbling).partition("Contents")[2].lstrip("/")
root = str(sibling).partition("Contents")[2].lstrip("/")
# ../../../../
backward = "../" * (root.count("/") + 1)
# ../../../../Resources/PyQt6/Qt/qml/QtQml/Models.2
Expand All @@ -41,7 +41,7 @@ def fix_dll(dll: Path) -> None:

def match_func(pth: str) -> Optional[str]:
"""Callback function for MachO.rewriteLoadCommands() that is
called on every lookup path setted in the DLL headers.
called on every lookup path set in the DLL headers.
By returning None for system libraries, it changes nothing.
Else we return a relative path pointing to the good file
in the MacOS folder.
Expand Down Expand Up @@ -73,7 +73,7 @@ def find_problematic_folders(folder: Path) -> Generator[Path, None, None]:
"""Recursively yields problematic folders (containing a dot in their name)."""
for path in folder.iterdir():
if not path.is_dir() or path.is_symlink():
# Skip simlinks as they are allowed (even with a dot)
# Skip symlinks as they are allowed (even with a dot)
continue
if "." in path.name:
yield path
Expand All @@ -83,18 +83,18 @@ def find_problematic_folders(folder: Path) -> Generator[Path, None, None]:

def move_contents_to_resources(folder: Path) -> Generator[Path, None, None]:
"""Recursively move any non symlink file from a problematic folder
to the sibbling one in Resources.
to the sibling one in Resources.
"""
for path in folder.iterdir():
if path.is_symlink():
continue
if path.name == "qml":
yield from move_contents_to_resources(path)
else:
sibbling = Path(str(path).replace("MacOS", "Resources"))
sibbling.parent.mkdir(parents=True, exist_ok=True)
shutil.move(path, sibbling)
yield sibbling
sibling = Path(str(path).replace("MacOS", "Resources"))
sibling.parent.mkdir(parents=True, exist_ok=True)
shutil.move(path, sibling)
yield sibling


def main(args: List[str]) -> int:
Expand Down
7 changes: 1 addition & 6 deletions src/vorta/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,11 +308,6 @@ def check_failed_response(self, result: Dict[str, Any]):
Displays a `QMessageBox` with an error message depending on the
return code of the `BorgJob`.
Parameters
----------
repo_url : str
The url of the repo of concern
"""
# extract data from the params for the borg job
repo_url = result['params']['repo_url']
Expand Down Expand Up @@ -344,7 +339,7 @@ def check_failed_response(self, result: Dict[str, Any]):
elif returncode > 128:
# 128+N - killed by signal N (e.g. 137 == kill -9)
signal = returncode - 128
text = self.tr('Repository data check for repo was killed by signal %s.') % (signal)
text = self.tr('Repository data check for repo was killed by signal %s.') % signal
infotext = self.tr('The process running the check job got a kill signal. Try again.')
else:
# Real error
Expand Down
31 changes: 17 additions & 14 deletions src/vorta/borg/jobs_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ def repo_id(self):
@abstractmethod
def cancel(self):
"""
Cancel can be called when the job is not started. It is the responsability of FuncJob to not cancel job if
Cancel can be called when the job is not started. It is the responsibility of FuncJob to not cancel job if
no job is running.
The cancel mehod of JobsManager calls the cancel method on the running jobs only. Other jobs are dequeued.
The cancel method of JobsManager calls the cancel method on the running jobs only. Other jobs are dequeued.
"""
pass

Expand All @@ -50,6 +50,7 @@ def __init__(self, jobs):
self.current_job = None

def run(self):
job = None
while True:
try:
job = self.jobs.get(False)
Expand All @@ -58,7 +59,8 @@ def run(self):
job.run()
logger.debug("Finish job for site: %s", job.repo_id())
except queue.Empty:
logger.debug("No more jobs for site: %s", job.repo_id())
if job is not None:
logger.debug("No more jobs for site: %s", job.repo_id())
return


Expand All @@ -77,19 +79,20 @@ def __init__(self):

def is_worker_running(self, site=None):
"""
See if there are any active jobs. The user can't start a backup if a job is
running. The scheduler can.
See if there are any active jobs.
The user can't start a backup if a job is running. The scheduler can.
If site is None, check if there is any worker active for any site (repo).
If site is not None, only check if there is a worker active for the given site (repo).
"""
# Check status for specific site (repo)
if site in self.workers:
return self.workers[site].is_alive()
if site is not None:
if site in self.workers:
if self.workers[site].is_alive():
return True
else:
return False

# Check if *any* worker is active
for _, worker in self.workers.items():
if worker.is_alive():
return True
for _, worker in self.workers.items():
if worker.is_alive():
return True
return False

def add_job(self, job):
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/network_status/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def get_network_status_monitor(cls) -> 'NetworkStatusMonitor':

def is_network_status_available(self):
"""Is the network status really available, and not just a dummy implementation?"""
return type(self) != NetworkStatusMonitor
return type(self) is not NetworkStatusMonitor

def is_network_metered(self) -> bool:
"""Is the currently connected network a metered connection?"""
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/profile_export.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def schema_version(self):
def repo_url(self):
if (
'repo' in self._profile_dict
and type(self._profile_dict['repo']) == dict
and isinstance(self._profile_dict['repo'], dict)
and 'url' in self._profile_dict['repo']
):
return self._profile_dict['repo']['url']
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self):
self.bus = bus
self.bus.connect(service, path, interface, name, "b", self.loginSuspendNotify)
else:
logger.warn('Failed to connect to DBUS interface to detect sleep/resume events')
logger.warning('Failed to connect to DBUS interface to detect sleep/resume events')

@QtCore.pyqtSlot(bool)
def loginSuspendNotify(self, suspend: bool):
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/views/archive_tab.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ def confirm_dialog(self, title, text):
return msg.exec() == QMessageBox.StandardButton.Yes

def delete_action(self):
# Since this function modify the UI, we can't put the whole function in a JobQUeue.
# Since this function modify the UI, we can't put the whole function in a JobQueue.

# determine selected archives
archives = []
Expand Down
1 change: 0 additions & 1 deletion src/vorta/views/diff_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,6 @@ def parse_diff_lines(lines: List[str], model: 'DiffTree'):

if not parsed_line:
raise Exception("Couldn't parse diff output `{}`".format(line))
continue

path = PurePath(parsed_line['path'])
file_type = FileType.FILE
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/views/partials/treemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ def getItem(self, path: Union[PurePath, PathLike]) -> Optional[FileSystemItem[T]
if isinstance(path, PurePath):
path = path.parts

return self.root.get_path(path) # handels empty path
return self.root.get_path(path) # handles empty path

def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/views/profile_add_edit_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(self, parent=None):

self.name_blank = trans_late('AddProfileWindow', 'Please enter a profile name.')
self.name_exists = trans_late('AddProfileWindow', 'A profile with this name already exists.')
# Call validate to set inital messages
# Call validate to set initial messages
self.buttonBox.button(QDialogButtonBox.StandardButton.Save).setEnabled(self.validate())

def _set_status(self, text):
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/views/repo_tab.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(self, parent=None):
# compression or speed on a unified scale. this is not 1-dimensional and also depends
# on the input data. so we just tell what we know for sure.
# "auto" is used for some slower / older algorithms to avoid wasting a lot of time
# on uncompressible data.
# on incompressible data.
self.repoCompression.addItem(self.tr('LZ4 (modern, default)'), 'lz4')
self.repoCompression.addItem(self.tr('Zstandard Level 3 (modern)'), 'zstd,3')
self.repoCompression.addItem(self.tr('Zstandard Level 8 (modern)'), 'zstd,8')
Expand Down
2 changes: 1 addition & 1 deletion src/vorta/views/source_tab.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def source_remove(self):
profile = self.profile()
# sort indexes, starting with lowest
indexes.sort()
# remove each selected row, starting with highest index (otherways, higher indexes become invalid)
# remove each selected row, starting with the highest index (otherwise, higher indexes become invalid)
for index in reversed(indexes):
db_item = SourceFileModel.get(
dir=self.sourceFilesWidget.item(index.row(), SourceColumn.Path).text(),
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_treemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_get(self):
item.add(child2)
item.add(child3)

# test get inexistent subpath
# test get nonexistent subpath
assert item.get('unknown') is None
assert item.get('unknown', default='default') == 'default'

Expand Down

0 comments on commit 675010e

Please sign in to comment.