[appimage.controller] String formatting method

This commit is contained in:
Vinicius Moreira
2021-11-29 12:03:18 -03:00
parent d9b6ee96ab
commit 3d0733a0d6

View File

@@ -108,7 +108,7 @@ class AppImageManager(SoftwareManager):
input_description = TextInputComponent(label=self.i18n['description'].capitalize()) input_description = TextInputComponent(label=self.i18n['description'].capitalize())
cat_ops = [InputOption(label=self.i18n['category.none'].capitalize(), value=0)] cat_ops = [InputOption(label=self.i18n['category.none'].capitalize(), value=0)]
cat_ops.extend([InputOption(label=self.i18n.get('category.{}'.format(c.lower()), c.lower()).capitalize(), value=c) for c in self.context.default_categories]) cat_ops.extend([InputOption(label=self.i18n.get(f'category.{c.lower()}', c.lower()).capitalize(), value=c) for c in self.context.default_categories])
inp_cat = SingleSelectComponent(label=self.i18n['category'], type_=SelectViewType.COMBO, options=cat_ops, inp_cat = SingleSelectComponent(label=self.i18n['category'], type_=SelectViewType.COMBO, options=cat_ops,
default_option=cat_ops[0]) default_option=cat_ops[0])
@@ -184,13 +184,13 @@ class AppImageManager(SoftwareManager):
try: try:
return sqlite3.connect(db_path) return sqlite3.connect(db_path)
except: except:
self.logger.error("Could not connect to database file '{}'".format(db_path)) self.logger.error(f"Could not connect to database file '{db_path}'")
traceback.print_exc() traceback.print_exc()
else: else:
self.logger.warning("Could not get a connection for database '{}'".format(db_path)) self.logger.warning(f"Could not get a connection for database '{db_path}'")
def _gen_app_key(self, app: AppImage): def _gen_app_key(self, app: AppImage):
return '{}{}'.format(app.name.lower(), app.github.lower() if app.github else '') return f"{app.name.lower()}{app.github.lower() if app.github else ''}"
def search(self, words: str, disk_loader: DiskCacheLoader, limit: int = -1, is_url: bool = False) -> SearchResult: def search(self, words: str, disk_loader: DiskCacheLoader, limit: int = -1, is_url: bool = False) -> SearchResult:
if is_url: if is_url:
@@ -243,7 +243,7 @@ class AppImageManager(SoftwareManager):
try: try:
apps_conn.close() apps_conn.close()
except: except:
self.logger.error("An exception happened when trying to close the connection to database file '{}'".format(DATABASE_APPS_FILE)) self.logger.error(f"An exception happened when trying to close the connection to database file '{DATABASE_APPS_FILE}'")
traceback.print_exc() traceback.print_exc()
return SearchResult(new=not_installed, installed=installed_found, total=len(not_installed) + len(installed_found)) return SearchResult(new=not_installed, installed=installed_found, total=len(not_installed) + len(installed_found))
@@ -265,7 +265,7 @@ class AppImageManager(SoftwareManager):
app.icon_url = app.icon_path app.icon_url = app.icon_path
installed_apps.append(app) installed_apps.append(app)
names.add("'{}'".format(app.name.lower())) names.add(f"'{app.name.lower()}'")
if installed_apps: if installed_apps:
apps_con = self._get_db_connection(DATABASE_APPS_FILE) if not connection else connection apps_con = self._get_db_connection(DATABASE_APPS_FILE) if not connection else connection
@@ -299,7 +299,7 @@ class AppImageManager(SoftwareManager):
break break
except: except:
self.logger.error("An exception happened while querying the database file {}".format(apps_con)) self.logger.error(f"An exception happened while querying the database file '{DATABASE_APPS_FILE}'")
traceback.print_exc() traceback.print_exc()
finally: finally:
if not connection: # the connection can only be closed if it was opened within this method if not connection: # the connection can only be closed if it was opened within this method
@@ -363,7 +363,7 @@ class AppImageManager(SoftwareManager):
not_upgraded = [] not_upgraded = []
for req in requirements.to_upgrade: for req in requirements.to_upgrade:
watcher.change_status("{} {} ({})...".format(self.i18n['manage_window.status.upgrading'], req.pkg.name, req.pkg.version)) watcher.change_status(f"{self.i18n['manage_window.status.upgrading']} {req.pkg.name} ({req.pkg.version})...")
download_data = None download_data = None
@@ -413,17 +413,17 @@ class AppImageManager(SoftwareManager):
self.revert_ignored_update(pkg) self.revert_ignored_update(pkg)
if pkg.symlink and os.path.islink(pkg.symlink): if pkg.symlink and os.path.islink(pkg.symlink):
self.logger.info("Removing symlink '{}'".format(pkg.symlink)) self.logger.info(f"Removing symlink '{pkg.symlink}'")
try: try:
os.remove(pkg.symlink) os.remove(pkg.symlink)
self.logger.info("symlink '{}' successfully removed".format(pkg.symlink)) self.logger.info(f"symlink '{pkg.symlink}' successfully removed")
except: except:
msg = "could not remove symlink '{}'".format(pkg.symlink) msg = f"could not remove symlink '{pkg.symlink}'"
self.logger.error(msg) self.logger.error(msg)
if watcher: if watcher:
watcher.print("[error] {}".format(msg)) watcher.print(f"[error] {msg}")
return TransactionResult(success=True, installed=None, removed=[pkg]) return TransactionResult(success=True, installed=None, removed=[pkg])
@@ -444,7 +444,7 @@ class AppImageManager(SoftwareManager):
categories = data.get('categories') categories = data.get('categories')
if categories: if categories:
data['categories'] = [self.i18n.get('category.{}'.format(c.lower()), self.i18n.get(c, c)).capitalize() for c in data['categories']] data['categories'] = [self.i18n.get(f'category.{c.lower()}', self.i18n.get(c, c)).capitalize() for c in data['categories']]
if data.get('symlink') and not os.path.islink(data['symlink']): if data.get('symlink') and not os.path.islink(data['symlink']):
del data['symlink'] del data['symlink']
@@ -467,10 +467,10 @@ class AppImageManager(SoftwareManager):
app_tuple = cursor.fetchone() app_tuple = cursor.fetchone()
if not app_tuple: if not app_tuple:
self.logger.warning("Could not retrieve {} from the database {}".format(pkg, DATABASE_APPS_FILE)) self.logger.warning(f"Could not retrieve {pkg} from the database '{DATABASE_APPS_FILE}'")
return res return res
except: except:
self.logger.error("An exception happened while querying the database file '{}'".format(DATABASE_APPS_FILE)) self.logger.error(f"An exception happened while querying the database file '{DATABASE_APPS_FILE}'")
traceback.print_exc() traceback.print_exc()
app_con.close() app_con.close()
return res return res
@@ -498,7 +498,7 @@ class AppImageManager(SoftwareManager):
return res return res
except: except:
self.logger.error("An exception happened while querying the database file '{}'".format(DATABASE_RELEASES_FILE)) self.logger.error(f"An exception happened while querying the database file '{DATABASE_RELEASES_FILE}'")
traceback.print_exc() traceback.print_exc()
finally: finally:
releases_con.close() releases_con.close()
@@ -557,8 +557,8 @@ class AppImageManager(SoftwareManager):
counter = 0 counter = 0
while True: while True:
if os.path.exists(out_dir): if os.path.exists(out_dir):
self.logger.info("Installation dir '{}' already exists. Generating a different one".format(out_dir)) self.logger.info(f"Installation dir '{out_dir}' already exists. Generating a different one")
out_dir += '-{}'.format(counter) out_dir += f'-{counter}'
counter += 1 counter += 1
else: else:
break break
@@ -576,7 +576,7 @@ class AppImageManager(SoftwareManager):
moved, output = handler.handle_simple(SimpleProcess(['mv', pkg.local_file_path, install_file_path])) moved, output = handler.handle_simple(SimpleProcess(['mv', pkg.local_file_path, install_file_path]))
except: except:
output = '' output = ''
self.logger.error("Could not rename file '' as '{}'".format(pkg.local_file_path, install_file_path)) self.logger.error(f"Could not rename file '{pkg.local_file_path}' as '{install_file_path}'")
moved = False moved = False
if not moved: if not moved:
@@ -632,12 +632,12 @@ class AppImageManager(SoftwareManager):
return TransactionResult.fail() return TransactionResult.fail()
watcher.change_substatus(self.i18n['appimage.install.desktop_entry']) watcher.change_substatus(self.i18n['appimage.install.desktop_entry'])
extracted_folder = '{}/{}'.format(out_dir, 'squashfs-root') extracted_folder = f'{out_dir}/squashfs-root'
if os.path.exists(extracted_folder): if os.path.exists(extracted_folder):
desktop_entry = self._find_desktop_file(extracted_folder) desktop_entry = self._find_desktop_file(extracted_folder)
with open('{}/{}'.format(extracted_folder, desktop_entry)) as f: with open(f'{extracted_folder}/{desktop_entry}') as f:
de_content = f.read() de_content = f.read()
if de_content: if de_content:
@@ -651,7 +651,7 @@ class AppImageManager(SoftwareManager):
shutil.copy(extracted_icon, icon_path) shutil.copy(extracted_icon, icon_path)
if de_content: if de_content:
de_content = RE_DESKTOP_ICON.sub('Icon={}\n'.format(icon_path), de_content) de_content = RE_DESKTOP_ICON.sub(f'Icon={icon_path}\n', de_content)
pkg.icon_path = icon_path pkg.icon_path = icon_path
@@ -673,7 +673,7 @@ class AppImageManager(SoftwareManager):
return TransactionResult(success=True, installed=[pkg], removed=[]) return TransactionResult(success=True, installed=[pkg], removed=[])
else: else:
watcher.show_message(title=self.i18n['error'], watcher.show_message(title=self.i18n['error'],
body='Could extract content from {}'.format(bold(file_name)), body=f'Could extract content from {bold(file_name)}',
type_=MessageType.ERROR) type_=MessageType.ERROR)
handler.handle(SystemProcess(new_subprocess(['rm', '-rf', out_dir]))) handler.handle(SystemProcess(new_subprocess(['rm', '-rf', out_dir])))
@@ -773,12 +773,12 @@ class AppImageManager(SoftwareManager):
break break
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(query.FIND_APPS_BY_NAME_FULL.format(','.join(["'{}'".format(s) for s in sugs_map.keys()]))) cursor.execute(query.FIND_APPS_BY_NAME_FULL.format(','.join([f"'{s}'" for s in sugs_map.keys()])))
for t in cursor.fetchall(): for t in cursor.fetchall():
app = AppImage(*t, i18n=self.i18n, custom_actions=self.custom_app_actions) app = AppImage(*t, i18n=self.i18n, custom_actions=self.custom_app_actions)
res.append(PackageSuggestion(app, sugs_map[app.name.lower()])) res.append(PackageSuggestion(app, sugs_map[app.name.lower()]))
self.logger.info("Mapped {} suggestions".format(len(res))) self.logger.info(f"Mapped {len(res)} suggestions")
except: except:
traceback.print_exc() traceback.print_exc()
finally: finally:
@@ -798,7 +798,7 @@ class AppImageManager(SoftwareManager):
subprocess.Popen(args=[appimag_path], shell=True, env={**os.environ}, subprocess.Popen(args=[appimag_path], shell=True, env={**os.environ},
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL) stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
else: else:
self.logger.error("Could not find the AppImage file of '{}' in '{}'".format(pkg.name, installation_dir)) self.logger.error(f"Could not find the AppImage file of '{pkg.name}' in '{installation_dir}'")
def cache_to_disk(self, pkg: SoftwarePackage, icon_bytes: Optional[bytes], only_icon: bool): def cache_to_disk(self, pkg: SoftwarePackage, icon_bytes: Optional[bytes], only_icon: bool):
self.serialize_to_disk(pkg, icon_bytes, only_icon) self.serialize_to_disk(pkg, icon_bytes, only_icon)
@@ -810,17 +810,17 @@ class AppImageManager(SoftwareManager):
return [] return []
def clear_data(self, logs: bool = True): def clear_data(self, logs: bool = True):
for f in glob.glob('{}/*.db'.format(APPIMAGE_SHARED_DIR)): for f in glob.glob(f'{APPIMAGE_SHARED_DIR}/*.db'):
try: try:
if logs: if logs:
print('[bauh][appimage] Deleting {}'.format(f)) print(f'[bauh][appimage] Deleting {f}')
os.remove(f) os.remove(f)
if logs: if logs:
print('{}[bauh][appimage] {} deleted{}'.format(Fore.YELLOW, f, Fore.RESET)) print(f'{Fore.YELLOW}[bauh][appimage] {f} deleted{Fore.RESET}')
except: except:
if logs: if logs:
print('{}[bauh][appimage] An exception has happened when deleting {}{}'.format(Fore.RED, f, Fore.RESET)) print(f'{Fore.RED}[bauh][appimage] An exception has happened when deleting {f}{Fore.RESET}')
traceback.print_exc() traceback.print_exc()
def get_settings(self, screen_width: int, screen_height: int) -> ViewComponent: def get_settings(self, screen_width: int, screen_height: int) -> ViewComponent:
@@ -910,7 +910,7 @@ class AppImageManager(SoftwareManager):
with open(UPDATES_IGNORED_FILE, 'w+') as f: with open(UPDATES_IGNORED_FILE, 'w+') as f:
if ignored_list: if ignored_list:
for ignored in ignored_list: for ignored in ignored_list:
f.write('{}\n'.format(ignored)) f.write(f'{ignored}\n')
else: else:
f.write('') f.write('')