[snap] refactoring: String formatting method

This commit is contained in:
Vinicius Moreira
2021-12-10 11:14:16 -03:00
parent 34d5234977
commit f34db97661
5 changed files with 32 additions and 29 deletions

View File

@@ -10,11 +10,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- allowing AUR packages to be installed when bauh is launched by the root user [#196](https://github.com/vinifmor/bauh/issues/196)
- it creates a non-root user called **bauh-aur** for building the packages (`useradd` and `runuser` commands must be installed)
### Improvements
- code refactoring (String formatting method)
### Fixes
- Arch
- not updating the view (GUI) status correctly after uninstalling a package whose PKGBUILD file was edited (specifically the **name**)
- missing error handling when hard requirements for optional dependencies cannot be found by pacman
## [0.9.22] 2021-11-30
### Improvements
- General

View File

@@ -124,7 +124,7 @@ class SnapManager(SoftwareManager):
return ProcessHandler(watcher).handle_simple(snap.downgrade_and_stream(pkg.name, root_password))[0]
def upgrade(self, requirements: UpgradeRequirements, root_password: str, watcher: ProcessWatcher) -> SystemProcess:
raise Exception("'upgrade' is not supported by {}".format(SnapManager.__class__.__name__))
raise Exception(f"'upgrade' is not supported by {SnapManager.__class__.__name__}")
def uninstall(self, pkg: SnapApplication, root_password: str, watcher: ProcessWatcher, disk_loader: DiskCacheLoader) -> TransactionResult:
if snap.is_installed() and snapd.is_running():
@@ -173,7 +173,7 @@ class SnapManager(SoftwareManager):
return info
def get_history(self, pkg: SnapApplication) -> PackageHistory:
raise Exception("'get_history' is not supported by {}".format(pkg.__class__.__name__))
raise Exception(f"'get_history' is not supported by {pkg.__class__.__name__}")
def install(self, pkg: SnapApplication, root_password: str, disk_loader: DiskCacheLoader, watcher: ProcessWatcher) -> TransactionResult:
# retrieving all installed so it will be possible to know the additional installed runtimes after the operation succeeds
@@ -210,20 +210,20 @@ class SnapManager(SoftwareManager):
if channels:
opts = [InputOption(label=c[0], value=c[1]) for c in channels]
channel_select = SingleSelectComponent(type_=SelectViewType.RADIO, label='', options=opts, default_option=opts[0])
body = '<p>{}.</p>'.format(self.i18n['snap.install.available_channels.message'].format(bold(self.i18n['stable']), bold(pkg.name)))
body += '<p>{}:</p>'.format(self.i18n['snap.install.available_channels.help'])
body = f"<p>{self.i18n['snap.install.available_channels.message'].format(bold(self.i18n['stable']), bold(pkg.name))}.</p>"
body += f"<p>{self.i18n['snap.install.available_channels.help']}:</p>"
if watcher.request_confirmation(title=self.i18n['snap.install.available_channels.title'],
body=body,
components=[channel_select],
confirmation_label=self.i18n['continue'],
deny_label=self.i18n['cancel']):
self.logger.info("Installing '{}' with the custom command '{}'".format(pkg.name, channel_select.value))
self.logger.info(f"Installing '{pkg.name}' with the custom command '{channel_select.value}'")
res = ProcessHandler(watcher).handle(SystemProcess(new_root_subprocess(channel_select.value.value.split(' '), root_password=root_password)))
return self._gen_installation_response(success=res, pkg=pkg,
installed=installed_names, disk_loader=disk_loader)
else:
self.logger.error("Could not find available channels in the installation output: {}".format(output))
self.logger.error(f"Could not find available channels in the installation output: {output}")
return self._gen_installation_response(success=res, pkg=pkg, installed=installed_names, disk_loader=disk_loader)
@@ -321,14 +321,13 @@ class SnapManager(SoftwareManager):
if not snapd.is_running():
snap_bold = bold('Snap')
return [self.i18n['snap.notification.snapd_unavailable'].format(bold('snapd'), snap_bold),
self.i18n['snap.notification.snap.disable'].format(snap_bold, bold(
'{} > {}'.format(self.i18n['settings'].capitalize(),
self.i18n['core.config.tab.types'])))]
self.i18n['snap.notification.snap.disable'].format(snap_bold,
bold(f"{self.i18n['settings'].capitalize()} > {self.i18n['core.config.tab.types']}"))]
elif internet_available:
available, output = snap.is_api_available()
if not available:
self.logger.warning('It seems Snap API is not available. Search output: {}'.format(output))
self.logger.warning(f'It seems Snap API is not available. Search output: {output}')
return [self.i18n['snap.notifications.api.unavailable'].format(bold('Snaps'), bold('Snap'))]
def _fill_suggestion(self, name: str, priority: SuggestionPriority, snapd_client: SnapdClient, out: List[PackageSuggestion]):
@@ -347,7 +346,7 @@ class SnapManager(SoftwareManager):
out.append(sug)
return
self.logger.warning("Could not retrieve suggestion '{}'".format(name))
self.logger.warning(f"Could not retrieve suggestion '{name}'")
def _map_to_app(self, app_json: dict, installed: bool, disk_loader: Optional[DiskCacheLoader] = None, is_application: bool = False) -> SnapApplication:
app = SnapApplication(id=app_json.get('id'),
@@ -382,11 +381,11 @@ class SnapManager(SoftwareManager):
res = []
if snapd.is_running():
self.logger.info('Downloading suggestions file {}'.format(SUGGESTIONS_FILE))
self.logger.info(f'Downloading suggestions file {SUGGESTIONS_FILE}')
file = self.http_client.get(SUGGESTIONS_FILE)
if not file or not file.text:
self.logger.warning("No suggestion found in {}".format(SUGGESTIONS_FILE))
self.logger.warning(f"No suggestion found in {SUGGESTIONS_FILE}")
return res
else:
self.logger.info('Mapping suggestions')
@@ -437,7 +436,7 @@ class SnapManager(SoftwareManager):
else:
cmd = commands[0]['name']
self.logger.info("Running '{}': {}".format(pkg.name, cmd))
self.logger.info(f"Running '{pkg.name}': {cmd}")
snap.run(cmd)
def get_screenshots(self, pkg: SnapApplication) -> List[str]:
@@ -482,19 +481,19 @@ class SnapManager(SoftwareManager):
try:
data = [r for r in snapd_client.find_by_name(pkg.name) if r['name'] == pkg.name]
except:
self.logger.warning("snapd client could not retrieve channels for '{}'".format(pkg.name))
self.logger.warning(f"snapd client could not retrieve channels for '{pkg.name}'")
return
if not data:
self.logger.warning("snapd client could find a match for name '{}' when retrieving its channels".format(pkg.name))
self.logger.warning(f"snapd client could find a match for name '{pkg.name}' when retrieving its channels")
else:
if not data[0].get('channels'):
self.logger.info("No channel available for '{}'. Skipping selection.".format(pkg.name))
self.logger.info(f"No channel available for '{pkg.name}'. Skipping selection.")
else:
if pkg.channel:
current_channel = pkg.channel if '/' in pkg.channel else 'latest/{}'.format(pkg.channel)
current_channel = pkg.channel if '/' in pkg.channel else f'latest/{pkg.channel}'
else:
current_channel = 'latest/{}'.format(data[0].get('channel', 'stable'))
current_channel = f"latest/{data[0].get('channel', 'stable')}"
opts = []
def_opt = None
@@ -510,7 +509,7 @@ class SnapManager(SoftwareManager):
def_opt = op
if not opts:
self.logger.info("No different channel available for '{}'. Skipping selection.".format(pkg.name))
self.logger.info(f"No different channel available for '{pkg.name}'. Skipping selection.")
return
select = SingleSelectComponent(label='',

View File

@@ -70,7 +70,7 @@ class SnapApplication(SoftwarePackage):
return self.type == 'app'
def get_disk_cache_path(self):
return super(SnapApplication, self).get_disk_cache_path() + '/installed/' + self.name
return f'{super(SnapApplication, self).get_disk_cache_path()}/installed/{self.name}'
def is_trustable(self) -> bool:
return self.verified_publisher

View File

@@ -27,7 +27,7 @@ def install_and_stream(app_name: str, confinement: str, root_password: str, chan
install_cmd.append('--classic')
if channel:
install_cmd.append('--channel={}'.format(channel))
install_cmd.append(f'--channel={channel}')
return SimpleProcess(install_cmd, root_password=root_password, shell=True)
@@ -42,7 +42,7 @@ def refresh_and_stream(app_name: str, root_password: str, channel: Optional[str]
cmd = [BASE_CMD, 'refresh', app_name]
if channel:
cmd.append('--channel={}'.format(channel))
cmd.append(f'--channel={channel}')
return SimpleProcess(cmd=cmd,
root_password=root_password,
@@ -51,7 +51,7 @@ def refresh_and_stream(app_name: str, root_password: str, channel: Optional[str]
def run(cmd: str):
subprocess.Popen(['snap run {}'.format(cmd)], shell=True, env={**os.environ})
subprocess.Popen([f'{BASE_CMD} run {cmd}'], shell=True, env={**os.environ})
def is_api_available() -> Tuple[bool, str]:

View File

@@ -55,7 +55,7 @@ class SnapdClient:
final_query = query.strip()
if final_query and self.session:
res = self.session.get(url='{}/find'.format(URL_BASE), params={'q': final_query})
res = self.session.get(url=f'{URL_BASE}/find', params={'q': final_query})
if res.status_code == 200:
json_res = res.json()
@@ -65,7 +65,7 @@ class SnapdClient:
def find_by_name(self, name: str) -> Optional[List[dict]]:
if name and self.session:
res = self.session.get('{}/find?name={}'.format(URL_BASE, name))
res = self.session.get(f'{URL_BASE}/find?name={name}')
if res.status_code == 200:
json_res = res.json()
@@ -75,7 +75,7 @@ class SnapdClient:
def list_all_snaps(self) -> List[dict]:
if self.session:
res = self.session.get('{}/snaps'.format(URL_BASE))
res = self.session.get(f'{URL_BASE}/snaps')
if res.status_code == 200:
json_res = res.json()
@@ -87,7 +87,7 @@ class SnapdClient:
def list_only_apps(self) -> List[dict]:
if self.session:
res = self.session.get('{}/apps'.format(URL_BASE))
res = self.session.get(f'{URL_BASE}/apps')
if res.status_code == 200:
json_res = res.json()
@@ -98,7 +98,7 @@ class SnapdClient:
def list_commands(self, name: str) -> List[dict]:
if self.session:
res = self.session.get('{}/apps?names={}'.format(URL_BASE, name))
res = self.session.get(f'{URL_BASE}/apps?names={name}')
if res.status_code == 200:
json_res = res.json()