def _show_did_you_mean(self, entropy_client, package, from_installed): """ Show "Did you mean?" results for the given package name. """ items = entropy_client.get_meant_packages( package, from_installed=from_installed) if not items: return mytxt = "%s %s %s %s %s" % ( bold(const_convert_to_unicode(" ?")), teal(_("When you wrote")), bold(const_convert_to_unicode(package)), darkgreen(_("You Meant(tm)")), teal(_("one of these below?")), ) entropy_client.output(mytxt) _cache = set() for pkg_id, repo_id in items: if from_installed: repo = entropy_client.installed_repository() else: repo = entropy_client.open_repository(repo_id) key_slot = repo.retrieveKeySlotAggregated(pkg_id) if key_slot not in _cache: entropy_client.output(enlightenatom(key_slot), header=brown(" # ")) _cache.add(key_slot)
def _show_did_you_mean(self, entropy_client, package, from_installed): """ Show "Did you mean?" results for the given package name. """ items = entropy_client.get_meant_packages( package, from_installed=from_installed) if not items: return mytxt = "%s %s %s %s %s" % ( bold(const_convert_to_unicode(" ?")), teal(_("When you wrote")), bold(const_convert_to_unicode(package)), darkgreen(_("You Meant(tm)")), teal(_("one of these below?")), ) entropy_client.output(mytxt) _cache = set() for pkg_id, repo_id in items: if from_installed: repo = entropy_client.installed_repository() else: repo = entropy_client.open_repository(repo_id) key_slot = repo.retrieveKeySlotAggregated(pkg_id) if key_slot not in _cache: entropy_client.output( enlightenatom(key_slot), header=brown(" # ")) _cache.add(key_slot)
def _trigger_call_ext_generic(self): try: return self._do_trigger_call_ext_generic() except Exception as err: mykey = self._pkgdata['category']+"/"+self._pkgdata['name'] tback = entropy.tools.get_traceback() self._entropy.output(tback, importance = 0, level = "error") self._entropy.logger.write(tback) self._entropy.logger.log( "[Trigger]", etpConst['logging']['normal_loglevel_id'], "[POST] ATTENTION Cannot run External trigger for " + \ mykey + "!! " + str(Exception) + ": " + repr(err) ) mytxt = "%s: %s %s. %s." % ( bold(_("QA")), brown(_("Cannot run External trigger for")), bold(mykey), brown(_("Please report it")), ) self._entropy.output( mytxt, importance = 0, header = red(" ## ") ) return 0
def __export_key(self, entropy_server, repo_sec, is_pubkey, repo, store_path): """ Internal key export logic. """ key_msg = _("Exporting private key for repository") func_check = repo_sec.is_privkey_available if is_pubkey: func_check = repo_sec.is_pubkey_available key_msg = _("Exporting public key for repository") try: if not func_check(repo): entropy_server.output("%s: %s" % ( blue(_("No keypair available for repository")), purple(repo), ), level = "error" ) return 1 except repo_sec.KeyExpired: entropy_server.output("%s: %s" % ( darkred(_("Keypair is EXPIRED for repository")), purple(repo), ), level = "error" ) return 1 entropy_server.output("%s: %s" % (blue(key_msg), purple(repo),)) if is_pubkey: key_stream = repo_sec.get_pubkey(repo) else: key_stream = repo_sec.get_privkey(repo) # write to file try: with open(store_path, "w") as dest_w: dest_w.write(key_stream) dest_w.flush() except IOError as err: entropy_server.output("%s: %s [%s]" % ( darkgreen( _("Unable to export GPG key for repository")), bold(repo), err, ), level = "error" ) return 1 entropy_server.output("%s: %s [%s]" % ( darkgreen(_("Exported GPG key for repository")), bold(repo), brown(store_path), ), level = "info" ) return 0
def _updates(self, entropy_client): """ Solo Query Updates command. """ quiet = self._nsargs.quiet verbose = self._nsargs.verbose if not quiet: entropy_client.output(brown(_("Available Updates")), header=darkred(" @@ ")) outcome = entropy_client.calculate_updates(quiet=True) update, remove = outcome["update"], outcome["remove"] fine, critical_f = outcome["fine"], outcome["critical_found"] if quiet: entropy_client.output("%d" % (len(update),), level="generic") return 0 toc = [] toc.append((darkgreen(_("Packages to update:")), bold(const_convert_to_unicode(len(update))))) toc.append((darkred(_("Packages to remove:")), bold(const_convert_to_unicode(len(remove))))) if verbose: toc.append((blue(_("Packages already up-to-date:")), bold(const_convert_to_unicode(len(fine))))) toc.append((purple(_("Critical updates found:")), teal(const_convert_to_unicode(str(critical_f))))) print_table(entropy_client, toc) return 0
def _execute_package_phase(self, action_metadata, package_metadata, action_name, phase_name): """ Wrapper against Source Package Manager's execute_package_phase. This method handles both fatal and non-fatal exceptions. """ self._entropy.output( "%s: %s" % (brown(_("Package phase")), teal(phase_name),), importance = 0, header = red(" ## ")) spm = self._spm try: spm.execute_package_phase( action_metadata, package_metadata, action_name, phase_name) except spm.PhaseFailure as err: txt = "%s: %s %s, %s. %s." % ( bold(_("QA")), brown(_("Cannot run phase")), bold(phase_name), err.message, brown(_("Please report it")), ) self._entropy.output( txt, importance = 1, header = red(" ## "), level = "warning") return 0 # non-fatal except spm.OutdatedPhaseError as err: err_msg = "%s: %s" % ( brown(_("Source Package Manager is too old, " "please update it")), err) self._entropy.output( err_msg, importance = 1, header = darkred(" ## "), level = "error" ) return 1 except spm.PhaseError as err: err_msg = "%s: %s" % ( brown(_("Source Package Manager phase error")), err) self._entropy.output( err_msg, importance = 1, header = darkred(" ## "), level = "error" ) return 1 return 0
def _status(self, entropy_server): """ Actual Eit key status code. """ repo_sec = self._get_gpg(entropy_server) if repo_sec is None: return 1 repo = entropy_server.repository() try: key_meta = repo_sec.get_key_metadata(repo) except KeyError: entropy_server.output("%s: %s" % ( darkgreen(_("Keys metadata not available for")), bold(repo), ), level="error") return 1 entropy_server.output("%s: %s" % ( brown(_("GPG information for repository")), bold(repo), ), level="info") def just_print(mystr): return purple(mystr) def print_list(myl): return purple(' '.join(myl)) def print_date(mydate): if not mydate: return _("N/A") try: return convert_unix_time_to_human_time(int(mydate)) except ( ValueError, TypeError, ): return _("N/A") out_data = [ ('uids', _("Description"), print_list), ('keyid', _("Public key identifier"), just_print), ('fingerprint', _("Public key fingerprint"), just_print), ('length', _("Key size"), just_print), ('date', _("Creation date"), print_date), ('expires', _("Expires on"), print_date), ] for key_id, key_desc, out_func in out_data: entropy_server.output("%s: %s" % ( teal(key_desc), out_func(key_meta[key_id]), )) return 0
def _changelog(self, entropy_client, inst_repo): """ Solo Query Changelog command. """ quiet = self._nsargs.quiet verbose = self._nsargs.verbose packages = self._nsargs.packages if not quiet: entropy_client.output(darkgreen(_("ChangeLog Search")), header=darkred(" @@ ")) for package in packages: repo = inst_repo if inst_repo is not None: pkg_id, rc = inst_repo.atomMatch(package) if rc != 0: entropy_client.output("%s: %s" % (darkred(_("No match for")), bold(package))) continue else: pkg_id, r_id = entropy_client.atom_match(package) if pkg_id == -1: entropy_client.output("%s: %s" % (darkred(_("No match for")), bold(package))) continue repo = entropy_client.open_repository(r_id) repo_atom = repo.retrieveAtom(pkg_id) if repo_atom is None: continue if quiet: entropy_client.output("%s :" % (repo_atom,), level="generic") else: entropy_client.output("%s: %s" % (blue(_("Package")), bold(repo_atom)), header=" ") changelog = repo.retrieveChangelog(pkg_id) if not changelog or (changelog == "None"): # == "None" is a bug, see: # 685b865453d552d37ce3a9559f4cefb9a88f8beb entropy_client.output(_("No ChangeLog available"), level="generic") else: entropy_client.output(changelog, level="generic") entropy_client.output("=" * 80) if not quiet: # check developer repo mode repo_conf = entropy_client.Settings().get_setting_files_data()["repositories"] dev_repo = entropy_client.Settings()["repositories"]["developer_repo"] if not dev_repo: entropy_client.output( "%s ! [%s]" % (brown(_("Attention: developer-repo " "option not enabled")), blue(repo_conf)), level=bold(" !!! "), ) return 0
def _status(self, entropy_server): """ Actual Eit key status code. """ repo_sec = self._get_gpg(entropy_server) if repo_sec is None: return 1 repo = entropy_server.repository() try: key_meta = repo_sec.get_key_metadata(repo) except KeyError: entropy_server.output("%s: %s" % ( darkgreen(_("Keys metadata not available for")), bold(repo), ), level = "error" ) return 1 entropy_server.output("%s: %s" % ( brown(_("GPG information for repository")), bold(repo), ), level = "info" ) def just_print(mystr): return purple(mystr) def print_list(myl): return purple(' '.join(myl)) def print_date(mydate): if not mydate: return _("N/A") try: return convert_unix_time_to_human_time(int(mydate)) except (ValueError, TypeError,): return _("N/A") out_data = [ ('uids', _("Description"), print_list), ('keyid', _("Public key identifier"), just_print), ('fingerprint', _("Public key fingerprint"), just_print), ('length', _("Key size"), just_print), ('date', _("Creation date"), print_date), ('expires', _("Expires on"), print_date), ] for key_id, key_desc, out_func in out_data: entropy_server.output("%s: %s" % ( teal(key_desc), out_func(key_meta[key_id]),)) return 0
def _execute_package_phase(self, action_metadata, package_metadata, action_name, phase_name): """ Wrapper against Source Package Manager's execute_package_phase. This method handles both fatal and non-fatal exceptions. """ self._entropy.output("%s: %s" % ( brown(_("Package phase")), teal(phase_name), ), importance=0, header=red(" ## ")) spm = self._spm try: spm.execute_package_phase(action_metadata, package_metadata, action_name, phase_name) except spm.PhaseFailure as err: txt = "%s: %s %s, %s. %s." % ( bold(_("QA")), brown(_("Cannot run phase")), bold(phase_name), err.message, brown(_("Please report it")), ) self._entropy.output(txt, importance=1, header=red(" ## "), level="warning") return 0 # non-fatal except spm.OutdatedPhaseError as err: err_msg = "%s: %s" % (brown( _("Source Package Manager is too old, " "please update it")), err) self._entropy.output(err_msg, importance=1, header=darkred(" ## "), level="error") return 1 except spm.PhaseError as err: err_msg = "%s: %s" % (brown( _("Source Package Manager phase error")), err) self._entropy.output(err_msg, importance=1, header=darkred(" ## "), level="error") return 1 return 0
def _prompt_final_removal(self, entropy_client, inst_repo, removal_queue): """ Prompt some final information to User with respect to the removal queue. """ total = len(removal_queue) mytxt = "%s: %s" % ( blue(_("Packages that would be removed")), darkred(const_convert_to_unicode(total)), ) entropy_client.output( mytxt, header=darkred(" @@ ")) total_removal_size = 0 total_pkg_size = 0 for package_id in set(removal_queue): on_disk_size = inst_repo.retrieveOnDiskSize(package_id) if on_disk_size is None: on_disk_size = 0 pkg_size = inst_repo.retrieveSize(package_id) if pkg_size is None: pkg_size = 0 extra_downloads = inst_repo.retrieveExtraDownload(package_id) for extra_download in extra_downloads: pkg_size += extra_download['size'] on_disk_size += extra_download['disksize'] total_removal_size += on_disk_size total_pkg_size += pkg_size human_removal_size = entropy.tools.bytes_into_human( total_removal_size) human_pkg_size = entropy.tools.bytes_into_human(total_pkg_size) mytxt = "%s: %s" % ( blue(_("Freed disk space")), bold(const_convert_to_unicode(human_removal_size)), ) entropy_client.output( mytxt, header=darkred(" @@ ")) mytxt = "%s: %s" % ( blue(_("Total bandwidth wasted")), bold(str(human_pkg_size)), ) entropy_client.output( mytxt, header=darkred(" @@ "))
def _delete(self, entropy_server): """ Actual Eit key delete code. """ repo_sec = self._get_gpg(entropy_server) if repo_sec is None: return 1 repo = entropy_server.repository() entropy_server.output("%s: %s" % ( blue(_("Deleting keys for repository")), purple(repo),)) if not repo_sec.is_keypair_available(repo): entropy_server.output("%s: %s" % ( blue(_("No keys available for given repository")), purple(repo), ), level = "warning" ) return 0 answer = entropy_server.ask_question(_("Are you really sure?")) if answer == _("No"): return 1 try: key_meta = repo_sec.get_key_metadata(repo) except KeyError: entropy_server.output("%s: %s" % ( darkgreen(_("Keys metadata not available for")), bold(repo), ), level = "error" ) return 1 # remove signatures from repository database dbconn = entropy_server.open_server_repository( repo, read_only = False) dbconn.dropGpgSignatures() repo_sec.delete_keypair(repo) entropy_server.output("%s: %s" % ( darkgreen(_("Deleted GPG key with fingerprint")), bold(key_meta['fingerprint']), ), level = "info" ) return 0
def _show_removal_info(self, entropy_client, package_ids, manual=False): """ Show packages removal information. """ if manual: entropy_client.output( "%s:" % ( blue(_("These are the packages that " "should be MANUALLY removed")),), header=darkred(" @@ ")) else: entropy_client.output( "%s:" % ( blue(_("These are the packages that " "would be removed")),), header=darkred(" @@ ")) total = len(package_ids) inst_repo = entropy_client.installed_repository() for count, package_id in enumerate(package_ids, 1): atom = inst_repo.retrieveAtom(package_id) installedfrom = inst_repo.getInstalledPackageRepository( package_id) if installedfrom is None: installedfrom = _("Not available") on_disk_size = inst_repo.retrieveOnDiskSize(package_id) pkg_size = inst_repo.retrieveSize(package_id) extra_downloads = inst_repo.retrieveExtraDownload(package_id) for extra_download in extra_downloads: pkg_size += extra_download['size'] on_disk_size += extra_download['disksize'] disksize = entropy.tools.bytes_into_human(on_disk_size) disksize_info = "%s%s%s" % ( bold("["), brown("%s" % (disksize,)), bold("]")) repo_info = bold("[") + brown(installedfrom) + bold("]") mytxt = "%s %s %s" % ( repo_info, enlightenatom(atom), disksize_info) entropy_client.output(mytxt, header=darkred(" ## "))
def _read_lic_selection(): entropy_client.output( darkred(_("Please select an option")), header=" ") entropy_client.output( "(%d) %s" % ( 1, darkgreen(_("Read the license"))), header=" ") entropy_client.output( "(%d) %s" % ( 2, brown(_("Accept the license (I've read it)"))), header=" ") entropy_client.output( "(%d) %s" % ( 3, darkred(_("Accept the license and don't " "ask anymore (I've read it)"))), header=" ") entropy_client.output( "(%d) %s" % (0, bold(_("Quit"))), header=" ") # wait user interaction try: action = readtext( " %s: " % ( _("Your choice (type a number and press enter)"),) ) except EOFError: action = None return action
def show_successful_download(down_list, data_transfer): for _pkg_id, repository_id, fname, _cksum, _signatures in down_list: best_mirror = get_best_mirror(repository_id) mirrorcount = repo_uris[repository_id].index(best_mirror) + 1 basef = os.path.basename(fname) txt = "( mirror #%s ) [%s] %s %s %s" % ( mirrorcount, brown(basef), darkred(_("success")), blue("@"), red(self._get_url_name(best_mirror)), ) self._entropy.output( txt, importance = 1, level = "info", header = red(" ## ") ) if data_transfer: txt = " %s: %s%s%s" % ( blue(_("Aggregated transfer rate")), bold(entropy.tools.bytes_into_human(data_transfer)), darkred("/"), darkblue(_("second")), ) self._entropy.output( txt, importance = 1, level = "info", header = red(" ## ") )
def _desc(self, entropy_server): """ Eit query desc code. """ repository_ids = [] if self._repository_id is None: repository_ids += entropy_server.repositories() else: repository_ids.append(self._repository_id) for repository_id in repository_ids: repo = entropy_server.open_repository(repository_id) key_sorter = lambda x: repo.retrieveAtom(x) for desc in self._nsargs.descriptions: pkg_ids = repo.searchDescription(desc, just_id = True) for pkg_id in sorted(pkg_ids, key = key_sorter): if self._quiet: entropy_server.output( repo.retrieveAtom(pkg_id), level="generic") else: print_package_info(pkg_id, entropy_server, repo, extended = self._verbose, strict_output = False, quiet = False) if not self._quiet: entropy_server.output( "[%s] %s %s" % ( darkgreen(desc), bold(str(len(pkg_ids))), teal(_("packages found")))) return 0
def _description(self, entropy_client, inst_repo): """ Solo Query Description command. """ quiet = self._nsargs.quiet verbose = self._nsargs.verbose descriptions = self._nsargs.descriptions settings = entropy_client.Settings() found = False if not quiet: entropy_client.output(darkgreen(_("Description Search")), header=darkred(" @@ ")) repo_number = 0 for repo_id in entropy_client.repositories(): repo_number += 1 repo_data = settings["repositories"]["available"][repo_id] if not quiet: header = ( const_convert_to_unicode(" #") + const_convert_to_unicode(repo_number) + const_convert_to_unicode(" ") ) entropy_client.output("%s" % (bold(repo_data["description"]),), header=blue(header)) repo = entropy_client.open_repository(repo_id) found = self._search_descriptions(descriptions, entropy_client, repo, quiet, verbose) if not quiet and not found: entropy_client.output(darkgreen("%s." % (_("No matches"),)), header=darkred(" @@ ")) return 0
def _files(self, entropy_server): """ Actual Eit files code. """ exit_st = 0 for package in self._packages: pkg_id, pkg_repo = entropy_server.atom_match(package) if pkg_id == -1: exit_st = 1 if not self._quiet: entropy_server.output( "%s: %s" % ( purple(_("Not matched")), teal(package)), level="warning", importance=1) continue entropy_repository = entropy_server.open_repository(pkg_repo) files = entropy_repository.retrieveContent( pkg_id, order_by="file") atom = entropy_repository.retrieveAtom(pkg_id) if self._quiet: for path in files: entropy_server.output(path, level="generic") else: for path in files: entropy_server.output(path) entropy_server.output( "[%s] %s: %s %s" % ( purple(pkg_repo), darkgreen(atom), bold(str(len(files))), teal(_("files found")))) return exit_st
def _files(self, entropy_server): """ Actual Eit files code. """ exit_st = 0 for package in self._packages: pkg_id, pkg_repo = entropy_server.atom_match(package) if pkg_id == -1: exit_st = 1 if not self._quiet: entropy_server.output( "%s: %s" % (purple(_("Not matched")), teal(package)), level="warning", importance=1) continue entropy_repository = entropy_server.open_repository(pkg_repo) files = entropy_repository.retrieveContent(pkg_id, order_by="file") atom = entropy_repository.retrieveAtom(pkg_id) if self._quiet: for path in files: entropy_server.output(path, level="generic") else: for path in files: entropy_server.output(path) entropy_server.output( "[%s] %s: %s %s" % (purple(pkg_repo), darkgreen(atom), bold(str( len(files))), teal(_("files found")))) return exit_st
def _read_lic_selection(): entropy_client.output(darkred(_("Please select an option")), header=" ") entropy_client.output("(%d) %s" % (1, darkgreen(_("Read the license"))), header=" ") entropy_client.output( "(%d) %s" % (2, brown(_("Accept the license (I've read it)"))), header=" ") entropy_client.output("(%d) %s" % (3, darkred( _("Accept the license and don't " "ask anymore (I've read it)"))), header=" ") entropy_client.output("(%d) %s" % (0, bold(_("Quit"))), header=" ") # wait user interaction try: action = readtext( " %s: " % (_("Your choice (type a number and press enter)"), )) except EOFError: action = None return action
def _show_notice_board_summary(self, entropy_client, repository): """ Show NoticeBoard information to user after repository update. """ mytxt = "%s %s: %s" % ( darkgreen(" @@ "), brown(_("Notice board")), bold(repository), ) entropy_client.output(mytxt) mydict = self._check_notice_board_availability(entropy_client, repository) if not mydict: return for key in sorted(mydict.keys()): mydata = mydict.get(key) mytxt = " [%s] [%s] %s: %s" % ( blue(str(key)), brown(mydata['pubDate']), _("Title"), darkred(mydata['title']), ) entropy_client.output(mytxt)
def _show_config_files_update(self, entropy_client): """ Inform User about configuration file updates, if any. """ entropy_client.output( blue(_("Scanning configuration files to update")), header=darkgreen(" @@ "), back=True) updates = entropy_client.ConfigurationUpdates() scandata = updates.get() if not scandata: entropy_client.output( blue(_("No configuration files to update.")), header=darkgreen(" @@ ")) return mytxt = ngettext( "There is %s configuration file needing update", "There are %s configuration files needing update", len(scandata)) % (len(scandata),) entropy_client.output( darkgreen(mytxt), level="warning") mytxt = "%s: %s" % ( purple(_("Please run")), bold("equo conf update")) entropy_client.output( darkgreen(mytxt), level="warning")
def _show_removal_info(self, entropy_client, package_ids, manual=False): """ Show packages removal information. """ if manual: entropy_client.output( "%s:" % ( blue(_("These are the packages that " "should be MANUALLY removed")),), header=darkred(" @@ ")) else: entropy_client.output( "%s:" % ( blue(_("These are the packages that " "would be removed")),), header=darkred(" @@ ")) inst_repo = entropy_client.installed_repository() for package_id in package_ids: atom = inst_repo.retrieveAtom(package_id) installedfrom = inst_repo.getInstalledPackageRepository( package_id) if installedfrom is None: installedfrom = _("Not available") on_disk_size = inst_repo.retrieveOnDiskSize(package_id) extra_downloads = inst_repo.retrieveExtraDownload(package_id) for extra_download in extra_downloads: on_disk_size += extra_download['disksize'] disksize = entropy.tools.bytes_into_human(on_disk_size) disksize_info = "%s%s%s" % ( bold("["), brown("%s" % (disksize,)), bold("]")) repo_info = bold("[") + brown(installedfrom) + bold("]") mytxt = "%s %s %s" % ( repo_info, enlightenatom(atom), disksize_info) entropy_client.output(mytxt, header=darkred(" ## "))
def _show_document(self, entropy_client, doc, repository, pkgkey): title = const_convert_to_unicode(doc[Document.DOCUMENT_TITLE_ID]) if not title: title = _("No title") title = darkgreen(title) ts = doc.document_timestamp() ts = entropy.tools.convert_unix_time_to_human_time(ts) entropy_client.output(" %s [%s|%s|%s|%s|%s|%s]" % ( bold("@@"), bold(str(doc.document_id())), darkred(str(doc.document_type())), darkgreen(repository), purple(pkgkey), blue(doc[DocumentFactory.DOCUMENT_USERNAME_ID]), darkgreen(ts), ) ) entropy_client.output("\t%s: %s" % ( blue(_("Title")), title, ) ) if const_isstring(doc.document_data()): text = doc.document_data() else: text = doc.document_data().tostring() text = const_convert_to_unicode(text) self._formatted_print( entropy_client, text, "\t%s: " % (blue(_("Content")),), "\t") entropy_client.output("\t%s: %s" % ( blue(_("Keywords")), doc.document_keywords(), ) ) url = doc.document_url() if url is not None: entropy_client.output("\t%s: %s" % ( blue(_("Download")), url, ) )
def _repackage_scan(self, entropy_server): """ If in repackage mode (self._repackage not empty), scan for packages to re-package and return them. """ packages = set() spm = entropy_server.Spm() for dep in self._repackage: package_id, repository_id = entropy_server.atom_match(dep) if package_id == -1: entropy_server.output( "%s: %s" % ( darkred(_("Cannot find package")), bold(dep), ), header=darkred(" !!! "), importance=1, level="warning") continue repo = entropy_server.open_repository(repository_id) try: spm_uid = spm.resolve_package_uid(repo, package_id) except spm.Error as err: entropy_server.output( "%s: %s, %s" % ( darkred(_("Cannot find package")), bold(dep), err, ), header=darkred(" !!! "), importance=1, level="warning") continue spm_name = spm.convert_from_entropy_package_name( repo.retrieveAtom(package_id)) packages.add(spm_name) return packages
def _search_mimetype(self, entropy_client, inst_repo, associate=False): """ Solo Query Mimetype command. """ installed = self._nsargs.installed quiet = self._nsargs.quiet verbose = self._nsargs.verbose settings = entropy_client.Settings() inst_repo_id = inst_repo.repository_id() if associate: mimetypes = self._nsargs.files else: mimetypes = self._nsargs.mimes if not quiet: entropy_client.output(darkgreen(_("Searching Mimetype")), header=darkred(" @@ ")) found = False for mimetype in mimetypes: if associate: # consider mimetype a file path mimetype = get_file_mime(mimetype) if mimetype is None: continue if not quiet: entropy_client.output(bold(mimetype), header=blue(" # ")) if installed: matches = [(x, inst_repo_id) for x in entropy_client.search_installed_mimetype(mimetype)] else: matches = entropy_client.search_available_mimetype(mimetype) if matches: found = True key_sorter = lambda x: entropy_client.open_repository(x[1]).retrieveAtom(x[0]) for pkg_id, pkg_repo in sorted(matches, key=key_sorter): repo = entropy_client.open_repository(pkg_repo) print_package_info(pkg_id, entropy_client, repo, extended=verbose, quiet=quiet) if not quiet: entry_str = ngettext("entry", "entries", len(matches)) toc = [] toc.append(("%s:" % (blue(_("Keyword")),), purple(mimetype))) toc.append(("%s:" % (blue(_("Found")),), "%s %s" % (len(matches), brown(entry_str)))) print_table(entropy_client, toc) if not quiet and not found: entropy_client.output(darkgreen("%s." % (_("No matches"),)), header=darkred(" @@ ")) return 0
def _search(self, entropy_server, repository_id, repo): results = {} flatresults = {} reverse_symlink_map = self._settings()['system_rev_symlinks'] for xfile in self._paths: results[xfile] = set() pkg_ids = repo.searchBelongs(xfile) if not pkg_ids: # try real path if possible pkg_ids = repo.searchBelongs(os.path.realpath(xfile)) if not pkg_ids: # try using reverse symlink mapping for sym_dir in reverse_symlink_map: if xfile.startswith(sym_dir): for sym_child in reverse_symlink_map[sym_dir]: my_file = sym_child+xfile[len(sym_dir):] pkg_ids = repo.searchBelongs(my_file) if pkg_ids: break for pkg_id in pkg_ids: if not flatresults.get(pkg_id): results[xfile].add(pkg_id) flatresults[pkg_id] = True if results: key_sorter = lambda x: repo.retrieveAtom(x) for result in results: # print info xfile = result result = results[result] for pkg_id in sorted(result, key = key_sorter): if self._quiet: entropy_server.output( repo.retrieveAtom(pkg_id), level="generic") else: print_package_info(pkg_id, entropy_server, repo, installed_search = True, extended = self._verbose, quiet = self._quiet) if not self._quiet: entropy_server.output( "[%s] %s: %s %s" % ( purple(repository_id), darkgreen(xfile), bold(str(len(result))), teal(_("packages found")))) return 0
def _check_entropy_updates(self): rc = False if self.entropy_updates_alert: try: rc, pkg_match = self._entropy.check_package_update( "sys-apps/entropy", deep = True) except: pass if rc: self.new_entropy = True mytxt = "%s: %s. %s." % ( bold("Entropy"), blue(_("a new release is available")), darkred(_("Mind to install it before any other package")), ) self._entropy.output( mytxt, importance = 1, level = "info", header = bold(" !!! ") )
def _show_vote(self, entropy_client, vote, repository, pkgkey): if vote is None: vote = _("no votes") else: vote = const_convert_to_unicode("%.2f" % (vote,)) entropy_client.output(" %s [%s] %s: %s" % ( bold(const_convert_to_unicode("@@")), purple(pkgkey), darkred(_("current package vote")), darkgreen(vote), ) )
def warn_version_mismatch(): equo_ver = read_client_release() entropy_ver = etpConst['entropyversion'] if equo_ver != entropy_ver: print_warning("") print_warning("%s: %s" % ( bold(_("Entropy/Equo version mismatch")), purple(_("it could make your system explode!")),)) print_warning("(%s [equo] & %s [entropy])" % ( blue(equo_ver), blue(entropy_ver),)) print_warning("")
def _search(self, entropy_server, repository_id, repo): results = {} flatresults = {} reverse_symlink_map = self._settings()['system_rev_symlinks'] for xfile in self._paths: results[xfile] = set() pkg_ids = repo.searchBelongs(xfile) if not pkg_ids: # try real path if possible pkg_ids = repo.searchBelongs(os.path.realpath(xfile)) if not pkg_ids: # try using reverse symlink mapping for sym_dir in reverse_symlink_map: if xfile.startswith(sym_dir): for sym_child in reverse_symlink_map[sym_dir]: my_file = sym_child + xfile[len(sym_dir):] pkg_ids = repo.searchBelongs(my_file) if pkg_ids: break for pkg_id in pkg_ids: if not flatresults.get(pkg_id): results[xfile].add(pkg_id) flatresults[pkg_id] = True if results: key_sorter = lambda x: repo.retrieveAtom(x) for result in results: # print info xfile = result result = results[result] for pkg_id in sorted(result, key=key_sorter): if self._quiet: entropy_server.output(repo.retrieveAtom(pkg_id), level="generic") else: print_package_info(pkg_id, entropy_server, repo, installed_search=True, extended=self._verbose, quiet=self._quiet) if not self._quiet: entropy_server.output( "[%s] %s: %s %s" % (purple(repository_id), darkgreen(xfile), bold(str(len(result))), teal(_("packages found")))) return 0
def _advise_repository_update(self, entropy_client): """ Warn user about old repositories if needed. """ old_repos = Repository.are_repositories_old() if old_repos: entropy_client.output("") mytxt = "%s %s" % ( purple(_("Repositories are old, please run:")), bold("equo update"), ) entropy_client.output(mytxt, level="warning", importance=1) entropy_client.output("")
def _trigger_call_ext_generic(self): try: return self._do_trigger_call_ext_generic() except Exception as err: mykey = self._pkgdata['category'] + "/" + self._pkgdata['name'] tback = entropy.tools.get_traceback() self._entropy.output(tback, importance=0, level="error") self._entropy.logger.write(tback) self._entropy.logger.log( "[Trigger]", etpConst['logging']['normal_loglevel_id'], "[POST] ATTENTION Cannot run External trigger for " + \ mykey + "!! " + str(Exception) + ": " + repr(err) ) mytxt = "%s: %s %s. %s." % ( bold(_("QA")), brown(_("Cannot run External trigger for")), bold(mykey), brown(_("Please report it")), ) self._entropy.output(mytxt, importance=0, header=red(" ## ")) return 0
def enlightenatom(atom): """ Colorize package atoms with standard colors. @param atom: atom string @type atom: string @return: colorized string @rtype: string """ entropy_rev = entropy.dep.dep_get_entropy_revision(atom) if entropy_rev is None: entropy_rev = '' else: entropy_rev = '~%s' % (str(entropy_rev),) entropy_tag = entropy.dep.dep_gettag(atom) if entropy_tag is None: entropy_tag = '' else: entropy_tag = '#%s' % (entropy_tag,) slot = entropy.dep.dep_getslot(atom) slot_pfx = "" if slot is None: slot = "" else: slot_pfx = etpConst['entropyslotprefix'] clean_atom = entropy.dep.remove_entropy_revision(atom) clean_atom = entropy.dep.remove_tag(clean_atom) clean_atom = entropy.dep.remove_slot(atom) only_cpv = entropy.dep.dep_getcpv(clean_atom) cpv_split = entropy.dep.catpkgsplit(only_cpv) if cpv_split is None: cat, name = only_cpv.split("/", 1) pv = "" rev = "r0" operator = "" else: operator = clean_atom[:len(clean_atom)-len(only_cpv)] cat, name, pv, rev = cpv_split pv = "-" + pv if rev == "r0": rev = '' else: rev = '-%s' % (rev,) return "%s%s%s%s%s%s%s%s%s" % ( purple(operator), teal(cat + "/"), darkgreen(name), purple(pv), bold(slot_pfx), darkred(slot), purple(rev), brown(entropy_tag), teal(entropy_rev),)
def warn_version_mismatch(): equo_ver = read_client_release() entropy_ver = etpConst['entropyversion'] if equo_ver != entropy_ver: print_warning("") print_warning("%s: %s" % ( bold(_("Entropy/Equo version mismatch")), purple(_("it could make your system explode!")), )) print_warning("(%s [equo] & %s [entropy])" % ( blue(equo_ver), blue(entropy_ver), )) print_warning("")
def _advise_repository_update(self, entropy_client): """ Warn user about old repositories if needed. """ old_repos = Repository.are_repositories_old() if old_repos: entropy_client.output("") mytxt = "%s %s" % ( purple(_("Repositories are old, please run:")), bold("equo update"), ) entropy_client.output( mytxt, level="warning", importance=1) entropy_client.output("")
def _license(self, entropy_client): """ Solo Query License command. """ quiet = self._nsargs.quiet verbose = self._nsargs.verbose licenses = self._nsargs.licenses settings = entropy_client.Settings() if not quiet: entropy_client.output(darkgreen(_("License Search")), header=darkred(" @@ ")) found = False repo_number = 0 for repo_id in entropy_client.repositories(): repo_number += 1 repo_data = settings["repositories"]["available"][repo_id] if not quiet: header = ( const_convert_to_unicode(" #") + const_convert_to_unicode(repo_number) + const_convert_to_unicode(" ") ) entropy_client.output("%s" % (bold(repo_data["description"]),), header=blue(header)) repo = entropy_client.open_repository(repo_id) key_sorter = lambda x: repo.retrieveAtom(x) for mylicense in licenses: results = repo.searchLicense(mylicense, just_id=True) if not results: continue found = True for pkg_id in sorted(results, key=key_sorter): print_package_info(pkg_id, entropy_client, repo, extended=verbose, strict_output=quiet, quiet=quiet) if not quiet: res_txt = ngettext("entry", "entries", len(results)) toc = [] toc.append(("%s:" % (blue(_("Keyword")),), purple(mylicense))) toc.append(("%s:" % (blue(_("Found")),), "%s %s" % (len(results), brown(res_txt)))) print_table(entropy_client, toc) if not quiet and not found: entropy_client.output(darkgreen("%s." % (_("No matches"),)), header=darkred(" @@ ")) return 0
def _sets(self, entropy_server): """ Eit query sets code. """ repository_ids = [] if self._repository_id is None: repository_ids += entropy_server.repositories() else: repository_ids.append(self._repository_id) repository_ids = tuple(repository_ids) sets = entropy_server.Sets() match_num = 0 if not self._nsargs.sets: self._nsargs.sets.append("*") for item in self._nsargs.sets: results = sets.search(item, match_repo=repository_ids) key_sorter = lambda x: x[1] for repo, set_name, set_data in sorted(results, key=key_sorter): match_num += 1 found = True if not self._quiet: entropy_server.output( "%s%s" % (brown(etpConst['packagesetprefix']), darkgreen(set_name),)) if self._verbose: elements = sorted(set_data) for element in elements: entropy_server.output( teal(element), header=" ") else: entropy_server.output( "%s%s" % (etpConst['packagesetprefix'], set_name,), level="generic") if self._verbose: for element in sorted(set_data): entropy_server.output( element, level="generic") if not self._quiet: entropy_server.output( "[%s] %s %s" % ( darkgreen(item), bold(str(match_num)), teal(_("sets found")))) return 0
def __init__(self, entropy_client, action, phase, package_metadata, action_metadata): """ Trigger manager interface constructor. @param entropy_client: Entropy Client interface object @type entropy_client: entropy.client.interfaces.client.Client @param action: package handling action, can be "install", "remove", etc. see entropy.client.interfaces.package.Package @type action: string @param phase: the package phase that is required to be run, can be either on of the Trigger.VALID_PHASES values. @type phase: string @param package_metadata: package metadata that can be used by this Trigger interface @type package_metadata: dict @param action_metadata: trigger metadata bound to action (and not to phase) @type action_metadata: dict or None """ self._entropy = entropy_client self._pkgdata = package_metadata self._action = action self._action_metadata = action_metadata self._prepared = False self._triggers = [] self._trigger_data = {} self._spm = None try: self._spm = self._entropy.Spm() except Exception as err: entropy.tools.print_traceback() mytxt = darkred("%s, %s: %s, %s !") % ( _("Source Package Manager interface can't be loaded"), _("Error"), repr(err), _("please fix"), ) self._entropy.output( mytxt, importance = 0, header = bold(" !!! ") ) self._phase = phase # validate phase if self._phase not in Trigger.VALID_PHASES: mytxt = "Valid phases: %s" % (Trigger.VALID_PHASES,) raise AttributeError(mytxt)
def _compress_packages(self, entropy_server, repository_id, packages): """ Compress (and generate package tarball) the list of given spm package names inside the given Entropy repository. """ entropy_server.output( blue(_("Compressing packages")), header=brown(" @@ ")) generated_packages = collections.deque() store_dir = entropy_server._get_local_store_directory(repository_id) if not os.path.isdir(store_dir): try: os.makedirs(store_dir) except (IOError, OSError) as err: entropy_server.output( "%s: %s" % (_("Cannot create store directory"), err), header=brown(" !!! "), importance=1, level="error") return generated_packages, 1 for count, spm_name in enumerate(packages, 1): entropy_server.output( teal(spm_name), header=brown(" # "), count=(count, len(packages))) try: pkg_list = entropy_server.Spm().generate_package(spm_name, store_dir) generated_packages.append(pkg_list) except OSError: entropy.tools.print_traceback() entropy_server.output( bold(_("Ignoring broken Spm entry, please recompile it")), header=brown(" !!! "), importance=1, level="warning") if not generated_packages: entropy_server.output( red(_("Nothing to do, check later.")), header=brown(" * ")) return generated_packages, 0 return generated_packages, None
def _tags(self, entropy_client): """ Solo Query Tags command. """ quiet = self._nsargs.quiet verbose = self._nsargs.verbose tags = self._nsargs.tags settings = entropy_client.Settings() if not quiet: entropy_client.output(darkgreen(_("Tag Search")), header=darkred(" @@ ")) found = False # search inside each available database repo_number = 0 for repo_id in entropy_client.repositories(): repo_number += 1 repo_data = settings["repositories"]["available"][repo_id] if not quiet: header = ( const_convert_to_unicode(" #") + const_convert_to_unicode(repo_number) + const_convert_to_unicode(" ") ) entropy_client.output("%s" % (bold(repo_data["description"]),), header=blue(header)) repo = entropy_client.open_repository(repo_id) for tag in tags: results = repo.searchTaggedPackages(tag) key_sorter = lambda x: repo.retrieveAtom(x) for pkg_id in sorted(results, key=key_sorter): found = True print_package_info(pkg_id, entropy_client, repo, extended=verbose, strict_output=quiet, quiet=quiet) if not quiet: toc = [] entity_str = ngettext("entry", "entries", len(results)) toc.append(("%s:" % (blue(_("Keyword")),), purple(tag))) toc.append(("%s:" % (blue(_("Found")),), "%s %s" % (len(results), brown(entity_str)))) print_table(entropy_client, toc) if not quiet and not found: entropy_client.output(darkgreen("%s." % (_("No matches"),)), header=darkred(" @@ ")) return 0
def _logout(self, entropy_client): """ Solo Ugc Logout command. """ repository = self._nsargs.repo force = self._nsargs.force if repository not in entropy_client.repositories(): entropy_client.output( "%s: %s." % ( darkred(_("Invalid repository")), teal(repository),), level="error", importance=1) return 1 try: webserv = _get_service(entropy_client, repository) except WebService.UnsupportedService: entropy_client.output( "[%s] %s" % ( darkgreen(repository), blue(_("Repository does not support Entropy Services.")), ) ) return 1 username = webserv.get_credentials() if username is None: entropy_client.output( "[%s] %s" % ( darkgreen(repository), blue(_("Not logged in.")), ) ) return 0 webserv.remove_credentials() entropy_client.output( "[%s] %s %s %s" % ( darkgreen(repository), blue(_("User")), bold(username), blue(_("has been logged out.")), ) ) return 0
def _needed(self, entropy_server): """ Eit query needed code. """ repository_ids = [] if self._repository_id is None: repository_ids += entropy_server.repositories() else: repository_ids.append(self._repository_id) exit_st = 0 for package in self._nsargs.packages: pkg_id, repo_id = entropy_server.atom_match(package) if pkg_id == -1: if not self._quiet: entropy_server.output( "%s: %s" % ( purple(_("Not matched")), teal(package)), level="warning", importance=1) exit_st = 1 continue repo = entropy_server.open_repository(repo_id) atom = repo.retrieveAtom(pkg_id) neededs = repo.retrieveNeededLibraries(pkg_id) for usr_path, usr_soname, soname, elfclass, rpath in neededs: out_str = "%s:%s:%s:%s:%s" % ( usr_path, usr_soname, soname, elfclass, rpath) if self._quiet: entropy_server.output(out_str, level="generic") else: entropy_server.output( darkred(const_convert_to_unicode(out_str)), header=blue(" # ")) if not self._quiet: entropy_server.output( "[%s] %s: %s %s" % ( purple(repo_id), darkgreen(atom), bold(str(len(neededs))), teal(_("libraries found")))) return exit_st
def _import(self, entropy_server): """ Actual Eit key import code. """ repo_sec = self._get_gpg(entropy_server) if repo_sec is None: return 1 repo = entropy_server.repository() privkey_path = self._nsargs.privkey.name pubkey_path = self._nsargs.pubkey.name # no need to close files here entropy_server.output("%s: %s" % ( blue(_("Importing keypair")), purple(repo),)) if repo_sec.is_keypair_available(repo): entropy_server.output( "%s: %s" % ( blue(_("Another keypair already exists")), purple(repo), ), level = "error" ) return 1 # install private key finger_print = repo_sec.install_key(repo, privkey_path) repo_sec.install_key(repo, pubkey_path, ignore_nothing_imported = True) entropy_server.output("%s: %s" % ( darkgreen(_("Imported GPG key with fingerprint")), bold(finger_print), ), level = "info" ) entropy_server.output("%s: %s" % ( darkgreen(_("Now sign all the packages in it")), blue(repo), ), level = "warning" ) return 0
def pkg_filter(spm_name): if spm_name in to_be_added: return spm_name try: inst_spm_name = entropy_server.Spm( ).match_installed_package(spm_name) except KeyError: entropy_server.output( "%s: %s" % (darkred(_("Invalid package")), bold(spm_name)), header=darkred(" !!! "), importance=1, level="warning") return None if inst_spm_name in to_be_added: return inst_spm_name return None
def _revdeps(self, entropy_server): """ Eit query revdeps code. """ excluded_dep_types = None if not self._nsargs.bdeps: excluded_dep_types = [ etpConst['dependency_type_ids']['bdepend_id'] ] exit_st = 0 for package in self._nsargs.packages: package_id, repository_id = entropy_server.atom_match(package) if package_id == -1: if not self._quiet: entropy_server.output( "%s: %s" % ( purple(_("Not matched")), teal(package)), level="warning", importance=1) exit_st = 1 continue repo = entropy_server.open_repository(repository_id) key_sorter = lambda x: repo.retrieveAtom(x) results = repo.retrieveReverseDependencies(package_id, exclude_deptypes = excluded_dep_types) for pkg_id in sorted(results, key = key_sorter): print_package_info(pkg_id, entropy_server, repo, installed_search = True, strict_output = self._quiet, extended = self._verbose, quiet = self._quiet) if not self._quiet: atom = repo.retrieveAtom(package_id) entropy_server.output( "[%s] %s: %s %s" % ( purple(repository_id), darkgreen(atom), bold(str(len(results))), teal(_("revdep(s) found")))) return exit_st
def print_repository_status(entropy_server, repository_id): remote_db_status = entropy_server.Mirrors.remote_repository_status( repository_id) entropy_server.output("%s:" % (brown(_("Entropy Repository Status")), ), importance=1, header=darkgreen(" * ")) for url, revision in remote_db_status.items(): host = EntropyTransceiver.get_uri_name(url) entropy_server.output("%s: %s" % (darkgreen(_("Host")), bold(host)), header=" ") entropy_server.output("%s: %s" % (purple(_("Remote")), blue(str(revision))), header=" ") local_revision = entropy_server.local_repository_revision( repository_id) entropy_server.output("%s: %s" % (brown(_("Local")), teal(str(local_revision))), header=" ")
def _show_config_files_update(self, entropy_client): """ Inform User about configuration file updates, if any. """ entropy_client.output(blue( _("Scanning configuration files to update")), header=darkgreen(" @@ "), back=True) updates = entropy_client.ConfigurationUpdates() scandata = updates.get() if not scandata: entropy_client.output(blue(_("No configuration files to update.")), header=darkgreen(" @@ ")) return mytxt = ngettext("There is %s configuration file needing update", "There are %s configuration files needing update", len(scandata)) % (len(scandata), ) entropy_client.output(darkgreen(mytxt), level="warning") mytxt = "%s: %s" % (purple(_("Please run")), bold("equo conf update")) entropy_client.output(darkgreen(mytxt), level="warning")
def _print_advisory_information(self, entropy_client, advisory_data, key): """ Print Security Advisory. """ toc = [] # print advisory code toc.append( blue(" @@ ") + \ red("%s " % (_("Advisory Identifier"),)) + bold(key) + \ red(" | ")+blue(advisory_data['url'])) # title toc.append((darkgreen(" %s:" % (_("Title"),)), darkred(advisory_data['title']))) # description description = advisory_data['description'].split("\n") desc_text = darkgreen(" %s:" % (_("Description"),) ) for x in description: toc.append((desc_text, x.strip())) desc_text = " " for item in advisory_data['description_items']: desc_text = " %s " % (darkred("(*)"),) count = 8 mystr = [] for word in item.split(): count -= 1 mystr.append(word) if count < 1: toc.append((" ", desc_text+' '.join(mystr))) desc_text = " " mystr = [] count = 8 if count < 8: toc.append((" ", desc_text+' '.join(mystr))) # background if advisory_data['background']: background = advisory_data['background'].split("\n") bg_text = darkgreen(" %s:" % (_("Background"),)) for x in background: toc.append((bg_text, purple(x.strip()))) bg_text = " " # access if advisory_data['access']: toc.append((darkgreen(" %s:" % (_("Exploitable"),)), bold(advisory_data['access']))) # impact if advisory_data['impact']: impact = advisory_data['impact'].split("\n") imp_text = darkgreen(" %s:" % (_("Impact"),)) for x in impact: toc.append((imp_text, brown(x.strip()))) imp_text = " " # impact type if advisory_data['impacttype']: toc.append((darkgreen(" %s:" % (_("Impact type"),)), bold(advisory_data['impacttype']))) # revised if advisory_data['revised']: toc.append((darkgreen(" %s:" % (_("Revised"),)), brown(advisory_data['revised']))) # announced if advisory_data['announced']: toc.append((darkgreen(" %s:" % (_("Announced"),)), brown(advisory_data['announced']))) # synopsis synopsis = advisory_data['synopsis'].split("\n") syn_text = darkgreen(" %s:" % (_("Synopsis"),)) for x in synopsis: toc.append((syn_text, x.strip())) syn_text = " " # references if advisory_data['references']: toc.append(darkgreen(" %s:" % (_("References"),))) for reference in advisory_data['references']: toc.append((" ", darkblue(reference))) # gentoo bugs if advisory_data['bugs']: toc.append(darkgreen(" %s:" % (_("Upstream bugs"),))) for bug in advisory_data['bugs']: toc.append((" ", darkblue(bug))) # affected if advisory_data['affected']: toc.append(darkgreen(" %s:" % (_("Affected"),))) for key in advisory_data['affected']: toc.append((" ", darkred(key))) affected_data = advisory_data['affected'][key][0] vul_vers = affected_data['vul_vers'] unaff_vers = affected_data['unaff_vers'] if vul_vers: toc.append((" ", brown("%s: " % ( _("vulnerable versions"),))+", ".join(vul_vers))) if unaff_vers: toc.append((" ", brown("%s: " % ( _("unaffected versions"),))+", ".join(unaff_vers))) # workaround workaround = advisory_data['workaround'].split("\n") if advisory_data['workaround']: work_text = darkgreen(" %s:" % (_("Workaround"),)) for x in workaround: toc.append((work_text, darkred(x.strip()))) work_text = " " # resolution if advisory_data['resolution']: res_text = darkgreen(" %s:" % (_("Resolution"),)) resolutions = advisory_data['resolution'] for resolution in resolutions: for x in resolution.split("\n"): toc.append((res_text, x.strip())) res_text = " " print_table(entropy_client, toc, cell_spacing=3)