def history_undo_transaction(self, extcmd): """Undo given transaction.""" old = self.history_get_transaction((extcmd,)) if old is None: return 1, ['Failed history undo'] tm = time.ctime(old.beg_timestamp) print("Undoing transaction %u, from %s" % (old.tid, tm)) self.output.historyInfoCmdPkgsAltered(old) # :todo history = dnf.history.open_history(self.history) # :todo hibeg = self.output.term.MODE['bold'] hiend = self.output.term.MODE['normal'] try: self.history_undo_operations(history.transaction_nevra_ops(old.tid)) except dnf.exceptions.PackagesNotInstalledError as err: self.logger.info(_('No package %s%s%s installed.'), hibeg, unicode(err.pkg_spec), hiend) return 1, ['An operation cannot be undone'] except dnf.exceptions.PackagesNotAvailableError as err: self.logger.info(_('No package %s%s%s available.'), hibeg, unicode(err.pkg_spec), hiend) return 1, ['An operation cannot be undone'] except dnf.exceptions.MarkingError: assert False else: return 2, ["Undoing transaction %u" % (old.tid,)]
def display_summary(self, apkg_adv_insts, description): """Display the summary of advisories.""" typ2cnt = self._summary(apkg_adv_insts) if typ2cnt: print(_('Updates Information Summary: ') + description) # Convert types to strings and order the entries. label_counts = [ (0, _('New Package notice(s)'), typ2cnt[hawkey.ADVISORY_NEWPACKAGE]), (0, _('Security notice(s)'), typ2cnt[hawkey.ADVISORY_SECURITY]), (1, _('Critical Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Critical')]), (1, _('Important Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Important')]), (1, _('Moderate Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Moderate')]), (1, _('Low Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Low')]), (1, _('Unknown Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, None)]), (0, _('Bugfix notice(s)'), typ2cnt[hawkey.ADVISORY_BUGFIX]), (0, _('Enhancement notice(s)'), typ2cnt[hawkey.ADVISORY_ENHANCEMENT]), (0, _('other notice(s)'), typ2cnt[hawkey.ADVISORY_UNKNOWN]) ] width = _maxlen(unicode(v[2]) for v in label_counts if v[2]) for indent, label, count in label_counts: if not count: continue print(' %*s %s' % (width + 4 * indent, unicode(count), label)) if self.base.conf.autocheck_running_kernel: self.cli._check_running_kernel()
def display_summary(self, apkg_adv_insts, description): """Display the summary of advisories.""" typ2cnt = self._summary(apkg_adv_insts) if typ2cnt: print(_('Updates Information Summary: ') + description) # Convert types to strings and order the entries. label_counts = [ (0, _('New Package notice(s)'), typ2cnt[hawkey.ADVISORY_NEWPACKAGE]), (0, _('Security notice(s)'), typ2cnt[hawkey.ADVISORY_SECURITY]), (1, _('Critical Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Critical')]), (1, _('Important Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Important')]), (1, _('Moderate Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Moderate')]), (1, _('Low Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Low')]), (1, _('Unknown Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, None)]), (0, _('Bugfix notice(s)'), typ2cnt[hawkey.ADVISORY_BUGFIX]), (0, _('Enhancement notice(s)'), typ2cnt[hawkey.ADVISORY_ENHANCEMENT]), (0, _('other notice(s)'), typ2cnt[hawkey.ADVISORY_UNKNOWN])] width = _maxlen(unicode(v[2]) for v in label_counts if v[2]) for indent, label, count in label_counts: if not count: continue print(' %*s %s' % (width + 4 * indent, unicode(count), label)) if self.base.conf.autocheck_running_kernel: self.cli._check_running_kernel()
def end(self, payload, status, err_msg): start = now = time() text = unicode(payload) size = int(payload.download_size) if self.multi_download_id is not None: text = self.multi_download_id # update state if status == dnf.callback.STATUS_MIRROR: pass elif status == dnf.callback.STATUS_DRPM: self.done_drpm += 1 elif text in self.state: if self.multi_download_id is not None: start, done = self.state[text] size = 0 else: start, done = self.state.pop(text) size -= done if unicode(payload) in self.active: self.active.remove(unicode(payload)) self.done_files += 1 self.done_size += size elif status == dnf.callback.STATUS_ALREADY_EXISTS: self.done_files += 1 self.done_size += size text = unicode(payload) if status: # the error message, no trimming if status is dnf.callback.STATUS_DRPM and self.total_drpm > 1: msg = '[%s %d/%d] %s: ' % (self.STATUS_2_STR[status], self.done_drpm, self.total_drpm, text) else: msg = '[%s] %s: ' % (self.STATUS_2_STR[status], text) left = _term_width() - len(msg) - 1 msg = '%s%-*s\n' % (msg, left, err_msg) else: if self.total_files > 1: text = '(%d/%d): %s' % (self.done_files, self.total_files, text) # average rate, file size, download time tm = max(now - start, 0.001) msg = ' %5sB/s | %5sB %9s \n' % (format_number( float(done) / tm), format_number(done), format_time(tm)) left = _term_width() - len(msg) msg = '%-*.*s%s' % (left, left, text, msg) self.message(msg) # now there's a blank line. fill it if possible. if self.active: self._update(now)
def history_rollback_transaction(self, extcmd): """Rollback given transaction.""" old = self.history_get_transaction((extcmd,)) if old is None: return 1, ['Failed history rollback, no transaction'] last = self.history.last() if last is None: return 1, ['Failed history rollback, no last?'] if old.tid == last.tid: return 0, ['Rollback to current, nothing to do'] mobj = None for tid in self.history.old(list(range(old.tid + 1, last.tid + 1))): if tid.altered_lt_rpmdb: self.logger.warning(_('Transaction history is incomplete, before %u.'), tid.tid) elif tid.altered_gt_rpmdb: self.logger.warning(_('Transaction history is incomplete, after %u.'), tid.tid) if mobj is None: mobj = dnf.yum.history.YumMergedHistoryTransaction(tid) else: mobj.merge(tid) tm = time.ctime(old.beg_timestamp) print("Rollback to transaction %u, from %s" % (old.tid, tm)) print(self.output.fmtKeyValFill(" Undoing the following transactions: ", ", ".join((str(x) for x in mobj.tid)))) self.output.historyInfoCmdPkgsAltered(mobj) # :todo history = dnf.history.open_history(self.history) # :todo operations = dnf.history.NEVRAOperations() for id_ in range(old.tid + 1, last.tid + 1): operations += history.transaction_nevra_ops(id_) hibeg = self.output.term.MODE['bold'] hiend = self.output.term.MODE['normal'] try: self.history_undo_operations(operations) except dnf.exceptions.PackagesNotInstalledError as err: self.logger.info(_('No package %s%s%s installed.'), hibeg, unicode(err.pkg_spec), hiend) return 1, ['A transaction cannot be undone'] except dnf.exceptions.PackagesNotAvailableError as err: self.logger.info(_('No package %s%s%s available.'), hibeg, unicode(err.pkg_spec), hiend) return 1, ['A transaction cannot be undone'] except dnf.exceptions.MarkingError: assert False else: return 2, ["Rollback to transaction %u" % (old.tid,)]
def progress(self, payload, done): now = time() text = unicode(payload) total = int(payload.download_size) done = int(done) if text not in self.active: self.active.append(text) if self.multi_download_id is not None: text = self.multi_download_id # update done_size if text not in self.state: self.state[text] = now, 0 start, old = self.state[text] self.state[text] = start, done self.done_size += done - old if total > self.total_size: self.total_size = total # update screen if enough time has elapsed if now - self.last_time > self.update_period: self._update(now)
def display_summary(cls, apkg_adv_insts, mixed, description): """Display the summary of advisories.""" typ2cnt = cls._summary(apkg_adv_insts) if not typ2cnt: return print(_('Updates Information Summary: ') + description) # Convert types to strings and order the entries. label_counts = [ (0, _('New Package notice(s)'), typ2cnt[hawkey.ADVISORY_NEWPACKAGE]), (0, _('Security notice(s)'), typ2cnt[hawkey.ADVISORY_SECURITY]), (1, _('Critical Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Critical')]), (1, _('Important Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Important')]), (1, _('Moderate Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Moderate')]), (1, _('Low Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Low')]), (1, _('Unknown Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, None)]), (0, _('Bugfix notice(s)'), typ2cnt[hawkey.ADVISORY_BUGFIX]), (0, _('Enhancement notice(s)'), typ2cnt[hawkey.ADVISORY_ENHANCEMENT]), (0, _('other notice(s)'), typ2cnt[hawkey.ADVISORY_UNKNOWN]) ] # Convert counts to strings and skip missing types. label2value = OrderedDict((label, (indent, unicode(count))) for indent, label, count in label_counts if count) width = _maxlen(v[1] for v in label2value.values()) for label, (indent, value) in label2value.items(): print(' %*s %s' % (width + 4 * indent, value, label))
def display_summary(cls, apkg_adv_insts, mixed, description): """Display the summary of advisories.""" typ2cnt = cls._summary(apkg_adv_insts) if not typ2cnt: return print(_('Updates Information Summary: ') + description) # Convert types to strings and order the entries. label_counts = [ (0, _('New Package notice(s)'), typ2cnt[hawkey.ADVISORY_NEWPACKAGE]), (0, _('Security notice(s)'), typ2cnt[hawkey.ADVISORY_SECURITY]), (1, _('Critical Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Critical')]), (1, _('Important Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Important')]), (1, _('Moderate Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Moderate')]), (1, _('Low Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, 'Low')]), (1, _('Unknown Security notice(s)'), typ2cnt[(hawkey.ADVISORY_SECURITY, None)]), (0, _('Bugfix notice(s)'), typ2cnt[hawkey.ADVISORY_BUGFIX]), (0, _('Enhancement notice(s)'), typ2cnt[hawkey.ADVISORY_ENHANCEMENT]), (0, _('other notice(s)'), typ2cnt[hawkey.ADVISORY_UNKNOWN])] # Convert counts to strings and skip missing types. label2value = OrderedDict((label, (indent, unicode(count))) for indent, label, count in label_counts if count) width = _maxlen(v[1] for v in label2value.values()) for label, (indent, value) in label2value.items(): print(' %*s %s' % (width + 4 * indent, value, label))
def display_info(self, apkg_adv_insts, mixed, description): """Display the details about available advisories.""" info = self._info(apkg_adv_insts).items() # Convert objects to string lines and mark verbose fields. verbse = lambda value: value if self.base.conf.verbose else None info = ( (tit, ([id_], [self.TYPE2LABEL[typ]], [unicode(upd)], (id_title[0] + (' - ' + id_title[1] if id_title[1] else '') for id_title in bzs), (id_title[0] for id_title in cvs), desc.splitlines(), [sev], verbse(rigs.splitlines() if rigs else None), verbse(fils), None if not mixed else [_('true') if ins else _('false')])) for tit, (id_, typ, upd, bzs, cvs, desc, sev, rigs, fils, ins) in info) labels = (_('Update ID'), _('Type'), _('Updated'), _('Bugs'), _('CVEs'), _('Description'), _('Severity'), _('Rights'), _('Files'), _('Installed')) width = _maxlen(labels) for title, vallines in info: print('=' * 79) print(' ' + title) print('=' * 79) for label, lines in zip(labels, vallines): if lines is None or lines == [None]: continue # Use the label only for the first item. For the remaining # items, use an empty label. labels_ = chain([label], itertools.repeat('')) for label_, line in zip(labels_, lines): print('%*s : %s' % (width, label_, line)) print()
def display_info(self, apkg_adv_insts, mixed, description): """Display the details about available advisories.""" info = self._info(apkg_adv_insts).items() # Convert objects to string lines and mark verbose fields. verbse = lambda value: value if self.base.conf.verbose else None info = ((tit, ([id_], [self.TYPE2LABEL[typ]], [unicode(upd)], (id_title[0] + (' - ' + id_title[1] if id_title[1] else '') for id_title in bzs), (id_title[0] for id_title in cvs), desc.splitlines(), [sev], verbse(rigs.splitlines() if rigs else None), verbse(fils), None if not mixed else [_('true') if ins else _('false')])) for tit, (id_, typ, upd, bzs, cvs, desc, sev, rigs, fils, ins) in info) labels = (_('Update ID'), _('Type'), _('Updated'), _('Bugs'), _('CVEs'), _('Description'), _('Severity'), _('Rights'), _('Files'), _('Installed')) width = _maxlen(labels) for title, vallines in info: print('=' * 79) print(' ' + title) print('=' * 79) for label, lines in zip(labels, vallines): if lines is None or lines == [None]: continue # Use the label only for the first item. For the remaining # items, use an empty label. labels_ = chain([label], itertools.repeat('')) for label_, line in zip(labels_, lines): print('%*s : %s' % (width, label_, line)) print()
def to_unicode(obj, encoding='utf-8', errors='replace'): """ Convert string to unicode. Consider using the more general dnf.i18n.ucd(). """ if is_py2str_py3bytes(obj): obj = unicode(obj, encoding, errors) return obj
def ucd(obj): """ Like the builtin unicode() but tries to use a reasonable encoding. """ if PY3: if is_py3bytes(obj): return str(obj, _guess_encoding()) elif isinstance(obj, str): return obj return str(obj) else: if hasattr(obj, '__unicode__'): # see the doc for the unicode() built-in. The logic here is: if obj # implements __unicode__, let it take a crack at it, but handle the # situation if it fails: try: return unicode(obj) except UnicodeError: pass return unicode(str(obj), _guess_encoding())
def test_dump(self): dump = self.repo.dump() f = io.StringIO(unicode(dump)) parser = iniparse.compat.ConfigParser() parser.readfp(f) self.assertIn("r", parser.sections()) opts = parser.options("r") self.assertIn("bandwidth", opts) self.assertIn("gpgkey", opts) self.assertEqual(parser.get("r", "timeout"), "30.0")
def test_dump(self): dump = self.repo.dump() f = io.StringIO(unicode(dump)) parser = iniparse.compat.ConfigParser() parser.readfp(f) self.assertIn('r', parser.sections()) opts = parser.options('r') self.assertIn('bandwidth', opts) self.assertIn('gpgkey', opts) self.assertEqual(parser.get('r', 'timeout'), '30.0')
def ucd(obj): """ Like the builtin unicode() but tries to use a reasonable encoding. """ if PY3: if is_py3bytes(obj): return str(obj, _guess_encoding()) elif isinstance(obj, str): return obj return str(obj) else: if isinstance(obj, unicode): return obj if hasattr(obj, '__unicode__'): # see the doc for the unicode() built-in. The logic here is: if obj # implements __unicode__, let it take a crack at it, but handle the # situation if it fails: try: return unicode(obj) except UnicodeError: pass return unicode(str(obj), _guess_encoding())
def display_info(self, apkg_adv_insts, mixed, description): """Display the details about available advisories.""" info = self._info(apkg_adv_insts).items() # Convert objects to string lines and mark verbose fields. verbse = lambda value: value if self.base.conf.verbose else None info = ( ( tit, ( [id_], [self.TYPE2LABEL[typ]], [unicode(upd)], (id_title[0] + " - " + id_title[1] for id_title in bzs), (id_title[0] for id_title in cvs), desc.splitlines(), verbse(rigs.splitlines() if rigs else None), verbse(fils), None if not mixed else [_("true") if ins else _("false")], ), ) for tit, (id_, typ, upd, bzs, cvs, desc, rigs, fils, ins) in info ) labels = ( _("Update ID"), _("Type"), _("Updated"), _("Bugs"), _("CVEs"), _("Description"), _("Rights"), _("Files"), _("Installed"), ) width = _maxlen(labels) for title, vallines in info: print("=" * 79) print(" " + title) print("=" * 79) for label, lines in zip(labels, vallines): if lines is None: continue # Use the label only for the first item. For the remaining # items, use an empty label. labels_ = chain([label], itertools.repeat("")) for label_, line in zip(labels_, lines): print("%*s : %s" % (width, label_, line)) print()
def end(self, payload, status, err_msg): start = now = time() text = unicode(payload) size = int(payload.download_size) done = 0 # update state if status == dnf.callback.STATUS_MIRROR: pass elif status == dnf.callback.STATUS_DRPM: self.done_drpm += 1 elif text in self.state: start, done = self.state.pop(text) self.active.remove(text) size -= done self.done_files += 1 self.done_size += size elif status == dnf.callback.STATUS_ALREADY_EXISTS: self.done_files += 1 self.done_size += size if status: # the error message, no trimming if status is dnf.callback.STATUS_DRPM and self.total_drpm > 1: msg = '[%s %d/%d] %s: ' % (self.STATUS_2_STR[status], self.done_drpm, self.total_drpm, text) else: msg = '[%s] %s: ' % (self.STATUS_2_STR[status], text) left = _term_width() - len(msg) - 1 msg = '%s%-*s\n' % (msg, left, err_msg) else: if self.total_files > 1: text = '(%d/%d): %s' % (self.done_files, self.total_files, text) # average rate, file size, download time tm = max(now - start, 0.001) msg = ' %5sB/s | %5sB %9s \n' % ( format_number(float(done) / tm), format_number(done), format_time(tm)) left = _term_width() - len(msg) msg = '%-*.*s%s' % (left, left, text, msg) self.message(msg) # now there's a blank line. fill it if possible. if self.active: self._update(now)
def _info(self, apkg_adv_insts): """Make detailed information about advisories.""" arches = self.base.sack.list_arches() # Get mapping from title to [title, ID, type, time, BZs, CVEs, # description, rights, files, installed]. This way we get rid of # unneeded advisory packages given with the advisories and we remove # duplicate advisories (that SPEEDS UP the information extraction # because the advisory attribute getters are expensive, so we won't get # the attributes multiple times). We cannot use a set because # advisories are not hashable. verbose = self.base.conf.verbose bytitle = dict() # mapping from title to list of identities for apkg, advisory, installed in apkg_adv_insts: title = advisory.title.lower() try: advlist = bytitle[title] except KeyError: advlist = [ advisory.title, advisory.id, self.TYPE2LABEL.get(advisory.type, _('unknown')), unicode(advisory.updated), set((ref.type, ref.id, ref.title) for ref in advisory.references), [], advisory.description, advisory.severity, advisory.rights if verbose else None, set(pkg.filename for pkg in advisory.packages if pkg.arch in arches) if verbose else None, installed ] bytitle[title] = advlist else: # References and files are merged. advlist[4].update( set((ref.type, ref.id, ref.title) for ref in advisory.references)) if verbose: advlist[9].update( set(pkg.filename for pkg in advisory.packages if pkg.arch in arches)) # If the stored advisory is marked as not installed and the # current is marked as installed, mark the stored as installed. advlist[10] = advlist[10] or installed for title in sorted(bytitle.keys()): yield bytitle[title]
def display_summary(cls, apkg_adv_insts, mixed, description): """Display the summary of advisories.""" typ2cnt = cls._summary(apkg_adv_insts) if not typ2cnt: return print(_('Updates Information Summary: ') + description) # Convert types to strings and order the entries. label_counts = [ (_('Security notice(s)'), typ2cnt[hawkey.ADVISORY_SECURITY]), (_('Bugfix notice(s)'), typ2cnt[hawkey.ADVISORY_BUGFIX]), (_('Enhancement notice(s)'), typ2cnt[hawkey.ADVISORY_ENHANCEMENT]), (_('other notice(s)'), typ2cnt[hawkey.ADVISORY_UNKNOWN])] # Convert counts to strings and skip missing types. label2value = OrderedDict( (label, unicode(count)) for label, count in label_counts if count) width = _maxlen(label2value.values()) for label, value in label2value.items(): print(' %*s %s' % (width, value, label))
def get(self, *patterns): res = dnf.util.Bunch() res.environments = [] res.groups = [] for pat in patterns: envs = grps = None if self.kinds & self.ENVIRONMENTS: envs = self._get(self.comps.environments_by_pattern(pat), self.prst.environment) res.environments.extend(envs) if self.kinds & self.GROUPS: grps = self._get(self.comps.groups_by_pattern(pat), self.prst.group) res.groups.extend(grps) if not envs and not grps: msg = _("No relevant match for the specified '%s'.") msg = msg % unicode(pat) raise dnf.cli.CliError(msg) return res
def progress(self, payload, done): now = time() text = unicode(payload) total = int(payload.download_size) done = int(done) # update done_size if text not in self.state: self.state[text] = now, 0 self.active.append(text) start, old = self.state[text] self.state[text] = start, done self.done_size += done - old # update screen if enough time has elapsed if now - self.last_time > self.update_period: if total > self.total_size: self.total_size = total self._update(now)
def advisory2info(advisory, installed): attributes = [[advisory.id], [self.TYPE2LABEL.get(advisory.type, _('unknown'))], [unicode(advisory.updated)], [], [], (advisory.description or '').splitlines(), [advisory.severity], (advisory.rights or '').splitlines(), sorted( set(pkg.filename for pkg in advisory.packages if pkg.arch in arches)), None] for ref in advisory.references: if ref.type == hawkey.REFERENCE_BUGZILLA: attributes[3].append('{} - {}'.format( ref.id, ref.title or '')) elif ref.type == hawkey.REFERENCE_CVE: attributes[4].append(ref.id) attributes[3].sort() attributes[4].sort() if not verbose: attributes[7] = None attributes[8] = None if mixed: attributes[9] = [_('true') if installed else _('false')] width = _maxlen(labels) lines = [] lines.append('=' * 79) lines.append(' ' + advisory.title) lines.append('=' * 79) for label, atr_lines in zip(labels, attributes): if atr_lines in (None, [None]): continue for i, line in enumerate(atr_lines): key = label if i == 0 else '' key_padding = width - exact_width(label) lines.append('%*s%s: %s' % (key_padding, "", key, line)) return '\n'.join(lines)
def advisory2info(advisory, installed): attributes = [ [advisory.id], [self.TYPE2LABEL.get(advisory.type, _('unknown'))], [unicode(advisory.updated)], [], [], (advisory.description or '').splitlines(), [advisory.severity], (advisory.rights or '').splitlines(), sorted(set(pkg.filename for pkg in advisory.packages if pkg.arch in arches)), None] for ref in advisory.references: if ref.type == hawkey.REFERENCE_BUGZILLA: attributes[3].append('{} - {}'.format(ref.id, ref.title or '')) elif ref.type == hawkey.REFERENCE_CVE: attributes[4].append(ref.id) attributes[3].sort() attributes[4].sort() if not verbose: attributes[7] = None attributes[8] = None if mixed: attributes[9] = [_('true') if installed else _('false')] width = _maxlen(labels) lines = [] lines.append('=' * 79) lines.append(' ' + advisory.title) lines.append('=' * 79) for label, atr_lines in zip(labels, attributes): if atr_lines in (None, [None]): continue for i, line in enumerate(atr_lines): lines.append('%*s: %s' % (width, label if i == 0 else '', line)) return '\n'.join(lines)
def exception2msg(e): """Convert an exception to a message. This function will convert the exception using to_unicode, unicode, or str, whichever works correctly. deprecated, this function is not conceptual. :param e: an exception :return: a string representation of the exception """ try: return to_unicode(e.value) except: pass try: return unicode(e) except: pass try: return to_unicode(str(e)) except: pass return "<exception failed to convert to text>"
def __init__(self, value=None): Exception.__init__(self) self.value = unicode(value)
def ex_IOError(e): logger.log(dnf.logging.SUBDEBUG, '', exc_info=True) logger.critical(unicode(e)) return 1
def ex_Error(e): if e.value is not None: logger.critical(_('Error: %s'), unicode(e)) return 1
def __unicode__(self): return unicode(str(self))
def configure(self, args): """Parse command line arguments, and set up :attr:`self.base.conf` and :attr:`self.cmds`, as well as logger objects in base instance. :param args: a list of command line arguments """ self.optparser = dnf.cli.option_parser.OptionParser() opts, cmds = self.optparser.parse_known_args(args) # Just print out the version if that's what the user wanted if opts.version: print(dnf.const.VERSION) opts.quiet = True opts.verbose = False # go through all the setopts and set the global ones bad_setopt_tm, bad_setopt_ne = self._parse_setopts(opts.setopts) if self.main_setopts: for opt in self.main_setopts.items: setattr(opts, opt, getattr(self.main_setopts, opt)) # get the install root to use self.optparser._checkAbsInstallRoot(opts.installroot) (root, opts.conffile) = self._root_and_conffile(opts.installroot, opts.conffile) # the conffile is solid now assert(opts.conffile is not None) if opts.quiet: opts.debuglevel = 0 if opts.verbose: opts.debuglevel = opts.errorlevel = dnf.const.VERBOSE_LEVEL # Read up configuration options and initialize plugins overrides = self.optparser._non_nones2dict(self._get_first_config(opts)) releasever = opts.releasever try: self.read_conf_file(opts.conffile, root, releasever, overrides) # now set all the non-first-start opts from main from our setopts if self.main_setopts: for opt in self.main_setopts.items: if not hasattr(self.base.conf, opt): msg ="Main config did not have a %s attr. before setopt" self.logger.warning(msg % opt) setattr(self.base.conf, opt, getattr(self.main_setopts, opt)) except (dnf.exceptions.ConfigError, ValueError) as e: self.logger.critical(_('Config error: %s'), e) sys.exit(1) except IOError as e: e = '%s: %s' % (unicode(e.args[1]), repr(e.filename)) self.logger.critical(_('Config error: %s'), e) sys.exit(1) for item in bad_setopt_tm: msg = "Setopt argument has multiple values: %s" self.logger.warning(msg % item) for item in bad_setopt_ne: msg = "Setopt argument has no value: %s" self.logger.warning(msg % item) self.optparser.configure_from_options(opts, self.base.conf, self.demands, self.base.output) self.base.cmds = cmds if opts.version: opts.quiet = True opts.verbose = False if opts.quiet: opts.debuglevel = 0 if opts.verbose: opts.debuglevel = opts.errorlevel = dnf.const.VERBOSE_LEVEL self.nogpgcheck = opts.nogpgcheck # the configuration reading phase is now concluded, finish the init self._configure_cachedir() # with cachedir in place we can configure stuff depending on it: self.base.activate_persistor() self._configure_repos(opts) if opts.version: print_versions(self.base.conf.history_record_packages, self.base, self.base.output) sys.exit(0) if opts.sleeptime is not None: sleeptime = random.randrange(opts.sleeptime*60) else: sleeptime = 0 # store the main commands & summaries, before plugins are loaded self.optparser.add_commands(self.cli_commands, 'main') if self.base.conf.plugins: self.base.plugins.load(self.base.conf.pluginpath, opts.disableplugins) self.base.plugins.run_init(self.base, self) # store the plugin commands & summaries self.optparser.add_commands(self.cli_commands,'plugin') # build the usage info and put it into the optparser. self.optparser.usage = self.optparser.get_usage() # show help if the user requests it # this is done here, because we first have the full # usage info after the plugins are loaded. if opts.help: self.optparser.print_help() sys.exit(0) # save our original args out self.base.args = args # save out as a nice command string self.cmdstring = dnf.const.PROGRAM_NAME + ' ' for arg in self.base.args: self.cmdstring += '%s ' % arg try: self._parse_commands() # before we return check over the base command # + args make sure they match/make sense except CliError: sys.exit(1) self.command.configure(self.base.extcmds) if opts.debugrepodata: self.write_out_metadata() if opts.debugsolver: self.base.conf.debug_solver = True self.base.plugins.run_config() # run the sleep - if it's unchanged then it won't matter time.sleep(sleeptime)