diff --git a/.gitignore b/.gitignore index 3a173d7d..c9e6723f 100755 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ env venv +.venv +.vscode/ *.pyc .idea __pycache__ diff --git a/bauh/api/abstract/model.py b/bauh/api/abstract/model.py index 0c9f1d7e..108673cc 100644 --- a/bauh/api/abstract/model.py +++ b/bauh/api/abstract/model.py @@ -1,14 +1,19 @@ +from __future__ import annotations from abc import ABC, abstractmethod from enum import Enum from typing import List, Optional, Iterable from bauh.api.paths import CACHE_DIR +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from bauh.api.abstract.controller import SoftwareManager + class CustomSoftwareAction: def __init__(self, i18n_label_key: str, i18n_status_key: str, icon_path: str, manager_method: str, - requires_root: bool, manager: "SoftwareManager" = None, + requires_root: bool, manager: SoftwareManager = None, backup: bool = False, refresh: bool = True, i18n_confirm_key: str = None, requires_internet: bool = False, diff --git a/bauh/api/abstract/view.py b/bauh/api/abstract/view.py index ce9fc0ec..8450a740 100644 --- a/bauh/api/abstract/view.py +++ b/bauh/api/abstract/view.py @@ -193,7 +193,7 @@ class TextComponent(ViewComponent): class TwoStateButtonComponent(ViewComponent): - def __init__(self, label: str, tooltip: str = None, state: bool = False, id_: str = None): + def __init__(self, label: str, tooltip: str = None, state: bool = False, id_: str = None): super(TwoStateButtonComponent, self).__init__(id_=id_) self.label = label self.tooltip = tooltip diff --git a/bauh/api/exception.py b/bauh/api/exception.py index ae00707c..930efa3f 100644 --- a/bauh/api/exception.py +++ b/bauh/api/exception.py @@ -3,4 +3,3 @@ from typing import Optional class NoInternetException(Exception): pass - diff --git a/bauh/api/http.py b/bauh/api/http.py index ba4406e3..882b81f3 100644 --- a/bauh/api/http.py +++ b/bauh/api/http.py @@ -96,7 +96,7 @@ class HttpClient: if size: try: return int(size) - except: + except Exception: pass def get_content_length(self, url: str, session: bool = True) -> Optional[str]: diff --git a/bauh/app.py b/bauh/app.py index 68800f9c..8dcb57b2 100755 --- a/bauh/app.py +++ b/bauh/app.py @@ -28,7 +28,7 @@ def main(tray: bool = False): try: locale.setlocale(locale.LC_NUMERIC, '') - except: + except Exception: logger.error("Could not set locale 'LC_NUMBERIC' to '' to display localized numbers") traceback.print_exc() @@ -45,7 +45,7 @@ def main(tray: bool = False): scale_factor = float(app_config['ui']['scale_factor']) os.environ['QT_SCALE_FACTOR'] = str(scale_factor) logger.info("Scale factor set to {}".format(scale_factor)) - except: + except Exception: traceback.print_exc() if bool(app_config['ui']['hdpi']): diff --git a/bauh/commons/category.py b/bauh/commons/category.py index 12b589d8..3d789f3e 100644 --- a/bauh/commons/category.py +++ b/bauh/commons/category.py @@ -85,7 +85,7 @@ class CategoriesDownloader(Thread): f.write(str(timestamp)) self.logger.info(self._msg("Categories timestamp ({}) cached to file '{}'".format(timestamp, categories_ts_path))) - except: + except Exception: self.logger.error(self._msg("Could not cache categories to the disk as '{}'".format(self.categories_path))) traceback.print_exc() @@ -106,7 +106,7 @@ class CategoriesDownloader(Thread): try: categories = self._map_categories(res.text) self.logger.info(self._msg('Loaded categories for {} applications'.format(len(categories)))) - except: + except Exception: self.logger.error(self._msg("Could not parse categories definitions")) traceback.print_exc() return {} @@ -140,7 +140,7 @@ class CategoriesDownloader(Thread): try: categories_timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: self.logger.error(self._msg("An exception occurred when trying to parse the categories file timestamp from '{}'. The categories file should be re-downloaded.".format(categories_ts_path))) traceback.print_exc() return True diff --git a/bauh/commons/config.py b/bauh/commons/config.py index 0ecc556a..f2e6cb40 100644 --- a/bauh/commons/config.py +++ b/bauh/commons/config.py @@ -98,5 +98,5 @@ class YAMLConfigManager(ConfigManager, ABC): try: with open(self.file_path, 'w+') as f: f.write(yaml.dump(config_obj)) - except: + except Exception: traceback.print_exc() diff --git a/bauh/commons/internet.py b/bauh/commons/internet.py index de5bc61a..4245191c 100644 --- a/bauh/commons/internet.py +++ b/bauh/commons/internet.py @@ -13,6 +13,5 @@ class InternetChecker: try: socket.gethostbyname('google.com') return True - except: + except Exception: return False - diff --git a/bauh/gems/appimage/controller.py b/bauh/gems/appimage/controller.py index 8c648f93..450fae0a 100644 --- a/bauh/gems/appimage/controller.py +++ b/bauh/gems/appimage/controller.py @@ -177,7 +177,7 @@ class AppImageManager(SoftwareManager, SettingsController): if os.path.exists(db_path): try: return sqlite3.connect(db_path) - except: + except Exception: self.logger.error(f"Could not connect to database file '{db_path}'") traceback.print_exc() else: @@ -207,13 +207,13 @@ class AppImageManager(SoftwareManager, SettingsController): not_installed.append(app) found_map[self._gen_app_key(app)] = {'app': app, 'idx': idx} idx += 1 - except: + except Exception: self.logger.error("An exception happened while querying the 'apps' database") traceback.print_exc() try: installed = self.read_installed(connection=apps_conn, disk_loader=disk_loader, limit=limit, only_apps=False, pkg_types=None, internet_available=True).installed - except: + except Exception: installed = None installed_found = [] @@ -241,7 +241,7 @@ class AppImageManager(SoftwareManager, SettingsController): installed_found.append(appim) try: apps_conn.close() - except: + except Exception: self.logger.error(f"An exception happened when trying to close the connection to database file '{DATABASE_APPS_FILE}'") traceback.print_exc() @@ -288,7 +288,7 @@ class AppImageManager(SoftwareManager, SettingsController): else: try: app.update = parse_version(tup[2]) > parse_version(app.version) if tup[2] else False - except: + except Exception: app.update = False traceback.print_exc() @@ -297,7 +297,7 @@ class AppImageManager(SoftwareManager, SettingsController): app.url_download_latest_version = tup[3] break - except: + except Exception: self.logger.error(f"An exception happened while querying the database file '{DATABASE_APPS_FILE}'") traceback.print_exc() finally: @@ -417,7 +417,7 @@ class AppImageManager(SoftwareManager, SettingsController): try: os.remove(pkg.symlink) self.logger.info(f"symlink '{pkg.symlink}' successfully removed") - except: + except Exception: msg = f"could not remove symlink '{pkg.symlink}'" self.logger.error(msg) @@ -490,7 +490,7 @@ class AppImageManager(SoftwareManager, SettingsController): if not app_tuple: self.logger.warning(f"Could not retrieve {pkg} from the database '{DATABASE_APPS_FILE}'") return res - except: + except Exception: self.logger.error(f"An exception happened while querying the database file '{DATABASE_APPS_FILE}'") traceback.print_exc() app_con.close() @@ -522,7 +522,7 @@ class AppImageManager(SoftwareManager, SettingsController): res.pkg_status_idx = idx return res - except: + except Exception: self.logger.error(f"An exception happened while querying the database file '{DATABASE_RELEASES_FILE}'") traceback.print_exc() finally: @@ -600,7 +600,7 @@ class AppImageManager(SoftwareManager, SettingsController): try: moved, output = handler.handle_simple(SimpleProcess(['mv', pkg.local_file_path, install_file_path])) - except: + except Exception: output = '' self.logger.error(f"Could not rename file '{pkg.local_file_path}' as '{install_file_path}'") moved = False @@ -649,7 +649,7 @@ class AppImageManager(SoftwareManager, SettingsController): type_=MessageType.ERROR) handler.handle(SystemProcess(new_subprocess(['rm', '-rf', out_dir]))) return TransactionResult.fail() - except: + except Exception: watcher.show_message(title=self.i18n['error'], body=traceback.format_exc(), type_=MessageType.ERROR) @@ -691,7 +691,7 @@ class AppImageManager(SoftwareManager, SettingsController): try: shutil.rmtree(extracted_folder) - except: + except Exception: traceback.print_exc() SymlinksVerifier.create_symlink(app=pkg, file_path=install_file_path, logger=self.logger, @@ -814,7 +814,7 @@ class AppImageManager(SoftwareManager, SettingsController): self.logger.info(f"Mapped {len(res)} AppImage suggestions") return res - except: + except Exception: traceback.print_exc() finally: connection.close() @@ -849,7 +849,7 @@ class AppImageManager(SoftwareManager, SettingsController): if logs: print(f'{Fore.YELLOW}[bauh][appimage] {f} deleted{Fore.RESET}') - except: + except Exception: if logs: print(f'{Fore.RED}[bauh][appimage] An exception has happened when deleting {f}{Fore.RESET}') traceback.print_exc() @@ -884,7 +884,7 @@ class AppImageManager(SoftwareManager, SettingsController): try: self.configman.save_config(config_) return True, None - except: + except Exception: return False, [traceback.format_exc()] def gen_custom_actions(self) -> Generator[CustomSoftwareAction, None, None]: diff --git a/bauh/gems/appimage/worker.py b/bauh/gems/appimage/worker.py index 95d8a3ae..69cb72a9 100644 --- a/bauh/gems/appimage/worker.py +++ b/bauh/gems/appimage/worker.py @@ -74,7 +74,7 @@ class DatabaseUpdater(Thread): try: dbs_timestamp = datetime.fromtimestamp(float(dbs_ts_str)) - except: + except Exception: self.logger.error('Could not parse the databases timestamp: {}'.format(dbs_ts_str)) traceback.print_exc() return True @@ -128,7 +128,7 @@ class DatabaseUpdater(Thread): tf = tarfile.open(self.COMPRESS_FILE_PATH) tf.extractall(APPIMAGE_CACHE_DIR) self.logger.info('Successfully uncompressed file {}'.format(self.COMPRESS_FILE_PATH)) - except: + except Exception: self.logger.error('Could not extract file {}'.format(self.COMPRESS_FILE_PATH)) traceback.print_exc() return False @@ -209,7 +209,7 @@ class SymlinksVerifier(Thread): else: try: Path(SYMLINKS_DIR).mkdir(parents=True, exist_ok=True) - except: + except Exception: logger.error("Could not create symlink directory '{}'".format(SYMLINKS_DIR)) return @@ -224,7 +224,7 @@ class SymlinksVerifier(Thread): if watcher: watcher.print(msg) - except: + except Exception: msg = "Could not create the symlink '{}'".format(symlink_path) logger.error(msg) @@ -244,7 +244,7 @@ class SymlinksVerifier(Thread): with open(json_file) as f: try: data = json.loads(f.read()) - except: + except Exception: self.logger.warning("Could not parse data from '{}'".format(json_file)) data = None @@ -264,7 +264,7 @@ class SymlinksVerifier(Thread): try: with open(json_file, 'w+') as f: f.write(json.dumps(data)) - except: + except Exception: self.logger.warning("Could not update cached data on '{}'".format(json_file)) traceback.print_exc() @@ -335,7 +335,7 @@ class AppImageSuggestionsDownloader(Thread): try: exp_hours = int(appimage_config['suggestions']['expiration']) - except: + except Exception: self.logger.error("An exception happened while trying to parse the AppImage 'suggestions.expiration'") traceback.print_exc() return True @@ -357,7 +357,7 @@ class AppImageSuggestionsDownloader(Thread): try: suggestions_timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: self.logger.error(f'Could not parse the cached AppImage suggestions timestamp: {timestamp_str}') traceback.print_exc() return True @@ -405,14 +405,14 @@ class AppImageSuggestionsDownloader(Thread): try: with open(self.cached_file_path, 'w+') as f: f.write(text) - except: + except Exception: self.logger.error(f"An exception happened while writing AppImage suggestions to {self.cached_file_path}") traceback.print_exc() try: with open(self.cached_ts_file_path, 'w+') as f: f.write(str(timestamp)) - except: + except Exception: self.logger.error(f"An exception happened while writing the cached AppImage suggestions timestamp " f"to {self.cached_ts_file_path}") traceback.print_exc() @@ -451,7 +451,7 @@ class AppImageSuggestionsDownloader(Thread): ti = time.time() if not self.is_custom_local_file_mapped(): - if self.create_config: + if self.create_config: wait_msg = self.i18n['task.waiting_task'].format(bold(self.create_config.task_name)) self.taskman.update_progress(self.task_id, 0, wait_msg) self.create_config.join() @@ -474,7 +474,7 @@ class AppImageSuggestionsDownloader(Thread): self.cache_suggestions(suggestions_str, suggestions_timestamp) else: self.logger.info("Cached AppImage suggestions are up-to-date") - except: + except Exception: self.logger.error("An unexpected exception happened while downloading AppImage suggestions") traceback.print_exc() diff --git a/bauh/gems/arch/aur.py b/bauh/gems/arch/aur.py index fa1b02de..79ff5767 100644 --- a/bauh/gems/arch/aur.py +++ b/bauh/gems/arch/aur.py @@ -281,7 +281,7 @@ class AURClient: return set() else: return index.values() - except: + except Exception: return set() def clean_caches(self): @@ -314,4 +314,3 @@ class AURClient: def is_supported(arch_config: dict) -> bool: return arch_config['aur'] and git.is_installed() - diff --git a/bauh/gems/arch/controller.py b/bauh/gems/arch/controller.py index c27724b9..22c982b9 100644 --- a/bauh/gems/arch/controller.py +++ b/bauh/gems/arch/controller.py @@ -414,7 +414,7 @@ class ArchManager(SoftwareManager, SettingsController): res.update_total() return res - def _fill_aur_pkgs_offline(self, aur_pkgs: dict, arch_config: dict, output: List[ArchPackage], disk_loader: Optional[DiskCacheLoader]): + def _fill_aur_pkgs_offline(self, aur_pkgs: dict, arch_config: dict, output: List[ArchPackage], disk_loader: Optional[DiskCacheLoader]): self.logger.info("Reading cached data from installed AUR packages") editable_pkgbuilds = self._read_editable_pkgbuilds() if arch_config['edit_aur_pkgbuild'] is not False else None @@ -850,7 +850,7 @@ class ArchManager(SoftwareManager, SettingsController): body=self.i18n['arch.action.db_locked.error'], type_=MessageType.ERROR) return True - except: + except Exception: self.logger.error("An error occurred while removing the pacman database lock") traceback.print_exc() handler.watcher.show_message(title=self.i18n['error'].capitalize(), @@ -1065,7 +1065,7 @@ class ArchManager(SoftwareManager, SettingsController): output_handler.join() self.logger.error("'pacman' returned an unexpected response or error phrase after upgrading the repository packages") return False - except: + except Exception: handler.watcher.change_substatus('') handler.watcher.print("An error occurred while upgrading repository packages") self.logger.error("An error occurred while upgrading repository packages") @@ -1092,7 +1092,7 @@ class ArchManager(SoftwareManager, SettingsController): return False return True - except: + except Exception: self.logger.error("An error occurred while removing packages: {}".format(', '.join(to_remove))) traceback.print_exc() output_handler.stop_working() @@ -1180,7 +1180,7 @@ class ArchManager(SoftwareManager, SettingsController): else: any_upgraded = True watcher.print(self.i18n['arch.upgrade.success'].format('"{}"'.format(pkg.name))) - except: + except Exception: if any_upgraded: self._update_aur_index(watcher) @@ -1307,7 +1307,7 @@ class ArchManager(SoftwareManager, SettingsController): return True - def _fill_aur_providers(self, names: str, output: Set[str]): + def _fill_aur_providers(self, names: str, output: Set[str]): for _, data in self.aur_client.gen_updates_data(names): providers = data.get('p') @@ -1596,7 +1596,7 @@ class ArchManager(SoftwareManager, SettingsController): if pkg.first_submitted: info['08_first_submitted'] = self._parse_timestamp(ts=pkg.first_submitted, - error_msg="Could not parse AUR package '{}' 'first_submitted' field".format(pkg.name, pkg.first_submitted)) + error_msg="Could not parse AUR package '{}' 'first_submitted' field ({})".format(pkg.name, pkg.first_submitted)) if pkg.last_modified: info['09_last_modified'] = self._parse_timestamp(ts=pkg.last_modified, @@ -1764,7 +1764,7 @@ class ArchManager(SoftwareManager, SettingsController): try: Path(extract_path).mkdir(parents=True, exist_ok=True) - except: + except Exception: self.logger.error("Could not create temp dir {} to extract previous versions data".format(extract_path)) traceback.print_exc() return data @@ -1814,7 +1814,7 @@ class ArchManager(SoftwareManager, SettingsController): try: self.logger.info("Removing temporary history dir {}".format(extract_path)) shutil.rmtree(extract_path) - except: + except Exception: self.logger.error("Could not remove temp path '{}'".format(extract_path)) raise @@ -2181,7 +2181,7 @@ class ArchManager(SoftwareManager, SettingsController): if not os.path.exists(cache_path): try: os.mkdir(cache_path) - except: + except Exception: print("Could not create cache directory '{}'".format(cache_path)) traceback.print_exc() return @@ -2190,11 +2190,11 @@ class ArchManager(SoftwareManager, SettingsController): dest_pkgbuild = '{}/PKGBUILD'.format(cache_path) try: shutil.copy(src_pkgbuild, dest_pkgbuild) - except: + except Exception: context.watcher.print("Could not copy '{}' to '{}'".format(src_pkgbuild, dest_pkgbuild)) traceback.print_exc() - def _ask_and_install_missing_deps(self, context: TransactionContext, missing_deps: List[Tuple[str, str]]) -> bool: + def _ask_and_install_missing_deps(self, context: TransactionContext, missing_deps: List[Tuple[str, str]]) -> bool: context.watcher.change_substatus(self.i18n['arch.missing_deps_found'].format(bold(context.name))) if not confirm_missing_deps(missing_deps, context.watcher, self.i18n): @@ -2264,7 +2264,7 @@ class ArchManager(SoftwareManager, SettingsController): missing_deps = self._list_missing_deps(context) except PackageNotFoundException: return False - except: + except Exception: traceback.print_exc() return False @@ -2406,8 +2406,8 @@ class ArchManager(SoftwareManager, SettingsController): def _multithreaded_download_enabled(self, arch_config: dict) -> bool: return bool(arch_config['repositories_mthread_download']) \ - and self.context.file_downloader.is_multithreaded() \ - and pacman.is_mirrors_available() + and self.context.file_downloader.is_multithreaded() \ + and pacman.is_mirrors_available() def _download_packages(self, pkgnames: List[str], handler: ProcessHandler, root_password: Optional[str], sizes: Dict[str, int] = None, multithreaded: bool = True) -> int: if multithreaded: @@ -2431,7 +2431,7 @@ class ArchManager(SoftwareManager, SettingsController): return len(pkgnames) else: raise ArchDownloadException() - except: + except Exception: traceback.print_exc() raise ArchDownloadException() @@ -2516,7 +2516,7 @@ class ArchManager(SoftwareManager, SettingsController): status_handler = None installed_with_same_name = self.read_installed(disk_loader=context.disk_loader, internet_available=True, names=context.get_package_names()).installed - context.watcher.change_substatus(self.i18n['arch.installing.package'].format(bold(context.name))) # + context.watcher.change_substatus(self.i18n['arch.installing.package'].format(bold(context.name))) # installed = self._handle_install_call(context=context, to_install=to_install, status_handler=status_handler) @@ -3128,7 +3128,7 @@ class ArchManager(SoftwareManager, SettingsController): try: self.configman.save_config(arch_config) return True, None - except: + except Exception: return False, [traceback.format_exc()] def get_upgrade_requirements(self, pkgs: List[ArchPackage], root_password: Optional[str], watcher: ProcessWatcher) -> UpgradeRequirements: @@ -3323,7 +3323,7 @@ class ArchManager(SoftwareManager, SettingsController): if not cache_dir or not os.path.isdir(cache_dir): watcher.show_message(title=self.i18n['arch.custom_action.clean_cache'].capitalize(), - body=self.i18n['arch.custom_action.clean_cache.no_dir'.format(bold(cache_dir))].capitalize(), + body=self.i18n['arch.custom_action.clean_cache.no_dir'].format(bold(cache_dir)).capitalize(), type_=MessageType.WARNING) return True @@ -3415,7 +3415,7 @@ class ArchManager(SoftwareManager, SettingsController): self._write_editable_pkgbuilds(editable) return True - except: + except Exception: traceback.print_exc() return False @@ -3436,7 +3436,7 @@ class ArchManager(SoftwareManager, SettingsController): editable.remove(pkgname) self._write_editable_pkgbuilds(editable) - except: + except Exception: traceback.print_exc() return False @@ -3679,7 +3679,7 @@ class ArchManager(SoftwareManager, SettingsController): else: rebuild_detector.remove_from_ignored(pkg.name) pkg.allow_rebuild = True - except: + except Exception: self.logger.error("An unexpected exception happened") traceback.print_exc() return False diff --git a/bauh/gems/arch/database.py b/bauh/gems/arch/database.py index 63a17f80..dda0c053 100644 --- a/bauh/gems/arch/database.py +++ b/bauh/gems/arch/database.py @@ -31,7 +31,7 @@ def should_sync(arch_config: dict, aur_supported: bool, handler: Optional[Proces if handler: handler.watcher.print(msg) return False - except: + except Exception: logger.warning("Could not convert the database synchronization time from '{}".format(SYNC_FILE)) traceback.print_exc() return True @@ -48,6 +48,6 @@ def register_sync(logger: Logger): Path('/'.join(SYNC_FILE.split('/')[0:-1])).mkdir(parents=True, exist_ok=True) with open(SYNC_FILE, 'w+') as f: f.write(str(int(time.time()))) - except: + except Exception: logger.error("Could not write to database sync file '{}'".format(SYNC_FILE)) traceback.print_exc() diff --git a/bauh/gems/arch/dependencies.py b/bauh/gems/arch/dependencies.py index f84ff783..f48af8ad 100644 --- a/bauh/gems/arch/dependencies.py +++ b/bauh/gems/arch/dependencies.py @@ -288,7 +288,7 @@ class DependenciesAnalyser: if not version_required or match_required_version(pkgdata['v'], exp_op, version_required): yield pkgname, pkgdata - except: + except Exception: self._log.warning(f"Could not compare AUR package '{pkgname}' version '{pkgdata['v']}' " f"with the dependency expression '{dep_exp}'") traceback.print_exc() @@ -588,7 +588,7 @@ class DependenciesAnalyser: if repo_selected: providers_data.update(pacman.map_updates_data(repo_selected)) # adding the providers as "installed" packages - provided_map.update(pacman.map_provided(remote=True, pkgs=repo_selected)) + provided_map.update(pacman.map_provided(remote=True, pkgs=repo_selected)) if aur_selected: for pkgname, pkgdata in self.aur_client.gen_updates_data(aur_selected): diff --git a/bauh/gems/arch/disk.py b/bauh/gems/arch/disk.py index 657dda8f..d47a09b0 100644 --- a/bauh/gems/arch/disk.py +++ b/bauh/gems/arch/disk.py @@ -11,7 +11,7 @@ RE_DESKTOP_ENTRY = re.compile(r'[\n^](Exec|Icon|NoDisplay)\s*=\s*(.+)') RE_CLEAN_NAME = re.compile(r'[+*?%]') -def write_several(pkgs: Dict[str, ArchPackage], overwrite: bool = True, maintainer: str = None, after_desktop_files: Optional[Callable] = None, after_written: Optional[Callable[[str], None]] = None) -> int: +def write_several(pkgs: Dict[str, ArchPackage], overwrite: bool = True, maintainer: str = None, after_desktop_files: Optional[Callable] = None, after_written: Optional[Callable[[str], None]] = None) -> int: if overwrite: to_cache = {p.name for p in pkgs.values()} else: diff --git a/bauh/gems/arch/download.py b/bauh/gems/arch/download.py index acf10c5f..09513473 100644 --- a/bauh/gems/arch/download.py +++ b/bauh/gems/arch/download.py @@ -56,7 +56,7 @@ class MultiThreadedDownloader: msg = "Package '{}' signature successfully downloaded".format(pkg['n']) self.logger.info(msg) watcher.print(msg) - except: + except Exception: self.logger.warning("An error occurred while download package '{}' signature".format(pkg['n'])) traceback.print_exc() @@ -178,7 +178,7 @@ class MultithreadedDownloadService: substatus_prefix=status_prefix, size=sizes.get(pkg['n']) if sizes else None): downloaded += 1 - except: + except Exception: traceback.print_exc() watcher.show_message(title=self.i18n['error'].capitalize(), body=self.i18n['arch.mthread_downloaded.error.cancelled'], diff --git a/bauh/gems/arch/mirrors.py b/bauh/gems/arch/mirrors.py index 81dacebd..47ec7411 100644 --- a/bauh/gems/arch/mirrors.py +++ b/bauh/gems/arch/mirrors.py @@ -26,7 +26,7 @@ def should_sync(logger: logging.Logger): msg = "Package databases already synchronized" logger.info(msg) return False - except: + except Exception: logger.warning("Could not convert the database synchronization time from '{}".format(SYNC_FILE)) traceback.print_exc() return True @@ -37,6 +37,6 @@ def register_sync(logger: Logger): Path('/'.join(SYNC_FILE.split('/')[0:-1])).mkdir(parents=True, exist_ok=True) with open(SYNC_FILE, 'w+') as f: f.write(str(int(time.time()))) - except: + except Exception: logger.error("Could not write to mirrors sync file '{}'".format(SYNC_FILE)) traceback.print_exc() diff --git a/bauh/gems/arch/model.py b/bauh/gems/arch/model.py index 7f6b27ba..d7e36886 100644 --- a/bauh/gems/arch/model.py +++ b/bauh/gems/arch/model.py @@ -250,7 +250,7 @@ class ArchPackage(SoftwarePackage): if isinstance(other, ArchPackage): if self.view_name is not None and other.view_name is not None: return self.view_name == other.view_name and self.repository == other.repository - + return self.name == other.name and self.repository == other.repository def get_cached_pkgbuild_path(self) -> str: diff --git a/bauh/gems/arch/pacman.py b/bauh/gems/arch/pacman.py index 15ce12a2..d29ae838 100644 --- a/bauh/gems/arch/pacman.py +++ b/bauh/gems/arch/pacman.py @@ -697,7 +697,7 @@ def map_updates_data(pkgs: Iterable[str], files: bool = False, description: bool latest_name = None latest_field = None data = {'ds': None, 's': None, 'c': None, 'p': None, 'd': None, - 'r': None, 'v': None, 'des': None} + 'r': None, 'v': None, 'des': None} else: latest_field = None @@ -862,7 +862,7 @@ def map_required_by(names: Iterable[str] = None, remote: bool = False) -> Dict[s if output: latest_name, required = None, None res = {} - + for l in output.split('\n'): if l: if l[0] != ' ': diff --git a/bauh/gems/arch/proc_util.py b/bauh/gems/arch/proc_util.py index 4ef77ce8..13bb59d4 100644 --- a/bauh/gems/arch/proc_util.py +++ b/bauh/gems/arch/proc_util.py @@ -17,7 +17,7 @@ class CallAsUser: try: os.setuid(getpwnam(self._user).pw_uid) return self._target() - except: + except Exception: traceback.print_exc() @@ -33,7 +33,7 @@ class WriteToFile: f.write(self._content) return True - except: + except Exception: traceback.print_exc() return False diff --git a/bauh/gems/arch/suggestions.py b/bauh/gems/arch/suggestions.py index b87f9acf..08ec8a83 100644 --- a/bauh/gems/arch/suggestions.py +++ b/bauh/gems/arch/suggestions.py @@ -91,7 +91,7 @@ class RepositorySuggestionsDownloader(Thread): try: suggestions_timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: self._log.error(f'Could not parse the Arch cached suggestions timestamp: {timestamp_str}') traceback.print_exc() return True @@ -122,14 +122,14 @@ class RepositorySuggestionsDownloader(Thread): try: with open(self.file_suggestions(), 'w+') as f: f.write(text) - except: + except Exception: self._log.error(f"An exception happened while writing the file '{self.file_suggestions()}'") traceback.print_exc() try: with open(self.file_suggestions_timestamp(), 'w+') as f: f.write(str(timestamp)) - except: + except Exception: self._log.error(f"An exception happened while writing the file '{self.file_suggestions_timestamp()}'") traceback.print_exc() diff --git a/bauh/gems/arch/updates.py b/bauh/gems/arch/updates.py index 9ec192bf..b25a6e7d 100644 --- a/bauh/gems/arch/updates.py +++ b/bauh/gems/arch/updates.py @@ -216,7 +216,7 @@ class UpdatesSummarizer: self.logger.warning("No version declared in SRCINFO of '{}'".format(pkg_data[0])) else: self.logger.warning("Could not retrieve the SRCINFO for '{}'".format(pkg_data[0])) - except: + except Exception: self.logger.warning("Could not retrieve the SRCINFO for '{}'".format(pkg_data[0])) else: version = pacman.get_version_for_not_installed(pkg_data[0]) @@ -341,7 +341,7 @@ class UpdatesSummarizer: if pkgdata: requirement.required_size = pkgdata['ds'] requirement.extra_size = pkgdata['s'] - + current_size = installed_sizes.get(pkg.name) if installed_sizes else None if current_size is not None and pkgdata['s'] is not None: @@ -742,7 +742,7 @@ class UpdatesSummarizer: if match_required_version(current_version=v, operator=op, required_version=dep_split[1]): version_match = True break - except: + except Exception: self.logger.error("Error when comparing versions {} (provided) and {} (required)".format(v, dep_split[1])) traceback.print_exc() diff --git a/bauh/gems/arch/worker.py b/bauh/gems/arch/worker.py index bd1bdae4..ecd81883 100644 --- a/bauh/gems/arch/worker.py +++ b/bauh/gems/arch/worker.py @@ -1,3 +1,4 @@ +from __future__ import annotations import glob import logging import os @@ -22,6 +23,10 @@ from bauh.gems.arch import pacman, disk, CUSTOM_MAKEPKG_FILE, ARCH_CONFIG_DIR, A from bauh.gems.arch.aur import URL_INDEX from bauh.view.util.translation import I18n +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from bauh.gems.arch.controller import ArchManager + URL_INFO = 'https://aur.archlinux.org/rpc/?v=5&type=info&arg={}' GLOBAL_MAKEPKG = '/etc/makepkg.conf' @@ -49,7 +54,7 @@ class AURIndexUpdater(Thread): try: exp_hours = int(self.config['aur_idx_exp']) - except: + except Exception: traceback.print_exc() return True @@ -68,7 +73,7 @@ class AURIndexUpdater(Thread): try: index_timestamp = datetime.fromtimestamp(float(timestamp_str)) return (index_timestamp + timedelta(hours=exp_hours)) <= datetime.utcnow() - except: + except Exception: traceback.print_exc() return True @@ -143,7 +148,7 @@ class AURIndexUpdater(Thread): class ArchDiskCacheUpdater(Thread): def __init__(self, taskman: TaskManager, i18n: I18n, logger: logging.Logger, - controller: "ArchManager", internet_available: bool, aur_indexer: Thread, + controller: ArchManager, internet_available: bool, aur_indexer: Thread, create_config: CreateConfigFile): super(ArchDiskCacheUpdater, self).__init__(daemon=True) self.logger = logger @@ -265,7 +270,7 @@ class ArchCompilationOptimizer(Thread): ti = time.time() try: ncpus = os.cpu_count() - except: + except Exception: self.logger.error('Could not determine the number of processors. Aborting...') ncpus = None @@ -385,7 +390,7 @@ class ArchCompilationOptimizer(Thread): if self.create_config.config['optimize'] and aur.is_supported(self.create_config.config): try: self.optimize() - except: + except Exception: self.logger.error("Unexpected exception") traceback.print_exc() self.taskman.update_progress(self.task_id, 100, None) @@ -396,7 +401,7 @@ class ArchCompilationOptimizer(Thread): try: self.logger.info("Removing custom 'makepkg.conf' -> '{}'".format(CUSTOM_MAKEPKG_FILE)) os.remove(CUSTOM_MAKEPKG_FILE) - except: + except Exception: self.logger.error("Unexpected exception") traceback.print_exc() @@ -428,7 +433,7 @@ class RefreshMirrors(Thread): @staticmethod def is_enabled(arch_config: dict, aur_supported: bool) -> bool: return (arch_config['repositories'] or aur_supported) \ - and arch_config['refresh_mirrors_startup'] and pacman.is_mirrors_available() + and arch_config['refresh_mirrors_startup'] and pacman.is_mirrors_available() @classmethod def should_synchronize(cls, arch_config: dict, aur_supported: bool, logger: logging.Logger) -> bool: @@ -468,7 +473,7 @@ class RefreshMirrors(Thread): self.taskman.update_progress(self.task_id, 50, self.i18n['arch.custom_action.refresh_mirrors.status.updating']) try: handler.handle_simple(pacman.sort_fastest_mirrors(self.root_password, sort_limit), output_handler=self._notify_output) - except: + except Exception: self.logger.error("Could not sort mirrors by speed") traceback.print_exc() @@ -476,7 +481,7 @@ class RefreshMirrors(Thread): self.refreshed = True else: self.logger.error("It was not possible to refresh mirrors") - except: + except Exception: self.logger.error("It was not possible to refresh mirrors") traceback.print_exc() @@ -518,7 +523,7 @@ class SyncDatabases(Thread): self.taskman.update_progress(self.task_id, 0, self.i18n['task.waiting_task'].format(bold(self.refresh_mirrors.task_name))) self.refresh_mirrors.join() - self.taskman.update_progress(self.task_id, 1, self.i18n['arch.task.checking_settings']) + self.taskman.update_progress(self.task_id, 1, self.i18n['arch.task.checking_settings']) arch_config = self.create_config.config aur_supported = aur.is_supported(arch_config) @@ -580,7 +585,7 @@ class SyncDatabases(Thread): else: self.logger.error("Could not synchronize database") - except: + except Exception: self.logger.info("Error while synchronizing databases") traceback.print_exc() diff --git a/bauh/gems/debian/aptitude.py b/bauh/gems/debian/aptitude.py index 8a3f62f1..097ea5df 100644 --- a/bauh/gems/debian/aptitude.py +++ b/bauh/gems/debian/aptitude.py @@ -201,7 +201,7 @@ class Aptitude: query = f"'({'|'.join(f'?exact-name({n})' for n in names)})'" yield from self.search(query=query, fill_size=fill_size) - def remove(self, packages: Iterable[str], root_password: Optional[str], purge: bool = False) -> SimpleProcess: + def remove(self, packages: Iterable[str], root_password: Optional[str], purge: bool = False) -> SimpleProcess: return SimpleProcess(cmd=self.gen_remove_cmd(packages, purge).split(' '), shell=True, root_password=root_password, extra_env=self.vars_fixes, preserve_env=self._preserve_env) diff --git a/bauh/gems/debian/config.py b/bauh/gems/debian/config.py index 1369d248..a81ccd3d 100644 --- a/bauh/gems/debian/config.py +++ b/bauh/gems/debian/config.py @@ -9,9 +9,9 @@ class DebianConfigManager(YAMLConfigManager): def get_default_config(self) -> dict: return { - 'suggestions.exp': 24, # hours - 'index_apps.exp': 1440, # 24 hours - 'sync_pkgs.time': 1440, # 24 hours - 'pkg_sources.app': None, - 'remove.purge': False - } + 'suggestions.exp': 24, # hours + 'index_apps.exp': 1440, # 24 hours + 'sync_pkgs.time': 1440, # 24 hours + 'pkg_sources.app': None, + 'remove.purge': False + } diff --git a/bauh/gems/debian/controller.py b/bauh/gems/debian/controller.py index 3e8dbc49..6708aeb1 100644 --- a/bauh/gems/debian/controller.py +++ b/bauh/gems/debian/controller.py @@ -69,7 +69,7 @@ class DebianPackageManager(SoftwareManager, SettingsController): for pkg in self.aptitude.search(words): if fill_config.is_alive(): fill_config.join() - + pkg.global_purge = bool(config_.get('remove.purge', False)) if pkg.installed: pkg.bind_app(self.apps_index.get(pkg.name)) @@ -688,7 +688,7 @@ class DebianPackageManager(SoftwareManager, SettingsController): try: self.configman.save_config(config_) return True, None - except: + except Exception: return False, [traceback.format_exc()] def gen_custom_actions(self) -> Generator[CustomSoftwareAction, None, None]: diff --git a/bauh/gems/debian/index.py b/bauh/gems/debian/index.py index f2f8418d..b86f7941 100644 --- a/bauh/gems/debian/index.py +++ b/bauh/gems/debian/index.py @@ -53,7 +53,7 @@ class ApplicationIndexer: try: timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: self._log.error(f'Could not parse the Debian applications index timestamp: {timestamp_str} ' f'({self._file_timestamp_path})') traceback.print_exc() diff --git a/bauh/gems/debian/suggestions.py b/bauh/gems/debian/suggestions.py index 878a6a54..de6cb9ae 100644 --- a/bauh/gems/debian/suggestions.py +++ b/bauh/gems/debian/suggestions.py @@ -96,7 +96,7 @@ class DebianSuggestionsDownloader(Thread): try: suggestions_timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: self._log.error(f'Could not parse the Debian cached suggestions timestamp: {timestamp_str}') traceback.print_exc() return True @@ -128,14 +128,14 @@ class DebianSuggestionsDownloader(Thread): try: with open(self.file_suggestions(), 'w+') as f: f.write(text) - except: + except Exception: self._log.error(f"An exception happened while writing the file '{self.file_suggestions()}'") traceback.print_exc() try: with open(self.file_suggestions_timestamp(), 'w+') as f: f.write(str(timestamp)) - except: + except Exception: self._log.error(f"An exception happened while writing the file '{self.file_suggestions_timestamp()}'") traceback.print_exc() diff --git a/bauh/gems/debian/tasks.py b/bauh/gems/debian/tasks.py index 51a18730..f526c764 100644 --- a/bauh/gems/debian/tasks.py +++ b/bauh/gems/debian/tasks.py @@ -101,7 +101,7 @@ class UpdateApplicationIndex(Thread): try: self._indexer.update_index(self._mapping_apps.apps) - except: + except Exception: finish_msg = self._i18n['error'] self._taskman.update_progress(self._id, 100, finish_msg) @@ -150,7 +150,7 @@ class SynchronizePackages(Thread): try: last_timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: logger.error(f'Could not parse the packages synchronization timestamp: {timestamp_str} ' f'({PACKAGE_SYNC_TIMESTAMP_FILE})') traceback.print_exc() @@ -169,7 +169,7 @@ class SynchronizePackages(Thread): ti = time.time() self._log.info("Begin: packages synchronization") self._taskman.update_progress(self._id, 1, None) - + handler = ProcessHandler(self._watcher) updated, _ = handler.handle_simple(self._aptitude.update(self._root_password), output_handler=self._notify_output) diff --git a/bauh/gems/flatpak/controller.py b/bauh/gems/flatpak/controller.py index a2cc9112..0cdf0ca7 100644 --- a/bauh/gems/flatpak/controller.py +++ b/bauh/gems/flatpak/controller.py @@ -317,7 +317,7 @@ class FlatpakManager(SoftwareManager, SettingsController): if not res: self.logger.warning("Could not upgrade '{}'".format(req.pkg.id)) return False - except: + except Exception: watcher.change_substatus('') self.logger.error("An error occurred while upgrading '{}'".format(req.pkg.id)) traceback.print_exc() @@ -394,7 +394,7 @@ class FlatpakManager(SoftwareManager, SettingsController): if res.get(to_date): try: res[to_date] = datetime.strptime(res[to_date], DATE_FORMAT) - except: + except Exception: self.context.logger.error('Could not convert date string {} as {}'.format(res[to_date], DATE_FORMAT)) pass @@ -437,7 +437,7 @@ class FlatpakManager(SoftwareManager, SettingsController): watcher.print('Creating dir {}'.format(EXPORTS_PATH)) try: Path(EXPORTS_PATH).mkdir(parents=True, exist_ok=True) - except: + except Exception: watcher.print('Error while creating the directory {}'.format(EXPORTS_PATH)) return False @@ -530,7 +530,7 @@ class FlatpakManager(SoftwareManager, SettingsController): if fields: pkg.ref = fields[0] pkg.branch = fields[1] - except: + except Exception: traceback.print_exc() if installed: @@ -735,7 +735,7 @@ class FlatpakManager(SoftwareManager, SettingsController): try: self.configman.save_config(flatpak_config) return True, None - except: + except Exception: return False, [traceback.format_exc()] def get_upgrade_requirements(self, pkgs: List[FlatpakApplication], root_password: Optional[str], watcher: ProcessWatcher) -> UpgradeRequirements: diff --git a/bauh/gems/flatpak/flatpak.py b/bauh/gems/flatpak/flatpak.py index a8336bd7..c111dcd0 100755 --- a/bauh/gems/flatpak/flatpak.py +++ b/bauh/gems/flatpak/flatpak.py @@ -81,7 +81,7 @@ def get_version() -> Optional[Version]: def get_app_info(app_id: str, branch: str, installation: str) -> Optional[str]: try: return run_cmd(f'flatpak info {app_id} {branch} --{installation}') - except: + except Exception: traceback.print_exc() return '' @@ -235,7 +235,7 @@ def fill_updates(version: Version, installation: str, res: Dict[str, Set[str]]): for line in output.split(f'Updating in {installation}:\n')[1].split('\n'): if not line.startswith('Is this ok'): res['full'].add('{}/{}'.format(installation, line.split('\t')[0].strip())) - except: + except Exception: traceback.print_exc() else: updates = new_subprocess(('flatpak', 'update', f'--{installation}', '--no-deps')).stdout @@ -270,7 +270,7 @@ def fill_updates(version: Version, installation: str, res: Dict[str, Set[str]]): res['full'].add(update_id) else: res['full'].add(update_id) - except: + except Exception: traceback.print_exc() @@ -293,7 +293,7 @@ def get_app_commits(app_ref: str, origin: str, installation: str, handler: Proce return else: return re.findall(r'Commit+:\s(.+)', output) - except: + except Exception: raise NoInternetException() @@ -479,11 +479,11 @@ def map_update_download_size(app_ids: Iterable[str], installation: str, version: if size and len(size) > 1: try: res[related_id[0].strip()] = size_to_byte(size[0], size[1].strip()) - except: + except Exception: traceback.print_exc() else: try: res[related_id[0].strip()] = size_to_byte(size_tuple[0], size_tuple[1].strip()) - except: + except Exception: traceback.print_exc() return res diff --git a/bauh/gems/flatpak/model.py b/bauh/gems/flatpak/model.py index e2bac51e..3d8d19ae 100644 --- a/bauh/gems/flatpak/model.py +++ b/bauh/gems/flatpak/model.py @@ -11,7 +11,7 @@ class FlatpakApplication(SoftwarePackage): def __init__(self, id: str = None, name: str = None, version: str = None, latest_version: str = None, description: str = None, branch: str = None, arch: str = None, origin: str = None, runtime: bool = False, ref: str = None, commit: str = None, installation: str = None, - i18n: I18n = None, partial: bool = False, updates_ignored: bool = False, installed: bool = False, + i18n: I18n = None, partial: bool = False, updates_ignored: bool = False, installed: bool = False, update: bool = False, update_component: bool = False): super(FlatpakApplication, self).__init__(id=id, name=name, version=version, latest_version=latest_version, description=description, installed=installed, update=update) @@ -126,8 +126,8 @@ class FlatpakApplication(SoftwarePackage): def __eq__(self, other): if isinstance(other, FlatpakApplication): return self.id == other.id and self.installation == other.installation and self.branch == other.branch \ - and self.runtime == other.runtime and self.partial == other.partial and \ - self.update_component == other.update_component + and self.runtime == other.runtime and self.partial == other.partial and \ + self.update_component == other.update_component def __hash__(self) -> int: hash_sum = 0 diff --git a/bauh/gems/flatpak/worker.py b/bauh/gems/flatpak/worker.py index e16df1bb..9f25b59b 100644 --- a/bauh/gems/flatpak/worker.py +++ b/bauh/gems/flatpak/worker.py @@ -89,7 +89,7 @@ class FlatpakAsyncDataLoader(Thread): self.persist = self.app.supports_disk_cache() else: self.logger.warning("Could not retrieve app data for id '{}'. Server response: {}. Body: {}".format(self.app.id, res.status_code if res else '?', res.content.decode() if res else '?')) - except: + except Exception: self.logger.error("Could not retrieve app data for id '{}'".format(self.app.id)) traceback.print_exc() diff --git a/bauh/gems/snap/controller.py b/bauh/gems/snap/controller.py index 7cabfd17..03468e2a 100644 --- a/bauh/gems/snap/controller.py +++ b/bauh/gems/snap/controller.py @@ -180,7 +180,7 @@ class SnapManager(SoftwareManager, SettingsController): try: channel = self._request_channel_installation(pkg=pkg, snap_config=snap_config, snapd_client=client, watcher=watcher) pkg.channel = channel - except: + except Exception: watcher.print('Aborted by user') return TransactionResult.fail() @@ -220,7 +220,7 @@ class SnapManager(SoftwareManager, SettingsController): try: net_available = self.context.internet_checker.is_available() current_installed = self.read_installed(disk_loader=disk_loader, internet_available=net_available).installed - except: + except Exception: new_installed = [pkg] traceback.print_exc() current_installed = None @@ -268,7 +268,7 @@ class SnapManager(SoftwareManager, SettingsController): return ProcessHandler(watcher).handle_simple(snap.refresh_and_stream(app_name=pkg.name, root_password=root_password, channel=channel))[0] - except: + except Exception: return False def _start_category_task(self, taskman: TaskManager, create_config: CreateConfigFile, downloader: CategoriesDownloader): @@ -501,14 +501,14 @@ class SnapManager(SoftwareManager, SettingsController): try: self.configman.save_config(config_) return True, None - except: + except Exception: return False, [traceback.format_exc()] def _request_channel_installation(self, pkg: SnapApplication, snap_config: Optional[dict], snapd_client: SnapdClient, watcher: ProcessWatcher, exclude_current: bool = False) -> Optional[str]: if snap_config is None or snap_config['install_channel']: try: data = [r for r in snapd_client.find_by_name(pkg.name) if r['name'] == pkg.name] - except: + except Exception: self.logger.warning(f"snapd client could not retrieve channels for '{pkg.name}'") return diff --git a/bauh/gems/snap/snapd.py b/bauh/gems/snap/snapd.py index 4a8b0f63..50e08b72 100644 --- a/bauh/gems/snap/snapd.py +++ b/bauh/gems/snap/snapd.py @@ -47,7 +47,7 @@ class SnapdClient: session = Session() session.mount("http://snapd/", SnapdAdapter()) return session - except: + except Exception: self.logger.error("Could not establish a connection to 'snapd.socker'") traceback.print_exc() diff --git a/bauh/gems/web/controller.py b/bauh/gems/web/controller.py index 7de6698e..02ab6f1f 100644 --- a/bauh/gems/web/controller.py +++ b/bauh/gems/web/controller.py @@ -44,14 +44,14 @@ try: from bs4 import BeautifulSoup, SoupStrainer BS4_AVAILABLE = True -except: +except Exception: BS4_AVAILABLE = False try: import lxml LXML_AVAILABLE = True -except: +except Exception: LXML_AVAILABLE = False RE_SEVERAL_SPACES = re.compile(r'\s+') @@ -99,7 +99,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): else: return DEFAULT_LANGUAGE_HEADER - except: + except Exception: return DEFAULT_LANGUAGE_HEADER def clean_environment(self, root_password: Optional[str], watcher: ProcessWatcher) -> bool: @@ -115,7 +115,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): if not res: success = False - except: + except Exception: watcher.print(traceback.format_exc()) success = False @@ -189,7 +189,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): try: utf8_desc = description.encode('iso-8859-1').decode('utf-8') description = utf8_desc - except: + except Exception: pass return description @@ -416,7 +416,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): self.logger.info("Removing {} installation directory {}".format(pkg.name, pkg.installation_dir)) try: shutil.rmtree(pkg.installation_dir) - except: + except Exception: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(pkg.installation_dir)), type_=MessageType.ERROR) @@ -427,7 +427,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): if os.path.exists(pkg.desktop_entry): try: os.remove(pkg.desktop_entry) - except: + except Exception: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(pkg.desktop_entry)), type_=MessageType.ERROR) @@ -437,7 +437,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): if os.path.exists(autostart_path): try: os.remove(autostart_path) - except: + except Exception: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(autostart_path)), type_=MessageType.WARNING) @@ -448,7 +448,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): if config_path and os.path.exists(config_path): try: shutil.rmtree(config_path) - except: + except Exception: watcher.show_message(title=self.i18n['error'], body=self.i18n['web.uninstall.error.remove'].format(bold(config_path)), type_=MessageType.WARNING) @@ -461,7 +461,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): self.logger.info(f"Removing fix file '{fix_path}'") try: os.remove(fix_path) - except: + except Exception: self.logger.error(f"Could not remove fix file '{fix_path}'") traceback.print_exc() watcher.show_message(title=self.i18n['error'], @@ -499,8 +499,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): def get_history(self, pkg: SoftwarePackage) -> PackageHistory: pass - def _ask_install_options(self, app: WebApplication, watcher: ProcessWatcher, pre_validated: bool) -> Tuple[ - bool, List[str]]: + def _ask_install_options(self, app: WebApplication, watcher: ProcessWatcher, pre_validated: bool) -> Tuple[bool, List[str]]: watcher.change_substatus(self.i18n['web.install.substatus.options']) max_width = 350 @@ -713,13 +712,13 @@ class WebApplicationManager(SoftwareManager, SettingsController): self.logger.info('Could not download the icon {}'.format(pkg.icon_url)) else: return icon_path, res.content - except: + except Exception: self.logger.error("An exception has happened when downloading {}".format(pkg.icon_url)) traceback.print_exc() else: self.logger.warning( 'Could no retrieve the icon {} defined for the suggestion {}'.format(pkg.icon_url, pkg.name)) - except: + except Exception: self.logger.warning( 'An exception happened when trying to retrieve the icon {} for the suggestion {}'.format(pkg.icon_url, pkg.name)) @@ -814,7 +813,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): self.logger.info( f"Using custom installation property '{prop}' ({val if val else ''}) for '{url_domain}' " f"(Electron: {electron_version})") - except: + except Exception: self.logger.error( f"Could not set the custom installation property '{prop}' ({val if val else ''}) " f"for '{url_domain}' (Electron: {electron_version})") @@ -872,7 +871,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): with open(package_info_path) as f: package_info_path = json.loads(f.read()) pkg.package_name = package_info_path['name'] - except: + except Exception: self.logger.info("Could not read the the package info from '{}'".format(package_info_path)) traceback.print_exc() @@ -1024,7 +1023,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): try: find_url = not app.icon_url or ( - app.icon_url and not self.http_client.exists(app.icon_url, session=False)) + app.icon_url and not self.http_client.exists(app.icon_url, session=False)) except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout): find_url = None @@ -1156,7 +1155,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): shutil.rmtree(ENV_PATH) if logs: print('{}[bauh][web] Directory {} deleted{}'.format(Fore.YELLOW, ENV_PATH, Fore.RESET)) - except: + except Exception: if logs: print('{}[bauh][web] An exception has happened when deleting {}{}'.format(Fore.RED, ENV_PATH, Fore.RESET)) @@ -1231,7 +1230,7 @@ class WebApplicationManager(SoftwareManager, SettingsController): try: self.configman.save_config(config_) return True, None - except: + except Exception: return False, [traceback.format_exc()] def gen_custom_actions(self) -> Generator[CustomSoftwareAction, None, None]: diff --git a/bauh/gems/web/environment.py b/bauh/gems/web/environment.py index edbc63d2..d32e004b 100644 --- a/bauh/gems/web/environment.py +++ b/bauh/gems/web/environment.py @@ -68,14 +68,14 @@ class EnvironmentUpdater: self.logger.info(f"Removing old NodeJS version installation dir -> {NODE_DIR_PATH}") try: shutil.rmtree(NODE_DIR_PATH) - except: + except Exception: self.logger.error(f"Could not delete old NodeJS version dir -> {NODE_DIR_PATH}") traceback.print_exc() return False try: os.rename(extracted_file, NODE_DIR_PATH) - except: + except Exception: self.logger.error(f"Could not rename the NodeJS version file {extracted_file} as {NODE_DIR_PATH}") traceback.print_exc() return False @@ -84,12 +84,12 @@ class EnvironmentUpdater: self.logger.info(f'Deleting {NODE_MODULES_PATH}') try: shutil.rmtree(NODE_MODULES_PATH) - except: + except Exception: self.logger.error(f"Could not delete the directory {NODE_MODULES_PATH}") return False return True - except: + except Exception: self.logger.error(f'Could not extract {tarf_path}') traceback.print_exc() return False @@ -97,7 +97,7 @@ class EnvironmentUpdater: if os.path.exists(tarf_path): try: os.remove(tarf_path) - except: + except Exception: self.logger.error(f'Could not delete file {tarf_path}') def check_node_installed(self, version: str) -> bool: @@ -152,7 +152,7 @@ class EnvironmentUpdater: try: shutil.rmtree(NODE_DIR_PATH) return self._install_nodejs(version=version, version_url=version_url, watcher=watcher) - except: + except Exception: self.logger.error(f'Could not delete the dir {NODE_DIR_PATH}') return False @@ -246,7 +246,7 @@ class EnvironmentUpdater: try: env_timestamp = datetime.fromtimestamp(float(env_ts_str)) - except: + except Exception: self.logger.error(f"Could not parse environment settings file timestamp: {env_ts_str}") return True diff --git a/bauh/gems/web/nativefier.py b/bauh/gems/web/nativefier.py index afd91fa6..a59870dc 100644 --- a/bauh/gems/web/nativefier.py +++ b/bauh/gems/web/nativefier.py @@ -31,5 +31,3 @@ def is_available() -> bool: def get_version() -> str: return run_cmd('{} --version'.format(NATIVEFIER_BIN_PATH), print_error=False, extra_paths=NODE_PATHS) - - diff --git a/bauh/gems/web/search.py b/bauh/gems/web/search.py index f2ebeeb8..5d37f5e8 100644 --- a/bauh/gems/web/search.py +++ b/bauh/gems/web/search.py @@ -60,7 +60,7 @@ class SearchIndexManager: f.write(yaml.safe_dump(index)) self.logger.info("Search index successfully written at {}".format(SEARCH_INDEX_FILE)) return True - except: + except Exception: self.logger.error("Could not write the search index to {}".format(SEARCH_INDEX_FILE)) traceback.print_exc() diff --git a/bauh/gems/web/suggestions.py b/bauh/gems/web/suggestions.py index 90256ee1..9d133a8e 100644 --- a/bauh/gems/web/suggestions.py +++ b/bauh/gems/web/suggestions.py @@ -69,7 +69,7 @@ class SuggestionsManager: try: sugs_timestamp = datetime.fromtimestamp(float(timestamp_str)) - except: + except Exception: self.logger.error(f"Could not parse the cached suggestions file timestamp: {timestamp_str}") return True @@ -105,7 +105,7 @@ class SuggestionsManager: try: return yaml.safe_load(sugs_str) - except: + except Exception: self.logger.error("An unexpected exception happened") traceback.print_exc() return {} @@ -147,7 +147,7 @@ class SuggestionsManager: try: with open(self._cached_file_path, 'w+') as f: f.write(yaml.safe_dump(suggestions)) - except: + except Exception: self.logger.error(f"Could write to {self._cached_file_path}") traceback.print_exc() return @@ -157,7 +157,7 @@ class SuggestionsManager: try: with open(self._cached_file_ts_path, 'w+') as f: f.write(str(timestamp)) - except: + except Exception: self.logger.error(f"Could not write to {self._cached_file_ts_path}") traceback.print_exc() return diff --git a/bauh/gems/web/worker.py b/bauh/gems/web/worker.py index df0f3916..31ef0c71 100644 --- a/bauh/gems/web/worker.py +++ b/bauh/gems/web/worker.py @@ -59,7 +59,7 @@ class SuggestionsLoader(Thread): if self.suggestions: self.taskman.update_progress(self.task_id, 50, self.i18n['web.task.suggestions.saving']) self.manager.save_to_disk(self.suggestions, timestamp) - except: + except Exception: self.logger.error("Unexpected exception") traceback.print_exc() @@ -67,7 +67,7 @@ class SuggestionsLoader(Thread): self.taskman.update_progress(self.task_id, 75, None) try: self.suggestions_callback(self.suggestions) - except: + except Exception: self.logger.error("Unexpected exception") traceback.print_exc() @@ -125,7 +125,7 @@ class UpdateEnvironmentSettings(Thread): def run(self): self.taskman.register_task(self.task_id, self.i18n['web.task.download_settings'], get_icon_path()) - self.taskman.update_progress(self.task_id, 1, self.i18n['task.waiting_task'].format(bold(self.create_config.task_name))) + self.taskman.update_progress(self.task_id, 1, self.i18n['task.waiting_task'].format(bold(self.create_config.task_name))) self.create_config.join() web_config = self.create_config.config diff --git a/bauh/view/core/__init__.py b/bauh/view/core/__init__.py index 8b137891..e69de29b 100755 --- a/bauh/view/core/__init__.py +++ b/bauh/view/core/__init__.py @@ -1 +0,0 @@ - diff --git a/bauh/view/core/controller.py b/bauh/view/core/controller.py index 66f9acaa..f1987914 100755 --- a/bauh/view/core/controller.py +++ b/bauh/view/core/controller.py @@ -107,7 +107,7 @@ class GenericSoftwareManager(SoftwareManager, SettingsController): try: Popen(['timeshift-launcher'], stderr=STDOUT) return True - except: + except Exception: traceback.print_exc() watcher.show_message(title=self.i18n["error"].capitalize(), body=self.i18n['action.backups.tool_error'].format(bold('Timeshift')), @@ -266,7 +266,7 @@ class GenericSoftwareManager(SoftwareManager, SettingsController): self.logger.info(f'Took {tf - ti:.2f} seconds') return res - def _add_category(self, pkg: SoftwarePackage, category: str): + def _add_category(self, pkg: SoftwarePackage, category: str): if isinstance(pkg.categories, tuple): pkg.categories = tuple((*pkg.categories, category)) elif isinstance(pkg.categories, list): @@ -331,7 +331,7 @@ class GenericSoftwareManager(SoftwareManager, SettingsController): disk_loader.join() self._update_post_transaction_status(res) return res - except: + except Exception: traceback.print_exc() return TransactionResult(success=False, installed=[], removed=[]) finally: @@ -352,7 +352,7 @@ class GenericSoftwareManager(SoftwareManager, SettingsController): disk_loader.join() self._update_post_transaction_status(res) return res - except: + except Exception: traceback.print_exc() return TransactionResult(success=False, installed=[], removed=[]) finally: @@ -617,7 +617,7 @@ class GenericSoftwareManager(SoftwareManager, SettingsController): try: clean_app_files(managers=self.managers, logs=False) restart_app() - except: + except Exception: return False return True diff --git a/bauh/view/core/downloader.py b/bauh/view/core/downloader.py index c6ef0024..313fd865 100644 --- a/bauh/view/core/downloader.py +++ b/bauh/view/core/downloader.py @@ -114,7 +114,7 @@ class AdaptableFileDownloader(FileDownloader): if size: base_substatus.write(f' ( {size} )') watcher.change_substatus(base_substatus.getvalue()) - except: + except Exception: pass def _get_appropriate_threads_number(self, max_threads: int, known_size: int) -> int: @@ -193,7 +193,7 @@ class AdaptableFileDownloader(FileDownloader): watcher.change_substatus(msg.getvalue()) success, _ = handler.handle_simple(process) - except: + except Exception: traceback.print_exc() self._rm_bad_file(file_name, output_path, final_cwd, handler, root_password) diff --git a/bauh/view/core/settings.py b/bauh/view/core/settings.py index 4b9d99bf..dc1b69f5 100644 --- a/bauh/view/core/settings.py +++ b/bauh/view/core/settings.py @@ -587,16 +587,17 @@ class GenericSettingsManager(SettingsController): opts=ops_opts, id_='downgrade') - mode = new_select(label=self.i18n['core.config.backup.mode'], - tip=None, - value=core_config['backup']['mode'], - opts=[ - (self.i18n['core.config.backup.mode.incremental'], 'incremental', - self.i18n['core.config.backup.mode.incremental.tip']), - (self.i18n['core.config.backup.mode.only_one'], 'only_one', - self.i18n['core.config.backup.mode.only_one.tip']) - ], - id_='mode') + mode = new_select( + label=self.i18n['core.config.backup.mode'], + tip=None, + value=core_config['backup']['mode'], + opts=[ + (self.i18n['core.config.backup.mode.incremental'], 'incremental', + self.i18n['core.config.backup.mode.incremental.tip']), + (self.i18n['core.config.backup.mode.only_one'], 'only_one', + self.i18n['core.config.backup.mode.only_one.tip']) + ], + id_='mode') type_ = new_select(label=self.i18n['type'].capitalize(), tip=None, value=core_config['backup']['type'], diff --git a/bauh/view/core/update.py b/bauh/view/core/update.py index 168fdb20..d54e64b6 100644 --- a/bauh/view/core/update.py +++ b/bauh/view/core/update.py @@ -42,7 +42,7 @@ def check_for_update(logger: logging.Logger, http_client: HttpClient, i18n: I18n Path(notifications_dir).mkdir(parents=True, exist_ok=True) with open(release_file, 'w+') as f: f.write('') - except: + except Exception: logger.error("An error occurred while trying to create the update notification file: {}".format(release_file)) if tray: @@ -55,5 +55,5 @@ def check_for_update(logger: logging.Logger, http_client: HttpClient, i18n: I18n logger.warning("No official release found") else: logger.warning("No releases returned from the GitHub API") - except: + except Exception: logger.error("An error occurred while trying to retrieve the current releases") diff --git a/bauh/view/qt/apps_table.py b/bauh/view/qt/apps_table.py index c08e58e6..29c2922d 100644 --- a/bauh/view/qt/apps_table.py +++ b/bauh/view/qt/apps_table.py @@ -99,9 +99,9 @@ class PackagesTable(QTableWidget): def has_any_settings(self, pkg: PackageView): return pkg.model.has_history() or \ - pkg.model.can_be_downgraded() or \ - pkg.model.supports_ignored_updates() or \ - bool(pkg.model.get_custom_actions()) + pkg.model.can_be_downgraded() or \ + pkg.model.supports_ignored_updates() or \ + bool(pkg.model.get_custom_actions()) def show_pkg_actions(self, pkg: PackageView): menu_row = QMenu() @@ -123,11 +123,10 @@ class PackagesTable(QTableWidget): if pkg.model.can_be_downgraded(): def downgrade(): - if ConfirmationDialog(title=self.i18n['manage_window.apps_table.row.actions.downgrade'], - body=self._parag(self.i18n[ - 'manage_window.apps_table.row.actions.downgrade.popup.body'].format( - self._bold(str(pkg)))), - i18n=self.i18n).ask(): + if ConfirmationDialog( + title=self.i18n['manage_window.apps_table.row.actions.downgrade'], + body=self._parag(self.i18n['manage_window.apps_table.row.actions.downgrade.popup.body'].format(self._bold(str(pkg)))), + i18n=self.i18n).ask(): self.window.begin_downgrade(pkg) menu_row.addAction(QCustomMenuAction(parent=menu_row, @@ -414,7 +413,7 @@ class PackagesTable(QTableWidget): elif pkg.model.icon_url: self.icon_cache.add_non_existing(pkg.model.icon_url, {'icon': icon, 'bytes': None}) - except: + except Exception: icon = QIcon(pkg.model.get_default_icon_path()) elif not pkg.model.icon_url: diff --git a/bauh/view/qt/components.py b/bauh/view/qt/components.py index 7c04a9cc..dabd6bc9 100644 --- a/bauh/view/qt/components.py +++ b/bauh/view/qt/components.py @@ -216,7 +216,7 @@ class QtComponentsManager: if state['r'] != self._is_read_only(comp): self._set_read_only(comp, state['r']) - def restore_group_state(self, group_id: int, state_id: int): + def restore_group_state(self, group_id: int, state_id: int): states = self._saved_states.get(state_id) if states: @@ -808,7 +808,7 @@ class FormQt(QGroupBox): label, field = self._new_file_chooser(c) self.layout().addRow(label, field) elif isinstance(c, FormComponent): - label, field = None, FormQt(c, self.i18n) + label, field = None, FormQt(c, self.i18n) self.layout().addRow(field) elif isinstance(c, TwoStateButtonComponent): label, field = self._new_label(c), TwoStateButtonQt(c) @@ -1037,7 +1037,7 @@ class TabGroupQt(QTabWidget): for c in model.tabs: try: icon = QIcon(c.icon_path) if c.icon_path else QIcon() - except: + except Exception: traceback.print_exc() icon = QIcon() diff --git a/bauh/view/qt/history.py b/bauh/view/qt/history.py index 496ac76d..30ad4d02 100644 --- a/bauh/view/qt/history.py +++ b/bauh/view/qt/history.py @@ -45,7 +45,7 @@ class HistoryDialog(QDialog): if current_status: item.setCursor(QCursor(Qt.WhatsThisCursor)) - item.setProperty('outdated', str(row != 0).lower()) + item.setProperty('outdated', str(row != 0).lower()) tip = '{}. {}.'.format(i18n['popup.history.selected.tooltip'], i18n['version.{}'.format('updated'if row == 0 else 'outdated')].capitalize()) diff --git a/bauh/view/qt/root.py b/bauh/view/qt/root.py index e0ac654d..0c58c10c 100644 --- a/bauh/view/qt/root.py +++ b/bauh/view/qt/root.py @@ -29,7 +29,7 @@ class ValidatePassword(QThread): if isinstance(self.password, str): try: valid = validate_password(self.password) - except: + except Exception: traceback.print_exc() valid = False diff --git a/bauh/view/qt/systray.py b/bauh/view/qt/systray.py index 1567eccd..1d39829f 100755 --- a/bauh/view/qt/systray.py +++ b/bauh/view/qt/systray.py @@ -46,7 +46,7 @@ def get_cli_path() -> str: return cli_path else: return shutil.which(CLI_NAME) - + def list_updates(logger: logging.Logger) -> List[PackageUpdate]: cli_path = get_cli_path() @@ -94,7 +94,7 @@ class UpdateCheck(QThread): self._notify_updates() try: os.remove(TRAY_CHECK_FILE) - except: + except Exception: traceback.print_exc() else: self.sleep(self.check_interval) diff --git a/bauh/view/qt/thread.py b/bauh/view/qt/thread.py index 5b8eb18c..6f38ecae 100644 --- a/bauh/view/qt/thread.py +++ b/bauh/view/qt/thread.py @@ -48,7 +48,7 @@ class AsyncAction(QThread, ProcessWatcher): signal_root_password = pyqtSignal() signal_progress_control = pyqtSignal(bool) - def __init__(self, i18n: I18n, root_password: Optional[Tuple[bool, str]] = None): + def __init__(self, i18n: I18n, root_password: Optional[Tuple[bool, str]] = None): super(AsyncAction, self).__init__() self.i18n = i18n self.wait_confirmation = False @@ -135,7 +135,7 @@ class AsyncAction(QThread, ProcessWatcher): def _generate_backup(self, app_config: dict, root_password: Optional[str]) -> bool: if app_config['backup']['mode'] not in ('only_one', 'incremental'): self.show_message(title=self.i18n['error'].capitalize(), - body='{}: {}'.format(self.i18n['action.backup.invalid_mode'],bold(app_config['backup']['mode'])), + body='{}: {}'.format(self.i18n['action.backup.invalid_mode'], bold(app_config['backup']['mode'])), type_=MessageType.ERROR) self.change_substatus('') return False @@ -414,7 +414,7 @@ class UpgradeSelected(AsyncAction): with open(self.SUMMARY_FILE.format(upgrade_id), 'w+') as f: f.write(summary_text.read()) - except: + except Exception: traceback.print_exc() def _handle_internet_off(self): @@ -592,7 +592,7 @@ class RefreshApps(AsyncAction): refreshed_types = self.pkg_types self.notify_finished({'installed': res.installed, 'total': res.total, 'types': refreshed_types}) - except: + except Exception: traceback.print_exc() self.notify_finished({'installed': [], 'total': 0, 'types': set()}) finally: @@ -631,7 +631,7 @@ class UninstallPackage(AsyncAction): self.manager.clean_cache_for(p) self.notify_finished({'success': res.success, 'removed': res.removed, 'pkg': self.pkg}) - except: + except Exception: traceback.print_exc() self.notify_finished({'success': False, 'removed': None, 'pkg': self.pkg}) finally: @@ -948,7 +948,7 @@ class LaunchPackage(AsyncAction): super(LaunchPackage, self).msleep(250) self.manager.launch(self.pkg.model) self.notify_finished(True) - except: + except Exception: traceback.print_exc() finally: self.notify_finished(False) @@ -1083,7 +1083,7 @@ class SaveTheme(QThread): try: configman.save_config(core_config) - except: + except Exception: traceback.print_exc() diff --git a/bauh/view/qt/window.py b/bauh/view/qt/window.py index 3f287cbe..7a061f9c 100755 --- a/bauh/view/qt/window.py +++ b/bauh/view/qt/window.py @@ -1601,7 +1601,7 @@ class ManageWindow(QWidget): icon = QIcon(action.icon_path) else: icon = QIcon.fromTheme(action.icon_path) - except: + except Exception: icon = None else: icon = None diff --git a/bauh/view/util/cache.py b/bauh/view/util/cache.py index 963edd0d..09b8cfdd 100644 --- a/bauh/view/util/cache.py +++ b/bauh/view/util/cache.py @@ -112,5 +112,5 @@ class DefaultMemoryCacheFactory(MemoryCacheFactory): if self.cleaner: self.cleaner.register(instance) - + return instance diff --git a/bauh/view/util/translation.py b/bauh/view/util/translation.py index 40350c30..6e31c422 100644 --- a/bauh/view/util/translation.py +++ b/bauh/view/util/translation.py @@ -54,7 +54,7 @@ def get_locale_keys(key: str = None, locale_dir: str = resource.get_path('locale if current_locale is None or current_locale[0] is None: current_locale = ('en', 'UTF-8') - except: + except Exception: current_locale = ('en', 'UTF-8') else: @@ -83,7 +83,7 @@ def get_locale_keys(key: str = None, locale_dir: str = resource.get_path('locale try: keyval = line_strip.split('=') locale_obj[keyval[0].strip()] = keyval[1].strip() - except: + except Exception: print("Error decoding i18n line '{}'".format(line)) return locale_path.split('/')[-1], locale_obj diff --git a/bauh/view/util/util.py b/bauh/view/util/util.py index a1a8e3b1..2ec4365b 100644 --- a/bauh/view/util/util.py +++ b/bauh/view/util/util.py @@ -69,7 +69,7 @@ def clean_app_files(managers: List[SoftwareManager], logs: bool = True): shutil.rmtree(path) if logs: print('{}[bauh] Directory {} deleted{}'.format(Fore.YELLOW, path, Fore.RESET)) - except: + except Exception: if logs: print('{}[bauh] An exception has happened when deleting {}{}'.format(Fore.RED, path, Fore.RESET)) traceback.print_exc() diff --git a/setup.py b/setup.py index 920927b9..2f3cbae4 100644 --- a/setup.py +++ b/setup.py @@ -35,7 +35,7 @@ setup( python_requires=">=3.5", url=URL, packages=find_packages(exclude=["tests.*", "tests"]), - package_data={NAME: ["view/resources/locale/*", "view/resources/img/*", "view/resources/style/*", 'view/resources/style/*/img/*', "gems/*/resources/img/*", "gems/*/resources/locale/*", "desktop/*"]}, + package_data={NAME: ["view/resources/locale/*", "view/resources/img/*", "view/resources/style/*", 'view/resources/style/*/img/*', "gems/*/resources/img/*", "gems/*/resources/locale/*", "desktop/*"]}, install_requires=requirements, test_suite="tests", entry_points={ diff --git a/tests/common/test_view_utils.py b/tests/common/test_view_utils.py index dc4e5e29..486fb38f 100644 --- a/tests/common/test_view_utils.py +++ b/tests/common/test_view_utils.py @@ -9,7 +9,7 @@ class GetHumanSizeStrTest(TestCase): def setUp(self): try: locale.setlocale(locale.LC_NUMERIC, "C") - except: + except Exception: print("Error: could not set locale.LC_NUMERIC to None") def test__must_properly_display_B(self): @@ -53,4 +53,3 @@ class GetHumanSizeStrTest(TestCase): def test__must_not_concatenate_the_plus_sign_if_positive_sign_is_true_and_value_is_negative(self): self.assertEqual('-999 B', get_human_size_str(-999, positive_sign=True)) self.assertEqual('-1.00 kB', get_human_size_str(-1000, positive_sign=True)) - diff --git a/tests/gems/appimage/test_util.py b/tests/gems/appimage/test_util.py index 3a5b894d..ebf685e7 100644 --- a/tests/gems/appimage/test_util.py +++ b/tests/gems/appimage/test_util.py @@ -293,7 +293,7 @@ X-AppImage-Version=bionic-0.16.0-83-dev-0ca783e appname='gamehub', file_path='/path/to/gamehub.appimage') - expected = """ + expected = """ [Desktop Entry] Name=GameHub GenericName=GameHub diff --git a/tests/gems/arch/test_pacman.py b/tests/gems/arch/test_pacman.py index 0ce047a6..283746f3 100644 --- a/tests/gems/arch/test_pacman.py +++ b/tests/gems/arch/test_pacman.py @@ -64,9 +64,9 @@ Optional Deps : pipewire-alsa Required By : None """) def test_map_optional_deps__no_remote_and_not_installed__only_one_not_installed_no_description(self, run_cmd: Mock): - res = pacman.map_optional_deps(('package-test',), remote=False, not_installed=True) - run_cmd.assert_called_once_with('pacman -Qi package-test') - self.assertEqual({'package-test': {'pipewire-alsa': ''}}, res) + res = pacman.map_optional_deps(('package-test',), remote=False, not_installed=True) + run_cmd.assert_called_once_with('pacman -Qi package-test') + self.assertEqual({'package-test': {'pipewire-alsa': ''}}, res) @patch(f'{__app_name__}.gems.arch.pacman.run_cmd', return_value=""" Name : package-test diff --git a/tests/gems/arch/test_sorting.py b/tests/gems/arch/test_sorting.py index 23c52012..ee9dea01 100644 --- a/tests/gems/arch/test_sorting.py +++ b/tests/gems/arch/test_sorting.py @@ -135,7 +135,7 @@ class SortingTest(TestCase): self.assertEqual(sorted_list[0][0], 'def') self.assertEqual(sorted_list[1][0], 'ghi') - self.assertNotEqual(sorted_list[2][0], sorted_list[3][0]) + self.assertNotEqual(sorted_list[2][0], sorted_list[3][0]) self.assertIn(sorted_list[2][0], {'abc', 'jkl'}) self.assertIn(sorted_list[3][0], {'abc', 'jkl'}) @@ -179,7 +179,7 @@ class SortingTest(TestCase): self.assertEqual(sorted_list[0][0], 'def') self.assertEqual(sorted_list[1][0], 'abc') self.assertEqual(sorted_list[2][0], 'ghi') - + def test_sort__aur_pkgs_should_be_always_in_the_end(self): """ dep order: diff --git a/tests/gems/debian/test_aptitude.py b/tests/gems/debian/test_aptitude.py index 05f775d2..87dcb3a4 100644 --- a/tests/gems/debian/test_aptitude.py +++ b/tests/gems/debian/test_aptitude.py @@ -58,7 +58,7 @@ gimp-help^^^^^ self.assertEqual([p.__dict__ for p in exp], [p.__dict__ for p in res]) @patch(f'{__app_name__}.gems.debian.aptitude.system.execute', return_value=(0, """ -Package: firefox +Package: firefox Version: 97.0+distro1+una State: installed (95.0.1+distro1.1+una), upgrade available (97.0+distro1+una) Automatically installed: no @@ -89,8 +89,8 @@ Suggests: gcc-multilib, make, manpages-dev, autoconf, automake, libtool, flex, b Conflicts: gcc-doc (< 1:2.95.3), gcc-doc:i386 (< 1:2.95.3), gcc:i386 Provides: c-compiler, gcc-x86-64-linux-gnu (= 4:9.3.0-1distro2), gcc:amd64 (= 4:9.3.0-1distro2) Description: GNU C compiler - This is the GNU C compiler, a fairly portable optimizing compiler for C. - + This is the GNU C compiler, a fairly portable optimizing compiler for C. + This is a dependency package providing the default GNU C compiler. """)) @@ -170,7 +170,7 @@ Description: GNU C compiler def test_map_transaction_output__it_should_map_i386_packages(self): output = "\nThe following NEW packages will be installed:\n" \ " gcc-12-base:i386{a} [12.1.0-2distro~22.04] <+272 kB> glib-networking:i386{a} [2.72.0-1] <+242 kB>\n" \ - "\nThe following packages will be REMOVED:\n" \ + "\nThe following packages will be REMOVED:\n" \ " celluloid{a} [0.21-linux+distro] <-1066 kB> libpcre3:i386{a} [2:8.39-13distro0.22.04.1] <-714 kB>" transaction = self.aptitude.map_transaction_output(output) diff --git a/tests/gems/debian/test_controller.py b/tests/gems/debian/test_controller.py index 5a423a5a..23bc2a47 100644 --- a/tests/gems/debian/test_controller.py +++ b/tests/gems/debian/test_controller.py @@ -14,14 +14,14 @@ class DebianPackageManagerTest(TestCase): self.controller._apps_index = {} @patch(f'{__app_name__}.gems.debian.controller.Aptitude.read_installed', return_value=iter(( - DebianPackage(name='gir1.2-javascriptcoregtk-4.0', version='2.34.1-0distro0.20.04.1', - latest_version='2.34.1-0distro0.20.04.1', - maintainer='Distro Developers', update=False, installed=True, - description='JavaScript engine library from WebKitGTK - GObject introspection data'), - DebianPackage(name='xwayland', version='2:1.20.13-1distro1~20.04.2', - latest_version='2:1.20.13-1distro1~20.04.2', - maintainer='Distro X-SWAT', update=False, installed=True, - description='Xwayland X server') + DebianPackage(name='gir1.2-javascriptcoregtk-4.0', version='2.34.1-0distro0.20.04.1', + latest_version='2.34.1-0distro0.20.04.1', + maintainer='Distro Developers', update=False, installed=True, + description='JavaScript engine library from WebKitGTK - GObject introspection data'), + DebianPackage(name='xwayland', version='2:1.20.13-1distro1~20.04.2', + latest_version='2:1.20.13-1distro1~20.04.2', + maintainer='Distro X-SWAT', update=False, installed=True, + description='Xwayland X server') ))) def test_read_installed__must_associated_packages_found_to_applications_if_appliable(self, read_installed: Mock): app = DebianApplication(name='xwayland', exe_path='xwayland', icon_path='xwayland', categories=('app',)) @@ -44,14 +44,14 @@ class DebianPackageManagerTest(TestCase): self.assertEqual(expected, result.installed) @patch(f'{__app_name__}.gems.debian.controller.Aptitude.read_installed', return_value=iter(( - DebianPackage(name='gir1.2-javascriptcoregtk-4.0', version='2.34.1-0distro0.20.04.1', - latest_version='2.34.1-0distro0.20.04.1', - maintainer='Distro Developers', update=False, installed=True, - description='JavaScript engine library from WebKitGTK - GObject introspection data'), - DebianPackage(name='xwayland', version='2:1.20.13-1distro1~20.04.2', - latest_version='2:1.20.13-1distro1~20.04.2', - maintainer='Distro X-SWAT', update=False, installed=True, - description='Xwayland X server') + DebianPackage(name='gir1.2-javascriptcoregtk-4.0', version='2.34.1-0distro0.20.04.1', + latest_version='2.34.1-0distro0.20.04.1', + maintainer='Distro Developers', update=False, installed=True, + description='JavaScript engine library from WebKitGTK - GObject introspection data'), + DebianPackage(name='xwayland', version='2:1.20.13-1distro1~20.04.2', + latest_version='2:1.20.13-1distro1~20.04.2', + maintainer='Distro X-SWAT', update=False, installed=True, + description='Xwayland X server') ))) def test_read_installed__internet_not_available(self, read_installed: Mock): result = self.controller.read_installed(disk_loader=None, pkg_types=None, internet_available=False) @@ -83,7 +83,7 @@ class DebianPackageManagerTest(TestCase): ))) def test_search__returned_packages_should_be_associated_with_apps_if_appliable(self, search: Mock): app = DebianApplication(name='myapp', exe_path='myapp', icon_path='myapp', - categories=('app',)) + categories=('app',)) self.controller._apps_index = {'myapp': app} words = 'test' diff --git a/tests/gems/debian/test_index.py b/tests/gems/debian/test_index.py index 01a5de24..b43d55c2 100644 --- a/tests/gems/debian/test_index.py +++ b/tests/gems/debian/test_index.py @@ -8,6 +8,7 @@ from bauh.gems.debian.index import ApplicationsMapper, ApplicationIndexer from bauh.gems.debian.model import DebianApplication from tests.gems.debian import DEBIAN_TESTS_DIR + def mock_read_file(fpath: str): if fpath.endswith('firefox.desktop'): return """ diff --git a/tests/gems/flatpak/test_flatpak.py b/tests/gems/flatpak/test_flatpak.py index a65b16bd..b460b7c5 100644 --- a/tests/gems/flatpak/test_flatpak.py +++ b/tests/gems/flatpak/test_flatpak.py @@ -10,10 +10,10 @@ class FlatpakTest(TestCase): @patch(f'{__app_name__}.gems.flatpak.flatpak.SimpleProcess') @patch(f'{__app_name__}.gems.flatpak.flatpak.ProcessHandler.handle_simple', return_value=(True, """ Looking for updates... - + \tID\tArch\tBranch\tRemote\tDownload 1.\t \torg.xpto.Xnote\tx86_64\tstable\tflathub\t< 4.3 MB - + """)) def test_map_update_download_size__for_flatpak_1_2(self, SimpleProcess: Mock, handle_simple: Mock): download_size = flatpak.map_update_download_size(app_ids={'org.xpto.Xnote'}, installation='user', version=VERSION_1_2) diff --git a/tests/gems/web/test_controller.py b/tests/gems/web/test_controller.py index 12dc76eb..32ff603d 100644 --- a/tests/gems/web/test_controller.py +++ b/tests/gems/web/test_controller.py @@ -61,4 +61,3 @@ class WebApplicationManagerTest(TestCase): def test_strip_url_protocol__https_with_www(self): res = self.manager.strip_url_protocol('https://www.test.com') self.assertEqual('test.com', res) -