asda?‰PNG  IHDR ? f ??C1 sRGB ??é gAMA ±? üa pHYs ? ??o¨d GIDATx^íüL”÷e÷Y?a?("Bh?_ò???¢§?q5k?*:t0A-o??¥]VkJ¢M??f?±8\k2íll£1]q?ù???T demand.py000064400000004747151030066770006367 0ustar00# demand.py # Demand sheet and related classes. # # Copyright (C) 2014-2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import unicode_literals class _BoolDefault(object): def __init__(self, default): self.default = default self._storing_name = '__%s%x' % (self.__class__.__name__, id(self)) def __get__(self, obj, objtype=None): objdict = obj.__dict__ if self._storing_name in objdict: return objdict[self._storing_name] return self.default def __set__(self, obj, val): objdict = obj.__dict__ if self._storing_name in objdict: current_val = objdict[self._storing_name] if current_val != val: raise AttributeError('Demand already set.') objdict[self._storing_name] = val class DemandSheet(object): """Collection of demands that different CLI parts have on other parts. :api""" # :api... allow_erasing = _BoolDefault(False) available_repos = _BoolDefault(False) resolving = _BoolDefault(False) root_user = _BoolDefault(False) sack_activation = _BoolDefault(False) load_system_repo = _BoolDefault(True) success_exit_status = 0 cacheonly = _BoolDefault(False) fresh_metadata = _BoolDefault(True) freshest_metadata = _BoolDefault(False) changelogs = _BoolDefault(False) transaction_display = None # This demand controlls applicability of the plugins that could filter # repositories packages (e.g. versionlock). # If it stays None, the demands.resolving is used as a fallback. plugin_filtering_enabled = _BoolDefault(None) aliases.py000064400000015735151030066770006557 0ustar00# aliases.py # Resolving aliases in CLI arguments. # # Copyright (C) 2018 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.i18n import _ import collections import dnf.cli from dnf.conf.config import PRIO_DEFAULT import dnf.exceptions import libdnf.conf import logging import os import os.path logger = logging.getLogger('dnf') ALIASES_DROPIN_DIR = '/etc/dnf/aliases.d/' ALIASES_CONF_PATH = os.path.join(ALIASES_DROPIN_DIR, 'ALIASES.conf') ALIASES_USER_PATH = os.path.join(ALIASES_DROPIN_DIR, 'USER.conf') class AliasesConfig(object): def __init__(self, path): self._path = path self._parser = libdnf.conf.ConfigParser() self._parser.read(self._path) @property def enabled(self): option = libdnf.conf.OptionBool(True) try: option.set(PRIO_DEFAULT, self._parser.getData()["main"]["enabled"]) except IndexError: pass return option.getValue() @property def aliases(self): result = collections.OrderedDict() section = "aliases" if not self._parser.hasSection(section): return result for key in self._parser.options(section): value = self._parser.getValue(section, key) if not value: continue result[key] = value.split() return result class Aliases(object): def __init__(self): self.aliases = collections.OrderedDict() self.conf = None self.enabled = True if self._disabled_by_environ(): self.enabled = False return self._load_main() if not self.enabled: return self._load_aliases() def _disabled_by_environ(self): option = libdnf.conf.OptionBool(True) try: option.set(PRIO_DEFAULT, os.environ['DNF_DISABLE_ALIASES']) return option.getValue() except KeyError: return False except RuntimeError: logger.warning( _('Unexpected value of environment variable: ' 'DNF_DISABLE_ALIASES=%s'), os.environ['DNF_DISABLE_ALIASES']) return True def _load_conf(self, path): try: return AliasesConfig(path) except RuntimeError as e: raise dnf.exceptions.ConfigError( _('Parsing file "%s" failed: %s') % (path, e)) except IOError as e: raise dnf.exceptions.ConfigError( _('Cannot read file "%s": %s') % (path, e)) def _load_main(self): try: self.conf = self._load_conf(ALIASES_CONF_PATH) self.enabled = self.conf.enabled except dnf.exceptions.ConfigError as e: logger.debug(_('Config error: %s'), e) def _load_aliases(self, filenames=None): if filenames is None: try: filenames = self._dropin_dir_filenames() except dnf.exceptions.ConfigError: return for filename in filenames: try: conf = self._load_conf(filename) if conf.enabled: self.aliases.update(conf.aliases) except dnf.exceptions.ConfigError as e: logger.warning(_('Config error: %s'), e) def _dropin_dir_filenames(self): # Get default aliases config filenames: # all files from ALIASES_DROPIN_DIR, # and ALIASES_USER_PATH as the last one (-> override all others) ignored_filenames = [os.path.basename(ALIASES_CONF_PATH), os.path.basename(ALIASES_USER_PATH)] def _ignore_filename(filename): return filename in ignored_filenames or\ filename.startswith('.') or\ not filename.endswith(('.conf', '.CONF')) filenames = [] try: if not os.path.exists(ALIASES_DROPIN_DIR): os.mkdir(ALIASES_DROPIN_DIR) for fn in sorted(os.listdir(ALIASES_DROPIN_DIR)): if _ignore_filename(fn): continue filenames.append(os.path.join(ALIASES_DROPIN_DIR, fn)) except (IOError, OSError) as e: raise dnf.exceptions.ConfigError(e) if os.path.exists(ALIASES_USER_PATH): filenames.append(ALIASES_USER_PATH) return filenames def _resolve(self, args): stack = [] self.prefix_options = [] def store_prefix(args): num = 0 for arg in args: if arg and arg[0] != '-': break num += 1 self.prefix_options += args[:num] return args[num:] def subresolve(args): suffix = store_prefix(args) if (not suffix or # Current alias on stack is resolved suffix[0] not in self.aliases or # End resolving suffix[0].startswith('\\')): # End resolving try: stack.pop() # strip the '\' if it exists if suffix[0].startswith('\\'): suffix[0] = suffix[0][1:] except IndexError: pass return suffix if suffix[0] in stack: # Infinite recursion detected raise dnf.exceptions.Error( _('Aliases contain infinite recursion')) # Next word must be an alias stack.append(suffix[0]) current_alias_result = subresolve(self.aliases[suffix[0]]) if current_alias_result: # We reached non-alias or '\' return current_alias_result + suffix[1:] else: # Need to resolve aliases in the rest return subresolve(suffix[1:]) suffix = subresolve(args) return self.prefix_options + suffix def resolve(self, args): if self.enabled: try: args = self._resolve(args) except dnf.exceptions.Error as e: logger.error(_('%s, using original arguments.'), e) return args term.py000064400000034546151030066770006106 0ustar00# Copyright (C) 2013-2014 Red Hat, Inc. # Terminal routines. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals import curses import dnf.pycomp import fcntl import re import struct import sys import termios def _real_term_width(fd=1): """ Get the real terminal width """ try: buf = 'abcdefgh' buf = fcntl.ioctl(fd, termios.TIOCGWINSZ, buf) ret = struct.unpack(b'hhhh', buf)[1] return ret except IOError: return None def _term_width(fd=1): """ Compute terminal width falling to default 80 in case of trouble""" tw = _real_term_width(fd=1) if not tw: return 80 elif tw < 20: return 20 else: return tw class Term(object): """A class to provide some terminal "UI" helpers based on curses.""" # From initial search for "terminfo and python" got: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 # ...it's probably not copyrightable, but if so ASPN says: # # Except where otherwise noted, recipes in the Python Cookbook are # published under the Python license. __enabled = True real_columns = property(lambda self: _real_term_width()) columns = property(lambda self: _term_width()) __cap_names = { 'underline' : 'smul', 'reverse' : 'rev', 'normal' : 'sgr0', } __colors = { 'black' : 0, 'blue' : 1, 'green' : 2, 'cyan' : 3, 'red' : 4, 'magenta' : 5, 'yellow' : 6, 'white' : 7 } __ansi_colors = { 'black' : 0, 'red' : 1, 'green' : 2, 'yellow' : 3, 'blue' : 4, 'magenta' : 5, 'cyan' : 6, 'white' : 7 } __ansi_forced_MODE = { 'bold' : '\x1b[1m', 'blink' : '\x1b[5m', 'dim' : '', 'reverse' : '\x1b[7m', 'underline' : '\x1b[4m', 'normal' : '\x1b(B\x1b[m' } __ansi_forced_FG_COLOR = { 'black' : '\x1b[30m', 'red' : '\x1b[31m', 'green' : '\x1b[32m', 'yellow' : '\x1b[33m', 'blue' : '\x1b[34m', 'magenta' : '\x1b[35m', 'cyan' : '\x1b[36m', 'white' : '\x1b[37m' } __ansi_forced_BG_COLOR = { 'black' : '\x1b[40m', 'red' : '\x1b[41m', 'green' : '\x1b[42m', 'yellow' : '\x1b[43m', 'blue' : '\x1b[44m', 'magenta' : '\x1b[45m', 'cyan' : '\x1b[46m', 'white' : '\x1b[47m' } def __forced_init(self): self.MODE = self.__ansi_forced_MODE self.FG_COLOR = self.__ansi_forced_FG_COLOR self.BG_COLOR = self.__ansi_forced_BG_COLOR def reinit(self, term_stream=None, color='auto'): """Reinitializes the :class:`Term`. :param term_stream: the terminal stream that the :class:`Term` should be initialized to use. If *term_stream* is not given, :attr:`sys.stdout` is used. :param color: when to colorize output. Valid values are 'always', 'auto', and 'never'. 'always' will use ANSI codes to always colorize output, 'auto' will decide whether do colorize depending on the terminal, and 'never' will never colorize. """ self.__enabled = True self.lines = 24 if color == 'always': self.__forced_init() return # Output modes: self.MODE = { 'bold' : '', 'blink' : '', 'dim' : '', 'reverse' : '', 'underline' : '', 'normal' : '' } # Colours self.FG_COLOR = { 'black' : '', 'blue' : '', 'green' : '', 'cyan' : '', 'red' : '', 'magenta' : '', 'yellow' : '', 'white' : '' } self.BG_COLOR = { 'black' : '', 'blue' : '', 'green' : '', 'cyan' : '', 'red' : '', 'magenta' : '', 'yellow' : '', 'white' : '' } if color == 'never': self.__enabled = False return assert color == 'auto' # If the stream isn't a tty, then assume it has no capabilities. if not term_stream: term_stream = sys.stdout if not term_stream.isatty(): self.__enabled = False return # Check the terminal type. If we fail, then assume that the # terminal has no capabilities. try: curses.setupterm(fd=term_stream.fileno()) except Exception: self.__enabled = False return self._ctigetstr = curses.tigetstr self.lines = curses.tigetnum('lines') # Look up string capabilities. for cap_name in self.MODE: mode = cap_name if cap_name in self.__cap_names: cap_name = self.__cap_names[cap_name] self.MODE[mode] = self._tigetstr(cap_name) # Colors set_fg = self._tigetstr('setf').encode('utf-8') if set_fg: for (color, val) in self.__colors.items(): self.FG_COLOR[color] = curses.tparm(set_fg, val).decode() or '' set_fg_ansi = self._tigetstr('setaf').encode('utf-8') if set_fg_ansi: for (color, val) in self.__ansi_colors.items(): fg_color = curses.tparm(set_fg_ansi, val).decode() or '' self.FG_COLOR[color] = fg_color set_bg = self._tigetstr('setb').encode('utf-8') if set_bg: for (color, val) in self.__colors.items(): self.BG_COLOR[color] = curses.tparm(set_bg, val).decode() or '' set_bg_ansi = self._tigetstr('setab').encode('utf-8') if set_bg_ansi: for (color, val) in self.__ansi_colors.items(): bg_color = curses.tparm(set_bg_ansi, val).decode() or '' self.BG_COLOR[color] = bg_color def __init__(self, term_stream=None, color='auto'): self.reinit(term_stream, color) def _tigetstr(self, cap_name): # String capabilities can include "delays" of the form "$<2>". # For any modern terminal, we should be able to just ignore # these, so strip them out. cap = self._ctigetstr(cap_name) or '' if dnf.pycomp.is_py3bytes(cap): cap = cap.decode() return re.sub(r'\$<\d+>[/*]?', '', cap) def color(self, color, s): """Colorize string with color""" return (self.MODE[color] + str(s) + self.MODE['normal']) def bold(self, s): """Make string bold.""" return self.color('bold', s) def sub(self, haystack, beg, end, needles, escape=None, ignore_case=False): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with *end*, then return the modified string. For example:: >>> yt = Term() >>> yt.sub('spam and eggs', 'x', 'z', ['and']) 'spam xandz eggs' This is particularly useful for emphasizing certain words in output: for example, calling :func:`sub` with *beg* = MODE['bold'] and *end* = MODE['normal'] will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. Note, however, that the :func:`sub_mode`, :func:`sub_bold`, :func:`sub_fg`, and :func:`sub_bg` methods provide convenient ways to access this same emphasizing functionality. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :param escape: a function that accepts a string and returns the same string with problematic characters escaped. By default, :func:`re.escape` is used. :param ignore_case: whether case should be ignored when searching for matches :return: *haystack* with *beg* prefixing, and *end* postfixing, occurrences of the strings in *needles* """ if not self.__enabled: return haystack if not escape: escape = re.escape render = lambda match: beg + match.group() + end for needle in needles: pat = escape(needle) if ignore_case: pat = re.template(pat, re.I) haystack = re.sub(pat, render, haystack) return haystack def sub_norm(self, haystack, beg, needles, **kwds): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with self.MODE['normal'], then return the modified string. If *beg* is an ANSI escape code, such as given by self.MODE['bold'], this method will return *haystack* with the formatting given by the code only applied to the strings in *needles*. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with *beg* prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* """ return self.sub(haystack, beg, self.MODE['normal'], needles, **kwds) def sub_mode(self, haystack, mode, needles, **kwds): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE[*mode*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given *mode*. :param haystack: the string to be modified :param mode: the mode to set the matches to be in. Valid values are given by self.MODE.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE[*mode*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* """ return self.sub_norm(haystack, self.MODE[mode], needles, **kwds) def sub_bold(self, haystack, needles, **kwds): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE['bold'], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. :param haystack: the string to be modified :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE['bold'] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* """ return self.sub_mode(haystack, 'bold', needles, **kwds) def sub_fg(self, haystack, color, needles, **kwds): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.FG_COLOR[*color*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given color. :param haystack: the string to be modified :param color: the color to set the matches to be in. Valid values are given by self.FG_COLOR.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.FG_COLOR[*color*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* """ return self.sub_norm(haystack, self.FG_COLOR[color], needles, **kwds) def sub_bg(self, haystack, color, needles, **kwds): """Search the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.BG_COLOR[*color*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* highlighted in the given background color. :param haystack: the string to be modified :param color: the background color to set the matches to be in. Valid values are given by self.BG_COLOR.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.BG_COLOR[*color*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* """ return self.sub_norm(haystack, self.BG_COLOR[color], needles, **kwds) progress.py000064400000016671151030066770007002 0ustar00# Copyright (C) 2013-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. from __future__ import unicode_literals from dnf.cli.format import format_number, format_time from dnf.cli.term import _term_width from dnf.pycomp import unicode from time import time import sys import dnf.callback import dnf.util class MultiFileProgressMeter(dnf.callback.DownloadProgress): """Multi-file download progress meter""" STATUS_2_STR = { dnf.callback.STATUS_FAILED: 'FAILED', dnf.callback.STATUS_ALREADY_EXISTS: 'SKIPPED', dnf.callback.STATUS_MIRROR: 'MIRROR', dnf.callback.STATUS_DRPM: 'DRPM', } def __init__(self, fo=sys.stderr, update_period=0.3, tick_period=1.0, rate_average=5.0): """Creates a new progress meter instance update_period -- how often to update the progress bar tick_period -- how fast to cycle through concurrent downloads rate_average -- time constant for average speed calculation """ self.fo = fo self.update_period = update_period self.tick_period = tick_period self.rate_average = rate_average self.unknown_progres = 0 self.total_drpm = 0 self.isatty = sys.stdout.isatty() self.done_drpm = 0 self.done_files = 0 self.done_size = 0 self.active = [] self.state = {} self.last_time = 0 self.last_size = 0 self.rate = None self.total_files = 0 self.total_size = 0 def message(self, msg): dnf.util._terminal_messenger('write_flush', msg, self.fo) def start(self, total_files, total_size, total_drpms=0): self.total_files = total_files self.total_size = total_size self.total_drpm = total_drpms # download state self.done_drpm = 0 self.done_files = 0 self.done_size = 0 self.active = [] self.state = {} # rate averaging self.last_time = 0 self.last_size = 0 self.rate = None 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 _update(self, now): if self.last_time: delta_time = now - self.last_time delta_size = self.done_size - self.last_size if delta_time > 0 and delta_size > 0: # update the average rate rate = delta_size / delta_time if self.rate is not None: weight = min(delta_time/self.rate_average, 1) rate = rate*weight + self.rate*(1 - weight) self.rate = rate self.last_time = now self.last_size = self.done_size if not self.isatty: return # pick one of the active downloads text = self.active[int(now/self.tick_period) % len(self.active)] if self.total_files > 1: n = '%d' % (self.done_files + 1) if len(self.active) > 1: n += '-%d' % (self.done_files + len(self.active)) text = '(%s/%d): %s' % (n, self.total_files, text) # average rate, total done size, estimated remaining time if self.rate and self.total_size: time_eta = format_time((self.total_size - self.done_size) / self.rate) else: time_eta = '--:--' msg = ' %5sB/s | %5sB %9s ETA\r' % ( format_number(self.rate) if self.rate else '--- ', format_number(self.done_size), time_eta) left = _term_width() - len(msg) bl = (left - 7)//2 if bl > 8: # use part of the remaining space for progress bar if self.total_size: pct = self.done_size * 100 // self.total_size n, p = divmod(self.done_size * bl * 2 // self.total_size, 2) bar = '=' * n + '-' * p msg = '%3d%% [%-*s]%s' % (pct, bl, bar, msg) left -= bl + 7 else: n = self.unknown_progres - 3 p = 3 n = 0 if n < 0 else n bar = ' ' * n + '=' * p msg = ' [%-*s]%s' % (bl, bar, msg) left -= bl + 7 self.unknown_progres = self.unknown_progres + 3 if self.unknown_progres + 3 < bl \ else 0 self.message('%-*.*s%s' % (left, left, text, msg)) 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) cli.py000064400000126261151030066770005702 0ustar00# Copyright 2005 Duke University # Copyright (C) 2012-2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Written by Seth Vidal """ Command line interface yum class and related. """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals try: from collections.abc import Sequence except ImportError: from collections import Sequence import datetime import logging import operator import os import random import rpm import sys import time import hawkey import libdnf.transaction from . import output from dnf.cli import CliError from dnf.i18n import ucd, _ import dnf import dnf.cli.aliases import dnf.cli.commands import dnf.cli.commands.alias import dnf.cli.commands.autoremove import dnf.cli.commands.check import dnf.cli.commands.clean import dnf.cli.commands.deplist import dnf.cli.commands.distrosync import dnf.cli.commands.downgrade import dnf.cli.commands.group import dnf.cli.commands.history import dnf.cli.commands.install import dnf.cli.commands.makecache import dnf.cli.commands.mark import dnf.cli.commands.module import dnf.cli.commands.reinstall import dnf.cli.commands.remove import dnf.cli.commands.repolist import dnf.cli.commands.repoquery import dnf.cli.commands.search import dnf.cli.commands.shell import dnf.cli.commands.swap import dnf.cli.commands.updateinfo import dnf.cli.commands.upgrade import dnf.cli.commands.upgrademinimal import dnf.cli.demand import dnf.cli.format import dnf.cli.option_parser import dnf.conf import dnf.conf.substitutions import dnf.const import dnf.db.history import dnf.exceptions import dnf.logging import dnf.persistor import dnf.plugin import dnf.rpm import dnf.sack import dnf.transaction import dnf.util import dnf.yum.misc logger = logging.getLogger('dnf') def _add_pkg_simple_list_lens(data, pkg, indent=''): """ Get the length of each pkg's column. Add that to data. This "knows" about simpleList and printVer. """ na = len(pkg.name) + 1 + len(pkg.arch) + len(indent) ver = len(pkg.evr) rid = len(pkg._from_repo) for (d, v) in (('na', na), ('ver', ver), ('rid', rid)): data[d].setdefault(v, 0) data[d][v] += 1 def _list_cmd_calc_columns(output, ypl): """ Work out the dynamic size of the columns to pass to fmtColumns. """ data = {'na' : {}, 'ver' : {}, 'rid' : {}} for lst in (ypl.installed, ypl.available, ypl.extras, ypl.autoremove, ypl.updates, ypl.recent): for pkg in lst: _add_pkg_simple_list_lens(data, pkg) if len(ypl.obsoletes) > 0: for (npkg, opkg) in ypl.obsoletesTuples: _add_pkg_simple_list_lens(data, npkg) _add_pkg_simple_list_lens(data, opkg, indent=" " * 4) data = [data['na'], data['ver'], data['rid']] columns = output.calcColumns(data, remainder_column=1) return (-columns[0], -columns[1], -columns[2]) def print_versions(pkgs, base, output): def sm_ui_time(x): return time.strftime("%c", time.gmtime(x)) rpmdb_sack = dnf.sack.rpmdb_sack(base) done = False for pkg in rpmdb_sack.query().installed().filterm(name=pkgs): if done: print("") done = True if pkg.epoch == '0': ver = '%s-%s.%s' % (pkg.version, pkg.release, pkg.arch) else: ver = '%s:%s-%s.%s' % (pkg.epoch, pkg.version, pkg.release, pkg.arch) name = output.term.bold(pkg.name) print(_(" Installed: %s-%s at %s") %(name, ver, sm_ui_time(pkg.installtime))) print(_(" Built : %s at %s") % (pkg.packager if pkg.packager else "", sm_ui_time(pkg.buildtime))) # :hawkey, no changelist information yet # print(_(" Committed: %s at %s") % (pkg.committer, # sm_ui_date(pkg.committime))) def report_module_switch(switchedModules): msg1 = _("The operation would result in switching of module '{0}' stream '{1}' to " "stream '{2}'") for moduleName, streams in switchedModules.items(): logger.warning(msg1.format(moduleName, streams[0], streams[1])) class BaseCli(dnf.Base): """This is the base class for yum cli.""" def __init__(self, conf=None): conf = conf or dnf.conf.Conf() super(BaseCli, self).__init__(conf=conf) self.output = output.Output(self, self.conf) def do_transaction(self, display=()): """Take care of package downloading, checking, user confirmation and actually running the transaction. :param display: `rpm.callback.TransactionProgress` object(s) :return: history database transaction ID or None """ if dnf.base.WITH_MODULES: if not self.conf.module_stream_switch: switchedModules = dict(self._moduleContainer.getSwitchedStreams()) if switchedModules: report_module_switch(switchedModules) msg = _("It is not possible to switch enabled streams of a module unless explicitly " "enabled via configuration option module_stream_switch.\n" "It is recommended to rather remove all installed content from the module, and " "reset the module using '{prog} module reset ' command. After " "you reset the module, you can install the other stream.").format( prog=dnf.util.MAIN_PROG) raise dnf.exceptions.Error(msg) trans = self.transaction pkg_str = self.output.list_transaction(trans) if pkg_str: logger.info(pkg_str) if trans: # Check which packages have to be downloaded install_pkgs = [] rmpkgs = [] install_only = True for tsi in trans: if tsi.action in dnf.transaction.FORWARD_ACTIONS: install_pkgs.append(tsi.pkg) elif tsi.action in dnf.transaction.BACKWARD_ACTIONS: install_only = False rmpkgs.append(tsi.pkg) # Close the connection to the rpmdb so that rpm doesn't hold the # SIGINT handler during the downloads. del self._ts # report the total download size to the user if not install_pkgs: self.output.reportRemoveSize(rmpkgs) else: self.output.reportDownloadSize(install_pkgs, install_only) if trans or self._moduleContainer.isChanged() or \ (self._history and (self._history.group or self._history.env)): # confirm with user if self.conf.downloadonly: logger.info(_("{prog} will only download packages for the transaction.").format( prog=dnf.util.MAIN_PROG_UPPER)) elif 'test' in self.conf.tsflags: logger.info(_("{prog} will only download packages, install gpg keys, and check the " "transaction.").format(prog=dnf.util.MAIN_PROG_UPPER)) if self._promptWanted(): if self.conf.assumeno or not self.output.userconfirm(): raise CliError(_("Operation aborted.")) else: logger.info(_('Nothing to do.')) return if trans: if install_pkgs: logger.info(_('Downloading Packages:')) try: total_cb = self.output.download_callback_total_cb self.download_packages(install_pkgs, self.output.progress, total_cb) except dnf.exceptions.DownloadError as e: specific = dnf.cli.format.indent_block(ucd(e)) errstr = _('Error downloading packages:') + '\n%s' % specific # setting the new line to prevent next chars being eaten up # by carriage returns print() raise dnf.exceptions.Error(errstr) # Check GPG signatures self.gpgsigcheck(install_pkgs) if self.conf.downloadonly: return if not isinstance(display, Sequence): display = [display] display = [output.CliTransactionDisplay()] + list(display) tid = super(BaseCli, self).do_transaction(display) # display last transaction (which was closed during do_transaction()) if tid is not None: trans = self.history.old([tid])[0] trans = dnf.db.group.RPMTransaction(self.history, trans._trans) else: trans = None if trans: # the post transaction summary is already written to log during # Base.do_transaction() so here only print the messages to the # user arranged in columns print() print('\n'.join(self.output.post_transaction_output(trans))) print() for tsi in trans: if tsi.state == libdnf.transaction.TransactionItemState_ERROR: raise dnf.exceptions.Error(_('Transaction failed')) return tid def gpgsigcheck(self, pkgs): """Perform GPG signature verification on the given packages, installing keys if possible. :param pkgs: a list of package objects to verify the GPG signatures of :raises: Will raise :class:`Error` if there's a problem """ error_messages = [] for po in pkgs: result, errmsg = self._sig_check_pkg(po) if result == 0: # Verified ok, or verify not req'd continue elif result == 1: ay = self.conf.assumeyes and not self.conf.assumeno if (not sys.stdin or not sys.stdin.isatty()) and not ay: raise dnf.exceptions.Error(_('Refusing to automatically import keys when running ' \ 'unattended.\nUse "-y" to override.')) # the callback here expects to be able to take options which # userconfirm really doesn't... so fake it fn = lambda x, y, z: self.output.userconfirm() try: self._get_key_for_package(po, fn) except (dnf.exceptions.Error, ValueError) as e: error_messages.append(str(e)) else: # Fatal error error_messages.append(errmsg) if error_messages: for msg in error_messages: logger.critical(msg) raise dnf.exceptions.Error(_("GPG check FAILED")) def latest_changelogs(self, package): """Return list of changelogs for package newer then installed version""" newest = None # find the date of the newest changelog for installed version of package # stored in rpmdb for mi in self._rpmconn.readonly_ts.dbMatch('name', package.name): changelogtimes = mi[rpm.RPMTAG_CHANGELOGTIME] if changelogtimes: newest = datetime.date.fromtimestamp(changelogtimes[0]) break chlogs = [chlog for chlog in package.changelogs if newest is None or chlog['timestamp'] > newest] return chlogs def format_changelog(self, changelog): """Return changelog formatted as in spec file""" chlog_str = '* %s %s\n%s\n' % ( changelog['timestamp'].strftime("%a %b %d %X %Y"), dnf.i18n.ucd(changelog['author']), dnf.i18n.ucd(changelog['text'])) return chlog_str def print_changelogs(self, packages): # group packages by src.rpm to avoid showing duplicate changelogs bysrpm = dict() for p in packages: # there are packages without source_name, use name then. bysrpm.setdefault(p.source_name or p.name, []).append(p) for source_name in sorted(bysrpm.keys()): bin_packages = bysrpm[source_name] print(_("Changelogs for {}").format(', '.join([str(pkg) for pkg in bin_packages]))) for chl in self.latest_changelogs(bin_packages[0]): print(self.format_changelog(chl)) def check_updates(self, patterns=(), reponame=None, print_=True, changelogs=False): """Check updates matching given *patterns* in selected repository.""" ypl = self.returnPkgLists('upgrades', patterns, reponame=reponame) if self.conf.obsoletes or self.conf.verbose: typl = self.returnPkgLists('obsoletes', patterns, reponame=reponame) ypl.obsoletes = typl.obsoletes ypl.obsoletesTuples = typl.obsoletesTuples if print_: columns = _list_cmd_calc_columns(self.output, ypl) if len(ypl.updates) > 0: local_pkgs = {} highlight = self.output.term.MODE['bold'] if highlight: # Do the local/remote split we get in "yum updates" for po in sorted(ypl.updates): local = po.localPkg() if os.path.exists(local) and po.verifyLocalPkg(): local_pkgs[(po.name, po.arch)] = po cul = self.conf.color_update_local cur = self.conf.color_update_remote self.output.listPkgs(ypl.updates, '', outputType='list', highlight_na=local_pkgs, columns=columns, highlight_modes={'=' : cul, 'not in' : cur}) if changelogs: self.print_changelogs(ypl.updates) if len(ypl.obsoletes) > 0: print(_('Obsoleting Packages')) # The tuple is (newPkg, oldPkg) ... so sort by new for obtup in sorted(ypl.obsoletesTuples, key=operator.itemgetter(0)): self.output.updatesObsoletesList(obtup, 'obsoletes', columns=columns) return ypl.updates or ypl.obsoletes def distro_sync_userlist(self, userlist): """ Upgrade or downgrade packages to match the latest versions available in the enabled repositories. :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage """ oldcount = self._goal.req_length() if len(userlist) == 0: self.distro_sync() else: for pkg_spec in userlist: self.distro_sync(pkg_spec) cnt = self._goal.req_length() - oldcount if cnt <= 0 and not self._goal.req_has_distupgrade_all(): msg = _('No packages marked for distribution synchronization.') raise dnf.exceptions.Error(msg) def downgradePkgs(self, specs=[], file_pkgs=[], strict=False): """Attempt to take the user specified list of packages or wildcards and downgrade them. If a complete version number is specified, attempt to downgrade them to the specified version :param specs: a list of names or wildcards specifying packages to downgrade :param file_pkgs: a list of pkg objects from local files """ result = False for pkg in file_pkgs: try: self.package_downgrade(pkg, strict=strict) result = True except dnf.exceptions.MarkingError as e: logger.info(_('No match for argument: %s'), self.output.term.bold(pkg.location)) for arg in specs: try: self.downgrade_to(arg, strict=strict) result = True except dnf.exceptions.PackageNotFoundError as err: msg = _('No package %s available.') logger.info(msg, self.output.term.bold(arg)) except dnf.exceptions.PackagesNotInstalledError as err: logger.info(_('Packages for argument %s available, but not installed.'), self.output.term.bold(err.pkg_spec)) except dnf.exceptions.MarkingError: assert False if not result: raise dnf.exceptions.Error(_('No packages marked for downgrade.')) def output_packages(self, basecmd, pkgnarrow='all', patterns=(), reponame=None): """Output selection *pkgnarrow* of packages matching *patterns* and *repoid*.""" try: highlight = self.output.term.MODE['bold'] ypl = self.returnPkgLists( pkgnarrow, patterns, installed_available=highlight, reponame=reponame) except dnf.exceptions.Error as e: return 1, [str(e)] else: update_pkgs = {} inst_pkgs = {} local_pkgs = {} columns = None if basecmd == 'list': # Dynamically size the columns columns = _list_cmd_calc_columns(self.output, ypl) if highlight and ypl.installed: # If we have installed and available lists, then do the # highlighting for the installed packages so you can see what's # available to update, an extra, or newer than what we have. for pkg in (ypl.hidden_available + ypl.reinstall_available + ypl.old_available): key = (pkg.name, pkg.arch) if key not in update_pkgs or pkg > update_pkgs[key]: update_pkgs[key] = pkg if highlight and ypl.available: # If we have installed and available lists, then do the # highlighting for the available packages so you can see what's # available to install vs. update vs. old. for pkg in ypl.hidden_installed: key = (pkg.name, pkg.arch) if key not in inst_pkgs or pkg > inst_pkgs[key]: inst_pkgs[key] = pkg if highlight and ypl.updates: # Do the local/remote split we get in "yum updates" for po in sorted(ypl.updates): if po.reponame != hawkey.SYSTEM_REPO_NAME: local_pkgs[(po.name, po.arch)] = po # Output the packages: clio = self.conf.color_list_installed_older clin = self.conf.color_list_installed_newer clir = self.conf.color_list_installed_reinstall clie = self.conf.color_list_installed_extra rip = self.output.listPkgs(ypl.installed, _('Installed Packages'), basecmd, highlight_na=update_pkgs, columns=columns, highlight_modes={'>' : clio, '<' : clin, '=' : clir, 'not in' : clie}) clau = self.conf.color_list_available_upgrade clad = self.conf.color_list_available_downgrade clar = self.conf.color_list_available_reinstall clai = self.conf.color_list_available_install rap = self.output.listPkgs(ypl.available, _('Available Packages'), basecmd, highlight_na=inst_pkgs, columns=columns, highlight_modes={'<' : clau, '>' : clad, '=' : clar, 'not in' : clai}) raep = self.output.listPkgs(ypl.autoremove, _('Autoremove Packages'), basecmd, columns=columns) rep = self.output.listPkgs(ypl.extras, _('Extra Packages'), basecmd, columns=columns) cul = self.conf.color_update_local cur = self.conf.color_update_remote rup = self.output.listPkgs(ypl.updates, _('Available Upgrades'), basecmd, highlight_na=local_pkgs, columns=columns, highlight_modes={'=' : cul, 'not in' : cur}) # XXX put this into the ListCommand at some point if len(ypl.obsoletes) > 0 and basecmd == 'list': # if we've looked up obsolete lists and it's a list request rop = len(ypl.obsoletes) print(_('Obsoleting Packages')) for obtup in sorted(ypl.obsoletesTuples, key=operator.itemgetter(0)): self.output.updatesObsoletesList(obtup, 'obsoletes', columns=columns) else: rop = self.output.listPkgs(ypl.obsoletes, _('Obsoleting Packages'), basecmd, columns=columns) rrap = self.output.listPkgs(ypl.recent, _('Recently Added Packages'), basecmd, columns=columns) if len(patterns) and \ rrap == 0 and rop == 0 and rup == 0 and rep == 0 and rap == 0 and raep == 0 and rip == 0: raise dnf.exceptions.Error(_('No matching Packages to list')) def returnPkgLists(self, pkgnarrow='all', patterns=None, installed_available=False, reponame=None): """Return a :class:`dnf.yum.misc.GenericHolder` object containing lists of package objects that match the given names or wildcards. :param pkgnarrow: a string specifying which types of packages lists to produce, such as updates, installed, available, etc. :param patterns: a list of names or wildcards specifying packages to list :param installed_available: whether the available package list is present as .hidden_available when doing all, available, or installed :param reponame: limit packages list to the given repository :return: a :class:`dnf.yum.misc.GenericHolder` instance with the following lists defined:: available = list of packageObjects installed = list of packageObjects upgrades = tuples of packageObjects (updating, installed) extras = list of packageObjects obsoletes = tuples of packageObjects (obsoleting, installed) recent = list of packageObjects """ done_hidden_available = False done_hidden_installed = False if installed_available and pkgnarrow == 'installed': done_hidden_available = True pkgnarrow = 'all' elif installed_available and pkgnarrow == 'available': done_hidden_installed = True pkgnarrow = 'all' ypl = self._do_package_lists( pkgnarrow, patterns, ignore_case=True, reponame=reponame) if self.conf.showdupesfromrepos: for pkg in ypl.reinstall_available: if not pkg.installed and not done_hidden_available: ypl.available.append(pkg) if installed_available: ypl.hidden_available = ypl.available ypl.hidden_installed = ypl.installed if done_hidden_available: ypl.available = [] if done_hidden_installed: ypl.installed = [] return ypl def provides(self, args): """Print out a list of packages that provide the given file or feature. This a cli wrapper to the provides methods in the rpmdb and pkgsack. :param args: the name of a file or feature to search for :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage """ # always in showdups mode old_sdup = self.conf.showdupesfromrepos self.conf.showdupesfromrepos = True matches = [] used_search_strings = [] for spec in args: query, used_search_string = super(BaseCli, self).provides(spec) matches.extend(query) used_search_strings.extend(used_search_string) for pkg in sorted(matches): self.output.matchcallback_verbose(pkg, used_search_strings, args) self.conf.showdupesfromrepos = old_sdup if not matches: raise dnf.exceptions.Error(_('No Matches found')) def _promptWanted(self): # shortcut for the always-off/always-on options if self.conf.assumeyes and not self.conf.assumeno: return False return True class Cli(object): def __init__(self, base): self.base = base self.cli_commands = {} self.command = None self.demands = dnf.cli.demand.DemandSheet() # :api self.register_command(dnf.cli.commands.alias.AliasCommand) self.register_command(dnf.cli.commands.autoremove.AutoremoveCommand) self.register_command(dnf.cli.commands.check.CheckCommand) self.register_command(dnf.cli.commands.clean.CleanCommand) self.register_command(dnf.cli.commands.distrosync.DistroSyncCommand) self.register_command(dnf.cli.commands.deplist.DeplistCommand) self.register_command(dnf.cli.commands.downgrade.DowngradeCommand) self.register_command(dnf.cli.commands.group.GroupCommand) self.register_command(dnf.cli.commands.history.HistoryCommand) self.register_command(dnf.cli.commands.install.InstallCommand) self.register_command(dnf.cli.commands.makecache.MakeCacheCommand) self.register_command(dnf.cli.commands.mark.MarkCommand) self.register_command(dnf.cli.commands.module.ModuleCommand) self.register_command(dnf.cli.commands.reinstall.ReinstallCommand) self.register_command(dnf.cli.commands.remove.RemoveCommand) self.register_command(dnf.cli.commands.repolist.RepoListCommand) self.register_command(dnf.cli.commands.repoquery.RepoQueryCommand) self.register_command(dnf.cli.commands.search.SearchCommand) self.register_command(dnf.cli.commands.shell.ShellCommand) self.register_command(dnf.cli.commands.swap.SwapCommand) self.register_command(dnf.cli.commands.updateinfo.UpdateInfoCommand) self.register_command(dnf.cli.commands.upgrade.UpgradeCommand) self.register_command(dnf.cli.commands.upgrademinimal.UpgradeMinimalCommand) self.register_command(dnf.cli.commands.InfoCommand) self.register_command(dnf.cli.commands.ListCommand) self.register_command(dnf.cli.commands.ProvidesCommand) self.register_command(dnf.cli.commands.CheckUpdateCommand) self.register_command(dnf.cli.commands.RepoPkgsCommand) self.register_command(dnf.cli.commands.HelpCommand) def _configure_repos(self, opts): self.base.read_all_repos(opts) if opts.repofrompath: for label, path in opts.repofrompath.items(): this_repo = self.base.repos.add_new_repo(label, self.base.conf, baseurl=[path]) this_repo._configure_from_options(opts) # do not let this repo to be disabled opts.repos_ed.append((label, "enable")) if opts.repo: opts.repos_ed.insert(0, ("*", "disable")) opts.repos_ed.extend([(r, "enable") for r in opts.repo]) notmatch = set() # Process repo enables and disables in order try: for (repo, operation) in opts.repos_ed: repolist = self.base.repos.get_matching(repo) if not repolist: if self.base.conf.strict and operation == "enable": msg = _("Unknown repo: '%s'") raise dnf.exceptions.RepoError(msg % repo) notmatch.add(repo) if operation == "enable": repolist.enable() else: repolist.disable() except dnf.exceptions.ConfigError as e: logger.critical(e) self.optparser.print_help() sys.exit(1) for repo in notmatch: logger.warning(_("No repository match: %s"), repo) expired_repos = self.base._repo_persistor.get_expired_repos() if expired_repos is None: expired_repos = self.base.repos.keys() for rid in expired_repos: repo = self.base.repos.get(rid) if repo: repo._repo.expire() # setup the progress bars/callbacks (bar, self.base._ds_callback) = self.base.output.setup_progress_callbacks() self.base.repos.all().set_progress_bar(bar) key_import = output.CliKeyImport(self.base, self.base.output) self.base.repos.all()._set_key_import(key_import) def _log_essentials(self): logger.debug('{prog} version: %s'.format(prog=dnf.util.MAIN_PROG_UPPER), dnf.const.VERSION) logger.log(dnf.logging.DDEBUG, 'Command: %s', self.cmdstring) logger.log(dnf.logging.DDEBUG, 'Installroot: %s', self.base.conf.installroot) logger.log(dnf.logging.DDEBUG, 'Releasever: %s', self.base.conf.releasever) logger.debug("cachedir: %s", self.base.conf.cachedir) def _process_demands(self): demands = self.demands repos = self.base.repos if demands.root_user: if not dnf.util.am_i_root(): raise dnf.exceptions.Error( _('This command has to be run with superuser privileges ' '(under the root user on most systems).')) if demands.changelogs: for repo in repos.iter_enabled(): repo.load_metadata_other = True if demands.cacheonly or self.base.conf.cacheonly: self.base.conf.cacheonly = True for repo in repos.values(): repo._repo.setSyncStrategy(dnf.repo.SYNC_ONLY_CACHE) else: if demands.freshest_metadata: for repo in repos.iter_enabled(): repo._repo.expire() elif not demands.fresh_metadata: for repo in repos.values(): repo._repo.setSyncStrategy(dnf.repo.SYNC_LAZY) if demands.sack_activation: self.base.fill_sack( load_system_repo='auto' if self.demands.load_system_repo else False, load_available_repos=self.demands.available_repos) def _parse_commands(self, opts, args): """Check that the requested CLI command exists.""" basecmd = opts.command command_cls = self.cli_commands.get(basecmd) if command_cls is None: logger.critical(_('No such command: %s. Please use %s --help'), basecmd, sys.argv[0]) if self.base.conf.plugins: logger.critical(_("It could be a {PROG} plugin command, " "try: \"{prog} install 'dnf-command(%s)'\"").format( prog=dnf.util.MAIN_PROG, PROG=dnf.util.MAIN_PROG_UPPER), basecmd) else: logger.critical(_("It could be a {prog} plugin command, " "but loading of plugins is currently disabled.").format( prog=dnf.util.MAIN_PROG_UPPER)) raise CliError self.command = command_cls(self) logger.log(dnf.logging.DDEBUG, 'Base command: %s', basecmd) logger.log(dnf.logging.DDEBUG, 'Extra commands: %s', args) def configure(self, args, option_parser=None): """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 :param option_parser: a class for parsing cli options """ aliases = dnf.cli.aliases.Aliases() args = aliases.resolve(args) self.optparser = dnf.cli.option_parser.OptionParser() \ if option_parser is None else option_parser opts = self.optparser.parse_main_args(args) # Just print out the version if that's what the user wanted if opts.version: print(dnf.const.VERSION) print_versions(self.base.conf.history_record_packages, self.base, self.base.output) sys.exit(0) if opts.quiet: opts.debuglevel = 0 opts.errorlevel = 2 if opts.verbose: opts.debuglevel = opts.errorlevel = dnf.const.VERBOSE_LEVEL # Read up configuration options and initialize plugins try: if opts.cacheonly: self.base.conf._set_value("cachedir", self.base.conf.system_cachedir, dnf.conf.PRIO_DEFAULT) self.demands.cacheonly = True self.base.conf._configure_from_options(opts) self._read_conf_file(opts.releasever) if 'arch' in opts: self.base.conf.arch = opts.arch self.base.conf._adjust_conf_options() except (dnf.exceptions.ConfigError, ValueError) as e: logger.critical(_('Config error: %s'), e) sys.exit(1) except IOError as e: e = '%s: %s' % (ucd(str(e)), repr(e.filename)) logger.critical(_('Config error: %s'), e) sys.exit(1) if opts.destdir is not None: self.base.conf.destdir = opts.destdir if not self.base.conf.downloadonly and opts.command not in ( 'download', 'system-upgrade', 'reposync', 'modulesync'): logger.critical(_('--destdir or --downloaddir must be used with --downloadonly ' 'or download or system-upgrade command.') ) sys.exit(1) if (opts.set_enabled or opts.set_disabled) and opts.command != 'config-manager': logger.critical( _('--enable, --set-enabled and --disable, --set-disabled ' 'must be used with config-manager command.')) sys.exit(1) if opts.sleeptime is not None: time.sleep(random.randrange(opts.sleeptime * 60)) # store the main commands & summaries, before plugins are loaded self.optparser.add_commands(self.cli_commands, 'main') # store the plugin commands & summaries self.base.init_plugins(opts.disableplugin, opts.enableplugin, self) self.optparser.add_commands(self.cli_commands,'plugin') # show help if no command specified # this is done here, because we first have the full # usage info after the plugins are loaded. if not opts.command: 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 = self.optparser.prog + ' ' for arg in self.base.args: self.cmdstring += '%s ' % arg self._log_essentials() try: self._parse_commands(opts, args) except CliError: sys.exit(1) # show help for dnf --help / --help-cmd if opts.help: self.optparser.print_help(self.command) sys.exit(0) opts = self.optparser.parse_command_args(self.command, args) if opts.allowerasing: self.demands.allow_erasing = opts.allowerasing self.base._allow_erasing = True if opts.freshest_metadata: self.demands.freshest_metadata = opts.freshest_metadata if opts.debugsolver: self.base.conf.debug_solver = True if opts.obsoletes: self.base.conf.obsoletes = True self.command.pre_configure() self.base.pre_configure_plugins() # with cachedir in place we can configure stuff depending on it: self.base._activate_persistor() self._configure_repos(opts) self.base.configure_plugins() self.base.conf._configure_from_options(opts) self.command.configure() if self.base.conf.destdir: dnf.util.ensure_dir(self.base.conf.destdir) self.base.repos.all().pkgdir = self.base.conf.destdir if self.base.conf.color != 'auto': self.base.output.term.reinit(color=self.base.conf.color) if rpm.expandMacro('%_pkgverify_level') in ('signature', 'all'): forcing = False for repo in self.base.repos.iter_enabled(): if repo.gpgcheck: continue repo.gpgcheck = True forcing = True if not self.base.conf.localpkg_gpgcheck: self.base.conf.localpkg_gpgcheck = True forcing = True if forcing: logger.warning( _("Warning: Enforcing GPG signature check globally " "as per active RPM security policy (see 'gpgcheck' in " "dnf.conf(5) for how to squelch this message)" ) ) def _read_conf_file(self, releasever=None): timer = dnf.logging.Timer('config') conf = self.base.conf # replace remote config path with downloaded file conf._check_remote_file('config_file_path') # search config file inside the installroot first conf._search_inside_installroot('config_file_path') # check whether a config file is requested from command line and the file exists filename = conf._get_value('config_file_path') if (conf._get_priority('config_file_path') == dnf.conf.PRIO_COMMANDLINE) and \ not os.path.isfile(filename): raise dnf.exceptions.ConfigError(_('Config file "{}" does not exist').format(filename)) # read config conf.read(priority=dnf.conf.PRIO_MAINCONFIG) # search reposdir file inside the installroot first from_root = conf._search_inside_installroot('reposdir') # Update vars from same root like repos were taken if conf._get_priority('varsdir') == dnf.conf.PRIO_COMMANDLINE: from_root = "/" subst = conf.substitutions subst.update_from_etc(from_root, varsdir=conf._get_value('varsdir')) # cachedir, logs, releasever, and gpgkey are taken from or stored in installroot if releasever is None and conf.releasever is None: releasever = dnf.rpm.detect_releasever(conf.installroot) elif releasever == '/': releasever = dnf.rpm.detect_releasever(releasever) if releasever is not None: conf.releasever = releasever if conf.releasever is None: logger.warning(_("Unable to detect release version (use '--releasever' to specify " "release version)")) for opt in ('cachedir', 'logdir', 'persistdir'): conf.prepend_installroot(opt) self.base._logging._setup_from_dnf_conf(conf) timer() return conf def _populate_update_security_filter(self, opts, cmp_type='eq', all=None): """ :param opts: :param cmp_type: string supported "eq", "gte" :param all: :return: """ if (opts is None) and (all is None): return types = [] if opts.bugfix or all: types.append('bugfix') if opts.enhancement or all: types.append('enhancement') if opts.newpackage or all: types.append('newpackage') if opts.security or all: types.append('security') self.base.add_security_filters(cmp_type, types=types, advisory=opts.advisory, bugzilla=opts.bugzilla, cves=opts.cves, severity=opts.severity) def redirect_logger(self, stdout=None, stderr=None): # :api """ Change minimal logger level for terminal output to stdout and stderr according to specific command requirements @param stdout: logging.INFO, logging.WARNING, ... @param stderr:logging.INFO, logging.WARNING, ... """ if stdout is not None: self.base._logging.stdout_handler.setLevel(stdout) if stderr is not None: self.base._logging.stderr_handler.setLevel(stderr) def redirect_repo_progress(self, fo=sys.stderr): progress = dnf.cli.progress.MultiFileProgressMeter(fo) self.base.output.progress = progress self.base.repos.all().set_progress_bar(progress) def _check_running_kernel(self): kernel = self.base.sack.get_running_kernel() if kernel is None: return q = self.base.sack.query().filterm(provides=kernel.name) q = q.installed() q.filterm(advisory_type='security') ikpkg = kernel for pkg in q: if pkg > ikpkg: ikpkg = pkg if ikpkg > kernel: print('Security: %s is an installed security update' % ikpkg) print('Security: %s is the currently running version' % kernel) def _option_conflict(self, option_string_1, option_string_2): print(self.optparser.print_usage()) raise dnf.exceptions.Error(_("argument {}: not allowed with argument {}".format( option_string_1, option_string_2))) def register_command(self, command_cls): """Register a Command. :api""" for name in command_cls.aliases: if name in self.cli_commands: raise dnf.exceptions.ConfigError(_('Command "%s" already defined') % name) self.cli_commands[name] = command_cls def run(self): """Call the base command, and pass it the extended commands or arguments. :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage """ self._process_demands() # Reports about excludes and includes (but not from plugins) if self.base.conf.excludepkgs: logger.debug( _('Excludes in dnf.conf: ') + ", ".join(sorted(set(self.base.conf.excludepkgs)))) if self.base.conf.includepkgs: logger.debug( _('Includes in dnf.conf: ') + ", ".join(sorted(set(self.base.conf.includepkgs)))) for repo in self.base.repos.iter_enabled(): if repo.excludepkgs: logger.debug(_('Excludes in repo ') + repo.id + ": " + ", ".join(sorted(set(repo.excludepkgs)))) if repo.includepkgs: logger.debug(_('Includes in repo ') + repo.id + ": " + ", ".join(sorted(set(repo.includepkgs)))) return self.command.run() format.py000064400000007406151030066770006422 0ustar00# Copyright (C) 2013-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. from __future__ import unicode_literals from dnf.pycomp import long def format_number(number, SI=0, space=' '): """Return a human-readable metric-like string representation of a number. :param number: the number to be converted to a human-readable form :param SI: If is 0, this function will use the convention that 1 kilobyte = 1024 bytes, otherwise, the convention that 1 kilobyte = 1000 bytes will be used :param space: string that will be placed between the number and the SI prefix :return: a human-readable metric-like string representation of *number* """ # copied from from urlgrabber.progress symbols = [ ' ', # (none) 'k', # kilo 'M', # mega 'G', # giga 'T', # tera 'P', # peta 'E', # exa 'Z', # zetta 'Y'] # yotta if SI: step = 1000.0 else: step = 1024.0 thresh = 999 depth = 0 max_depth = len(symbols) - 1 if number is None: number = 0.0 # we want numbers between 0 and thresh, but don't exceed the length # of our list. In that event, the formatting will be screwed up, # but it'll still show the right number. while number > thresh and depth < max_depth: depth = depth + 1 number = number / step if isinstance(number, int) or isinstance(number, long): format = '%i%s%s' elif number < 9.95: # must use 9.95 for proper sizing. For example, 9.99 will be # rounded to 10.0 with the .1f format string (which is too long) format = '%.1f%s%s' else: format = '%.0f%s%s' return(format % (float(number or 0), space, symbols[depth])) def format_time(seconds, use_hours=0): """Return a human-readable string representation of a number of seconds. The string will show seconds, minutes, and optionally hours. :param seconds: the number of seconds to convert to a human-readable form :param use_hours: If use_hours is 0, the representation will be in minutes and seconds. Otherwise, it will be in hours, minutes, and seconds :return: a human-readable string representation of *seconds* """ # copied from from urlgrabber.progress if seconds is None or seconds < 0: if use_hours: return '--:--:--' else: return '--:--' elif seconds == float('inf'): return 'Infinite' else: seconds = int(seconds) minutes = seconds // 60 seconds = seconds % 60 if use_hours: hours = minutes // 60 minutes = minutes % 60 return '%02i:%02i:%02i' % (hours, minutes, seconds) else: return '%02i:%02i' % (minutes, seconds) def indent_block(s): return '\n'.join(' ' + s for s in s.splitlines()) utils.py000064400000010650151030066770006265 0ustar00# Copyright (C) 2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Various utility functions, and a utility class.""" from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli.format import format_number from dnf.i18n import _ import dnf.util import logging import os import time _USER_HZ = os.sysconf(os.sysconf_names['SC_CLK_TCK']) logger = logging.getLogger('dnf') def jiffies_to_seconds(jiffies): """Convert a number of jiffies to seconds. How many jiffies are in a second is system-dependent, e.g. 100 jiffies = 1 second is common. :param jiffies: a number of jiffies :return: the equivalent number of seconds """ return int(jiffies) / _USER_HZ def seconds_to_ui_time(seconds): """Return a human-readable string representation of the length of a time interval given in seconds. :param seconds: the length of the time interval in seconds :return: a human-readable string representation of the length of the time interval """ if seconds >= 60 * 60 * 24: return "%d day(s) %d:%02d:%02d" % (seconds // (60 * 60 * 24), (seconds // (60 * 60)) % 24, (seconds // 60) % 60, seconds % 60) if seconds >= 60 * 60: return "%d:%02d:%02d" % (seconds // (60 * 60), (seconds // 60) % 60, (seconds % 60)) return "%02d:%02d" % ((seconds // 60), seconds % 60) def get_process_info(pid): """Return info dict about a process.""" pid = int(pid) # Maybe true if /proc isn't mounted, or not Linux ... or something. if (not os.path.exists("/proc/%d/status" % pid) or not os.path.exists("/proc/stat") or not os.path.exists("/proc/%d/stat" % pid)): return ps = {} with open("/proc/%d/status" % pid) as status_file: for line in status_file: if line[-1] != '\n': continue data = line[:-1].split(':\t', 1) if len(data) < 2: continue data[1] = dnf.util.rtrim(data[1], ' kB') ps[data[0].strip().lower()] = data[1].strip() if 'vmrss' not in ps: return if 'vmsize' not in ps: return boot_time = None with open("/proc/stat") as stat_file: for line in stat_file: if line.startswith("btime "): boot_time = int(line[len("btime "):-1]) break if boot_time is None: return with open('/proc/%d/stat' % pid) as stat_file: ps_stat = stat_file.read().split() ps['start_time'] = boot_time + jiffies_to_seconds(ps_stat[21]) ps['state'] = {'R' : _('Running'), 'S' : _('Sleeping'), 'D' : _('Uninterruptible'), 'Z' : _('Zombie'), 'T' : _('Traced/Stopped') }.get(ps_stat[2], _('Unknown')) return ps def show_lock_owner(pid): """Output information about process holding a lock.""" ps = get_process_info(pid) if not ps: msg = _('Unable to find information about the locking process (PID %d)') logger.critical(msg, pid) return msg = _(' The application with PID %d is: %s') % (pid, ps['name']) logger.critical("%s", msg) logger.critical(_(" Memory : %5s RSS (%5sB VSZ)"), format_number(int(ps['vmrss']) * 1024), format_number(int(ps['vmsize']) * 1024)) ago = seconds_to_ui_time(int(time.time()) - ps['start_time']) logger.critical(_(' Started: %s - %s ago'), dnf.util.normalize_time(ps['start_time']), ago) logger.critical(_(' State : %s'), ps['state']) return option_parser.py000064400000056464151030066770010026 0ustar00# optparse.py # CLI options parser. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import unicode_literals from dnf.i18n import _ from dnf.util import _parse_specs import argparse import dnf.exceptions import dnf.util import dnf.rpm import dnf.yum.misc import logging import os.path import re import sys logger = logging.getLogger("dnf") class MultilineHelpFormatter(argparse.HelpFormatter): def _split_lines(self, text, width): if '\n' in text: return text.splitlines() return super(MultilineHelpFormatter, self)._split_lines(text, width) class OptionParser(argparse.ArgumentParser): """ArgumentParser like class to do things the "yum way".""" def __init__(self, reset_usage=True): super(OptionParser, self).__init__(add_help=False, formatter_class=MultilineHelpFormatter) self.command_positional_parser = None self.command_group = None self._add_general_options() if reset_usage: self._cmd_usage = {} # names, summary for dnf commands, to build usage self._cmd_groups = set() # cmd groups added (main, plugin) def error(self, msg): """Output an error message, and exit the program. This method overrides standard argparser's error so that error output goes to the logger. :param msg: the error message to output """ self.print_usage() logger.critical(_("Command line error: %s"), msg) sys.exit(1) class _RepoCallback(argparse.Action): def __call__(self, parser, namespace, values, opt_str): operation = 'disable' if opt_str == '--disablerepo' else 'enable' l = getattr(namespace, self.dest) l.extend((x, operation) for x in re.split(r'\s*[,\s]\s*', values)) class _RepoCallbackEnable(argparse.Action): def __call__(self, parser, namespace, values, opt_str): namespace.repos_ed.append((values[0], 'enable')) setattr(namespace, 'reponame', values) class _SplitCallback(argparse._AppendAction): """ Split all strings in seq, at "," and whitespace. Returns a new list. """ SPLITTER = r'\s*[,\s]\s*' def __call__(self, parser, namespace, values, opt_str): first = True for val in re.split(self.SPLITTER, values): if first or val: # Empty values are sometimes used to clear existing content of the option. # Only the first value in the parsed string can be empty. Other empty values # are ignored. super(OptionParser._SplitCallback, self).__call__(parser, namespace, val, opt_str) first = False class _SplitExtendDictCallback(argparse.Action): """ Split string at "," or whitespace to (key, value). Extends dict with {key: value}.""" def __call__(self, parser, namespace, values, opt_str): try: key, val = values.split(',') if not key or not val: raise ValueError except ValueError: msg = _('bad format: %s') % values raise argparse.ArgumentError(self, msg) dct = getattr(namespace, self.dest) dct[key] = val class _SetoptsCallback(argparse.Action): """ Parse setopts arguments and put them into main_ and repo_.""" def __call__(self, parser, namespace, values, opt_str): vals = values.split('=') if len(vals) > 2: logger.warning(_("Setopt argument has multiple values: %s"), values) return if len(vals) < 2: logger.warning(_("Setopt argument has no value: %s"), values) return k, v = vals period = k.rfind('.') if period != -1: repo = k[:period] k = k[period+1:] if hasattr(namespace, 'repo_setopts'): repoopts = namespace.repo_setopts else: repoopts = {} repoopts.setdefault(repo, {}).setdefault(k, []).append(v) setattr(namespace, 'repo_' + self.dest, repoopts) else: if hasattr(namespace, 'main_setopts'): mainopts = namespace.main_setopts else: mainopts = {} mainopts.setdefault(k, []).append(v) setattr(namespace, 'main_' + self.dest, mainopts) class ParseSpecGroupFileCallback(argparse.Action): def __call__(self, parser, namespace, values, opt_str): _parse_specs(namespace, values) class PkgNarrowCallback(argparse.Action): def __init__(self, *args, **kwargs): self.pkgnarrow = {} try: for k in ['choices', 'default']: self.pkgnarrow[k] = kwargs[k] del kwargs[k] except KeyError as e: raise TypeError("%s() missing mandatory argument %s" % (self.__class__.__name__, e)) kwargs['default'] = [] super(OptionParser.PkgNarrowCallback, self).__init__(*args, **kwargs) def __call__(self, parser, namespace, values, opt_str): dest_action = self.dest + '_action' if not values or values[0] not in self.pkgnarrow['choices']: narrow = self.pkgnarrow['default'] else: narrow = values.pop(0) setattr(namespace, dest_action, narrow) setattr(namespace, self.dest, values) class ForceArchAction(argparse.Action): def __call__(self, parser, namespace, values, opt_str): namespace.ignorearch = True namespace.arch = values def _add_general_options(self): """ Standard options known to all dnf subcommands. """ # All defaults need to be a None, so we can always tell whether the user # has set something or whether we are getting a default. general_grp = self.add_argument_group(_('General {prog} options'.format( prog=dnf.util.MAIN_PROG_UPPER))) general_grp.add_argument("-c", "--config", dest="config_file_path", default=None, metavar='[config file]', help=_("config file location")) general_grp.add_argument("-q", "--quiet", dest="quiet", action="store_true", default=None, help=_("quiet operation")) general_grp.add_argument("-v", "--verbose", action="store_true", default=None, help=_("verbose operation")) general_grp.add_argument("--version", action="store_true", default=None, help=_("show {prog} version and exit").format( prog=dnf.util.MAIN_PROG_UPPER)) general_grp.add_argument("--installroot", help=_("set install root"), metavar='[path]') general_grp.add_argument("--nodocs", action="store_const", const=['nodocs'], dest='tsflags', help=_("do not install documentations")) general_grp.add_argument("--noplugins", action="store_false", default=None, dest='plugins', help=_("disable all plugins")) general_grp.add_argument("--enableplugin", dest="enableplugin", default=[], action=self._SplitCallback, help=_("enable plugins by name"), metavar='[plugin]') general_grp.add_argument("--disableplugin", dest="disableplugin", default=[], action=self._SplitCallback, help=_("disable plugins by name"), metavar='[plugin]') general_grp.add_argument("--releasever", default=None, help=_("override the value of $releasever" " in config and repo files")) general_grp.add_argument("--setopt", dest="setopts", default=[], action=self._SetoptsCallback, help=_("set arbitrary config and repo options")) general_grp.add_argument("--skip-broken", dest="skip_broken", action="store_true", default=None, help=_("resolve depsolve problems by skipping packages")) general_grp.add_argument('-h', '--help', '--help-cmd', action="store_true", dest='help', help=_("show command help")) general_grp.add_argument('--allowerasing', action='store_true', default=None, help=_('allow erasing of installed packages to ' 'resolve dependencies')) best_group = general_grp.add_mutually_exclusive_group() best_group.add_argument("-b", "--best", action="store_true", dest='best', default=None, help=_("try the best available package versions in transactions.")) best_group.add_argument("--nobest", action="store_false", dest='best', help=_("do not limit the transaction to the best candidate")) general_grp.add_argument("-C", "--cacheonly", dest="cacheonly", action="store_true", default=None, help=_("run entirely from system cache, " "don't update cache")) general_grp.add_argument("-R", "--randomwait", dest="sleeptime", type=int, default=None, metavar='[minutes]', help=_("maximum command wait time")) general_grp.add_argument("-d", "--debuglevel", dest="debuglevel", metavar='[debug level]', default=None, help=_("debugging output level"), type=int) general_grp.add_argument("--debugsolver", action="store_true", default=None, help=_("dumps detailed solving results into" " files")) general_grp.add_argument("--showduplicates", dest="showdupesfromrepos", action="store_true", default=None, help=_("show duplicates, in repos, " "in list/search commands")) general_grp.add_argument("-e", "--errorlevel", default=None, type=int, help=_("error output level")) general_grp.add_argument("--obsoletes", default=None, dest="obsoletes", action="store_true", help=_("enables {prog}'s obsoletes processing logic " "for upgrade or display capabilities that " "the package obsoletes for info, list and " "repoquery").format(prog=dnf.util.MAIN_PROG)) general_grp.add_argument("--rpmverbosity", default=None, help=_("debugging output level for rpm"), metavar='[debug level name]') general_grp.add_argument("-y", "--assumeyes", action="store_true", default=None, help=_("automatically answer yes" " for all questions")) general_grp.add_argument("--assumeno", action="store_true", default=None, help=_("automatically answer no" " for all questions")) general_grp.add_argument("--enablerepo", action=self._RepoCallback, dest='repos_ed', default=[], metavar='[repo]', help=_("Enable additional repositories. List option. " "Supports globs, can be specified multiple times.")) repo_group = general_grp.add_mutually_exclusive_group() repo_group.add_argument("--disablerepo", action=self._RepoCallback, dest='repos_ed', default=[], metavar='[repo]', help=_("Disable repositories. List option. " "Supports globs, can be specified multiple times.")) repo_group.add_argument('--repo', '--repoid', metavar='[repo]', dest='repo', action=self._SplitCallback, default=[], help=_('enable just specific repositories by an id or a glob, ' 'can be specified multiple times')) enable_group = general_grp.add_mutually_exclusive_group() enable_group.add_argument("--enable", default=False, dest="set_enabled", action="store_true", help=_("enable repos with config-manager " "command (automatically saves)")) enable_group.add_argument("--disable", default=False, dest="set_disabled", action="store_true", help=_("disable repos with config-manager " "command (automatically saves)")) general_grp.add_argument("-x", "--exclude", "--excludepkgs", default=[], dest='excludepkgs', action=self._SplitCallback, help=_("exclude packages by name or glob"), metavar='[package]') general_grp.add_argument("--disableexcludes", "--disableexcludepkgs", default=[], dest="disable_excludes", action=self._SplitCallback, help=_("disable excludepkgs"), metavar='[repo]') general_grp.add_argument("--repofrompath", default={}, action=self._SplitExtendDictCallback, metavar='[repo,path]', help=_("label and path to an additional repository to use (same " "path as in a baseurl), can be specified multiple times.")) general_grp.add_argument("--noautoremove", action="store_false", default=None, dest='clean_requirements_on_remove', help=_("disable removal of dependencies that are no longer used")) general_grp.add_argument("--nogpgcheck", action="store_false", default=None, dest='gpgcheck', help=_("disable gpg signature checking (if RPM policy allows)")) general_grp.add_argument("--color", dest="color", default=None, help=_("control whether color is used")) general_grp.add_argument("--refresh", dest="freshest_metadata", action="store_true", help=_("set metadata as expired before running" " the command")) general_grp.add_argument("-4", dest="ip_resolve", default=None, help=_("resolve to IPv4 addresses only"), action="store_const", const='ipv4') general_grp.add_argument("-6", dest="ip_resolve", default=None, help=_("resolve to IPv6 addresses only"), action="store_const", const='ipv6') general_grp.add_argument("--destdir", "--downloaddir", dest="destdir", default=None, help=_("set directory to copy packages to")) general_grp.add_argument("--downloadonly", dest="downloadonly", action="store_true", default=False, help=_("only download packages")) general_grp.add_argument("--comment", dest="comment", default=None, help=_("add a comment to transaction")) # Updateinfo options... general_grp.add_argument("--bugfix", action="store_true", help=_("Include bugfix relevant packages, " "in updates")) general_grp.add_argument("--enhancement", action="store_true", help=_("Include enhancement relevant packages," " in updates")) general_grp.add_argument("--newpackage", action="store_true", help=_("Include newpackage relevant packages," " in updates")) general_grp.add_argument("--security", action="store_true", help=_("Include security relevant packages, " "in updates")) general_grp.add_argument("--advisory", "--advisories", dest="advisory", default=[], action=self._SplitCallback, help=_("Include packages needed to fix the " "given advisory, in updates")) general_grp.add_argument("--bz", "--bzs", default=[], dest="bugzilla", action=self._SplitCallback, help=_( "Include packages needed to fix the given BZ, in updates")) general_grp.add_argument("--cve", "--cves", default=[], dest="cves", action=self._SplitCallback, help=_("Include packages needed to fix the given CVE, in updates")) general_grp.add_argument( "--sec-severity", "--secseverity", choices=['Critical', 'Important', 'Moderate', 'Low'], default=[], dest="severity", action=self._SplitCallback, help=_( "Include security relevant packages matching the severity, " "in updates")) general_grp.add_argument("--forcearch", metavar="ARCH", dest=argparse.SUPPRESS, action=self.ForceArchAction, choices=sorted(dnf.rpm._BASEARCH_MAP.keys()), help=_("Force the use of an architecture")) general_grp.add_argument('command', nargs='?', help=argparse.SUPPRESS) def _add_cmd_usage(self, cmd, group): """ store usage info about a single dnf command.""" summary = dnf.i18n.ucd(cmd.summary) name = dnf.i18n.ucd(cmd.aliases[0]) if not name in self._cmd_usage: self._cmd_usage[name] = (group, summary) self._cmd_groups.add(group) def add_commands(self, cli_cmds, group): """ store name & summary for dnf commands The stored information is used build usage information grouped by build-in & plugin commands. """ for cmd in set(cli_cmds.values()): self._add_cmd_usage(cmd, group) def get_usage(self): """ get the usage information to show the user. """ desc = {'main': _('List of Main Commands:'), 'plugin': _('List of Plugin Commands:')} usage = '%s [options] COMMAND\n' % dnf.util.MAIN_PROG for grp in ['main', 'plugin']: if not grp in self._cmd_groups: # dont add plugin usage, if we dont have plugins continue usage += "\n%s\n\n" % desc[grp] for name in sorted(self._cmd_usage.keys()): group, summary = self._cmd_usage[name] if group == grp: usage += "%-25s %s\n" % (name, summary) return usage def _add_command_options(self, command): self.prog = "%s %s" % (dnf.util.MAIN_PROG, command._basecmd) self.description = command.summary self.command_positional_parser = argparse.ArgumentParser(self.prog, add_help=False) self.command_positional_parser.print_usage = self.print_usage self.command_positional_parser._positionals.title = None self.command_group = self.add_argument_group( '{} command-specific options'.format(command._basecmd.capitalize())) self.command_group.add_argument = self.cmd_add_argument self.command_group._command = command._basecmd command.set_argparser(self.command_group) def cmd_add_argument(self, *args, **kwargs): if all([(arg[0] in self.prefix_chars) for arg in args]): return type(self.command_group).add_argument(self.command_group, *args, **kwargs) else: return self.command_positional_parser.add_argument(*args, **kwargs) def _check_encoding(self, args): for arg in args: try: arg.encode('utf-8') except UnicodeEncodeError as e: raise dnf.exceptions.ConfigError( _("Cannot encode argument '%s': %s") % (arg, str(e))) def parse_main_args(self, args): self._check_encoding(args) namespace, _unused_args = self.parse_known_args(args) return namespace def parse_command_args(self, command, args): self._add_command_options(command) namespace, unused_args = self.parse_known_args(args) namespace = self.command_positional_parser.parse_args(unused_args, namespace) command.opts = namespace return command.opts def print_usage(self, file_=None): if self.command_positional_parser: self._actions += self.command_positional_parser._actions super(OptionParser, self).print_usage(file_) def print_help(self, command=None): # pylint: disable=W0212 if command: if not self.command_group or self.command_group._command != command._basecmd: self._add_command_options(command) self._actions += self.command_positional_parser._actions self._action_groups.append(self.command_positional_parser._positionals) else: self.usage = self.get_usage() super(OptionParser, self).print_help() completion_helper.py000064400000016457151030066770010650 0ustar00#!/usr/libexec/platform-python # # This file is part of dnf. # # Copyright 2015 (C) Igor Gnatenko # Copyright 2016 (C) Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA import dnf.exceptions import dnf.cli import dnf.cli.commands.clean import sys def filter_list_by_kw(kw, lst): return filter(lambda k: str(k).startswith(kw), lst) def listpkg_to_setstr(pkgs): return set([str(x) for x in pkgs]) class RemoveCompletionCommand(dnf.cli.commands.remove.RemoveCommand): def __init__(self, args): super(RemoveCompletionCommand, self).__init__(args) def configure(self): self.cli.demands.root_user = False self.cli.demands.sack_activation = True def run(self): for pkg in ListCompletionCommand.installed(self.base, self.opts.pkg_specs): print(str(pkg)) class InstallCompletionCommand(dnf.cli.commands.install.InstallCommand): def __init__(self, args): super(InstallCompletionCommand, self).__init__(args) def configure(self): self.cli.demands.root_user = False self.cli.demands.available_repos = True self.cli.demands.sack_activation = True def run(self): installed = listpkg_to_setstr(ListCompletionCommand.installed(self.base, self.opts.pkg_specs)) available = listpkg_to_setstr(ListCompletionCommand.available(self.base, self.opts.pkg_specs)) for pkg in (available - installed): print(str(pkg)) class ReinstallCompletionCommand(dnf.cli.commands.reinstall.ReinstallCommand): def __init__(self, args): super(ReinstallCompletionCommand, self).__init__(args) def configure(self): self.cli.demands.root_user = False self.cli.demands.available_repos = True self.cli.demands.sack_activation = True def run(self): installed = listpkg_to_setstr(ListCompletionCommand.installed(self.base, self.opts.pkg_specs)) available = listpkg_to_setstr(ListCompletionCommand.available(self.base, self.opts.pkg_specs)) for pkg in (installed & available): print(str(pkg)) class ListCompletionCommand(dnf.cli.commands.ListCommand): def __init__(self, args): super(ListCompletionCommand, self).__init__(args) def run(self): subcmds = self.pkgnarrows args = self.opts.packages action = self.opts.packages_action if len(args) > 1 and args[1] not in subcmds: print("\n".join(filter_list_by_kw(args[1], subcmds))) else: if action == "installed": pkgs = self.installed(self.base, args) elif action == "available": pkgs = self.available(self.base, args) elif action == "updates": pkgs = self.updates(self.base, args) else: available = listpkg_to_setstr(self.available(self.base, args)) installed = listpkg_to_setstr(self.installed(self.base, args)) pkgs = (available | installed) if not pkgs: print("\n".join(filter_list_by_kw(args[0], subcmds))) return for pkg in pkgs: print(str(pkg)) @staticmethod def installed(base, arg): return base.sack.query().installed().filterm(name__glob="{}*".format(arg[0])) @staticmethod def available(base, arg): return base.sack.query().available().filterm(name__glob="{}*".format(arg[0])) @staticmethod def updates(base, arg): return base.check_updates(["{}*".format(arg[0])], print_=False) class RepoListCompletionCommand(dnf.cli.commands.repolist.RepoListCommand): def __init__(self, args): super(RepoListCompletionCommand, self).__init__(args) def run(self): args = self.opts if args.repos_action == "enabled": print("\n".join(filter_list_by_kw(args.repos[0], [r.id for r in self.base.repos.iter_enabled()]))) elif args.repos_action == "disabled": print("\n".join(filter_list_by_kw(args.repos[0], [r.id for r in self.base.repos.all() if not r.enabled]))) elif args.repos_action == "all": print("\n".join(filter_list_by_kw(args.repos[0], [r.id for r in self.base.repos.all()]))) class UpgradeCompletionCommand(dnf.cli.commands.upgrade.UpgradeCommand): def __init__(self, args): super(UpgradeCompletionCommand, self).__init__(args) def configure(self): self.cli.demands.root_user = False self.cli.demands.available_repos = True self.cli.demands.sack_activation = True def run(self): for pkg in ListCompletionCommand.updates(self.base, self.opts.pkg_specs): print(str(pkg)) class DowngradeCompletionCommand(dnf.cli.commands.downgrade.DowngradeCommand): def __init__(self, args): super(DowngradeCompletionCommand, self).__init__(args) def configure(self): self.cli.demands.root_user = False self.cli.demands.available_repos = True self.cli.demands.sack_activation = True def run(self): for pkg in ListCompletionCommand.available(self.base, self.opts.pkg_specs).downgrades(): print(str(pkg)) class CleanCompletionCommand(dnf.cli.commands.clean.CleanCommand): def __init__(self, args): super(CleanCompletionCommand, self).__init__(args) def run(self): subcmds = dnf.cli.commands.clean._CACHE_TYPES.keys() print("\n".join(filter_list_by_kw(self.opts.type[1], subcmds))) def main(args): base = dnf.cli.cli.BaseCli() cli = dnf.cli.Cli(base) if args[0] == "_cmds": base.init_plugins([], [], cli) print("\n".join(filter_list_by_kw(args[1], cli.cli_commands))) return cli.cli_commands.clear() cli.register_command(RemoveCompletionCommand) cli.register_command(InstallCompletionCommand) cli.register_command(ReinstallCompletionCommand) cli.register_command(ListCompletionCommand) cli.register_command(RepoListCompletionCommand) cli.register_command(UpgradeCompletionCommand) cli.register_command(DowngradeCompletionCommand) cli.register_command(CleanCompletionCommand) cli.configure(args) try: cli.run() except (OSError, dnf.exceptions.Error): sys.exit(0) if __name__ == "__main__": try: main(sys.argv[1:]) except KeyboardInterrupt: sys.exit(1) __pycache__/cli.cpython-36.opt-1.pyc000064400000074151151030066770013125 0ustar003 g @stdZddlmZddlmZddlmZyddlmZWn ek rXddlmZYnXddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlmZdd lmZdd lmZmZddlZddlZddlZddlZddlZddl Zddl!Zddl"Zddl#Zddl$Zddl%Zddl&Zddl'Zddl(Zddl)Zddl*Zddl+Zddl,Zddl-Zddl.Zddl/Zddl0Zddl1Zddl2Zddl3Zddl4Zddl5Zddl6Zddl7Zddl8Zddl9Zddl:Zddl;ZddlZddl?Zddl@ZddlAZddlBZddlCZddlDZe jEd ZFdd dZGddZHddZIddZJGdddejKZLGdddeMZNdS)z/ Command line interface yum class and related. )print_function)absolute_import)unicode_literals)SequenceN)output)CliError)ucd_dnfcCst|jdt|jt|}t|j}t|j}xFd|fd|fd|ffD],\}}||j|d|||d7<qLWdS)zl Get the length of each pkg's column. Add that to data. This "knows" about simpleList and printVer. rnaverridrN)lennamearchZevrZ _from_repo setdefault)datapkgindentr rrdvr/usr/lib/python3.6/cli.py_add_pkg_simple_list_lens]s     rcCsiiid}x<|j|j|j|j|j|jfD]}x|D]}t||q4Wq*Wt|jdkrx*|j D] \}}t||t||d dq`W|d|d|dg}|j |d d }|d |d  |d  fS) zA Work out the dynamic size of the columns to pass to fmtColumns. )r rrr )rr rrr)Zremainder_columnz ) installed availableextras autoremoveupdatesrecentrr obsoletesobsoletesTuplesZ calcColumns)ryplrZlstrZnpkgZopkgcolumnsrrr_list_cmd_calc_columnshs   r)c Csdd}tjj|}d}x|jjj|dD]}|r>tdd}|jdkrbd|j|j |j f}nd |j|j|j |j f}|j j |j }ttd ||||jfttd |jr|jnd||jfq.WdS) NcSstjdtj|S)Nz%c)timestrftimeZgmtime)xrrr sm_ui_timezsz"print_versions..sm_ui_timeF)rr T0z%s-%s.%sz %s:%s-%s.%sz Installed: %s-%s at %sz Built : %s at %s)r sack rpmdb_sackqueryrfiltermprintZepochversionreleasertermboldrr Z installtimeZpackagerZ buildtime) pkgsbaserr-r0donerrrrrrprint_versionsys    r;cCs>td}x0|jD]$\}}tj|j||d|dqWdS)NzTThe operation would result in switching of module '{0}' stream '{1}' to stream '{2}'rr)r itemsloggerwarningformat)switchedModulesZmsg1Z moduleNameZstreamsrrrreport_module_switchsrAcseZdZdZd fdd Zfffdd ZddZd d Zd d Zd dZ fdddfddZ ddZ ggdfddZ dfdfddZ d!ddZfddZddZZS)"BaseCliz#This is the base class for yum cli.Ncs4|p tjj}tt|j|dtj||j|_dS)N)conf)r rCZConfsuperrB__init__rZOutput)selfrC) __class__rrrEszBaseCli.__init__cstjjrJ|jjsJt|jj}|rJt|t dj tj j d}tj j||j}|jj|}|rjtj||rg}g}d}xF|D]>} | jtjjkr|j| jq| jtjjkrd}|j| jqW|`|s|jj|n|jj|||s|jjs|jr|jjs|jjr|jj r:tjt dj tj j!dn(d|jj"krbtjt dj tj j!d|j#r|jj$s|jj% rt&t dntjt d d S|rD|r:tjt d y|jj'} |j(||jj)| Wn\tj j*k r8} z:tj+j j,t-| } t d d | } t.tj j| WYd d } ~ XnX|j/||jj rRd St0|t1sd|g}tj2gt3|}t4t5|j6|}|d k r|j7j8|gd}tj9jj:|j7|j;}nd }|rt.t.dj<|jj=|t.x.|D]&} | j>t?jj@krtj jt dqW|S)zTake care of package downloading, checking, user confirmation and actually running the transaction. :param display: `rpm.callback.TransactionProgress` object(s) :return: history database transaction ID or None aQIt is not possible to switch enabled streams of a module unless explicitly enabled via configuration option module_stream_switch. It is recommended to rather remove all installed content from the module, and reset the module using '{prog} module reset ' command. After you reset the module, you can install the other stream.)progTFz7{prog} will only download packages for the transaction.ZtestzP{prog} will only download packages, install gpg keys, and check the transaction.zOperation aborted.zNothing to do.NzDownloading Packages:zError downloading packages:z %sr zTransaction failed)Ar r9Z WITH_MODULESrCZmodule_stream_switchdictZ_moduleContainerZgetSwitchedStreamsrAr r?util MAIN_PROG exceptionsErrorZ transactionrZlist_transactionr=infoactionZFORWARD_ACTIONSappendrZBACKWARD_ACTIONSZ_tsZreportRemoveSizeZreportDownloadSizeZ isChangedZ_historygroupenv downloadonlyMAIN_PROG_UPPERZtsflags _promptWantedassumeno userconfirmrZdownload_callback_total_cbZdownload_packagesprogressZ DownloadErrorcliZ indent_blockr r3 gpgsigcheck isinstancerZCliTransactionDisplaylistrDrBdo_transactionhistoryoldZdbZRPMTransactionZ_transjoinZpost_transaction_outputstatelibdnfZTransactionItemState_ERROR)rFZdisplayr@msgZtransZpkg_strZ install_pkgsZrmpkgsZ install_onlyZtsiZtotal_cbeZspecificZerrstrtid)rGrrr^s              zBaseCli.do_transactionc sg}x|D]}j|\}}|dkr(q q |dkrĈjjo@jj }tj sVtjj rl| rltjj t dfdd}yj ||Wqtjj t fk r}z|j t|WYdd}~XqXq |j |q W|rx|D]} tj| qWtjj t ddS)aPerform GPG signature verification on the given packages, installing keys if possible. :param pkgs: a list of package objects to verify the GPG signatures of :raises: Will raise :class:`Error` if there's a problem rrzTRefusing to automatically import keys when running unattended. Use "-y" to override.cs jjS)N)rrX)r,yz)rFrr$sz%BaseCli.gpgsigcheck..NzGPG check FAILED)Z_sig_check_pkgrC assumeyesrWsysstdinisattyr rMrNr Z_get_key_for_package ValueErrorrQstrr=critical) rFr8Zerror_messagesporesulterrmsgZayfnrerdr)rFrr[ s&  " zBaseCli.gpgsigcheckcsXdx:|jjjd|jD]$}|tj}|rtjj|dPqWfdd|j D}|S)zBReturn list of changelogs for package newer then installed versionNrrcs$g|]}dks|dkr|qS)N timestampr).0Zchlog)newestrr =sz-BaseCli.latest_changelogs..) Z_rpmconnZ readonly_tsZdbMatchrrpmZRPMTAG_CHANGELOGTIMEdatetimeZdateZ fromtimestamp changelogs)rFpackageZmiZchangelogtimesZchlogsr)rwrlatest_changelogs3s zBaseCli.latest_changelogscCs4d|djdtjj|dtjj|df}|S)z*Return changelog formatted as in spec filez * %s %s %s ruz%a %b %d %X %YZauthortext)r+r Zi18nr )rFZ changelogZ chlog_strrrrformat_changelogAs  zBaseCli.format_changelogcCst}x&|D]}|j|jp|jgj|q Wxdt|jD]T}||}ttdj dj dd|Dx$|j |dD]}t|j |qzWq.r) rJr source_namerrQsortedkeysr3r r?rar}r)rFZpackagesZbysrpmprZ bin_packagesZchlrrrprint_changelogsIs "zBaseCli.print_changelogsTFc CsR|jd||d}|jjs |jjr@|jd||d}|j|_|j|_|rDt|j|}t|jdkri}|jj j d} | rx>t |jD]0} | j } t jj| r| jr| || j| jf<qW|jj} |jj} |jj|jdd||| | dd |r|j|jt|jdkrDttd x0t |jtjdd D]}|jj|d|d q(W|jpP|jS) z?Check updates matching given *patterns* in selected repository.Zupgrades)reponamer%rr7r r])=znot in)Z outputType highlight_nar(highlight_modeszObsoleting Packages)key)r()returnPkgListsrCr%verboser&r)rrr#r6MODErZlocalPkgospathexistsZverifyLocalPkgrrcolor_update_localcolor_update_remotelistPkgsrr3r operator itemgetterupdatesObsoletesList)rFpatternsrZprint_r{r'Ztyplr( local_pkgs highlightrqZlocalculcurobtuprrr check_updatesUs:    zBaseCli.check_updatescCsr|jj}t|dkr |jnx|D]}|j|q&W|jj|}|dkrn|jj rntd}tjj|dS)ab Upgrade or downgrade packages to match the latest versions available in the enabled repositories. :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage rz4No packages marked for distribution synchronization.N) Z_goalZ req_lengthrZ distro_syncZreq_has_distupgrade_allr r rMrN)rFZuserlistZoldcountpkg_specZcntrdrrrdistro_sync_userlist{s    zBaseCli.distro_sync_userlistc CsJd}xf|D]^}y|j||dd}Wq tjjk rf}z"tjtd|jjj |j WYdd}~Xq Xq Wx|D]}y|j ||dd}Wqrtjj k r}z$td} tj| |jjj |WYdd}~Xqrtjj k r}z"tjtd|jjj |jWYdd}~Xqrtjjk r*YqrXqrW|sFtjjtddS) aaAttempt to take the user specified list of packages or wildcards and downgrade them. If a complete version number is specified, attempt to downgrade them to the specified version :param specs: a list of names or wildcards specifying packages to downgrade :param file_pkgs: a list of pkg objects from local files F)strictTzNo match for argument: %sNzNo package %s available.z6Packages for argument %s available, but not installed.z!No packages marked for downgrade.)Zpackage_downgrader rMZ MarkingErrorr=rOr rr6r7locationZ downgrade_toZPackageNotFoundErrorZPackagesNotInstalledErrorrrN) rFZspecsZ file_pkgsrrrrreargerrrdrrr downgradePkgss,   ( & " zBaseCli.downgradePkgsallc!CsDy$|jjjd}|j||||d}Wn0tjjk rT}zdt|gfSd}~XnXi}i} i} d} |dkrzt|j|} |r|j rxB|j |j |j D],} | j | jf} | |ks| || kr| || <qW|o|jrx8|jD].} | j | jf} | | ks| | | kr| | | <qW|rP|jrPx2t|jD]$}|jtjkr(|| |j |jf<q(W|jj}|jj}|jj}|jj}|jj|j td||| ||||dd}|jj}|jj}|jj}|jj }|jj|jtd || | ||||d d}|jj|j!td || d }|jj|j"td || d }|jj#}|jj$}|jj|jtd|| | ||dd}t%|j&dkr|dkrt%|j&}t'tdxLt|j(t)j*ddD]}|jj+|d| d qWn|jj|j&td|| d }|jj|j,td|| d } t%|r@| dkr@|dkr@|dkr@|dkr@|dkr@|dkr@|dkr@tjjtddS)zJOutput selection *pkgnarrow* of packages matching *patterns* and *repoid*.r7)installed_availablerrNr]zInstalled Packages)>r9 cli_commandscommandr rZZdemandZ DemandSheetdemandsregister_commandZcommandsaliasZ AliasCommandr"ZAutoremoveCommandZcheckZ CheckCommandZcleanZ CleanCommandZ distrosyncZDistroSyncCommandZdeplistZDeplistCommandZ downgradeZDowngradeCommandrRZ GroupCommandr_ZHistoryCommandZinstallZInstallCommandZ makecacheZMakeCacheCommandZmarkZ MarkCommandmoduleZ ModuleCommandZ reinstallZReinstallCommandremoveZ RemoveCommandrepolistZRepoListCommandZ repoqueryZRepoQueryCommandsearchZ SearchCommandshellZ ShellCommandZswapZ SwapCommandZ updateinfoZUpdateInfoCommandZupgradeZUpgradeCommandZupgrademinimalZUpgradeMinimalCommandZ InfoCommandZ ListCommandZProvidesCommandZCheckUpdateCommandZRepoPkgsCommandZ HelpCommand)rFr9rrrrEfsBz Cli.__init__cCs|jj||jr^xJ|jjD]<\}}|jjj||jj|gd}|j||jj |dfqW|j r|jj dd |jj dd|j Dt }yzxt|jD]j\}}|jjj|}|s|jjjr|dkrtd} tjj| ||j||dkr|jq|jqWWnFtjjk rP} z$tj| |jjtjd WYdd} ~ XnXx|D]}tjtd |qXW|jjj } | dkr|jjj!} x,| D]$} |jjj"| }|r|j#j$qW|jj%j&\} |j_'|jjj(j)| t%j*|j|jj%}|jjj(j+|dS) N)Zbaseurlenabler*disablecSsg|] }|dfqS)rr)rvrrrrrxsz(Cli._configure_repos..zUnknown repo: '%s'rzNo repository match: %s)rr),r9Zread_all_reposZ repofrompathr<reposZ add_new_reporC_configure_from_optionsZrepos_edrQrepoinsertrsetZ get_matchingrr r rMZ RepoErroraddrr ConfigErrorr=rp optparser print_helprkexitr>Z_repo_persistorZget_expired_reposrget_repoexpirerZsetup_progress_callbacksZ _ds_callbackrset_progress_barZ CliKeyImportZ_set_key_import)rFoptsZlabelrZ this_repoZnotmatchrZ operationrrdreZ expired_reposrZbarZ key_importrrr_configure_repossL            zCli._configure_reposcCsvtjdjtjjdtjjtjtj j d|j tjtj j d|j j jtjtj j d|j j jtjd|j j jdS)Nz{prog} version: %s)rHz Command: %szInstallroot: %szReleasever: %sz cachedir: %s)r=debugr?r rKrUconstVERSIONlogloggingDDEBUG cmdstringr9rC installroot releasevercachedir)rFrrr_log_essentialss      zCli._log_essentialscCs|j}|jj}|jr.tjjs.tjjt d|j rLx|j D] }d|_ q>W|j s\|jjj rd|jj_ xn|jD]}|jjtjjqpWnL|jrxD|j D]}|jjqWn(|jsx |jD]}|jjtjjqW|jr|jj|jjrdnd|jjddS)Nz[This command has to be run with superuser privileges (under the root user on most systems).TautoF)load_system_repoZload_available_repos)rr9rZ root_userr rKZ am_i_rootrMrNr r{ iter_enabledZload_metadata_other cacheonlyrCvaluesrZsetSyncStrategyrZSYNC_ONLY_CACHEfreshest_metadatarZfresh_metadataZ SYNC_LAZYZsack_activationZ fill_sackrZavailable_repos)rFrrrrrr_process_demandss.    zCli._process_demandscCs|j}|jj|}|dkr~tjtd|tjd|jj j r`tjtdj t j jt j jd|ntjtdj t j jdt|||_tjt jjd|tjt jjd |dS) z,Check that the requested CLI command exists.Nz)No such command: %s. Please use %s --helprzLIt could be a {PROG} plugin command, try: "{prog} install 'dnf-command(%s)'")rHZPROGzRIt could be a {prog} plugin command, but loading of plugins is currently disabled.)rHzBase command: %szExtra commands: %s)rrrr=rpr rkargvr9rCZpluginsr?r rKrLrUrrrr)rFrrr command_clsrrr_parse_commandss      zCli._parse_commandsNc Cstjjj}|j|}|dkr*tjjjn||_|jj|}|j rpt tj j t |jjj|j|jjtjd|jrd|_d|_|jrtj j|_|_yh|jr|jjjd|jjjtjjd|j_|jjj||j|j d|kr|j!|jj_!|jjj"Wntj#j$t%fk rF}z t&j't(d|tjdWYdd}~XnXt)k r}z:d t*t+|t,|j-f}t&j't(d|tjdWYdd}~XnX|j.dk r|j.|jj_.|jjj/ r|j0dkrt&j't(dtjd|j1s|j2r|j0dkrt&j't(dtjd|j3dk r>t4j5t6j7|j3d|jj8|j9d|jj:|j;|j<||jj8|j9d|j0s|jj=tjd||j_>|jj?d|_@x$|jj>D]}|j@d|7_@qW|jAy|jB||Wn tCk rtjdYnX|jDr$|jj=|j0tjd|jjE|j0|}|jFrN|jF|j_Gd|j_H|jIr`|jI|j_I|jJrrd|jj_K|jLrd|jj_L|j0jM|jjN|jjO|jP||jjQ|jjj||j0jR|jjj.rtjSjT|jjj.|jjj.|jjUjV_W|jjjXdkr(|jjjYjZ|jjjXdt[j\ddkrd}x,|jjUj]D]}|j^rZqJd|_^d}qJW|jjj_sd|jj__d}|rt&j`t(ddS)aParse 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 :param option_parser: a class for parsing cli options NrrrTrzConfig error: %srz%s: %sdownloadsystem-upgradereposync modulesynczb--destdir or --downloaddir must be used with --downloadonly or download or system-upgrade command.zconfig-managerz_--enable, --set-enabled and --disable, --set-disabled must be used with config-manager command.<mainZpluginrz%s r)colorz%_pkgverify_level signaturerFzWarning: Enforcing GPG signature check globally as per active RPM security policy (see 'gpgcheck' in dnf.conf(5) for how to squelch this message))rrrr)rr)ar rZaliasesZAliasesZresolve option_parserZ OptionParserrZparse_main_argsr4r3rrr;r9rCZhistory_record_packagesrrkrquietZ debuglevelZ errorlevelrZ VERBOSE_LEVELrZ _set_valueZsystem_cachedirZ PRIO_DEFAULTrr_read_conf_filerrZ_adjust_conf_optionsrMrrnr=rpr IOErrorr roreprfilenameZdestdirrTrZ set_enabledZ set_disabledZ sleeptimer*ZsleeprandomZ randrangeZ add_commandsrZ init_pluginsZ disablepluginZ enablepluginrrrHrrrrhelpZparse_command_argsZ allowerasingZ allow_erasingZ_allow_erasingrZ debugsolverZ debug_solverr%Z pre_configureZpre_configure_pluginsZ_activate_persistorrZconfigure_plugins configurerKZ ensure_dirrrZpkgdirrr6ZreinitryZ expandMacrorZgpgcheckZlocalpkg_gpgcheckr>) rFrrrrrerZforcingrrrrrs                                z Cli.configurecCsBtjjd}|jj}|jd|jd|jd}|jdtjj krht j j | rhtj jtdj||jtjjd|jd}|jdtjj krd}|j}|j||jdd|dkr|jdkrtjj|j}n|dkrtjj|}|dk r||_|jdkrtjtd xd D]}|j|qW|jjj|||S)NconfigZconfig_file_pathzConfig file "{}" does not exist)ZpriorityZreposdirvarsdir/)rzPUnable to detect release version (use '--releasever' to specify release version)rlogdir persistdir)rrr)r rZTimerr9rCZ_check_remote_fileZ_search_inside_installrootZ _get_valueZ _get_priorityZPRIO_COMMANDLINErrisfilerMrr r?readZPRIO_MAINCONFIGZ substitutionsZupdate_from_etcrryZdetect_releaseverrr=r>Zprepend_installroot_loggingZ_setup_from_dnf_conf)rFrZtimerrCrZ from_rootZsubstoptrrrrs6        zCli._read_conf_fileeqcCs|dkr|dkrdSg}|js"|r,|jd|js6|r@|jd|jsJ|rT|jd|js^|rh|jd|jj|||j|j|j |j ddS)zz :param opts: :param cmp_type: string supported "eq", "gte" :param all: :return: Nbugfix enhancement newpackagesecurity)typesadvisorybugzillacvesseverity) r rQr r r r9Zadd_security_filtersrrrr)rFrZcmp_typerr rrr _populate_update_security_filters        z$Cli._populate_update_security_filtercCs4|dk r|jjjj||dk r0|jjjj|dS)z Change minimal logger level for terminal output to stdout and stderr according to specific command requirements @param stdout: logging.INFO, logging.WARNING, ... @param stderr:logging.INFO, logging.WARNING, ... N)r9rZstdout_handlerZsetLevelZstderr_handler)rFstdoutstderrrrrredirect_loggerszCli.redirect_loggercCs.tjjj|}||jj_|jjjj|dS)N) r rZrYZMultiFileProgressMeterr9rrrr)rFZforYrrrredirect_repo_progresss zCli.redirect_repo_progresscCs|jjj}|dkrdS|jjjj|jd}|j}|jdd|}x|D]}||krL|}qLW||krtd|td|dS)N)rr )Z advisory_typez,Security: %s is an installed security updatez-Security: %s is the currently running version)r9r/Zget_running_kernelr1r2rrr3)rFZkernelqZikpkgrrrr_check_running_kernels    zCli._check_running_kernelcCs*t|jjtjjtdj||dS)Nz)argument {}: not allowed with argument {})r3rZ print_usager rMrNr r?)rFZoption_string_1Zoption_string_2rrr_option_conflicts zCli._option_conflictcCs<x6|jD],}||jkr*tjjtd|||j|<qWdS)zRegister a Command. :apizCommand "%s" already definedN)rrr rMrr )rFrrrrrrs  zCli.register_commandcCs|j|jjjr8tjtddjtt |jjj|jjj rhtjtddjtt |jjj xx|jj j D]h}|jrtjtd|j ddjtt |j|j rvtjtd|j ddjtt |j qvW|jjS)a2Call the base command, and pass it the extended commands or arguments. :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage zExcludes in dnf.conf: z, zIncludes in dnf.conf: zExcludes in repo z: zIncludes in repo )rr9rCZ excludepkgsr=rr rarrZ includepkgsrridrrun)rFrrrrrs  " "(,zCli.run)N)N)rN)NN)rrrrErrrrrrrrrkrrrrrrrrrrres$3   -  r)r )OrZ __future__rrrcollections.abcr ImportError collectionsrzrrrrryrkr*rZlibdnf.transactionrcr rZdnf.clirZdnf.i18nr r r Zdnf.cli.aliasesZdnf.cli.commandsZdnf.cli.commands.aliasZdnf.cli.commands.autoremoveZdnf.cli.commands.checkZdnf.cli.commands.cleanZdnf.cli.commands.deplistZdnf.cli.commands.distrosyncZdnf.cli.commands.downgradeZdnf.cli.commands.groupZdnf.cli.commands.historyZdnf.cli.commands.installZdnf.cli.commands.makecacheZdnf.cli.commands.markZdnf.cli.commands.moduleZdnf.cli.commands.reinstallZdnf.cli.commands.removeZdnf.cli.commands.repolistZdnf.cli.commands.repoqueryZdnf.cli.commands.searchZdnf.cli.commands.shellZdnf.cli.commands.swapZdnf.cli.commands.updateinfoZdnf.cli.commands.upgradeZdnf.cli.commands.upgrademinimalZdnf.cli.demandZdnf.cli.formatZdnf.cli.option_parserZdnf.confZdnf.conf.substitutionsZ dnf.constZdnf.db.historyZdnf.exceptionsZ dnf.loggingZ dnf.persistorZ dnf.pluginZdnf.rpmZdnf.sackZdnf.transactionZdnf.utilZ dnf.yum.miscZ getLoggerr=rr)r;rAZBaserBobjectrrrrrs       O__pycache__/aliases.cpython-36.pyc000064400000012474151030066770013040 0ustar003 ft`@sddlmZddlmZddlmZddlZddlZddlm Z ddl Zddl Z ddl Z ddlZddlZe jdZdZejjedZejjed ZGd d d eZGd d d eZdS))absolute_import)unicode_literals)_N) PRIO_DEFAULTdnfz/etc/dnf/aliases.d/z ALIASES.confz USER.confc@s,eZdZddZeddZeddZdS) AliasesConfigcCs$||_tjj|_|jj|jdS)N)_pathlibdnfconfZ ConfigParser_parserread)selfpathr/usr/lib/python3.6/aliases.py__init__*s zAliasesConfig.__init__c CsHtjjd}y|jt|jjddWntk r>YnX|jS)NTmainenabled) r r OptionBoolsetrr ZgetData IndexErrorgetValue)r optionrrrr/s  zAliasesConfig.enabledcCsVtj}d}|jj|s|Sx4|jj|D]$}|jj||}|sBq*|j||<q*W|S)Naliases) collections OrderedDictr Z hasSectionZoptionsrsplit)r resultZsectionkeyvaluerrrr8s zAliasesConfig.aliasesN)__name__ __module__ __qualname__rpropertyrrrrrrr)s rc@sNeZdZddZddZddZddZdd d Zd d ZddZ ddZ d S)AliasescCsFtj|_d|_d|_|jr(d|_dS|j|js:dS|jdS)NTF)rrrr r_disabled_by_environ _load_main _load_aliases)r rrrrGs zAliases.__init__c Cshtjjd}y|jttjd|jStk r:dSt k rbt j t dtjddSXdS)NTZDNF_DISABLE_ALIASESFz@Unexpected value of environment variable: DNF_DISABLE_ALIASES=%s) r r rrrosenvironrKeyError RuntimeErrorloggerwarningr)r rrrrr%Ws  zAliases._disabled_by_environcCsyt|Stk rB}ztjjtd||fWYdd}~Xn:tk rz}ztjjtd||fWYdd}~XnXdS)NzParsing file "%s" failed: %szCannot read file "%s": %s)rr+r exceptions ConfigErrorrIOError)r rerrr _load_confds"zAliases._load_confcCsVy|jt|_|jj|_Wn6tjjk rP}ztjt d|WYdd}~XnXdS)NzConfig error: %s) r2ALIASES_CONF_PATHr rrr.r/r,debugr)r r1rrrr&ns  zAliases._load_mainNcCs|dkr.y |j}Wntjjk r,dSXxf|D]^}y"|j|}|jrX|jj|jWq4tjjk r}ztj t d|WYdd}~Xq4Xq4WdS)NzConfig error: %s) _dropin_dir_filenamesrr.r/r2rrupdater,r-r)r filenamesfilenamer r1rrrr'us   zAliases._load_aliasescstjjttjjtgfdd}g}yPtjjts@tjtx4ttj tD]"}||r^qP|j tjj t|qPWWn2t t fk r}ztjj|WYdd}~XnXtjjtr|j t|S)Ncs|kp|jdp|jd S)N..conf.CONF)r:r;) startswithendswith)r8)ignored_filenamesrr_ignore_filenames z7Aliases._dropin_dir_filenames.._ignore_filename)r(rbasenamer3ALIASES_USER_PATHexistsALIASES_DROPIN_DIRmkdirsortedlistdirappendjoinr0OSErrorrr.r/)r r?r7fnr1r)r>rr5s       zAliases._dropin_dir_filenamescs:gg_fddfdd|}j|S)NcsNd}x&|D]}|r |ddkr P|d7}q Wj|d|7_||dS)Nr-)prefix_options)argsZnumarg)r rr store_prefixs  z&Aliases._resolve..store_prefixc s|}| s*|djks*|djdrry.j|djdrV|ddd|d<Wntk rlYnX|S|dkrtjjtdj|dj|d}|r||ddS|ddSdS)Nr\rLz"Aliases contain infinite recursion) rr<poprrr.ErrorrrG)rNsuffixZcurrent_alias_result)r stackrP subresolverrrVs&  z$Aliases._resolve..subresolve)rM)r rNrTr)r rUrPrVr_resolves  zAliases._resolvecCsP|jrLy|j|}Wn6tjjk rJ}ztjtd|WYdd}~XnX|S)Nz%s, using original arguments.)rrWrr.rSr,errorr)r rNr1rrrresolves "zAliases.resolve)N) r r!r"rr%r2r&r'r5rWrYrrrrr$Fs   /r$)Z __future__rrZdnf.i18nrrZdnf.clirZdnf.conf.configrZdnf.exceptionsZ libdnf.confr Zloggingr(Zos.pathZ getLoggerr,rCrrHr3rAobjectrr$rrrrs     __pycache__/__init__.cpython-36.pyc000064400000000755151030066770013155 0ustar003 ft`@sDddlmZddlZGdddejjZddlmZddl m Z dS))absolute_importNc@seZdZdZdS)CliErrorzCLI Exception. :apiN)__name__ __module__ __qualname____doc__rr/usr/lib/python3.6/__init__.pyrsr)Cli)Command) Z __future__rZdnf.exceptionsZdnf exceptionsErrorrZ dnf.cli.clir Zdnf.cli.commandsr rrrr s  __pycache__/__init__.cpython-36.opt-1.pyc000064400000000755151030066770014114 0ustar003 ft`@sDddlmZddlZGdddejjZddlmZddl m Z dS))absolute_importNc@seZdZdZdS)CliErrorzCLI Exception. :apiN)__name__ __module__ __qualname____doc__rr/usr/lib/python3.6/__init__.pyrsr)Cli)Command) Z __future__rZdnf.exceptionsZdnf exceptionsErrorrZ dnf.cli.clir Zdnf.cli.commandsr rrrr s  __pycache__/utils.cpython-36.opt-1.pyc000064400000006141151030066770013510 0ustar003 ft`@sdZddlmZddlmZddlmZddlmZddlZ ddl Z ddl Z ddl Z e j e jdZe jdZd d Zd d Zd dZddZdS)z/Various utility functions, and a utility class.)absolute_import)unicode_literals) format_number)_N SC_CLK_TCKdnfcCs t|tS)zConvert a number of jiffies to seconds. How many jiffies are in a second is system-dependent, e.g. 100 jiffies = 1 second is common. :param jiffies: a number of jiffies :return: the equivalent number of seconds )int_USER_HZ)Zjiffiesr /usr/lib/python3.6/utils.pyjiffies_to_secondssr cCsj|dkr0d|d |d d|dd|dfS|d krVd|d |dd|dfSd|d|dfS) aReturn a human-readable string representation of the length of a time interval given in seconds. :param seconds: the length of the time interval in seconds :return: a human-readable string representation of the length of the time interval <z%d day(s) %d:%02d:%02dz %d:%02d:%02dz %02d:%02diiQiiQiiir )Zsecondsr r r seconds_to_ui_time)s    rcCst|}tjjd| s:tjjd s:tjjd| r>dSi}td|v}xn|D]f}|ddkrhqV|ddjdd}t|dkrqVtjj |dd |d<|dj ||d j j <qVWWdQRXd |krdSd |krdSd}td4}x,|D]$}|j d rt|td d}PqWWdQRX|dkr6dStd|^}|j j}|t|d|d<tdtdtdtdtddj|dtd|d<WdQRX|S)z!Return info dict about a process.z/proc/%d/statusz /proc/statz /proc/%d/statN z: z kBrvmrssvmsizezbtime  start_timeZRunningZSleepingZUninterruptibleZZombiezTraced/Stopped)RSDZTZUnknownstaterr)rospathexistsopensplitlenrutilZrtrimstriplower startswithreadr rget)pidpsZ status_filelinedataZ boot_timeZ stat_fileZps_statr r r get_process_info<sJ   *      r.cCst|}|s$td}tj||dStd||df}tjd|tjtdtt|ddtt|d dtttj|d }tjtd tj j |d |tjtd |d dS)z0Output information about process holding a lock.z=Unable to find information about the locking process (PID %d)Nz$ The application with PID %d is: %snamez%sz Memory : %5s RSS (%5sB VSZ)rirrz Started: %s - %s agoz State : %sr) r.rloggerZcriticalrrrtimerr$Znormalize_time)r*r+msgZagor r r show_lock_ownerls    r3)__doc__Z __future__rrZdnf.cli.formatrZdnf.i18nrZdnf.utilrZloggingrr1sysconf sysconf_namesr Z getLoggerr0r rr.r3r r r r s      0__pycache__/progress.cpython-36.opt-1.pyc000064400000010777151030066770014226 0ustar003 ft`@spddlmZddlmZmZddlmZddlmZddl m Z ddl Z ddl Z ddl Z Gddde jjZdS) )unicode_literals) format_number format_time) _term_width)unicode)timeNc@sreZdZdZejjdejjdejjdejj diZ e j dddfd d Z d d ZdddZddZddZddZdS)MultiFileProgressMeterz"Multi-file download progress meterZFAILEDZSKIPPEDZMIRRORZDRPMg333333?g?g@cCsp||_||_||_||_d|_d|_tjj|_d|_ d|_ d|_ g|_ i|_ d|_d|_d|_d|_d|_dS)zCreates a new progress meter instance update_period -- how often to update the progress bar tick_period -- how fast to cycle through concurrent downloads rate_average -- time constant for average speed calculation rN)fo update_period tick_period rate_averageunknown_progres total_drpmsysstdoutisatty done_drpm done_files done_sizeactivestate last_time last_sizerate total_files total_size)selfr r r r r/usr/lib/python3.6/progress.py__init__&s" zMultiFileProgressMeter.__init__cCstjjd||jdS)NZ write_flush)dnfutilZ_terminal_messengerr )rmsgrrrmessage?szMultiFileProgressMeter.messagercCsF||_||_||_d|_d|_d|_g|_i|_d|_d|_ d|_ dS)Nr) rrrrrrrrrrr)rrrZ total_drpmsrrrstartBszMultiFileProgressMeter.startcCst}t|}t|j}t|}||jkrD|df|j|<|jj||j|\}}||f|j|<|j||7_||j|j kr||j kr||_ |j |dS)Nr) rrint download_sizerrappendrrr r_update)rpayloaddonenowtextZtotalr$oldrrrprogressSs    zMultiFileProgressMeter.progresscCsJ|jrj||j}|j|j}|dkrj|dkrj||}|jdk rdt||jd}|||jd|}||_||_|j|_|jsdS|jt||j t |j}|j dkrd|j d}t |jdkr|d|j t |j7}d||j |f}|jo|j rt|j |j|j}nd}d|jr,t|jndt|j|f} tt | } | d d } | d kr0|j r|jd |j } t|j| d |j d \}} d |d| }d| | || f} | | d 8} nj|jd}d} |dkrdn|}d|d | }d| || f} | | d 8} |jd| kr*|jdnd|_|jd| | || fdS)Nrz%dz-%dz (%s/%d): %sz--:--z %5sB/s | %5sB %9s ETA z--- d=-z%3d%% [%-*s]%s z [%-*s]%sz%-*.*s%s)rrrrminr rrr%r lenrrrrrrdivmodr r#)rr+Z delta_timeZ delta_sizerZweightr,nZtime_etar"leftZblZpctpZbarrrrr(gsX        zMultiFileProgressMeter._updatec Cst}}t|}t|j}d}|tjjkr.n|tjjkrJ|jd7_nt||j kr|j j |\}}|j j |||8}|j d7_ |j|7_n(|tjjkr|j d7_ |j|7_|r*|tjjkr|jdkrd|j||j|j|f} nd|j||f} tt| d} d| | |f} nl|jdkrHd|j |j|f}t||d} dtt|| t|t| f} tt| } d | | || f} |j| |j r|j|dS) Nrr/z[%s %d/%d] %s: z [%s] %s: z%s%-*s z (%d/%d): %sgMbP?z %5sB/s | %5sB %9s z%-*.*s%s)rrr%r&r callback STATUS_MIRROR STATUS_DRPMrrpoprremoverrSTATUS_ALREADY_EXISTSr STATUS_2_STRrr9rmaxrfloatrr#r() rr)ZstatusZerr_msgr$r+r,sizer*r"r<ZtmrrrendsH          zMultiFileProgressMeter.endN)r)__name__ __module__ __qualname____doc__r r>Z STATUS_FAILEDrCr?r@rDrstderrrr#r$r.r(rHrrrrrs  5r)Z __future__rZdnf.cli.formatrrZ dnf.cli.termrZ dnf.pycomprrrZ dnf.callbackr Zdnf.utilr>ZDownloadProgressrrrrrs    __pycache__/completion_helper.cpython-36.opt-1.pyc000064400000020733151030066770016063 0ustar003 g/ @s<ddlZddlZddlZddlZddZddZGdddejjj j Z Gdd d ejjj j ZGd d d ejjjjZGd d d ejjjZGdddejjjjZGdddejjjjZGdddejjjjZGdddejjjjZddZ e!dkr8ye ej"ddWn e#k r6ej$dYnXdS)Ncstfdd|S)Ncst|jS)N)str startswith)k)kw'/usr/lib/python3.6/completion_helper.pysz#filter_list_by_kw..)filter)rZlstr)rrfilter_list_by_kwsr cCstdd|DS)NcSsg|] }t|qSr)r).0xrrr !sz%listpkg_to_setstr..)set)pkgsrrrlistpkg_to_setstr srcs,eZdZfddZddZddZZS)RemoveCompletionCommandcstt|j|dS)N)superr__init__)selfargs) __class__rrr$sz RemoveCompletionCommand.__init__cCsd|jj_d|jj_dS)NFT)clidemands root_usersack_activation)rrrr configure's z!RemoveCompletionCommand.configurecCs,x&tj|j|jjD]}tt|qWdS)N)ListCompletionCommand installedbaseopts pkg_specsprintr)rpkgrrrrun+szRemoveCompletionCommand.run)__name__ __module__ __qualname__rrr# __classcell__rr)rrr#s rcs,eZdZfddZddZddZZS)InstallCompletionCommandcstt|j|dS)N)rr(r)rr)rrrr1sz!InstallCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrravailable_reposr)rrrrr4s  z"InstallCompletionCommand.configurecCsNttj|j|jj}ttj|j|jj}x||D]}tt|q6WdS)N) rrrrrr availabler!r)rrr*r"rrrr#9s     zInstallCompletionCommand.run)r$r%r&rrr#r'rr)rrr(0s r(cs,eZdZfddZddZddZZS)ReinstallCompletionCommandcstt|j|dS)N)rr+r)rr)rrrrCsz#ReinstallCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrrr)r)rrrrrFs  z$ReinstallCompletionCommand.configurecCsNttj|j|jj}ttj|j|jj}x||@D]}tt|q6WdS)N) rrrrrr r*r!r)rrr*r"rrrr#Ks     zReinstallCompletionCommand.run)r$r%r&rrr#r'rr)rrr+Bs r+csHeZdZfddZddZeddZeddZed d ZZ S) rcstt|j|dS)N)rrr)rr)rrrrTszListCompletionCommand.__init__cCs|j}|jj}|jj}t|dkrH|d|krHtdjt|d|n|dkr`|j|j |}n||dkrx|j |j |}nd|dkr|j |j |}nLt |j |j |}t |j|j |}||B}|stdjt|d|dSx|D]}tt |qWdS)N rr*updatesr)Z pkgnarrowsrZpackagesZpackages_actionlenr!joinr rrr*r.rr)rsubcmdsractionrr*rr"rrrr#Ws& zListCompletionCommand.runcCs |jjjjdj|ddS)Nz{}*r) name__glob)sackqueryrfiltermformat)rargrrrrnszListCompletionCommand.installedcCs |jjjjdj|ddS)Nz{}*r)r3)r4r5r*r6r7)rr8rrrr*rszListCompletionCommand.availablecCs|jdj|dgddS)Nz{}*rF)Zprint_)Z check_updatesr7)rr8rrrr.vszListCompletionCommand.updates) r$r%r&rr# staticmethodrr*r.r'rr)rrrSs    rcs$eZdZfddZddZZS)RepoListCompletionCommandcstt|j|dS)N)rr:r)rr)rrrr|sz"RepoListCompletionCommand.__init__cCs|j}|jdkr>tdjt|jddd|jjjDnn|jdkrvtdjt|jddd|jjjDn6|jdkrtdjt|jdd d|jjjDdS) Nenabledr-rcSsg|] }|jqSr)id)r rrrrr sz1RepoListCompletionCommand.run..ZdisabledcSsg|]}|js|jqSr)r;r<)r r=rrrr sallcSsg|] }|jqSr)r<)r r=rrrr s) rZ repos_actionr!r0r ZreposrZ iter_enabledr>)rrrrrr#s   zRepoListCompletionCommand.run)r$r%r&rr#r'rr)rrr:{s r:cs,eZdZfddZddZddZZS)UpgradeCompletionCommandcstt|j|dS)N)rr?r)rr)rrrrsz!UpgradeCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrrr)r)rrrrrs  z"UpgradeCompletionCommand.configurecCs,x&tj|j|jjD]}tt|qWdS)N)rr.rrr r!r)rr"rrrr#szUpgradeCompletionCommand.run)r$r%r&rrr#r'rr)rrr?s r?cs,eZdZfddZddZddZZS)DowngradeCompletionCommandcstt|j|dS)N)rr@r)rr)rrrrsz#DowngradeCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrrr)r)rrrrrs  z$DowngradeCompletionCommand.configurecCs0x*tj|j|jjjD]}tt|qWdS)N)rr*rrr Z downgradesr!r)rr"rrrr#szDowngradeCompletionCommand.run)r$r%r&rrr#r'rr)rrr@s r@cs$eZdZfddZddZZS)CleanCompletionCommandcstt|j|dS)N)rrAr)rr)rrrrszCleanCompletionCommand.__init__cCs0tjjjjj}tdjt|j j d|dS)Nr-r,) dnfrcommandscleanZ _CACHE_TYPESkeysr!r0r rtype)rr1rrrr#szCleanCompletionCommand.run)r$r%r&rr#r'rr)rrrAs rAc Cstjjj}tjj|}|ddkrP|jgg|tdjt|d|jdS|jj |j t |j t |j t |j t|j t|j t|j t|j t|j|y |jWn&ttjjfk rtjdYnXdS)NrZ_cmdsr-r,)rBrZBaseCliZCliZ init_pluginsr!r0r Z cli_commandsclearZregister_commandrr(r+rr:r?r@rArr#OSError exceptionsErrorsysexit)rrrrrrmains(              rM__main__r,)%Zdnf.exceptionsrBZdnf.cliZdnf.cli.commands.cleanrKr rrrCremoveZ RemoveCommandrZinstallZInstallCommandr(Z reinstallZReinstallCommandr+Z ListCommandrZrepolistZRepoListCommandr:ZupgradeZUpgradeCommandr?Z downgradeZDowngradeCommandr@rDZ CleanCommandrArMr$argvKeyboardInterruptrLrrrrs& (  __pycache__/utils.cpython-36.pyc000064400000006141151030066770012551 0ustar003 ft`@sdZddlmZddlmZddlmZddlmZddlZ ddl Z ddl Z ddl Z e j e jdZe jdZd d Zd d Zd dZddZdS)z/Various utility functions, and a utility class.)absolute_import)unicode_literals) format_number)_N SC_CLK_TCKdnfcCs t|tS)zConvert a number of jiffies to seconds. How many jiffies are in a second is system-dependent, e.g. 100 jiffies = 1 second is common. :param jiffies: a number of jiffies :return: the equivalent number of seconds )int_USER_HZ)Zjiffiesr /usr/lib/python3.6/utils.pyjiffies_to_secondssr cCsj|dkr0d|d |d d|dd|dfS|d krVd|d |dd|dfSd|d|dfS) aReturn a human-readable string representation of the length of a time interval given in seconds. :param seconds: the length of the time interval in seconds :return: a human-readable string representation of the length of the time interval <z%d day(s) %d:%02d:%02dz %d:%02d:%02dz %02d:%02diiQiiQiiir )Zsecondsr r r seconds_to_ui_time)s    rcCst|}tjjd| s:tjjd s:tjjd| r>dSi}td|v}xn|D]f}|ddkrhqV|ddjdd}t|dkrqVtjj |dd |d<|dj ||d j j <qVWWdQRXd |krdSd |krdSd}td4}x,|D]$}|j d rt|td d}PqWWdQRX|dkr6dStd|^}|j j}|t|d|d<tdtdtdtdtddj|dtd|d<WdQRX|S)z!Return info dict about a process.z/proc/%d/statusz /proc/statz /proc/%d/statN z: z kBrvmrssvmsizezbtime  start_timeZRunningZSleepingZUninterruptibleZZombiezTraced/Stopped)RSDZTZUnknownstaterr)rospathexistsopensplitlenrutilZrtrimstriplower startswithreadr rget)pidpsZ status_filelinedataZ boot_timeZ stat_fileZps_statr r r get_process_info<sJ   *      r.cCst|}|s$td}tj||dStd||df}tjd|tjtdtt|ddtt|d dtttj|d }tjtd tj j |d |tjtd |d dS)z0Output information about process holding a lock.z=Unable to find information about the locking process (PID %d)Nz$ The application with PID %d is: %snamez%sz Memory : %5s RSS (%5sB VSZ)rirrz Started: %s - %s agoz State : %sr) r.rloggerZcriticalrrrtimerr$Znormalize_time)r*r+msgZagor r r show_lock_ownerls    r3)__doc__Z __future__rrZdnf.cli.formatrZdnf.i18nrZdnf.utilrZloggingrr1sysconf sysconf_namesr Z getLoggerr0r rr.r3r r r r s      0__pycache__/main.cpython-36.pyc000064400000012241151030066770012333 0ustar003 ft`f@sPdZddlmZddlmZddlmZddlmZddlmZddl m Z ddl m Z dd l mZdd l mZdd lZdd lZdd l Zdd lZdd l Zdd lZdd lZdd lZdd lZdd lZdd lZdd lZdd lZdd lZejd Zd dZddZ eee fddZ!ddZ"ddZ#ddZ$d ddZ%e&dkrLe%ej'dd ddd S)!z4 Entrance point for the yum command line interface. )print_function)absolute_import)unicode_literals)Conf)Cli) OptionParser)ucd)show_lock_owner)_NdnfcCs&tjtjjdddtjt|dS)NT)exc_info)loggerlogr loggingSUBDEBUGcriticalr)er/usr/lib/python3.6/main.py ex_IOError2srcCs6tjtjjddd|jdk r2tjtdt|dS)Nr T)r z Error: %sr) rrr rrvaluerr r)rrrrex_Error8s rcCsy6tjjtjjj|}t||||SQRXWntjjk rr}ztj |j t |j dSd}~XnLtjj k r}ztj |j dSd}~Xntjjk r}zdSd}~Xntjjk r}zt|Sd}~Xntjk r$}ztj tdt|dSd}~Xntjjk r\}ztj tdt|dSd}~Xnbtk r}zt|Sd}~Xn>tk r}z tj djt|jtddSd}~XnXdS)Nrz Error: %sz{}: {}z Terminated.)r Zi18nZ setup_stdoutcliZBaseCli_main exceptionsZProcessLockErrorrrrr pid LockError DepsolveErrorErrorrhawkey Exceptionr rlibdnferrorIOErrorrKeyboardInterruptformattype__name__)argsZ conf_class cli_classZoption_parser_classbaserrrrmain?s4    r.cCsb|jj||}y|jttt||Wn(ttfk rV}zt|Sd}~XnXt ||S)z2Run the dnf program from a command line interface.N) Z_loggingZ _presetupZ configurelistmaprr&OSErrorrcli_run)r-r+r,Z option_parserrrrrrr\s rc,Csy td}WnFtk rR}z*|jtjkrBtjtdtjdWYdd}~Xn X|j y |j Wn@t j j k rYn(ttfk r}zt|Sd}~XnX|jjryt||}Wnt j jk r}zt|d}|jj r|jjddr|tdjd7}|jjjrN|s<|td jd 7}n|td jd 7}|jjjr|jjjd }|t jjkr|s|td jd7}n|tdjd7}|rtjdj|WYdd}~XnX|r|S|jj |jj!S)N.z8No read/execute access in current directory, moving to //r T)Z availablez?try to add '{}' to command line to replace conflicting packagesz--allowerasingz.try to add '{}' to skip uninstallable packagesz --skip-brokenz' or '{}' to skip uninstallable packagesbestz7try to add '{}' to use not only best candidate packagesz--nobestz0 or '{}' to use not only best candidate packagesz({}))"openr&errnoZEACCESrrr oschdircloseZrunr rrr1rdemands resolvingr r allow_erasingZ_goalZproblem_conflictsr(r-Zconfstrictr5Z _get_priorityZPRIO_MAINCONFIGinfocommandZrun_transactionZsuccess_exit_status)rr-frretmsgZpriorrrr2msT             r2cCs |jdkr&|j|jjtjtd|jjg}|jj dk rN|j |jj y|j |dWnt j jk r}ztjt|dSd}~Xnvt jjk r}z$x|jj|D]}tj|qWdSd}~Xn4tk r}zt|Sd}~XnXtjtddS)z9Perform the depsolve, download and RPM transaction stage.NzDependencies resolved.)Zdisplayrz Complete!r)Z transactionZresolver;r=rr?r r@Z run_resolvedZtransaction_displayappendZdo_transactionr rZCliErrorr%rrZTransactionCheckErrorZget_error_outputrr&r)rr-ZdisplaysexcerrrCrrrrr<s(   r<FcCst|}|rtj||S)apCall one of the multiple main() functions based on environment variables. :param args: command line arguments passed into yum :param exit_code: if *exit_code* is True, this function will exit python with its exit code when it has finished executing. Otherwise, it will return its exit code. :return: the exit code from dnf.yum execution )r.sysexit)r+ exit_codeZerrcoderrr user_mains  rJ__main__rT)rI)F)(__doc__Z __future__rrrZdnf.confrZ dnf.cli.clirZdnf.cli.option_parserrZdnf.i18nrZ dnf.cli.utilsr r Zdnf.clir Zdnf.exceptionsZ dnf.loggingZdnf.utilr7r"Z libdnf.errorr$rr8Zos.pathrGZ getLoggerrrrr.rr2r<rJr*argvrrrrsB          5  __pycache__/demand.cpython-36.opt-1.pyc000064400000003013151030066770013573 0ustar003 ft` @s0ddlmZGdddeZGdddeZdS))unicode_literalsc@s&eZdZddZdddZddZdS) _BoolDefaultcCs ||_d|jjt|f|_dS)Nz__%s%x)default __class____name__id _storing_name)selfrr /usr/lib/python3.6/demand.py__init__sz_BoolDefault.__init__NcCs |j}|j|kr||jS|jS)N)__dict__rr)r objZobjtypeobjdictr r r __get__s  z_BoolDefault.__get__cCs8|j}|j|kr*||j}||kr*td|||j<dS)NzDemand already set.)r rAttributeError)r rvalrZ current_valr r r __set__#s   z_BoolDefault.__set__)N)r __module__ __qualname__r rrr r r r rs rc@speZdZdZedZedZedZedZedZ edZ dZ edZ edZ edZedZdZedZdS) DemandSheetzHCollection of demands that different CLI parts have on other parts. :apiFTrN)rrr__doc__rZ allow_erasingZavailable_reposZ resolvingZ root_userZsack_activationZload_system_repoZsuccess_exit_statusZ cacheonlyZfresh_metadataZfreshest_metadataZ changelogsZtransaction_displayZplugin_filtering_enabledr r r r r+srN)Z __future__robjectrrr r r r s __pycache__/term.cpython-36.opt-1.pyc000064400000026773151030066770013334 0ustar003 ft`f9@sxddlmZddlmZddlZddlZddlZddlZddlZddl Z ddl Z d ddZ d ddZ Gd d d e ZdS) )absolute_import)unicode_literalsNc CsBy(d}tj|tj|}tjd|d}|Stk r<dSXdS)z Get the real terminal width ZabcdefghshhhhrN)fcntlZioctltermiosZ TIOCGWINSZstructunpackIOError)fdZbufretr /usr/lib/python3.6/term.py_real_term_widthsrcCs&tdd}|sdS|dkrdS|SdS)z@ Compute terminal width falling to default 80 in case of troubler)r PN)r)r Ztwr r r _term_width)s  rc @seZdZdZdZeddZeddZdddd Zd d d d dddddZ d d d d dddddZ dddddddZ dddddd d!d"dZ d#d$d%d&d'd(d)d*dZ d+d,ZdFd/d0ZdGd1d2Zd3d4Zd5d6Zd7d8ZdHd:d;Zdd?Zd@dAZdBdCZdDdEZd-S)ITermz>A class to provide some terminal "UI" helpers based on curses.TcCstS)N)r)selfr r r @sz Term.cCstS)N)r)rr r r rAsZsmulZrevZsgr0) underlinereversenormalrr)blackbluegreencyanredmagentayellowwhite)rr"r r$rr#r!r%zzzzz(B)boldblinkdimrrrzzzzzzzzzzzzzzzzcCs|j|_|j|_|j|_dS)N)_Term__ansi_forced_MODEMODE_Term__ansi_forced_FG_COLORFG_COLOR_Term__ansi_forced_BG_COLORBG_COLOR)rr r r Z __forced_initzszTerm.__forced_initNautoc CsLd|_d|_|dkr |jdSddddddd|_ddddddddd|_ddddddddd|_|dkrvd |_dS|stj}|jsd |_dSyt j |j d Wnt k rd |_dSXt j |_t jd |_x8|jD].}|}||jkr|j|}|j||j|<qW|jd jd }|r\x4|jjD]&\}}t j||jpNd|j|<q2W|jdjd }|rx8|jjD]*\}}t j||jpd}||j|<q~W|jdjd } | rx4|jjD]&\}}t j| |jpd|j|<qW|jdjd } | rHx8|jjD]*\}}t j| |jp6d} | |j|<qWdS)a Reinitializes the :class:`Term`. :param term_stream: the terminal stream that the :class:`Term` should be initialized to use. If *term_stream* is not given, :attr:`sys.stdout` is used. :param color: when to colorize output. Valid values are 'always', 'auto', and 'never'. 'always' will use ANSI codes to always colorize output, 'auto' will decide whether do colorize depending on the terminal, and 'never' will never colorize. TalwaysNr&)r'r(r)rrr)rrr r!r"r#r$r%ZneverF)r linesZsetfzutf-8ZsetafZsetbZsetab)_Term__enabledr3_Term__forced_initr+r-r/sysstdoutisattycursesZ setuptermfileno ExceptionZtigetstr _ctigetstrZtigetnum_Term__cap_names _tigetstrencode _Term__colorsitemsZtparmdecode_Term__ansi_colors) r term_streamcolorcap_namemodeZset_fgvalZ set_fg_ansiZfg_colorZset_bgZ set_bg_ansiZbg_colorr r r reinits        ""z Term.reinitcCs|j||dS)N)rI)rrDrEr r r __init__sz Term.__init__cCs0|j|p d}tjj|r"|j}tjdd|S)Nr&z \$<\d+>[/*]?)r<dnfZpycompZ is_py3bytesrBresub)rrFZcapr r r r>s zTerm._tigetstrcCs|j|t||jdS)zColorize string with colorr)r+str)rrEsr r r rEsz Term.colorcCs |jd|S)zMake string bold.r')rE)rrOr r r r'sz Term.boldFc s\|js |S|stj}fdd}x4|D],}||} |rFtj| tj} tj| ||}q(W|S)aSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with *end*, then return the modified string. For example:: >>> yt = Term() >>> yt.sub('spam and eggs', 'x', 'z', ['and']) 'spam xandz eggs' This is particularly useful for emphasizing certain words in output: for example, calling :func:`sub` with *beg* = MODE['bold'] and *end* = MODE['normal'] will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. Note, however, that the :func:`sub_mode`, :func:`sub_bold`, :func:`sub_fg`, and :func:`sub_bg` methods provide convenient ways to access this same emphasizing functionality. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :param escape: a function that accepts a string and returns the same string with problematic characters escaped. By default, :func:`re.escape` is used. :param ignore_case: whether case should be ignored when searching for matches :return: *haystack* with *beg* prefixing, and *end* postfixing, occurrences of the strings in *needles* cs|jS)N)group)match)begendr r rszTerm.sub..)r4rLescapetemplateIrM) rhaystackrRrSneedlesrTZ ignore_caseZrenderZneedleZpatr )rRrSr rMs  zTerm.subcKs|j|||jd|f|S)aOSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with self.MODE['normal'], then return the modified string. If *beg* is an ANSI escape code, such as given by self.MODE['bold'], this method will return *haystack* with the formatting given by the code only applied to the strings in *needles*. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with *beg* prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* r)rMr+)rrWrRrXkwdsr r r sub_norm&sz Term.sub_normcKs|j||j||f|S)aTSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE[*mode*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given *mode*. :param haystack: the string to be modified :param mode: the mode to set the matches to be in. Valid values are given by self.MODE.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE[*mode*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* )rZr+)rrWrGrXrYr r r sub_mode9sz Term.sub_modecKs|j|d|f|S)aSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE['bold'], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. :param haystack: the string to be modified :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE['bold'] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* r')r[)rrWrXrYr r r sub_boldMsz Term.sub_boldcKs|j||j||f|S)acSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.FG_COLOR[*color*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given color. :param haystack: the string to be modified :param color: the color to set the matches to be in. Valid values are given by self.FG_COLOR.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.FG_COLOR[*color*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* )rZr-)rrWrErXrYr r r sub_fg_sz Term.sub_fgcKs|j||j||f|S)aSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.BG_COLOR[*color*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* highlighted in the given background color. :param haystack: the string to be modified :param color: the background color to set the matches to be in. Valid values are given by self.BG_COLOR.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.BG_COLOR[*color*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* )rZr/)rrWrErXrYr r r sub_bgssz Term.sub_bg)Nr0)Nr0)NF)__name__ __module__ __qualname____doc__r4propertyZ real_columnscolumnsr=r@rCr*r,r.r5rIrJr>rEr'rMrZr[r\r]r^r r r r r4sr    f   -r)r)r)Z __future__rrr9Z dnf.pycomprKrrLrr6rrrobjectrr r r r s   __pycache__/option_parser.cpython-36.pyc000064400000040660151030066770014301 0ustar003 ft`4]@sddlmZddlmZddlmZddlZddlZddlZddl Zddl Zddl Z ddl Z ddlZddlZe jdZGdddejZGdd d ejZdS) )unicode_literals)_) _parse_specsNdnfcseZdZfddZZS)MultilineHelpFormattercs"d|kr|jStt|j||S)N ) splitlinessuperr _split_lines)selftextwidth) __class__#/usr/lib/python3.6/option_parser.pyr 'sz#MultilineHelpFormatter._split_lines)__name__ __module__ __qualname__r __classcell__rr)rrr&srcseZdZdZd.fdd ZddZGdddejZGd d d ejZ Gd d d ej Z Gd ddejZ GdddejZ GdddejZGdddejZGdddejZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd/fd*d+ Zd0fd,d- ZZS)1 OptionParserz5ArgumentParser like class to do things the "yum way".Tcs>tt|jdtdd|_d|_|j|r:i|_t|_ dS)NF)add_helpZformatter_class) r r__init__rcommand_positional_parser command_group_add_general_options _cmd_usageset _cmd_groups)r Z reset_usage)rrrr/s zOptionParser.__init__cCs&|jtjtd|tjddS)zOutput an error message, and exit the program. This method overrides standard argparser's error so that error output goes to the logger. :param msg: the error message to output zCommand line error: %sN) print_usageloggerZcriticalrsysexit)r msgrrrerror9szOptionParser.errorc@seZdZddZdS)zOptionParser._RepoCallbackcs@|dkr dndt||j}|jfddtjd|DdS)Nz --disablerepodisableenablec3s|]}|fVqdS)Nr).0x) operationrr Hsz6OptionParser._RepoCallback.__call__..z \s*[,\s]\s*)getattrdestextendresplit)r parser namespacevaluesopt_strlr)r)r__call__Es z#OptionParser._RepoCallback.__call__N)rrrr5rrrr _RepoCallbackDsr6c@seZdZddZdS)z OptionParser._RepoCallbackEnablecCs$|jj|ddft|d|dS)Nrr&Zreponame)repos_edappendsetattr)r r0r1r2r3rrrr5Ksz)OptionParser._RepoCallbackEnable.__call__N)rrrr5rrrr_RepoCallbackEnableJsr:cs$eZdZdZdZfddZZS)zOptionParser._SplitCallbackzN Split all strings in seq, at "," and whitespace. Returns a new list. z \s*[,\s]\s*csDd}x:tj|j|D](}|s |r8ttj|j||||d}qWdS)NTF)r.r/SPLITTERr r_SplitCallbackr5)r r0r1r2r3firstval)rrrr5Ts z$OptionParser._SplitCallback.__call__)rrr__doc__r;r5rrr)rrr<Osr<c@seZdZdZddZdS)z%OptionParser._SplitExtendDictCallbackz[ Split string at "," or whitespace to (key, value). Extends dict with {key: value}.c Cshy"|jd\}}| s| r tWn,tk rNtd|}tj||YnXt||j}|||<dS)N,zbad format: %s)r/ ValueErrorrargparseZ ArgumentErrorr+r,) r r0r1r2r3keyr>r#Zdctrrrr5bs   z.OptionParser._SplitExtendDictCallback.__call__N)rrrr?r5rrrr_SplitExtendDictCallback_srDc@seZdZdZddZdS)zOptionParser._SetoptsCallbackzY Parse setopts arguments and put them into main_ and repo_.c Cs|jd}t|dkr*tjtd|dSt|dkrJtjtd|dS|\}}|jd}|d kr|d|} ||dd}t|dr|j} ni} | j| ij|gj |t |d|j | n:t|d r|j } ni} | j|gj |t |d |j | dS) N=z'Setopt argument has multiple values: %sz Setopt argument has no value: %s.r repo_setoptsZrepo_ main_setoptsZmain_) r/lenr ZwarningrrfindhasattrrH setdefaultr8r9r,rI) r r0r1r2r3valskvZperiodrepoZrepooptsZmainoptsrrrr5ps,       z&OptionParser._SetoptsCallback.__call__N)rrrr?r5rrrr_SetoptsCallbackmsrSc@seZdZddZdS)z'OptionParser.ParseSpecGroupFileCallbackcCst||dS)N)r)r r0r1r2r3rrrr5sz0OptionParser.ParseSpecGroupFileCallback.__call__N)rrrr5rrrrParseSpecGroupFileCallbacksrTcs$eZdZfddZddZZS)zOptionParser.PkgNarrowCallbackcsi|_y&x dD]}|||j|<||=qWWn6tk rb}ztd|jj|fWYdd}~XnXg|d<ttj|j||dS)Nchoicesdefaultz"%s() missing mandatory argument %s)rUrV) pkgnarrowKeyError TypeErrorrrr rPkgNarrowCallbackr)r argskwargsrPe)rrrrs "z'OptionParser.PkgNarrowCallback.__init__cCsV|jd}| s"|d|jdkr.|jd}n |jd}t|||t||j|dS)NZ_actionrrUrV)r,rWpopr9)r r0r1r2r3Z dest_actionZnarrowrrrr5s     z'OptionParser.PkgNarrowCallback.__call__)rrrrr5rrr)rrrZs rZc@seZdZddZdS)zOptionParser.ForceArchActioncCsd|_||_dS)NT)Z ignorearchZarch)r r0r1r2r3rrrr5sz%OptionParser.ForceArchAction.__call__N)rrrr5rrrrForceArchActionsr_c Cs|jtdjtjjd}|jdddddtdd |jd d d d dtdd|jddd dtdd|jdd dtdjtjjdd|jdtddd|jdddgdtdd|jd d!dd"td#d$|jd%d&g|jtd'd(d)|jd*d+g|jtd,d(d)|jd-dtd.d/|jd0d1g|jtd2d3|jd4d5d dtd6d|jd7d8d9d d:td;d<|jd=d dtd>d|j }|jd?d@d dAdtdBdC|jdDd!dAtdEd<|jdFdGdHd dtdId|jdJdKdLt ddMtdNdO|jdPdQdRdSdtdTt dU|jdVd dtdWd|jdXdYd dtdZd|jd[d\dt td]d^|jd_dd`d tdajtjj ddb|jdcdtdddedf|jdgdhd dtdid|jdjd dtdkd|jdl|j dmgdntdodp|j }|jdq|j dmgdntdrdp|jdsdtdndu|jgtdvdw|j }|jdxdydzd td{db|jd|dyd}d td~db|jdddgd|jtddd|jddgd|jtddnd|jdi|j dtdd|jdd!ddtdd$|jdd!ddtdd$|jdddtdd|jddd tdd|jdddtdddd|jdddtdddd|jddddtdd|jddd dytdd|jdddtdd|jdd tdd|jdd tdd|jdd tdd|jdd tdd|jdddg|jtdd3|jddgd|jtddb|jddgd|jtdƒdb|jddddddggd|jtdʃdˍ|jddtj|jttjjjtd΃dύ|jddtjdҍdS)z0 Standard options known to all dnf subcommands. zGeneral {prog} options)progz-cz--configZconfig_file_pathNz [config file]zconfig file location)r,rVmetavarhelpz-qz--quietquiet store_truezquiet operation)r,actionrVrbz-vz --verbosezverbose operation)rerVrbz --versionzshow {prog} version and exitz --installrootzset install rootz[path])rbraz--nodocs store_constZnodocsZtsflagszdo not install documentations)reconstr,rbz --nopluginsZ store_falseZpluginszdisable all plugins)rerVr,rbz--enablepluginZ enablepluginzenable plugins by namez[plugin])r,rVrerbraz--disablepluginZ disablepluginzdisable plugins by namez --releaseverz:override the value of $releasever in config and repo files)rVrbz--setoptZsetoptsz%set arbitrary config and repo options)r,rVrerbz --skip-brokenZ skip_brokenz.resolve depsolve problems by skipping packagesz-hz--helpz --help-cmdrbzshow command help)rer,rbz--allowerasingz;allow erasing of installed packages to resolve dependenciesz-bz--bestZbestz8try the best available package versions in transactions.)rer,rVrbz--nobestz2do not limit the transaction to the best candidatez-Cz --cacheonlyZ cacheonlyz2run entirely from system cache, don't update cachez-Rz --randomwaitZ sleeptimez [minutes]zmaximum command wait time)r,typerVrarbz-dz --debuglevelZ debuglevelz [debug level]zdebugging output level)r,rarVrbrhz --debugsolverz)dumps detailed solving results into filesz--showduplicatesZshowdupesfromreposz2show duplicates, in repos, in list/search commandsz-ez --errorlevelzerror output level)rVrhrbz --obsoletesZ obsoleteszenables {prog}'s obsoletes processing logic for upgrade or display capabilities that the package obsoletes for info, list and repoquery)rVr,rerbz--rpmverbosityzdebugging output level for rpmz[debug level name])rVrbraz-yz --assumeyesz*automatically answer yes for all questionsz --assumenoz)automatically answer no for all questionsz --enablerepor7z[repo]z]Enable additional repositories. List option. Supports globs, can be specified multiple times.)rer,rVrarbz --disablerepozSDisable repositories. List option. Supports globs, can be specified multiple times.z--repoz--repoidrRzUenable just specific repositories by an id or a glob, can be specified multiple times)rar,rerVrbz--enableFZ set_enabledz>enable repos with config-manager command (automatically saves)z --disableZ set_disabledz?disable repos with config-manager command (automatically saves)z-xz --excludez --excludepkgsZ excludepkgsz exclude packages by name or globz [package])rVr,rerbraz--disableexcludesz--disableexcludepkgsZdisable_excludeszdisable excludepkgsz--repofrompathz [repo,path]zolabel and path to an additional repository to use (same path as in a baseurl), can be specified multiple times.)rVrerarbz--noautoremoveZclean_requirements_on_removez7disable removal of dependencies that are no longer usedz --nogpgcheckZgpgcheckz5disable gpg signature checking (if RPM policy allows)z--colorZcolorzcontrol whether color is used)r,rVrbz --refreshZfreshest_metadataz2set metadata as expired before running the command)r,rerbz-4Z ip_resolvezresolve to IPv4 addresses onlyZipv4)r,rVrbrergz-6zresolve to IPv6 addresses onlyZipv6z --destdirz --downloaddirZdestdirz!set directory to copy packages toz--downloadonlyZ downloadonlyzonly download packagesz --commentZcommentzadd a comment to transactionz--bugfixz,Include bugfix relevant packages, in updates)rerbz --enhancementz1Include enhancement relevant packages, in updatesz --newpackagez0Include newpackage relevant packages, in updatesz --securityz.Include security relevant packages, in updatesz --advisoryz --advisoriesZadvisoryz=Include packages needed to fix the given advisory, in updatesz--bzz--bzsZbugzillaz7Include packages needed to fix the given BZ, in updatesz--cvez--cvesZcvesz8Include packages needed to fix the given CVE, in updatesz--sec-severityz --secseverityZCriticalZ ImportantZModerateZLowZseverityzDInclude security relevant packages matching the severity, in updates)rUrVr,rerbz --forcearchZARCHz Force the use of an architecture)rar,rerUrbcommand?)nargsrb)add_argument_grouprformatrutilZMAIN_PROG_UPPER add_argumentr<rSZadd_mutually_exclusive_groupint MAIN_PROGr6rDrBZSUPPRESSr_sortedZrpmZ _BASEARCH_MAPkeys)r Z general_grpZ best_groupZ repo_groupZ enable_grouprrrrs:                                                                     z!OptionParser._add_general_optionscCsHtjj|j}tjj|jd}||jkrD||f|j|<|jj|dS)z- store usage info about a single dnf command.rN)rZi18nZucdsummaryaliasesrradd)r cmdgrouprtnamerrr_add_cmd_usageds  zOptionParser._add_cmd_usagecCs&x t|jD]}|j||qWdS)z store name & summary for dnf commands The stored information is used build usage information grouped by build-in & plugin commands. N)rr2rz)r Zcli_cmdsrxrwrrr add_commandslszOptionParser.add_commandscCstdtdd}dtjj}xfd D]^}||jkr4q$|d||7}xsz1OptionParser.cmd_add_argument..)allrhrror)r r[r\r)r rrszOptionParser.cmd_add_argumentcCs`xZ|D]R}y|jdWqtk rV}z"tjjtd|t|fWYdd}~XqXqWdS)Nzutf-8zCannot encode argument '%s': %s)encodeUnicodeEncodeErrorr exceptionsZ ConfigErrorrstr)r r[rr]rrr_check_encodings  zOptionParser._check_encodingcCs|j||j|\}}|S)N)rparse_known_args)r r[r1Z _unused_argsrrrparse_main_argss zOptionParser.parse_main_argscCs2|j||j|\}}|jj||}||_|jS)N)rrr parse_argsZopts)r rir[r1Z unused_argsrrrparse_command_argss  zOptionParser.parse_command_argsNcs,|jr|j|jj7_tt|j|dS)N)r_actionsr rr)r Zfile_)rrrrszOptionParser.print_usagecsd|rH|j s|jj|jkr$|j||j|jj7_|jj|jjn |j |_ t t |j dS)N)rrrrrrZ_action_groupsr8rrr~r r print_help)r ri)rrrrs  zOptionParser.print_help)T)N)N)rrrr?rr$rBZActionr6r:Z _AppendActionr<rDrSrTrZr_rrzr{rrrrrrrrrrr)rrr,s.  ;  r)Z __future__rZdnf.i18nrZdnf.utilrrBZdnf.exceptionsrZdnf.rpmZ dnf.yum.miscZloggingZos.pathosr.r!Z getLoggerr Z HelpFormatterrrrrrrrs    __pycache__/output.cpython-36.opt-1.pyc000064400000156715151030066770013725 0ustar003 ft`Z@sdZddlmZddlmZddlmZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZmZddlmZmZmZmZmZmZmZmZddlmZmZmZm Z m!Z!dd l"m#Z#dd l$m%Z%ddl&Z'ddl(Z'ddl)Z'ddl*Z'ddl+Z'ddl,Z'ddlZ'ddl-Z'ddl.Z'ddl/Z'e j0d Z1d d Z2Gddde3Z4Gddde'j5j6Z7Gddde'j5j8Z9Gddde#Z:dddZ;dS)z"Handle actual output from the cli.)absolute_import)print_function)unicode_literalsN) format_number format_time)_C_P_ucdfill_exact_width textwrap_fill exact_widthselect_short_long)xrange basestringlongunicode sys_maxsize)TransactionDisplay)MergedTransactionWrapperdnfcCsrtj|ftjd}t|}|d}| |}|s@tjd|}n|rR|jd|t|}tt|f|g|S)N)r) itertoolschainrepeatlenextenditerlistzip)Z cols_countZlabellstleftZ lst_lengthZ right_countZ missing_itemsZlst_iterr#/usr/lib/python3.6/output.py_spread_in_columns6s r%c @s eZdZdZdmZejdZddZddZ d d Z d d Z d dZ e ddZeddZeddZdnddZe ddZddZdoddZdpd!d"Zdqd#d$Zd%d&Zd'd(Zd)d*Zdrd,d-Zdsd.d/Zdtd0d1Zidifd2d3Zdud4d5Zd6d7Z d8d9Z!d:d;Z"dd?Z$d@dAZ%dvdBdCZ&dwdDdEZ'dxdFdGZ(dHdIZ)dJdKZ*dydLdMZ+dNdOZ,dPdQZ-dRdSZ.dTdUZ/dVdWZ0dzdXdYZ1d{dZd[Z2ge3fd\d]Z4gfd^d_Z5e6d`e6d`e6dae6dbe6dce6dde6dee6dfe6dge6dhe6didj Z7gfdkdlZ8dS)|Outputz+Main output class for the yum command line. z ^\*{0,2}/cCs$||_||_tjjj|_d|_dS)N)confbaserclitermZTermprogress)selfr*r)r#r#r$__init__IszOutput.__init__cCs0|jj}dd|}|jt||d}|||fS)Nz%s=r')r,columns fmtColumnsr )r.col_datarowZ term_widthZruleheaderr#r#r$_bannerOs zOutput._bannerc Cszdd|dD}xF|D]>}x8t|D],\}}||}t|}|j|dd||<q&WqW|j|ddd}tttj|S)NcSsg|] }tqSr#)dict).0rr#r#r$ Vsz&Output._col_widths..rrz )indent) enumeraterget calcColumnsrmapoperatorneg) r.rowsr3r4ivalZcol_dctZlengthcolsr#r#r$ _col_widthsUs zOutput._col_widthscCs(d}d}|snt|t s$|dkr2|jjd}n|dkr|St|}t||||d}|jddkr||dkrt|||d d}|S) zReturn a key value pair in the common two column output format. :param key: the key to be formatted :param val: the value associated with *key* :return: the key value pair formatted in two columns for output r'rZz: )riZinitial_indentZsubsequent_indent rr(z ...: )r r,r_rr r count)r.keyrCZkeylenrDZnxtrUr#r#r$ fmtKeyValFills zOutput.fmtKeyValFillr0cCsht|}|jjd}t|}||dkr6|d}}n$|||d}|||t|}d|||fS)aFormat and return a section header. The format of the header is a line with *name* centered, and *fill* repeated on either side to fill an entire line on the terminal. :param name: the name of the section :param fill: the character to repeat on either side of *name* to fill an entire line. *fill* must be a single character. :return: a string formatted to be a section header rZz%s %s %s)r r,r1r r)r.rwZfillrDZname_lenZbegrpr#r#r$ fmtSections   zOutput.fmtSectionc sdd}fdd}g}j|\}}tdtddtdd}|j||d ||j|f|jrv|j|td |jtdtdd tdd }|j|||j|j|td |jtdtdd tdd}|j|||j tdtddtdd}|j||t t |j |j|td|j tdtddtdd}|j|||j|jrjj|} | r|j|td| jjr>|j|td|j|j|tdtjj|j|jr|j|tdtjj|jjj|} | r>yt| jj} Wntk r"d} YnX|j|tdj| tdtddtdd}|j|||j |j!r|j|tdt"|j!|j|td|j#tdtddtdd}|j|||j$dj%|S)zPrint information about the given package. :param pkg: the package to print information about :param highlight: highlighting options for the name of the package cSsdjt|dddt|gS)Nr' :)joinr str)rrCr#r#r$format_key_valsz)Output.infoOutput..format_key_valcsjt|ddd|pdS)Nrz : r)rr )rrC)r.r#r$format_key_val_fillsz.Output.infoOutput..format_key_val_fillrshortNamerz%s%s%sZEpochVersionZReleaseArch ArchitectureSizeZSourceRepo Repositoryz From repoZPackagerZ Buildtimez Install timeNz Installed byZSummaryZURLZLicenseZ Descriptionr)&rPrrr`rwZepochrversionreleaserxrfloat_sizeZ sourcerpmrepoid _from_systemrXZrepor)verboseZpackagerrutilZnormalize_timeZ buildtimeZ installtimeZ package_dataint_itemZgetInstalledBy ValueError_pwd_ui_usernamesummaryurlr license descriptionr) r.r|rMrrZ output_listrNrOrZ history_repoZ history_pkguidr#)r.r$ infoOutputsh                   zOutput.infoOutputc Cs|\}}|dk rV|jj}|jtjkr,|jj}|j|||d|j||d|jjddS|j}d|j |j f}|j } t d|| ||fdS) a{Print a simple string that explains the relationship between the members of an update or obsoletes tuple. :param uotup: an update or obsoletes tuple. The first member is the new package, and the second member is the old package :param changetype: a string indicating what the change between the packages is, e.g. 'updates' or 'obsoletes' :param columns: a tuple containing information about how to format the columns of output. The absolute value of each number in the tuple indicates how much space has been allocated for the corresponding column. If the number is negative, the text in the column will be left justified, and if it is positive, the text will be right justified. The columns of output are the package name, version, and repository N)r1rMr'r)r1r:rMz%s.%sz%-35.35s [%.12s] %.10s %-20.20sz ) r)color_update_remotereponamehawkeyZSYSTEM_REPO_NAMEcolor_update_localrcolor_update_installedZ compactPrintrwrxrr{) r.ZuotupZ changetyper1Z changePkgZinstPkgZchiZ c_compactZ i_compactZc_repor#r#r$updatesObsoletesLists   zOutput.updatesObsoletesListc Csl|dkrht|dkr`td|t}|dkrbi}x"|D]} | |t| t| j<q' - highlighting used when the package has a higher version number :return: number of packages listed rinforwnevrarz%sFznot inrGr0>rF    zOutput.userconfirmcCs~|jjjj}|jjjj}i}xPtjtt|dD]6}||kr^||d||<q@||kr@||d||<q@W|S)Nrr) rYquery installedZ _name_dict availablerrrr )r.sectionsrrrfpkg_namer#r#r$_pkgs2name_dictszOutput._pkgs2name_dictc Csi}i}x~tjtt|dD]d}|j|}|dkr8q tt|t|j}tt|j}|j|dd||<|j|dd||<q W||fS)Nrr) rrrr r<r r GRP_PACKAGE_INDENTr) r.r name_dictZ nevra_lengthsZ repo_lengthsrr|Znevra_lZrepo_lr#r#r$_pkgs2col_lengthss zOutput._pkgs2col_lengthscCs$x|D]}td|j|fqWdS)Nz%s%s)r{r)r. pkg_namesrwr#r#r$_display_packagess zOutput._display_packagescCspxj|D]b}y ||}Wn(tk r>td|j|fwYnXd}|jsR|jj}|j|d|j||dqWdS)Nz%s%sFT)r}r:rMr1)KeyErrorr{rrr)Zcolor_list_available_installr)r.rrr1rwr|rMr#r#r$_display_packages_verboses  z Output._display_packages_verbosec Csldd}tdtd|j|jj}|r@ttdt|j|jr`ttdt|jp\d|jrxttd|jtd ||j ftd ||j ftd ||j ftd ||j ff}|r0|j |}|j||}|j|}|d  |d f}xp|D].\}} t| dkrqt||j| ||qWn8x6|D].\}} t| dkrPq6t||j| q6WdS)zOutput information about the packages in a given group :param group: a Group object to output information about cSstdd|DS)Ncss|] }|jVqdS)N)rw)r8r|r#r#r$ sz?Output.display_pkgs_in_groups..names..)r])packagesr#r#r$namessz,Output.display_pkgs_in_groups..namesrz Group: %sz Group-Id: %sz Description: %srz Language: %sz Mandatory Packages:z Default Packages:z Optional Packages:z Conditional Packages:rrN)r{rui_namer)rr idui_descriptionZ lang_onlyZmandatory_packagesZdefault_packagesZoptional_packagesZconditional_packagesrrr=rrr) r.grouprrrrZ col_lengthsr1 section_namerr#r#r$display_pkgs_in_groupss8   zOutput.display_pkgs_in_groupscCsdd}ttd|j|jjr8ttdt|j|jr\t|jpJd}ttd|td||jftd||j ff}x0|D](\}}t |d krqt||j |qWd S) zOutput information about the packages in a given environment :param environment: an Environment object to output information about cSstdd|DS)Ncss|] }|jVqdS)N)rw)r8rr#r#r$r szFOutput.display_groups_in_environment..names..)r])groupsr#r#r$rsz3Output.display_groups_in_environment..nameszEnvironment Group: %sz Environment-Id: %srz Description: %sz Mandatory Groups:z Optional Groups:rN) r{rrr)rr rrZmandatory_groupsZoptional_groupsrr)r.Z environmentrrrrrr#r#r$display_groups_in_environments z$Output.display_groups_in_environmentcsVdfdd fdd}jjr4d}ndjjf}j|jpRd}r|d krjjjj|d d }t||d krjj }|sd Stt d j d}d} xXt |D]J} j| krd } qˆj | krt d } | | |d dd }qˆj| kr,t d} | | |ddd }qˆj| krVt d} | | |ddd }q|| |rhd }qt d} xjD]} t| } tj| | r| | |ddd }n`| jd} t dtfdd| Dr| jd}n| }tj| |rx| | |ddd }qxWqWt|| gsLx*t |D]} t d} | | |ddq*Wtd S)aOutput search/provides type callback matches. :param po: the package object that matched the search :param values: the information associated with *po* that matched the search :param matchfor: a list of strings to be highlighted in the output :param verbose: whether to output extra verbose information :param highlight: highlighting options for the highlighted matches Fcsd|sttdt|pd}|dkr(dSr>j|dd}|rTtj||n t||dS)Nz Matched from:rT) ignore_case)r{rr rSr)ritemZprinted_headline can_overflow)rMmatchforr.r#r$print_highlighted_key_item's  z8Output.matchcallback..print_highlighted_key_itemcsTjj|sdStd}d}x2jD](}tj||r$|||p@|ddd}q$W|S)NFzFilename : %s)rT)FILE_PROVIDE_REmatchrfilesfnmatch)r printed_matchrZ file_matchfilename)porr.r#r$print_file_provides4s   z1Output.matchcallback..print_file_providesz%s : z%s.%s : rNT)rzRepo : %szDescription : )rzURL : %szLicense : %szProvide : %srz=<>c3s|]}|kVqdS)Nr#)r8char)possibler#r$rpsz'Output.matchcallback..zOther : %s)F)r)ZshowdupesfromreposrwrxrrZcolor_search_matchrSr{rrrrrrrZprovidesrrrKany)r.rrrrrMrrorZ name_matchrrZprovideZ first_provideZitem_newr#)rMrrrrr.r$ matchcallbacksp           zOutput.matchcallbackcCs|j|||ddS)aqOutput search/provides type callback matches. This will output more information than :func:`matchcallback`. :param po: the package object that matched the search :param values: the information associated with *po* that matched the search :param matchfor: a list of strings to be highlighted in the output T)r)r)r.rrrr#r#r$matchcallback_verboses zOutput.matchcallback_verbosec Csd}d}d}d}x|D]}yrt|j}||7}y|jr@||7}Wntk rVYnX|s^wyt|j}Wntk rYnX||7}Wqtk rd}td} tj| PYqXqW|s|rtjtdt |||krtjtdt |||rtjtdt |dS) zReport the total download size for a set of packages :param packages: a list of package objects :param installonly: whether the transaction consists only of installations rFTz2There was an error calculating total download sizezTotal size: %szTotal download size: %szInstalled size: %sN) rrZverifyLocalPkg ExceptionZ installsizerloggererrorrr) r.rZ installonlytotsizeZlocsizeZinsizerr|sizeror#r#r$reportDownloadSizesD          zOutput.reportDownloadSizec Csrd}d}xL|D]D}y|j}||7}Wqtk rPd}td}tj|PYqXqW|sntjtdt|dS)zmReport the total size of packages being removed. :param packages: a list of package objects rFTz-There was an error calculating installed sizezFreed space: %sN)rrrrrrr)r.rrrr|rror#r#r$reportRemoveSizes    zOutput.reportRemoveSizec Cs*|sdSg}g}|jr$|jtdxJ|jD]@}t|j|}|j|}|rR|jn|} |jtdd| |q,W|j r|jtdx@|j D]6}t|j |}|j j |j} |jtdd| |qW|r |j |} x$|D]} |j|jt| | dqW|j| tdtdddf|d d <d j|S) Nz+Marking packages as installed by the group:r@z)Marking packages as removed by the group:r'ZGroupPackagesrrr)Z new_groupsr`rrZadded_packagesZ _group_by_idrrr%Zremoved_groupsZremoved_packagesrr<rEr2r r6r) r.compsrXrhoutrAZgrp_idZpkgsZ group_objectZgrp_namer3r4r#r#r$list_group_transactions.     $zOutput.list_group_transactioncQ s tjtjBtjBtjBtjBtjB}t}t}|dkr\}}x2t+|D]&}|j&d||fddddddfqWqW|j&| |ft!t'j j(j,j*}|rt d} g}xF|D]>\}}x2t+|D]&}|j&d||fddddddfqWqW|j&| |ft!t'j j(j-j*}|rW|j&| |fj j1j7j3}"|"rt d$} g}x |"j4D]}|j&||qW|j&| |fj j1j7j5}#|#rt d%} g}x |#j4D]}|j&||qW|j&| |fj j1j7j6}$|$rNt d&} g}x |$j4D]}|j&||q(W|j&| |fj8j9 rvj j:j;|@rvg}j j|&}'d/d0|D}|j&|'|fg}x*t!|j*D]\}(}%| ||| |%g} qWt d1}'j j8j?rN|'d}'n |'t d2}'d3d0|D}|j&|'|fj@jA})|d4 rˆj j(jB rˆj j1oj j1j7pj j1j2 rdS|d4i|d5|d6ig}d| ddd7g}*jC|d8|*d9|d:}*|*\}+} },}-}.tD|*d7}/|)|/kr&|)n|/})tE|+td;d<td=d<}0tE| td;d>td=d?}1tE|,td;d@td=d@}2tE|-td;dAtd=dB}3tE|.td;dCtd=dC}4dDdE|)jF|0|+ f|1| f|2|, f|3|- f|4|.ffd.dE|)fg}5x|D]\} }| rdF| }6x|D]\}7}8}9}:};}<}=|7|+ |=f|8| f|9|, f|:|- f|;|.ff}*jF|*d.dG}>jGj8jH\}?}@xBt!|<D]6}AdHt dIdJ}B|B|?|AjI|@|AjJ|AjKf;}B|>|B7}> qrW|6|>}6 q W|r|5j&|6qW|5j&t dKdE|)t dLtL|jtL|jtL|jtL|jdft dMtL|jdft dNtL|jtL|jtL|jdft dOtL|jdft dPtL|tL|dff}Cd}Dd}Ed}Fd}Gx|CD]\} }H}I|H r|I r qtMd|5j&|>|P|E|HdU|F|Jf|G|I|Ofn$dV}>|5j&|>|P|E|Fd.|G|I|Ofn&|H r$dW}>|5j&|>tQ| |D|E|H|Jf q$Wdj>|5S)Xz]Return a string representation of the transaction in an easy-to-read format. N)rvrrcs|j\}}}}} |j} |j} t|j} |dkr2d}|jrBjj} n|jrRjj } njj } |j ||| | | || fxRdt |fdt | fdt | ffD],\}}||j |d|||d7<qWt|t |}|S)NZnoarchrrrrr)Zpkgtupryrzrrrr)rZ _from_cmdlinerrr`r setdefaultmax)linesrca_widr obsoletesraerrryrrhirf)r.r#r$ _add_lines"   ,z*Output.list_transaction.._add_linez Installing group/module packageszInstalling group packagesrZ InstallingZ UpgradingZ ReinstallingzInstalling dependencieszInstalling weak dependenciesZRemovingzRemoving dependent packageszRemoving unused dependenciesZ DowngradingcSs|jS)N)r|)xr#r#r$4sz)Output.list_transaction..)rzInstalling module profilesz%s/%srzDisabling module profileszEnabling module streamszSwitching module streamsz%s -> %srzDisabling moduleszResetting modulescSs&|j}|r|ntdddddddfS)Nz r)ZgetNamer)rrwr#r#r$ format_lineqsz,Output.list_transaction..format_linezInstalling Environment GroupszUpgrading Environment GroupszRemoving Environment GroupszInstalling GroupszUpgrading GroupszRemoving GroupsT)Zreport_problems transactioncss|]}t||fVqdS)N)r)r8r|r#r#r$rsz*Output.list_transaction..z--bestz--allowerasingzSSkipping packages with conflicts: (add '%s' to command line to force their upgrade)r'cSsg|]}|dddqS)Nrrr[)rr#)r8rBr#r#r$r9sz+Output.list_transaction..z,Skipping packages with broken dependencies%sz or part of a groupcSsg|]}|dddqS)Nrrr[)rr#)r8rBr#r#r$r9srrrz rZ)r:r1rdrerZPackagerrrrrrrz %s %s %s r0z%s: rz Z replacingz %s%s%s.%s %s z Transaction Summary %s InstallUpgradeZRemove DowngradeZSkiprzDependent packagezDependent packagesz%s %*d %s (+%*d %s) z%-*sz%s %s ( %*d %s) z %s %*d %s )RrZUPGRADEZ UPGRADE_ALLZ DISTUPGRADEZDISTUPGRADE_ALLZ DOWNGRADEINSTALLrrrZ _make_listsr*Z WITH_MODULESrrrZupgradedZ reinstalledZinstalled_groupZ installed_depZinstalled_weakZerasedZ erased_depZ erased_cleanZ downgradedactionlibdnfrZTransactionItemAction_OBSOLETEDrZ getReplacedByrrr]ZFORWARD_ACTIONSZTransactionItemAction_REMOVEr<r|r`r7Z_moduleContainerZgetInstalledProfilesr^rZgetRemovedProfilesZgetEnabledStreamsZgetSwitchedStreamsZgetDisabledModulesZgetResetModulesZ_historyenvZ _installedrZ _upgradedZ_removedrr)ZbestZ_goalactionsZ_skipped_packagesZ_allow_erasingrZupgrade_group_objects_upgrader,r1Z isChangedr=rarr2rPrrwrxryrr r rrr )Qr.rreZforward_actionsZskipped_conflictsZskipped_brokenZ list_bunchZ pkglist_linesrcrrZ ins_group_msgrZpkglistrZreplacestsirBZ obsoletedZinstalledProfilesrwZprofilesZprofileZremovedProfilesZenabledStreamsstreamZswitchedStreamsZdisabledModulesZ resetModulesrZinstall_env_grouprZupgrade_env_groupZremove_env_groupZ install_groupZ upgrade_groupZ remove_groupr|ZrecommendationsZskip_strrZ output_widthr1Zn_widZv_widZr_widZs_widZ real_widthZ msg_packageZmsg_archZ msg_versionZmsg_repositoryZmsg_sizerZtotalmsgrrryrrrrrorNrOZobspoZappendedZ summary_dataZmax_msg_actionZ max_msg_countZ max_msg_pkgsZmax_msg_depcountrZdepcountZmsg_pkgsZlen_msg_actionZ len_msg_countZ len_msg_pkgsZlen_msg_depcountZ msg_deppkgsZ action_msgr#)r.r$list_transactions$         ,,.               $                   zOutput.list_transactionc sfdd}|sdSg}g}|jdj|x|D]}|jt|q2Wxd D]}|||}|rNPqNW|szjjd  g}xD|r|dt|} |jd jjt| ||t|d}q|W|S)Ncst||krgSjj|dd}|dkr0gSdg|}d}x`|D]X}t|||krt|||}||krtgS||8}t|||<|d7}|t|;}qDWx8tt|D](}||||7<||d9<qW|S)zb Work out how many columns we can use to display stuff, in the post trans output. rrZrr[)rr,r1r\)msgsnumr"Zcol_lensrgrorh)r.r#r$ _fits_in_colsKs(    z+Output._pto_callback.._fits_in_colsrz{}:r rr(rZz {})rrrr rr(rZ)r`formatrr,r1rr2r ) r.rZtsisrrrrrrDZ current_msgsr#)r.r$ _pto_callbackHs&    zOutput._pto_callbackcCstjj|j||jS)z{ Return a human-readable summary of the transaction. Packages in sections are arranged to columns. )rrZ_post_transaction_outputr*r)r.rr#r#r$post_transaction_outputzszOutput.post_transaction_outputcCs@d}|jjdkr6tjjjtjd}tjjjtjd|_|tfS)z_Set up the progress callbacks and various output bars based on debug level. NrZ)Zfo) r)Z debuglevelrr+r-ZMultiFileProgressMetersysstdoutDepSolveProgressCallBack)r. progressbarr#r#r$setup_progress_callbackss  zOutput.setup_progress_callbackscCsz|dkr dS|jj}tjd|tdtj|}dt||t|t|f}tt d|t ||}tj|dS)a!Outputs summary information about the download process. :param remote_size: the total amount of information that was downloaded, in bytes :param download_start_timestamp: the time when the download process started, in seconds since the epoch rN-g{Gz?z %5sB/s | %5sB %9s ZTotal) r,r1rrrtimerrr rr)r.Z remote_sizeZdownload_start_timestampriZdl_timeror#r#r$download_callback_total_cbs  z!Output.download_callback_total_cbcCst}t}d}xD|D]<}|jtjjtjjfkr2q|j|j|j|j|d7}qWt |dkrt|dj t |fS|dj t |fS)Nrrz, r) rrrrZTransactionItemAction_UPGRADEDZ TransactionItemAction_DOWNGRADEDr action_nameZ action_shortrrr]r)r.ZhpkgsrZ actions_shortrr|r#r#r$_history_uiactionss     zOutput._history_uiactionsc st|trfdd|DS|dks.|dkrftd}tdd|}dk r^t|kr^|}t|Sdd }yrtjt|}|t|jd d }t|j }d ||f}dk rt|krd |||f}t|krd|}|St k rt|SXdS)Ncsg|]}j|qSr#)r)r8u)limitr.r#r$r9sz+Output._pwd_ui_username..zZSystemr'cWs|j|}|sdS|dS)zf Split gives us a [0] for everything _but_ '', this function returns '' in that case. rr)rK)textargsrUr#r#r$ _safe_split_0s z.Output._pwd_ui_username.._safe_split_0;rZz%s <%s>z %s ... <%s>z<%s>)r*r+) rIrrrr pwdgetpwuidrZpw_gecosZpw_namer) r.rr)Zloginidrwr.userfullnameZ user_namer#)r)r.r$rs*    zOutput._pwd_ui_usernamec Csj|jj|}|jjdkr"ddg}nV|jjdkr6dg}nBt}d}d}x2|D]*}|d7}|jdkrh|d7}|j|jqJWd}t|dkrt d} |j j } | dkrt j j jd} | dkrd } | d kr| d nd } n t d } d } t|tt d ddt| | | tt dddtt dddtt dddfd"| dddddd} td| d}|dkrlt|}x|D]}t|dkr|jpd} n|j|jd } t| } tjdtj|j} |j|j\}}t| | | } t|dd}d}}|jdkrd}}n"|jrd}}n|jr&d}}|jr2d}|jr>d }t||j| | ||fd!||fqrWdS)#zOutput a list of information about the history of yum transactions. :param tids: transaction Ids; lists all transactions if empty ZusersrrZZcommandsrNz%s | %s | %s | %s | %sz Command lineO7z User nameZIDrz Date and timersz Action(s)ZAlteredrr(r#z%6u | %s | %-16.16s | %s | %4uTrz%Y-%m-%d %H:%Mr'*#Errz%s%s )rXoldr)Zhistory_list_viewrcmdlinerloginuidrrr,r_rr+Z_real_term_widthr{r reversedrr r$strftime localtime beg_timestampr'rc return_codeZ is_outputaltered_lt_rpmdbaltered_gt_rpmdbtid)r.tidsreverse transactionsZuidsdoneZblanksrfmtrwZ real_colsZ name_widthZ table_widthZtmrZuiactsZrmarkZlmarkr#r#r$historyListCmdsp                 zOutput.historyListCmdcCst|}|jj}|dkr8tjtdtjjtd|j }|j }g}|sz|jjdd}|dk r|j |j |j |n |jj |}|stjtdtjjtdd \}} d} d} |rt|}|j\}} x|D]} |dk o| j |kr|jj} | jt| d}d}| j |krL| j | krL| dkr} t td | | |jdk r(|jrt td!|jdnt td!|jt|ttfrvt} xD|D],}|| krVqD| j|t td"|qDWnt td"|t|jttfr|j}|ddkrt td#dtd$d|dd}nHt|st td#td%n*|rnt td#td&d'jd(d|DnV|jdkr.Z InstalledZErasedUpgraded Downgraded)rBrorz Not installedZOlderZNewercSsg|] }t|qSr#)r)r8rr#r#r$r9zsmaxlenFrTc sd|}|r}n}|d}jjjj|jdj} | sH|d}nBjj| d} | r|j| } | dkrpn| dkr|d}n|d}|rj d\} } nj d \} } t ||d }d }|r|j }t d || || |t ||fdS) Nr'rB)rwrrrXrrFrGrYrz%s%s%s%s %-*s %s)rYrrZfiltermrwZrunrXpackageZcomparerPr rr{r)r|Z prefix_len was_installedrM pkg_max_lenZ show_reporlZ _pkg_statesstateZipkgsZinst_pkgresrNrOZui_repo)_pkg_states_available_pkg_states_installedr.r#r$ _simple_pkg~s2    z+Output._historyInfoCmd.._simple_pkgrzTransaction ID :z%u..%uz%czBegin time :zBegin rpmdb :z**r <z (%u seconds)z (%u minutes)r4z (%u hours)z (%u days)zEnd time :zEnd rpmdb :zUser :zReturn-Code :ZAbortedZSuccessz Failures:z, cSsg|] }t|qSr#)r)r8rBr#r#r$r9szFailure:zReleasever :zCommand Line :zComment :zTransaction performed with:r)r[r\zPackages Altered:zScriptlet output:z%4dzErrors:)FFrTr[i,i,iPFi,iPFiiiiQ)"r>rIrrrrrrGrr{rrBr$r@rAZbeg_rpmdb_versionrDZ end_timestamprQrErnrrrCallrZ releaseverr=commentZperformed_withrhistoryInfoCmdPkgsAlteredoutputr)r.r<rTr>rwrYrarGZbegtZbegtmZendtZendtmrhseenrBZcodesr=rdZ perf_withZmax_lenZwith_pkgZstr_lenZt_outrlineZt_errr#)r_r`r.r$rSps   (             &                   zOutput._historyInfoCmdr z Dep-Install Obsoleted ObsoletingErase Reinstallr rWr rV) z True-Installr z Dep-Installrirjrkrlr rWZUpdateZUpdatedc s|j}d}d}|j}xH|D]@|jjj}|t|krDt|}tt}||kr|}qWx|D]d } jtjj krd} d} |rt fdd|Drd} |j | \} } |jjj}t t ||}td | | || |tjfqfWd S) aPrint information about how packages are altered in a transaction. :param old: the :class:`DnfSwdbTrans` to print information about :param pats: a list of patterns. Packages that match a patten in *pats* will be highlighted in the output rr'rz ** rGcsg|]}j|qSr#)r)r8Zpat)r|r#r$r9Bsz4Output.historyInfoCmdPkgsAltered..rFz%s%s%s%s %-*s %sNz )_history_state2uistaterr<r&rrr]rrZTransactionItemState_DONErrPr r r{r) r.r<rTZ all_uistatesrYr\rZuistateZpkg_lenrlrMrNrOr#)r|r$re"s2      z Output.historyInfoCmdPkgsAlteredz )NrNr)rr)FrFN)FrFN)r0)F)N)NN)NNN)N)F)N)N)F)9__name__ __module__ __qualname____doc__rrecompilerr/r6rErPrS staticmethodrWpropertyrXrYr=rjrkr2rrrrrrrrrrrrrrrrrrrrrrrrr"r%r'rrLrrUrSrrmrer#r#r#r$r&Cs       /    V $N -  ' c / _2  " MM ' r&c@s(eZdZdZddZddZddZdS) r zGProvides text output callback functions for Dependency Solver callback.cCsd}|dkrtd}n||dkr(td}nj|dkr:td}nX|dkrLtd }nF|d kr^td }n4|d krptd }n"|dkrtd}n|dkrtd}|rtj||j|j|jdS)aPrint information about a package being added to the transaction set. :param pkgtup: tuple containing the package name, arch, version, and repository :param mode: a short string indicating why the package is being added to the transaction set. Valid current values for *mode* are:: i = the package will be installed u = the package will be an update e = the package will be erased r = the package will be reinstalled d = the package will be a downgrade o = the package will be obsoleting another package ud = the package will be updated od = the package will be obsoleted NrBz'---> Package %s.%s %s will be installedr(z(---> Package %s.%s %s will be an upgraderz$---> Package %s.%s %s will be erasedrz)---> Package %s.%s %s will be reinstalledrfz)---> Package %s.%s %s will be a downgraderXz(---> Package %s.%s %s will be obsoletingZudz&---> Package %s.%s %s will be upgradedZodz'---> Package %s.%s %s will be obsoleted)rrdebugrwrxry)r.r|moderfr#r#r$ pkg_addedPs&       z"DepSolveProgressCallBack.pkg_addedcCstjtddS)zRPerform setup at the beginning of the dependency solving process. z"--> Starting dependency resolutionN)rrvr)r.r#r#r$startyszDepSolveProgressCallBack.startcCstjtddS)zAOutput a message stating that dependency resolution has finished.z"--> Finished dependency resolutionN)rrvr)r.r#r#r$rpszDepSolveProgressCallBack.endN)rnrorprqrxryrpr#r#r#r$r Ms)r c@seZdZddZddZdS) CliKeyImportcCs||_||_dS)N)r*rf)r.r*rfr#r#r$r/szCliKeyImport.__init__cCsbdd}td|||tjj||jddf}tjd||jjj rJdS|jjj rXdS|j j S) NcSs$tjjr dnd}|ddjd|S)N00ri)rZpycompZPY3rjust)rZrjr#r#r$short_idsz'CliKeyImport._confirm..short_idzLImporting GPG key 0x%s: Userid : "%s" Fingerprint: %s From : %szfile://rz%sTF) rrZcryptoZ_printable_fingerprintrJrrNr*r)Z assumeyesZassumenorfr)r.rZuseridZ fingerprintrZ timestampr~ror#r#r$_confirms    zCliKeyImport._confirmN)rnrorpr/rr#r#r#r$rzsrzcsNeZdZdZeddZfddZddZdd Zd d Z dddZ Z S)CliTransactionDisplayz1A YUM specific callback class for RPM operations.cCs tjjjS)N)rr+r, _term_width)r.r#r#r$rszCliTransactionDisplay.cs0tt|jd|_d|_d|_d|_d|_dS)NrTr0rr)superrr/lastmsg lastpackagerfmarkmarks)r.) __class__r#r$r/s zCliTransactionDisplay.__init__c Csjtjjj|}|dkrdS|j}t|} ||_|dkr>d} n|td|} |j||||| || |dS)aOutput information about an rpm operation. This may include a text progress bar. :param package: the package involved in the event :param action: the type of action that is taking place. Valid values are given by :func:`rpmtrans.TransactionDisplay.action.keys()` :param ti_done: a number representing the amount of work already done in the current transaction :param ti_total: a number representing the total amount of work to be done in the current transaction :param ts_done: the number of the current transaction in transaction set :param ts_total: the total number of transactions in the transaction set Nrd) rrACTIONSr<_max_action_widthr rr _out_progress) r.rZrti_doneti_totalts_donets_totalZ action_strwid1pkgnamepercentr#r#r$r-s zCliTransactionDisplay.progresscCsHt|ds>d}x(tjjjD]}t|}||kr|}qW||_|j}|S)N_max_action_wid_cacher)hasattrrrrrr r)r.rrCZwid_valr#r#r$rs z'CliTransactionDisplay._max_action_widthc Cs|jrtjjs||kr|j|||tjj||d\} }} t|}| t|||t|| | f} | |jkrtj j d| tj| |_||krt ddS)N)r-rrZ write_flushr') rfrrisatty_makefmtr r rrr_terminal_messengerr{) r.rrrrrZprocessrrrKwid2ror#r#r$rs   z#CliTransactionDisplay._out_progressTNcCstt|}d||f}d|d|d} | ||f} |dkrFd} nt|} d|d} | d|d7} | d7} | d7} | d7} |j} | | kr| } | | 8} | | dkr| d} |j| | }d||f} d| d }| |d}|r|d krd | }|}n|rD|d kr*||jt||d f}nd}d|d| }| }nL|d kr\d| }|}n4|d krx||j|f}nd}d|d| }| }|||fS)Nz%s.%s%zs/%srrrZrz[%-zs]rz %s: %s r gY@rz %s: %s r'z %s: %s z %s: %s )rrr rirr)r.rrrr-rrlrZfmt_donerJZpnlZoverheadrirZfmt_barZfull_pnlrKrZbarr#r#r$rsP            zCliTransactionDisplay._makefmt)TNr) rnrorprqrurir/r-rrr __classcell__r#r#)rr$rs    rc Csd}tjjsdS|dkr d}n|dkr6t||}nd}tjjj}|dkrZ||krZd}d||f}|t|d8}|dkrd}|dkr|d8}|dkrd}|t ||}d|||f}n||krd t ||||f}nb|d 8}|dkrd}|d} | t |krt |} || 8}|t ||}d t || | |||f}||krZtj j d |tj||krvtj j d d tjtj j dtjddS)aIOutput the current status to the terminal using a simple text progress bar consisting of 50 # marks. :param current: a number representing the amount of work already done :param total: a number representing the total amount of work to be done :param name: a name to label the progress bar with r9Nrr#z %d/%drrZz [%-*s]%sz %s%srz %s: [%-*s]%swriterflush)r)rrrrrr+r,rrrr r rr) rTZtotalrwrrrirpZhashbarrfZnwidr#r#r$r!sL       r!)N)sb   (    7__pycache__/term.cpython-36.pyc000064400000027036151030066770012366 0ustar003 ft`f9@sxddlmZddlmZddlZddlZddlZddlZddlZddl Z ddl Z d ddZ d ddZ Gd d d e ZdS) )absolute_import)unicode_literalsNc CsBy(d}tj|tj|}tjd|d}|Stk r<dSXdS)z Get the real terminal width ZabcdefghshhhhrN)fcntlZioctltermiosZ TIOCGWINSZstructunpackIOError)fdZbufretr /usr/lib/python3.6/term.py_real_term_widthsrcCs&tdd}|sdS|dkrdS|SdS)z@ Compute terminal width falling to default 80 in case of troubler)r PN)r)r Ztwr r r _term_width)s  rc @seZdZdZdZeddZeddZdddd Zd d d d dddddZ d d d d dddddZ dddddddZ dddddd d!d"dZ d#d$d%d&d'd(d)d*dZ d+d,ZdFd/d0ZdGd1d2Zd3d4Zd5d6Zd7d8ZdHd:d;Zdd?Zd@dAZdBdCZdDdEZd-S)ITermz>A class to provide some terminal "UI" helpers based on curses.TcCstS)N)r)selfr r r @sz Term.cCstS)N)r)rr r r rAsZsmulZrevZsgr0) underlinereversenormalrr)blackbluegreencyanredmagentayellowwhite)rr"r r$rr#r!r%zzzzz(B)boldblinkdimrrrzzzzzzzzzzzzzzzzcCs|j|_|j|_|j|_dS)N)_Term__ansi_forced_MODEMODE_Term__ansi_forced_FG_COLORFG_COLOR_Term__ansi_forced_BG_COLORBG_COLOR)rr r r Z __forced_initzszTerm.__forced_initNautoc CsXd|_d|_|dkr |jdSddddddd|_ddddddddd|_ddddddddd|_|dkrvd |_dS|d kst|stj}|j sd |_dSyt j |j d Wnt k rd |_dSXt j|_t jd |_x8|jD].}|}||jkr|j|}|j||j|<qW|jd jd}|rhx4|jjD]&\}}t j||jpZd|j|<q>W|jdjd}|rx8|jjD]*\}}t j||jpd}||j|<qW|jdjd} | rx4|jjD]&\}}t j| |jpd|j|<qW|jdjd} | rTx8|jjD]*\}}t j| |jpBd} | |j|<q&WdS)a Reinitializes the :class:`Term`. :param term_stream: the terminal stream that the :class:`Term` should be initialized to use. If *term_stream* is not given, :attr:`sys.stdout` is used. :param color: when to colorize output. Valid values are 'always', 'auto', and 'never'. 'always' will use ANSI codes to always colorize output, 'auto' will decide whether do colorize depending on the terminal, and 'never' will never colorize. TalwaysNr&)r'r(r)rrr)rrr r!r"r#r$r%ZneverFr0)r linesZsetfzutf-8ZsetafZsetbZsetab)_Term__enabledr3_Term__forced_initr+r-r/AssertionErrorsysstdoutisattycursesZ setuptermfileno ExceptionZtigetstr _ctigetstrZtigetnum_Term__cap_names _tigetstrencode _Term__colorsitemsZtparmdecode_Term__ansi_colors) r term_streamcolorcap_namemodeZset_fgvalZ set_fg_ansiZfg_colorZset_bgZ set_bg_ansiZbg_colorr r r reinits         ""z Term.reinitcCs|j||dS)N)rJ)rrErFr r r __init__sz Term.__init__cCs0|j|p d}tjj|r"|j}tjdd|S)Nr&z \$<\d+>[/*]?)r=dnfZpycompZ is_py3bytesrCresub)rrGZcapr r r r?s zTerm._tigetstrcCs|j|t||jdS)zColorize string with colorr)r+str)rrFsr r r rFsz Term.colorcCs |jd|S)zMake string bold.r')rF)rrPr r r r'sz Term.boldFc s\|js |S|stj}fdd}x4|D],}||} |rFtj| tj} tj| ||}q(W|S)aSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with *end*, then return the modified string. For example:: >>> yt = Term() >>> yt.sub('spam and eggs', 'x', 'z', ['and']) 'spam xandz eggs' This is particularly useful for emphasizing certain words in output: for example, calling :func:`sub` with *beg* = MODE['bold'] and *end* = MODE['normal'] will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. Note, however, that the :func:`sub_mode`, :func:`sub_bold`, :func:`sub_fg`, and :func:`sub_bg` methods provide convenient ways to access this same emphasizing functionality. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :param escape: a function that accepts a string and returns the same string with problematic characters escaped. By default, :func:`re.escape` is used. :param ignore_case: whether case should be ignored when searching for matches :return: *haystack* with *beg* prefixing, and *end* postfixing, occurrences of the strings in *needles* cs|jS)N)group)match)begendr r rszTerm.sub..)r4rMescapetemplateIrN) rhaystackrSrTneedlesrUZ ignore_caseZrenderZneedleZpatr )rSrTr rNs  zTerm.subcKs|j|||jd|f|S)aOSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with *beg*, and postfix each occurrence with self.MODE['normal'], then return the modified string. If *beg* is an ANSI escape code, such as given by self.MODE['bold'], this method will return *haystack* with the formatting given by the code only applied to the strings in *needles*. :param haystack: the string to be modified :param beg: the string to be prefixed onto matches :param end: the string to be postfixed onto matches :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with *beg* prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* r)rNr+)rrXrSrYkwdsr r r sub_norm&sz Term.sub_normcKs|j||j||f|S)aTSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE[*mode*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given *mode*. :param haystack: the string to be modified :param mode: the mode to set the matches to be in. Valid values are given by self.MODE.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE[*mode*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* )r[r+)rrXrHrYrZr r r sub_mode9sz Term.sub_modecKs|j|d|f|S)aSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.MODE['bold'], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in bold face. :param haystack: the string to be modified :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.MODE['bold'] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* r')r\)rrXrYrZr r r sub_boldMsz Term.sub_boldcKs|j||j||f|S)acSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.FG_COLOR[*color*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* in the given color. :param haystack: the string to be modified :param color: the color to set the matches to be in. Valid values are given by self.FG_COLOR.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.FG_COLOR[*color*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* )r[r-)rrXrFrYrZr r r sub_fg_sz Term.sub_fgcKs|j||j||f|S)aSearch the string *haystack* for all occurrences of any string in the list *needles*. Prefix each occurrence with self.BG_COLOR[*color*], and postfix each occurrence with self.MODE['normal'], then return the modified string. This will return a string that when printed to the terminal will appear to be *haystack* with each occurrence of the strings in *needles* highlighted in the given background color. :param haystack: the string to be modified :param color: the background color to set the matches to be in. Valid values are given by self.BG_COLOR.keys(). :param needles: a list of strings to add the prefixes and postfixes to :return: *haystack* with self.BG_COLOR[*color*] prefixing, and self.MODE['normal'] postfixing, occurrences of the strings in *needles* )r[r/)rrXrFrYrZr r r sub_bgssz Term.sub_bg)Nr0)Nr0)NF)__name__ __module__ __qualname____doc__r4propertyZ real_columnscolumnsr>rArDr*r,r.r5rJrKr?rFr'rNr[r\r]r^r_r r r r r4sr    f   -r)r)r)Z __future__rrr:Z dnf.pycomprLrrMrr7rrrobjectrr r r r s   __pycache__/option_parser.cpython-36.opt-1.pyc000064400000040660151030066770015240 0ustar003 ft`4]@sddlmZddlmZddlmZddlZddlZddlZddl Zddl Zddl Z ddl Z ddlZddlZe jdZGdddejZGdd d ejZdS) )unicode_literals)_) _parse_specsNdnfcseZdZfddZZS)MultilineHelpFormattercs"d|kr|jStt|j||S)N ) splitlinessuperr _split_lines)selftextwidth) __class__#/usr/lib/python3.6/option_parser.pyr 'sz#MultilineHelpFormatter._split_lines)__name__ __module__ __qualname__r __classcell__rr)rrr&srcseZdZdZd.fdd ZddZGdddejZGd d d ejZ Gd d d ej Z Gd ddejZ GdddejZ GdddejZGdddejZGdddejZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd/fd*d+ Zd0fd,d- ZZS)1 OptionParserz5ArgumentParser like class to do things the "yum way".Tcs>tt|jdtdd|_d|_|j|r:i|_t|_ dS)NF)add_helpZformatter_class) r r__init__rcommand_positional_parser command_group_add_general_options _cmd_usageset _cmd_groups)r Z reset_usage)rrrr/s zOptionParser.__init__cCs&|jtjtd|tjddS)zOutput an error message, and exit the program. This method overrides standard argparser's error so that error output goes to the logger. :param msg: the error message to output zCommand line error: %sN) print_usageloggerZcriticalrsysexit)r msgrrrerror9szOptionParser.errorc@seZdZddZdS)zOptionParser._RepoCallbackcs@|dkr dndt||j}|jfddtjd|DdS)Nz --disablerepodisableenablec3s|]}|fVqdS)Nr).0x) operationrr Hsz6OptionParser._RepoCallback.__call__..z \s*[,\s]\s*)getattrdestextendresplit)r parser namespacevaluesopt_strlr)r)r__call__Es z#OptionParser._RepoCallback.__call__N)rrrr5rrrr _RepoCallbackDsr6c@seZdZddZdS)z OptionParser._RepoCallbackEnablecCs$|jj|ddft|d|dS)Nrr&Zreponame)repos_edappendsetattr)r r0r1r2r3rrrr5Ksz)OptionParser._RepoCallbackEnable.__call__N)rrrr5rrrr_RepoCallbackEnableJsr:cs$eZdZdZdZfddZZS)zOptionParser._SplitCallbackzN Split all strings in seq, at "," and whitespace. Returns a new list. z \s*[,\s]\s*csDd}x:tj|j|D](}|s |r8ttj|j||||d}qWdS)NTF)r.r/SPLITTERr r_SplitCallbackr5)r r0r1r2r3firstval)rrrr5Ts z$OptionParser._SplitCallback.__call__)rrr__doc__r;r5rrr)rrr<Osr<c@seZdZdZddZdS)z%OptionParser._SplitExtendDictCallbackz[ Split string at "," or whitespace to (key, value). Extends dict with {key: value}.c Cshy"|jd\}}| s| r tWn,tk rNtd|}tj||YnXt||j}|||<dS)N,zbad format: %s)r/ ValueErrorrargparseZ ArgumentErrorr+r,) r r0r1r2r3keyr>r#Zdctrrrr5bs   z.OptionParser._SplitExtendDictCallback.__call__N)rrrr?r5rrrr_SplitExtendDictCallback_srDc@seZdZdZddZdS)zOptionParser._SetoptsCallbackzY Parse setopts arguments and put them into main_ and repo_.c Cs|jd}t|dkr*tjtd|dSt|dkrJtjtd|dS|\}}|jd}|d kr|d|} ||dd}t|dr|j} ni} | j| ij|gj |t |d|j | n:t|d r|j } ni} | j|gj |t |d |j | dS) N=z'Setopt argument has multiple values: %sz Setopt argument has no value: %s.r repo_setoptsZrepo_ main_setoptsZmain_) r/lenr ZwarningrrfindhasattrrH setdefaultr8r9r,rI) r r0r1r2r3valskvZperiodrepoZrepooptsZmainoptsrrrr5ps,       z&OptionParser._SetoptsCallback.__call__N)rrrr?r5rrrr_SetoptsCallbackmsrSc@seZdZddZdS)z'OptionParser.ParseSpecGroupFileCallbackcCst||dS)N)r)r r0r1r2r3rrrr5sz0OptionParser.ParseSpecGroupFileCallback.__call__N)rrrr5rrrrParseSpecGroupFileCallbacksrTcs$eZdZfddZddZZS)zOptionParser.PkgNarrowCallbackcsi|_y&x dD]}|||j|<||=qWWn6tk rb}ztd|jj|fWYdd}~XnXg|d<ttj|j||dS)Nchoicesdefaultz"%s() missing mandatory argument %s)rUrV) pkgnarrowKeyError TypeErrorrrr rPkgNarrowCallbackr)r argskwargsrPe)rrrrs "z'OptionParser.PkgNarrowCallback.__init__cCsV|jd}| s"|d|jdkr.|jd}n |jd}t|||t||j|dS)NZ_actionrrUrV)r,rWpopr9)r r0r1r2r3Z dest_actionZnarrowrrrr5s     z'OptionParser.PkgNarrowCallback.__call__)rrrrr5rrr)rrrZs rZc@seZdZddZdS)zOptionParser.ForceArchActioncCsd|_||_dS)NT)Z ignorearchZarch)r r0r1r2r3rrrr5sz%OptionParser.ForceArchAction.__call__N)rrrr5rrrrForceArchActionsr_c Cs|jtdjtjjd}|jdddddtdd |jd d d d dtdd|jddd dtdd|jdd dtdjtjjdd|jdtddd|jdddgdtdd|jd d!dd"td#d$|jd%d&g|jtd'd(d)|jd*d+g|jtd,d(d)|jd-dtd.d/|jd0d1g|jtd2d3|jd4d5d dtd6d|jd7d8d9d d:td;d<|jd=d dtd>d|j }|jd?d@d dAdtdBdC|jdDd!dAtdEd<|jdFdGdHd dtdId|jdJdKdLt ddMtdNdO|jdPdQdRdSdtdTt dU|jdVd dtdWd|jdXdYd dtdZd|jd[d\dt td]d^|jd_dd`d tdajtjj ddb|jdcdtdddedf|jdgdhd dtdid|jdjd dtdkd|jdl|j dmgdntdodp|j }|jdq|j dmgdntdrdp|jdsdtdndu|jgtdvdw|j }|jdxdydzd td{db|jd|dyd}d td~db|jdddgd|jtddd|jddgd|jtddnd|jdi|j dtdd|jdd!ddtdd$|jdd!ddtdd$|jdddtdd|jddd tdd|jdddtdddd|jdddtdddd|jddddtdd|jddd dytdd|jdddtdd|jdd tdd|jdd tdd|jdd tdd|jdd tdd|jdddg|jtdd3|jddgd|jtddb|jddgd|jtdƒdb|jddddddggd|jtdʃdˍ|jddtj|jttjjjtd΃dύ|jddtjdҍdS)z0 Standard options known to all dnf subcommands. zGeneral {prog} options)progz-cz--configZconfig_file_pathNz [config file]zconfig file location)r,rVmetavarhelpz-qz--quietquiet store_truezquiet operation)r,actionrVrbz-vz --verbosezverbose operation)rerVrbz --versionzshow {prog} version and exitz --installrootzset install rootz[path])rbraz--nodocs store_constZnodocsZtsflagszdo not install documentations)reconstr,rbz --nopluginsZ store_falseZpluginszdisable all plugins)rerVr,rbz--enablepluginZ enablepluginzenable plugins by namez[plugin])r,rVrerbraz--disablepluginZ disablepluginzdisable plugins by namez --releaseverz:override the value of $releasever in config and repo files)rVrbz--setoptZsetoptsz%set arbitrary config and repo options)r,rVrerbz --skip-brokenZ skip_brokenz.resolve depsolve problems by skipping packagesz-hz--helpz --help-cmdrbzshow command help)rer,rbz--allowerasingz;allow erasing of installed packages to resolve dependenciesz-bz--bestZbestz8try the best available package versions in transactions.)rer,rVrbz--nobestz2do not limit the transaction to the best candidatez-Cz --cacheonlyZ cacheonlyz2run entirely from system cache, don't update cachez-Rz --randomwaitZ sleeptimez [minutes]zmaximum command wait time)r,typerVrarbz-dz --debuglevelZ debuglevelz [debug level]zdebugging output level)r,rarVrbrhz --debugsolverz)dumps detailed solving results into filesz--showduplicatesZshowdupesfromreposz2show duplicates, in repos, in list/search commandsz-ez --errorlevelzerror output level)rVrhrbz --obsoletesZ obsoleteszenables {prog}'s obsoletes processing logic for upgrade or display capabilities that the package obsoletes for info, list and repoquery)rVr,rerbz--rpmverbosityzdebugging output level for rpmz[debug level name])rVrbraz-yz --assumeyesz*automatically answer yes for all questionsz --assumenoz)automatically answer no for all questionsz --enablerepor7z[repo]z]Enable additional repositories. List option. Supports globs, can be specified multiple times.)rer,rVrarbz --disablerepozSDisable repositories. List option. Supports globs, can be specified multiple times.z--repoz--repoidrRzUenable just specific repositories by an id or a glob, can be specified multiple times)rar,rerVrbz--enableFZ set_enabledz>enable repos with config-manager command (automatically saves)z --disableZ set_disabledz?disable repos with config-manager command (automatically saves)z-xz --excludez --excludepkgsZ excludepkgsz exclude packages by name or globz [package])rVr,rerbraz--disableexcludesz--disableexcludepkgsZdisable_excludeszdisable excludepkgsz--repofrompathz [repo,path]zolabel and path to an additional repository to use (same path as in a baseurl), can be specified multiple times.)rVrerarbz--noautoremoveZclean_requirements_on_removez7disable removal of dependencies that are no longer usedz --nogpgcheckZgpgcheckz5disable gpg signature checking (if RPM policy allows)z--colorZcolorzcontrol whether color is used)r,rVrbz --refreshZfreshest_metadataz2set metadata as expired before running the command)r,rerbz-4Z ip_resolvezresolve to IPv4 addresses onlyZipv4)r,rVrbrergz-6zresolve to IPv6 addresses onlyZipv6z --destdirz --downloaddirZdestdirz!set directory to copy packages toz--downloadonlyZ downloadonlyzonly download packagesz --commentZcommentzadd a comment to transactionz--bugfixz,Include bugfix relevant packages, in updates)rerbz --enhancementz1Include enhancement relevant packages, in updatesz --newpackagez0Include newpackage relevant packages, in updatesz --securityz.Include security relevant packages, in updatesz --advisoryz --advisoriesZadvisoryz=Include packages needed to fix the given advisory, in updatesz--bzz--bzsZbugzillaz7Include packages needed to fix the given BZ, in updatesz--cvez--cvesZcvesz8Include packages needed to fix the given CVE, in updatesz--sec-severityz --secseverityZCriticalZ ImportantZModerateZLowZseverityzDInclude security relevant packages matching the severity, in updates)rUrVr,rerbz --forcearchZARCHz Force the use of an architecture)rar,rerUrbcommand?)nargsrb)add_argument_grouprformatrutilZMAIN_PROG_UPPER add_argumentr<rSZadd_mutually_exclusive_groupint MAIN_PROGr6rDrBZSUPPRESSr_sortedZrpmZ _BASEARCH_MAPkeys)r Z general_grpZ best_groupZ repo_groupZ enable_grouprrrrs:                                                                     z!OptionParser._add_general_optionscCsHtjj|j}tjj|jd}||jkrD||f|j|<|jj|dS)z- store usage info about a single dnf command.rN)rZi18nZucdsummaryaliasesrradd)r cmdgrouprtnamerrr_add_cmd_usageds  zOptionParser._add_cmd_usagecCs&x t|jD]}|j||qWdS)z store name & summary for dnf commands The stored information is used build usage information grouped by build-in & plugin commands. N)rr2rz)r Zcli_cmdsrxrwrrr add_commandslszOptionParser.add_commandscCstdtdd}dtjj}xfd D]^}||jkr4q$|d||7}xsz1OptionParser.cmd_add_argument..)allrhrror)r r[r\r)r rrszOptionParser.cmd_add_argumentcCs`xZ|D]R}y|jdWqtk rV}z"tjjtd|t|fWYdd}~XqXqWdS)Nzutf-8zCannot encode argument '%s': %s)encodeUnicodeEncodeErrorr exceptionsZ ConfigErrorrstr)r r[rr]rrr_check_encodings  zOptionParser._check_encodingcCs|j||j|\}}|S)N)rparse_known_args)r r[r1Z _unused_argsrrrparse_main_argss zOptionParser.parse_main_argscCs2|j||j|\}}|jj||}||_|jS)N)rrr parse_argsZopts)r rir[r1Z unused_argsrrrparse_command_argss  zOptionParser.parse_command_argsNcs,|jr|j|jj7_tt|j|dS)N)r_actionsr rr)r Zfile_)rrrrszOptionParser.print_usagecsd|rH|j s|jj|jkr$|j||j|jj7_|jj|jjn |j |_ t t |j dS)N)rrrrrrZ_action_groupsr8rrr~r r print_help)r ri)rrrrs  zOptionParser.print_help)T)N)N)rrrr?rr$rBZActionr6r:Z _AppendActionr<rDrSrTrZr_rrzr{rrrrrrrrrrr)rrr,s.  ;  r)Z __future__rZdnf.i18nrZdnf.utilrrBZdnf.exceptionsrZdnf.rpmZ dnf.yum.miscZloggingZos.pathosr.r!Z getLoggerr Z HelpFormatterrrrrrrrs    __pycache__/output.cpython-36.pyc000064400000157050151030066770012757 0ustar003 ft`Z@sdZddlmZddlmZddlmZddlZddlZddlZddlZ ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZmZddlmZmZmZmZmZmZmZmZddlmZmZmZm Z m!Z!dd l"m#Z#dd l$m%Z%ddl&Z'ddl(Z'ddl)Z'ddl*Z'ddl+Z'ddl,Z'ddlZ'ddl-Z'ddl.Z'ddl/Z'e j0d Z1d d Z2Gddde3Z4Gddde'j5j6Z7Gddde'j5j8Z9Gddde#Z:dddZ;dS)z"Handle actual output from the cli.)absolute_import)print_function)unicode_literalsN) format_number format_time)_C_P_ucdfill_exact_width textwrap_fill exact_widthselect_short_long)xrange basestringlongunicode sys_maxsize)TransactionDisplay)MergedTransactionWrapperdnfcCsrtj|ftjd}t|}|d}| |}|s@tjd|}n|rR|jd|t|}tt|f|g|S)N)r) itertoolschainrepeatlenextenditerlistzip)Z cols_countZlabellstleftZ lst_lengthZ right_countZ missing_itemsZlst_iterr#/usr/lib/python3.6/output.py_spread_in_columns6s r%c @s eZdZdZdmZejdZddZddZ d d Z d d Z d dZ e ddZeddZeddZdnddZe ddZddZdoddZdpd!d"Zdqd#d$Zd%d&Zd'd(Zd)d*Zdrd,d-Zdsd.d/Zdtd0d1Zidifd2d3Zdud4d5Zd6d7Z d8d9Z!d:d;Z"dd?Z$d@dAZ%dvdBdCZ&dwdDdEZ'dxdFdGZ(dHdIZ)dJdKZ*dydLdMZ+dNdOZ,dPdQZ-dRdSZ.dTdUZ/dVdWZ0dzdXdYZ1d{dZd[Z2ge3fd\d]Z4gfd^d_Z5e6d`e6d`e6dae6dbe6dce6dde6dee6dfe6dge6dhe6didj Z7gfdkdlZ8dS)|Outputz+Main output class for the yum command line. z ^\*{0,2}/cCs$||_||_tjjj|_d|_dS)N)confbaserclitermZTermprogress)selfr*r)r#r#r$__init__IszOutput.__init__cCs0|jj}dd|}|jt||d}|||fS)Nz%s=r')r,columns fmtColumnsr )r.col_datarowZ term_widthZruleheaderr#r#r$_bannerOs zOutput._bannerc Cszdd|dD}xF|D]>}x8t|D],\}}||}t|}|j|dd||<q&WqW|j|ddd}tttj|S)NcSsg|] }tqSr#)dict).0rr#r#r$ Vsz&Output._col_widths..rrz )indent) enumeraterget calcColumnsrmapoperatorneg) r.rowsr3r4ivalZcol_dctZlengthcolsr#r#r$ _col_widthsUs zOutput._col_widthscCs(d}d}|snt|t s$|dkr2|jjd}n|dkr|St|}t||||d}|jddkr||dkrt|||d d}|S) zReturn a key value pair in the common two column output format. :param key: the key to be formatted :param val: the value associated with *key* :return: the key value pair formatted in two columns for output r'rZz: )riZinitial_indentZsubsequent_indent rr(z ...: )r r,r_rr r count)r.keyrCZkeylenrDZnxtrUr#r#r$ fmtKeyValFills zOutput.fmtKeyValFillr0cCsht|}|jjd}t|}||dkr6|d}}n$|||d}|||t|}d|||fS)aFormat and return a section header. The format of the header is a line with *name* centered, and *fill* repeated on either side to fill an entire line on the terminal. :param name: the name of the section :param fill: the character to repeat on either side of *name* to fill an entire line. *fill* must be a single character. :return: a string formatted to be a section header rZz%s %s %s)r r,r1r r)r.rxZfillrDZname_lenZbegrqr#r#r$ fmtSections   zOutput.fmtSectionc sdd}fdd}g}j|\}}tdtddtdd}|j||d ||j|f|jrv|j|td |jtdtdd tdd }|j|||j|j|td |jtdtdd tdd}|j|||j tdtddtdd}|j||t t |j |j|td|j tdtddtdd}|j|||j|jrjj|} | r|j|td| jjr>|j|td|j|j|tdtjj|j|jr|j|tdtjj|jjj|} | r>yt| jj} Wntk r"d} YnX|j|tdj| tdtddtdd}|j|||j |j!r|j|tdt"|j!|j|td|j#tdtddtdd}|j|||j$dj%|S)zPrint information about the given package. :param pkg: the package to print information about :param highlight: highlighting options for the name of the package cSsdjt|dddt|gS)Nr' :)joinr str)rrCr#r#r$format_key_valsz)Output.infoOutput..format_key_valcsjt|ddd|pdS)Nrz : r)rr )rrC)r.r#r$format_key_val_fillsz.Output.infoOutput..format_key_val_fillrshortNamerz%s%s%sZEpochVersionZReleaseArch ArchitectureSizeZSourceRepo Repositoryz From repoZPackagerZ Buildtimez Install timeNz Installed byZSummaryZURLZLicenseZ Descriptionr)&rPrrr`rxZepochrversionreleaseryrfloat_sizeZ sourcerpmrepoid _from_systemrXZrepor)verboseZpackagerrutilZnormalize_timeZ buildtimeZ installtimeZ package_dataint_itemZgetInstalledBy ValueError_pwd_ui_usernamesummaryurlr license descriptionr) r.r}rMrrZ output_listrNrOrZ history_repoZ history_pkguidr#)r.r$ infoOutputsh                   zOutput.infoOutputc Cs|\}}|dk rV|jj}|jtjkr,|jj}|j|||d|j||d|jjddS|j}d|j |j f}|j } t d|| ||fdS) a{Print a simple string that explains the relationship between the members of an update or obsoletes tuple. :param uotup: an update or obsoletes tuple. The first member is the new package, and the second member is the old package :param changetype: a string indicating what the change between the packages is, e.g. 'updates' or 'obsoletes' :param columns: a tuple containing information about how to format the columns of output. The absolute value of each number in the tuple indicates how much space has been allocated for the corresponding column. If the number is negative, the text in the column will be left justified, and if it is positive, the text will be right justified. The columns of output are the package name, version, and repository N)r1rMr'r)r1r:rMz%s.%sz%-35.35s [%.12s] %.10s %-20.20sz ) r)color_update_remotereponamehawkeyZSYSTEM_REPO_NAMEcolor_update_localrcolor_update_installedZ compactPrintrxryrr|) r.ZuotupZ changetyper1Z changePkgZinstPkgZchiZ c_compactZ i_compactZc_repor#r#r$updatesObsoletesLists   zOutput.updatesObsoletesListc Csl|dkrht|dkr`td|t}|dkrbi}x"|D]} | |t| t| j<q' - highlighting used when the package has a higher version number :return: number of packages listed rinforxnevrarz%sFznot inrGr0>rF    zOutput.userconfirmcCs~|jjjj}|jjjj}i}xPtjtt|dD]6}||kr^||d||<q@||kr@||d||<q@W|S)Nrr) rYquery installedZ _name_dict availablerrrr )r.sectionsrrrfpkg_namer#r#r$_pkgs2name_dictszOutput._pkgs2name_dictc Csi}i}x~tjtt|dD]d}|j|}|dkr8q tt|t|j}tt|j}|j|dd||<|j|dd||<q W||fS)Nrr) rrrr r<r r GRP_PACKAGE_INDENTr) r.r name_dictZ nevra_lengthsZ repo_lengthsrr}Znevra_lZrepo_lr#r#r$_pkgs2col_lengthss zOutput._pkgs2col_lengthscCs$x|D]}td|j|fqWdS)Nz%s%s)r|r)r. pkg_namesrxr#r#r$_display_packagess zOutput._display_packagescCspxj|D]b}y ||}Wn(tk r>td|j|fwYnXd}|jsR|jj}|j|d|j||dqWdS)Nz%s%sFT)r~r:rMr1)KeyErrorr|rrr)Zcolor_list_available_installr)r.rrr1rxr}rMr#r#r$_display_packages_verboses  z Output._display_packages_verbosec Csldd}tdtd|j|jj}|r@ttdt|j|jr`ttdt|jp\d|jrxttd|jtd ||j ftd ||j ftd ||j ftd ||j ff}|r0|j |}|j||}|j|}|d  |d f}xp|D].\}} t| dkrqt||j| ||qWn8x6|D].\}} t| dkrPq6t||j| q6WdS)zOutput information about the packages in a given group :param group: a Group object to output information about cSstdd|DS)Ncss|] }|jVqdS)N)rx)r8r}r#r#r$ sz?Output.display_pkgs_in_groups..names..)r])packagesr#r#r$namessz,Output.display_pkgs_in_groups..namesrz Group: %sz Group-Id: %sz Description: %srz Language: %sz Mandatory Packages:z Default Packages:z Optional Packages:z Conditional Packages:rrN)r|rui_namer)rr idui_descriptionZ lang_onlyZmandatory_packagesZdefault_packagesZoptional_packagesZconditional_packagesrrr=rrr) r.grouprrrrZ col_lengthsr1 section_namerr#r#r$display_pkgs_in_groupss8   zOutput.display_pkgs_in_groupscCsdd}ttd|j|jjr8ttdt|j|jr\t|jpJd}ttd|td||jftd||j ff}x0|D](\}}t |d krqt||j |qWd S) zOutput information about the packages in a given environment :param environment: an Environment object to output information about cSstdd|DS)Ncss|] }|jVqdS)N)rx)r8rr#r#r$r szFOutput.display_groups_in_environment..names..)r])groupsr#r#r$rsz3Output.display_groups_in_environment..nameszEnvironment Group: %sz Environment-Id: %srz Description: %sz Mandatory Groups:z Optional Groups:rN) r|rrr)rr rrZmandatory_groupsZoptional_groupsrr)r.Z environmentrrrrrr#r#r$display_groups_in_environments z$Output.display_groups_in_environmentcsVdfdd fdd}jjr4d}ndjjf}j|jpRd}r|d krjjjj|d d }t||d krjj }|sd Stt d j d}d} xXt |D]J} j| krd } qˆj | krt d } | | |d dd }qˆj| kr,t d} | | |ddd }qˆj| krVt d} | | |ddd }q|| |rhd }qt d} xjD]} t| } tj| | r| | |ddd }n`| jd} t dtfdd| Dr| jd}n| }tj| |rx| | |ddd }qxWqWt|| gsLx*t |D]} t d} | | |ddq*Wtd S)aOutput search/provides type callback matches. :param po: the package object that matched the search :param values: the information associated with *po* that matched the search :param matchfor: a list of strings to be highlighted in the output :param verbose: whether to output extra verbose information :param highlight: highlighting options for the highlighted matches Fcsd|sttdt|pd}|dkr(dSr>j|dd}|rTtj||n t||dS)Nz Matched from:rT) ignore_case)r|rr rSr)ritemZprinted_headline can_overflow)rMmatchforr.r#r$print_highlighted_key_item's  z8Output.matchcallback..print_highlighted_key_itemcsTjj|sdStd}d}x2jD](}tj||r$|||p@|ddd}q$W|S)NFzFilename : %s)rT)FILE_PROVIDE_REmatchrfilesfnmatch)r printed_matchrZ file_matchfilename)porr.r#r$print_file_provides4s   z1Output.matchcallback..print_file_providesz%s : z%s.%s : rNT)rzRepo : %szDescription : )rzURL : %szLicense : %szProvide : %srz=<>c3s|]}|kVqdS)Nr#)r8char)possibler#r$rpsz'Output.matchcallback..zOther : %s)F)r)ZshowdupesfromreposrxryrrZcolor_search_matchrSr|rrrrrrrZprovidesrrrKany)r.rrrrrMrrprZ name_matchrrZprovideZ first_provideZitem_newr#)rMrrrrr.r$ matchcallbacksp           zOutput.matchcallbackcCs|j|||ddS)aqOutput search/provides type callback matches. This will output more information than :func:`matchcallback`. :param po: the package object that matched the search :param values: the information associated with *po* that matched the search :param matchfor: a list of strings to be highlighted in the output T)r)r)r.rrrr#r#r$matchcallback_verboses zOutput.matchcallback_verbosec Csd}d}d}d}x|D]}yrt|j}||7}y|jr@||7}Wntk rVYnX|s^wyt|j}Wntk rYnX||7}Wqtk rd}td} tj| PYqXqW|s|rtjtdt |||krtjtdt |||rtjtdt |dS) zReport the total download size for a set of packages :param packages: a list of package objects :param installonly: whether the transaction consists only of installations rFTz2There was an error calculating total download sizezTotal size: %szTotal download size: %szInstalled size: %sN) rrZverifyLocalPkg ExceptionZ installsizerloggererrorrr) r.rZ installonlytotsizeZlocsizeZinsizerr}sizerpr#r#r$reportDownloadSizesD          zOutput.reportDownloadSizec Csrd}d}xL|D]D}y|j}||7}Wqtk rPd}td}tj|PYqXqW|sntjtdt|dS)zmReport the total size of packages being removed. :param packages: a list of package objects rFTz-There was an error calculating installed sizezFreed space: %sN)rrrrrrr)r.rrrr}rrpr#r#r$reportRemoveSizes    zOutput.reportRemoveSizec Cs*|sdSg}g}|jr$|jtdxJ|jD]@}t|j|}|j|}|rR|jn|} |jtdd| |q,W|j r|jtdx@|j D]6}t|j |}|j j |j} |jtdd| |qW|r |j |} x$|D]} |j|jt| | dqW|j| tdtdddf|d d <d j|S) Nz+Marking packages as installed by the group:r@z)Marking packages as removed by the group:r'ZGroupPackagesrrr)Z new_groupsr`rrZadded_packagesZ _group_by_idrrr%Zremoved_groupsZremoved_packagesrr<rEr2r r6r) r.compsrXrhoutrAZgrp_idZpkgsZ group_objectZgrp_namer3r4r#r#r$list_group_transactions.     $zOutput.list_group_transactioncQ s tjtjBtjBtjBtjBtjB}t}t}|dkr\}}x2t+|D]&}|j&d||fddddddfqWqW|j&| |ft!t'j j(j,j*}|rt d} g}xF|D]>\}}x2t+|D]&}|j&d||fddddddfqWqW|j&| |ft!t'j j(j-j*}|rW|j&| |fj j1j7j3}"|"rt d$} g}x |"j4D]}|j&||qW|j&| |fj j1j7j5}#|#rt d%} g}x |#j4D]}|j&||qW|j&| |fj j1j7j6}$|$rNt d&} g}x |$j4D]}|j&||q(W|j&| |fj8j9 rvj j:j;|@rvg}j j|&}'d/d0|D}|j&|'|fg}x*t!|j*D]\}(}%| ||| |%g} qWt d1}'j j8j?rN|'d}'n |'t d2}'d3d0|D}|j&|'|fj@jA})|d4 rˆj j(jB rˆj j1oj j1j7pj j1j2 rdS|d4i|d5|d6ig}d| ddd7g}*jC|d8|*d9|d:}*|*\}+} },}-}.tD|*d7}/|)|/kr&|)n|/})tE|+td;d<td=d<}0tE| td;d>td=d?}1tE|,td;d@td=d@}2tE|-td;dAtd=dB}3tE|.td;dCtd=dC}4dDdE|)jF|0|+ f|1| f|2|, f|3|- f|4|.ffd.dE|)fg}5x|D]\} }| rdF| }6x|D]\}7}8}9}:};}<}=|7|+ |=f|8| f|9|, f|:|- f|;|.ff}*jF|*d.dG}>jGj8jH\}?}@xBt!|<D]6}AdHt dIdJ}B|B|?|AjI|@|AjJ|AjKf;}B|>|B7}> qrW|6|>}6 q W|r|5j&|6qW|5j&t dKdE|)t dLtL|jtL|jtL|jtL|jdft dMtL|jdft dNtL|jtL|jtL|jdft dOtL|jdft dPtL|tL|dff}Cd}Dd}Ed}Fd}Gx|CD]\} }H}I|H r|I r qtMd|5j&|>|P|E|HdU|F|Jf|G|I|Ofn$dV}>|5j&|>|P|E|Fd.|G|I|Ofn&|H r$dW}>|5j&|>tQ| |D|E|H|Jf q$Wdj>|5S)Xz]Return a string representation of the transaction in an easy-to-read format. N)rvrrcs|j\}}}}} |j} |j} t|j} |dkr2d}|jrBjj} n|jrRjj } njj } |j ||| | | || fxRdt |fdt | fdt | ffD],\}}||j |d|||d7<qWt|t |}|S)NZnoarchrrrrr)Zpkgtuprzr{rrrr)rZ _from_cmdlinerrr`r setdefaultmax)linesrca_widr obsoletesraerrrzrrhirf)r.r#r$ _add_lines"   ,z*Output.list_transaction.._add_linez Installing group/module packageszInstalling group packagesrZ InstallingZ UpgradingZ ReinstallingzInstalling dependencieszInstalling weak dependenciesZRemovingzRemoving dependent packageszRemoving unused dependenciesZ DowngradingcSs|jS)N)r})xr#r#r$4sz)Output.list_transaction..)rzInstalling module profilesz%s/%srzDisabling module profileszEnabling module streamszSwitching module streamsz%s -> %srzDisabling moduleszResetting modulescSs&|j}|r|ntdddddddfS)Nz r)ZgetNamer)rrxr#r#r$ format_lineqsz,Output.list_transaction..format_linezInstalling Environment GroupszUpgrading Environment GroupszRemoving Environment GroupszInstalling GroupszUpgrading GroupszRemoving GroupsT)Zreport_problems transactioncss|]}t||fVqdS)N)r)r8r}r#r#r$rsz*Output.list_transaction..z--bestz--allowerasingzSSkipping packages with conflicts: (add '%s' to command line to force their upgrade)r'cSsg|]}|dddqS)Nrrr[)rr#)r8rBr#r#r$r9sz+Output.list_transaction..z,Skipping packages with broken dependencies%sz or part of a groupcSsg|]}|dddqS)Nrrr[)rr#)r8rBr#r#r$r9srrrz rZ)r:r1rdrerZPackagerrrrrrrz %s %s %s r0z%s: rz Z replacingz %s%s%s.%s %s z Transaction Summary %s InstallUpgradeZRemove DowngradeZSkiprzDependent packagezDependent packagesz%s %*d %s (+%*d %s) z%-*sz%s %s ( %*d %s) z %s %*d %s )RrZUPGRADEZ UPGRADE_ALLZ DISTUPGRADEZDISTUPGRADE_ALLZ DOWNGRADEINSTALLrrrZ _make_listsr*Z WITH_MODULESrrrZupgradedZ reinstalledZinstalled_groupZ installed_depZinstalled_weakZerasedZ erased_depZ erased_cleanZ downgradedactionlibdnfr ZTransactionItemAction_OBSOLETEDrZ getReplacedByrrr]ZFORWARD_ACTIONSZTransactionItemAction_REMOVEr<r}r`r7Z_moduleContainerZgetInstalledProfilesr^rZgetRemovedProfilesZgetEnabledStreamsZgetSwitchedStreamsZgetDisabledModulesZgetResetModulesZ_historyenvZ _installedrZ _upgradedZ_removedrr)ZbestZ_goalactionsZ_skipped_packagesZ_allow_erasingrZupgrade_group_objects_upgrader,r1Z isChangedr=rarr2rPrrxryrzrr r rrr )Qr.r reZforward_actionsZskipped_conflictsZskipped_brokenZ list_bunchZ pkglist_linesrcrrZ ins_group_msgrZpkglistrZreplacestsirBZ obsoletedZinstalledProfilesrxZprofilesZprofileZremovedProfilesZenabledStreamsstreamZswitchedStreamsZdisabledModulesZ resetModulesrZinstall_env_grouprZupgrade_env_groupZremove_env_groupZ install_groupZ upgrade_groupZ remove_groupr}ZrecommendationsZskip_strrZ output_widthr1Zn_widZv_widZr_widZs_widZ real_widthZ msg_packageZmsg_archZ msg_versionZmsg_repositoryZmsg_sizerZtotalmsgrrrzrrrrrprNrOZobspoZappendedZ summary_dataZmax_msg_actionZ max_msg_countZ max_msg_pkgsZmax_msg_depcountrZdepcountZmsg_pkgsZlen_msg_actionZ len_msg_countZ len_msg_pkgsZlen_msg_depcountZ msg_deppkgsZ action_msgr#)r.r$list_transactions$         ,,.               $                   zOutput.list_transactionc sfdd}|sdSg}g}|jdj|x|D]}|jt|q2Wxd D]}|||}|rNPqNW|szjjd  g}xD|r|dt|} |jd jjt| ||t|d}q|W|S)Ncst||krgSjj|dd}|dkr0gSdg|}d}x`|D]X}t|||krt|||}||krtgS||8}t|||<|d7}|t|;}qDWx8tt|D](}||||7<||d9<qW|S)zb Work out how many columns we can use to display stuff, in the post trans output. rrZrr[)rr,r1r\)msgsnumr"Zcol_lensrgrprh)r.r#r$ _fits_in_colsKs(    z+Output._pto_callback.._fits_in_colsrz{}:r rr(rZz {})rrrr rr(rZ)r`formatrr,r1rr2r ) r.rZtsisrrrrrrDZ current_msgsr#)r.r$ _pto_callbackHs&    zOutput._pto_callbackcCstjj|j||jS)z{ Return a human-readable summary of the transaction. Packages in sections are arranged to columns. )rrZ_post_transaction_outputr*r)r.r r#r#r$post_transaction_outputzszOutput.post_transaction_outputcCs@d}|jjdkr6tjjjtjd}tjjjtjd|_|tfS)z_Set up the progress callbacks and various output bars based on debug level. NrZ)Zfo) r)Z debuglevelrr+r-ZMultiFileProgressMetersysstdoutDepSolveProgressCallBack)r. progressbarr#r#r$setup_progress_callbackss  zOutput.setup_progress_callbackscCsz|dkr dS|jj}tjd|tdtj|}dt||t|t|f}tt d|t ||}tj|dS)a!Outputs summary information about the download process. :param remote_size: the total amount of information that was downloaded, in bytes :param download_start_timestamp: the time when the download process started, in seconds since the epoch rN-g{Gz?z %5sB/s | %5sB %9s ZTotal) r,r1rrrtimerrr rr)r.Z remote_sizeZdownload_start_timestampriZdl_timerpr#r#r$download_callback_total_cbs  z!Output.download_callback_total_cbcCst}t}d}xD|D]<}|jtjjtjjfkr2q|j|j|j|j|d7}qWt |dkrt|dj t |fS|dj t |fS)Nrrz, r) rrrr ZTransactionItemAction_UPGRADEDZ TransactionItemAction_DOWNGRADEDr action_nameZ action_shortrrr]r)r.ZhpkgsrZ actions_shortrr}r#r#r$_history_uiactionss     zOutput._history_uiactionsc st|trfdd|DS|dks.|dkrftd}tdd|}dk r^t|kr^|}t|Sdd }yrtjt|}|t|jd d }t|j }d ||f}dk rt|krd |||f}t|krd|}|St k rt|SXdS)Ncsg|]}j|qSr#)r)r8u)limitr.r#r$r9sz+Output._pwd_ui_username..zZSystemr'cWs|j|}|sdS|dS)zf Split gives us a [0] for everything _but_ '', this function returns '' in that case. rr)rK)textargsrUr#r#r$ _safe_split_0s z.Output._pwd_ui_username.._safe_split_0;rZz%s <%s>z %s ... <%s>z<%s>)r+r,) rIrrrr pwdgetpwuidrZpw_gecosZpw_namer) r.rr*Zloginidrxr/userfullnameZ user_namer#)r*r.r$rs*    zOutput._pwd_ui_usernamec Csz|jj|}|jjdkr"ddg}nf|jjdkr6dg}nR|jjdksFtt}d}d}x2|D]*}|d7}|jdkrx|d7}|j|jqZWd}t |dkrt d } |j j } | dkrt jj jd} | dkrd } | d kr| d nd } n t d } d } t|tt dddt| | | tt dddtt dddtt dddfd#| dddddd} td| d}|dkr|t|}x|D]}t |dkr|jpd} n|j|jd } t| } tjdtj|j} |j|j\}}t| | | } t|dd}d}}|jdkrd}}n"|jr&d}}n|jr6d}}|jrBd }|jrNd!}t||j| | ||fd"||fqWdS)$zOutput a list of information about the history of yum transactions. :param tids: transaction Ids; lists all transactions if empty ZusersrrZZcommandszsingle-user-commandsrNz%s | %s | %s | %s | %sz Command lineO7z User nameZIDrz Date and timertz Action(s)ZAlteredrr(r$z%6u | %s | %-16.16s | %s | %4uTrz%Y-%m-%d %H:%Mr'*#Errz%s%s ) rXoldr)Zhistory_list_viewrkrcmdlinerloginuidrrr,r_rr+Z_real_term_widthr|r reversedrr r%strftime localtime beg_timestampr(rc return_codeZ is_outputaltered_lt_rpmdbaltered_gt_rpmdbtid)r.tidsreverse transactionsZuidsdoneZblanksr fmtrxZ real_colsZ name_widthZ table_widthZtmrZuiactsZrmarkZlmarkr#r#r$historyListCmdsr                 zOutput.historyListCmdcCst|}|jj}|dkr8tjtdtjjtd|j }|j }g}|sz|jjdd}|dk r|j |j |j |n |jj |}|stjtdtjjtdd \}} d} d} |rt|}|j\}} x|D]} |dk o| j |kr|jj} | jt| d}d}| j |krL| j | krL| dkr} t td | | |jdk r(|jrt td!|jdnt td!|jt|ttfrvt} xD|D],}|| krVqD| j|t td"|qDWnt td"|t|jttfr|j}|ddkrt td#dtd$d|dd}nHt|st td#td%n*|rnt td#td&d'jd(d|DnV|jdkr.Z InstalledZErasedUpgraded Downgraded)rBrorz Not installedZOlderZNewercSsg|] }t|qSr#)r)r8rr#r#r$r9zsmaxlenFrTc sd|}|r}n}|d}jjjj|jdj} | sH|d}nBjj| d} | r|j| } | dkrpn| dkr|d}n|d}|rj d\} } nj d \} } t ||d }d }|r|j }t d || || |t ||fdS) Nr'rB)rxrrrYrrFrGrZrz%s%s%s%s %-*s %s)rYrrZfiltermrxZrunrXpackageZcomparerPr rr|r)r}Z prefix_len was_installedrM pkg_max_lenZ show_repormZ _pkg_statesstateZipkgsZinst_pkgresrNrOZui_repo)_pkg_states_available_pkg_states_installedr.r#r$ _simple_pkg~s2    z+Output._historyInfoCmd.._simple_pkgrzTransaction ID :z%u..%uz%czBegin time :zBegin rpmdb :z**r <z (%u seconds)z (%u minutes)r5z (%u hours)z (%u days)zEnd time :zEnd rpmdb :zUser :zReturn-Code :ZAbortedZSuccessz Failures:z, cSsg|] }t|qSr#)r)r8rBr#r#r$r9szFailure:zReleasever :zCommand Line :zComment :zTransaction performed with:r)r\r]zPackages Altered:zScriptlet output:z%4dzErrors:)FFrTr[i,i,iPFi,iPFiiiiQ)"r?rIrrrrrrHrr|rrCr%rArBZbeg_rpmdb_versionrEZ end_timestamprRrFrorrrDallrZ releaseverr>commentZperformed_withrhistoryInfoCmdPkgsAlteredoutputr)r.r=rUr?rxrZrbrHZbegtZbegtmZendtZendtmrhseenrBZcodesr>reZ perf_withZmax_lenZwith_pkgZstr_lenZt_outrlineZt_errr#)r`rar.r$rTps   (             &                   zOutput._historyInfoCmdr z Dep-Install Obsoleted ObsoletingErase Reinstallr rXr rW) z True-Installr z Dep-Installrjrkrlrmr rXZUpdateZUpdatedc s|j}d}d}|j}xH|D]@|jjj}|t|krDt|}tt}||kr|}qWx|D]d } jtjj krd} d} |rt fdd|Drd} |j | \} } |jjj}t t ||}td | | || |tjfqfWd S) aPrint information about how packages are altered in a transaction. :param old: the :class:`DnfSwdbTrans` to print information about :param pats: a list of patterns. Packages that match a patten in *pats* will be highlighted in the output rr'rz ** rGcsg|]}j|qSr#)r)r8Zpat)r}r#r$r9Bsz4Output.historyInfoCmdPkgsAltered..rFz%s%s%s%s %-*s %sNz )_history_state2uistaterr<r'rrr^rr ZTransactionItemState_DONErrPr r r|r) r.r=rUZ all_uistatesrZr]rZuistateZpkg_lenrmrMrNrOr#)r}r$rf"s2      z Output.historyInfoCmdPkgsAlteredz )NrNr)rr)FrFN)FrFN)r0)F)N)NN)NNN)N)F)N)N)F)9__name__ __module__ __qualname____doc__rrecompilerr/r6rErPrS staticmethodrWpropertyrXrYr=rjrlr2rrrrrrrrrrrrrrrrrrrrrrrrr#r&r(rrMrrVrTrrnrfr#r#r#r$r&Cs       /    V $N -  ' c / _2  " MM ' r&c@s(eZdZdZddZddZddZdS) r!zGProvides text output callback functions for Dependency Solver callback.cCsd}|dkrtd}n||dkr(td}nj|dkr:td}nX|dkrLtd }nF|d kr^td }n4|d krptd }n"|dkrtd}n|dkrtd}|rtj||j|j|jdS)aPrint information about a package being added to the transaction set. :param pkgtup: tuple containing the package name, arch, version, and repository :param mode: a short string indicating why the package is being added to the transaction set. Valid current values for *mode* are:: i = the package will be installed u = the package will be an update e = the package will be erased r = the package will be reinstalled d = the package will be a downgrade o = the package will be obsoleting another package ud = the package will be updated od = the package will be obsoleted NrBz'---> Package %s.%s %s will be installedr)z(---> Package %s.%s %s will be an upgraderz$---> Package %s.%s %s will be erasedrz)---> Package %s.%s %s will be reinstalledrfz)---> Package %s.%s %s will be a downgraderYz(---> Package %s.%s %s will be obsoletingZudz&---> Package %s.%s %s will be upgradedZodz'---> Package %s.%s %s will be obsoleted)rrdebugrxryrz)r.r}modergr#r#r$ pkg_addedPs&       z"DepSolveProgressCallBack.pkg_addedcCstjtddS)zRPerform setup at the beginning of the dependency solving process. z"--> Starting dependency resolutionN)rrwr)r.r#r#r$startyszDepSolveProgressCallBack.startcCstjtddS)zAOutput a message stating that dependency resolution has finished.z"--> Finished dependency resolutionN)rrwr)r.r#r#r$rqszDepSolveProgressCallBack.endN)rorprqrrryrzrqr#r#r#r$r!Ms)r!c@seZdZddZddZdS) CliKeyImportcCs||_||_dS)N)r*rg)r.r*rgr#r#r$r/szCliKeyImport.__init__cCsbdd}td|||tjj||jddf}tjd||jjj rJdS|jjj rXdS|j j S) NcSs$tjjr dnd}|ddjd|S)N00ri)rZpycompZPY3rjust)rZrjr#r#r$short_idsz'CliKeyImport._confirm..short_idzLImporting GPG key 0x%s: Userid : "%s" Fingerprint: %s From : %szfile://rz%sTF) rrZcryptoZ_printable_fingerprintrJrrOr*r)Z assumeyesZassumenorgr)r.rZuseridZ fingerprintrZ timestamprrpr#r#r$_confirms    zCliKeyImport._confirmN)rorprqr/rr#r#r#r$r{sr{csNeZdZdZeddZfddZddZdd Zd d Z dddZ Z S)CliTransactionDisplayz1A YUM specific callback class for RPM operations.cCs tjjjS)N)rr+r, _term_width)r.r#r#r$rszCliTransactionDisplay.cs0tt|jd|_d|_d|_d|_d|_dS)NrTr0rs)superrr/lastmsg lastpackagergmarkmarks)r.) __class__r#r$r/s zCliTransactionDisplay.__init__c Csjtjjj|}|dkrdS|j}t|} ||_|dkr>d} n|td|} |j||||| || |dS)aOutput information about an rpm operation. This may include a text progress bar. :param package: the package involved in the event :param action: the type of action that is taking place. Valid values are given by :func:`rpmtrans.TransactionDisplay.action.keys()` :param ti_done: a number representing the amount of work already done in the current transaction :param ti_total: a number representing the total amount of work to be done in the current transaction :param ts_done: the number of the current transaction in transaction set :param ts_total: the total number of transactions in the transaction set Nrd) rr ACTIONSr<_max_action_widthr rr _out_progress) r.r[rti_doneti_totalts_donets_totalZ action_strwid1pkgnamepercentr#r#r$r-s zCliTransactionDisplay.progresscCsHt|ds>d}x(tjjjD]}t|}||kr|}qW||_|j}|S)N_max_action_wid_cacher)hasattrrr rrr r)r.rrCZwid_valr#r#r$rs z'CliTransactionDisplay._max_action_widthc Cs|jrtjjs||kr|j|||tjj||d\} }} t|}| t|||t|| | f} | |jkrtj j d| tj| |_||krt ddS)N)r-rrZ write_flushr') rgrr isatty_makefmtr r rrr_terminal_messengerr|) r.rrrrrZprocessrrrLwid2rpr#r#r$rs   z#CliTransactionDisplay._out_progressTNcCstt|}d||f}d|d|d} | ||f} |dkrFd} nt|} d|d} | d|d7} | d7} | d7} | d7} |j} | | kr| } | | 8} | | dkr| d} |j| | }d||f} d| d }| |d}|r|d krd | }|}n|rD|d kr*||jt||d f}nd}d|d| }| }nL|d kr\d| }|}n4|d krx||j|f}nd}d|d| }| }|||fS)Nz%s.%s%zs/%srsrZrz[%-zs]rz %s: %s r gY@rz %s: %s r'z %s: %s z %s: %s )rrr rirr)r.rrrr-rrlrZfmt_donerKZpnlZoverheadrirZfmt_barZfull_pnlrLrZbarr#r#r$rsP            zCliTransactionDisplay._makefmt)TNr) rorprqrrrvrir/r-rrr __classcell__r#r#)rr$rs    rc Csd}tjjsdS|dkr d}n|dkr6t||}nd}tjjj}|dkrZ||krZd}d||f}|t|d8}|dkrd}|dkr|d8}|dkrd}|t ||}d|||f}n||krd t ||||f}nb|d 8}|dkrd}|d} | t |krt |} || 8}|t ||}d t || | |||f}||krZtj j d |tj||krvtj j d d tjtj j dtjddS)aIOutput the current status to the terminal using a simple text progress bar consisting of 50 # marks. :param current: a number representing the amount of work already done :param total: a number representing the total amount of work to be done :param name: a name to label the progress bar with r:Nrr$z %d/%drrZz [%-*s]%sz %s%srz %s: [%-*s]%swriterflush)r)rr rrrr+r,rrrr r rr) rTZtotalrxrrrirqZhashbarrgZnwidr#r#r$r"sL       r")N)sb   (    7__pycache__/format.cpython-36.pyc000064400000004461151030066770012704 0ustar003 ft`@s8ddlmZddlmZd ddZd ddZdd Zd S) )unicode_literals)long c Csddddddddd g }|r d }nd }d }d }t|d}|dkrDd}x$||krh||krh|d}||}qFWt|ts~t|trd}n|dkrd}nd}|t|pd |||fS)aReturn a human-readable metric-like string representation of a number. :param number: the number to be converted to a human-readable form :param SI: If is 0, this function will use the convention that 1 kilobyte = 1024 bytes, otherwise, the convention that 1 kilobyte = 1000 bytes will be used :param space: string that will be placed between the number and the SI prefix :return: a human-readable metric-like string representation of *number* rkMGTPEZYg@@g@irNgz%i%s%sgfffff#@z%.1f%s%sz%.0f%s%s)len isinstanceintrfloat) ZnumberZSIZspaceZsymbolsstepZthreshdepthZ max_depthformatr/usr/lib/python3.6/format.py format_numbers4  rcCsx|dks|dkr|rdSdSnV|tdkr.dSt|}|d}|d}|rh|d}|d}d|||fSd ||fSdS) aReturn a human-readable string representation of a number of seconds. The string will show seconds, minutes, and optionally hours. :param seconds: the number of seconds to convert to a human-readable form :param use_hours: If use_hours is 0, the representation will be in minutes and seconds. Otherwise, it will be in hours, minutes, and seconds :return: a human-readable string representation of *seconds* Nrz--:--:--z--:--infZInfinite<z%02i:%02i:%02iz %02i:%02i)rr)ZsecondsZ use_hoursZminutesZhoursrrr format_timeIs rcCsdjdd|jDS)N css|]}d|VqdS)z Nr).0srrr hszindent_block..)join splitlines)rrrr indent_blockgsr!N)rr)r)Z __future__rZ dnf.pycomprrrr!rrrrs   5 __pycache__/aliases.cpython-36.opt-1.pyc000064400000012474151030066770013777 0ustar003 ft`@sddlmZddlmZddlmZddlZddlZddlm Z ddl Zddl Z ddl Z ddlZddlZe jdZdZejjedZejjed ZGd d d eZGd d d eZdS))absolute_import)unicode_literals)_N) PRIO_DEFAULTdnfz/etc/dnf/aliases.d/z ALIASES.confz USER.confc@s,eZdZddZeddZeddZdS) AliasesConfigcCs$||_tjj|_|jj|jdS)N)_pathlibdnfconfZ ConfigParser_parserread)selfpathr/usr/lib/python3.6/aliases.py__init__*s zAliasesConfig.__init__c CsHtjjd}y|jt|jjddWntk r>YnX|jS)NTmainenabled) r r OptionBoolsetrr ZgetData IndexErrorgetValue)r optionrrrr/s  zAliasesConfig.enabledcCsVtj}d}|jj|s|Sx4|jj|D]$}|jj||}|sBq*|j||<q*W|S)Naliases) collections OrderedDictr Z hasSectionZoptionsrsplit)r resultZsectionkeyvaluerrrr8s zAliasesConfig.aliasesN)__name__ __module__ __qualname__rpropertyrrrrrrr)s rc@sNeZdZddZddZddZddZdd d Zd d ZddZ ddZ d S)AliasescCsFtj|_d|_d|_|jr(d|_dS|j|js:dS|jdS)NTF)rrrr r_disabled_by_environ _load_main _load_aliases)r rrrrGs zAliases.__init__c Cshtjjd}y|jttjd|jStk r:dSt k rbt j t dtjddSXdS)NTZDNF_DISABLE_ALIASESFz@Unexpected value of environment variable: DNF_DISABLE_ALIASES=%s) r r rrrosenvironrKeyError RuntimeErrorloggerwarningr)r rrrrr%Ws  zAliases._disabled_by_environcCsyt|Stk rB}ztjjtd||fWYdd}~Xn:tk rz}ztjjtd||fWYdd}~XnXdS)NzParsing file "%s" failed: %szCannot read file "%s": %s)rr+r exceptions ConfigErrorrIOError)r rerrr _load_confds"zAliases._load_confcCsVy|jt|_|jj|_Wn6tjjk rP}ztjt d|WYdd}~XnXdS)NzConfig error: %s) r2ALIASES_CONF_PATHr rrr.r/r,debugr)r r1rrrr&ns  zAliases._load_mainNcCs|dkr.y |j}Wntjjk r,dSXxf|D]^}y"|j|}|jrX|jj|jWq4tjjk r}ztj t d|WYdd}~Xq4Xq4WdS)NzConfig error: %s) _dropin_dir_filenamesrr.r/r2rrupdater,r-r)r filenamesfilenamer r1rrrr'us   zAliases._load_aliasescstjjttjjtgfdd}g}yPtjjts@tjtx4ttj tD]"}||r^qP|j tjj t|qPWWn2t t fk r}ztjj|WYdd}~XnXtjjtr|j t|S)Ncs|kp|jdp|jd S)N..conf.CONF)r:r;) startswithendswith)r8)ignored_filenamesrr_ignore_filenames z7Aliases._dropin_dir_filenames.._ignore_filename)r(rbasenamer3ALIASES_USER_PATHexistsALIASES_DROPIN_DIRmkdirsortedlistdirappendjoinr0OSErrorrr.r/)r r?r7fnr1r)r>rr5s       zAliases._dropin_dir_filenamescs:gg_fddfdd|}j|S)NcsNd}x&|D]}|r |ddkr P|d7}q Wj|d|7_||dS)Nr-)prefix_options)argsZnumarg)r rr store_prefixs  z&Aliases._resolve..store_prefixc s|}| s*|djks*|djdrry.j|djdrV|ddd|d<Wntk rlYnX|S|dkrtjjtdj|dj|d}|r||ddS|ddSdS)Nr\rLz"Aliases contain infinite recursion) rr<poprrr.ErrorrrG)rNsuffixZcurrent_alias_result)r stackrP subresolverrrVs&  z$Aliases._resolve..subresolve)rM)r rNrTr)r rUrPrVr_resolves  zAliases._resolvecCsP|jrLy|j|}Wn6tjjk rJ}ztjtd|WYdd}~XnX|S)Nz%s, using original arguments.)rrWrr.rSr,errorr)r rNr1rrrresolves "zAliases.resolve)N) r r!r"rr%r2r&r'r5rWrYrrrrr$Fs   /r$)Z __future__rrZdnf.i18nrrZdnf.clirZdnf.conf.configrZdnf.exceptionsZ libdnf.confr Zloggingr(Zos.pathZ getLoggerr,rCrrHr3rAobjectrr$rrrrs     __pycache__/format.cpython-36.opt-1.pyc000064400000004461151030066770013643 0ustar003 ft`@s8ddlmZddlmZd ddZd ddZdd Zd S) )unicode_literals)long c Csddddddddd g }|r d }nd }d }d }t|d}|dkrDd}x$||krh||krh|d}||}qFWt|ts~t|trd}n|dkrd}nd}|t|pd |||fS)aReturn a human-readable metric-like string representation of a number. :param number: the number to be converted to a human-readable form :param SI: If is 0, this function will use the convention that 1 kilobyte = 1024 bytes, otherwise, the convention that 1 kilobyte = 1000 bytes will be used :param space: string that will be placed between the number and the SI prefix :return: a human-readable metric-like string representation of *number* rkMGTPEZYg@@g@irNgz%i%s%sgfffff#@z%.1f%s%sz%.0f%s%s)len isinstanceintrfloat) ZnumberZSIZspaceZsymbolsstepZthreshdepthZ max_depthformatr/usr/lib/python3.6/format.py format_numbers4  rcCsx|dks|dkr|rdSdSnV|tdkr.dSt|}|d}|d}|rh|d}|d}d|||fSd ||fSdS) aReturn a human-readable string representation of a number of seconds. The string will show seconds, minutes, and optionally hours. :param seconds: the number of seconds to convert to a human-readable form :param use_hours: If use_hours is 0, the representation will be in minutes and seconds. Otherwise, it will be in hours, minutes, and seconds :return: a human-readable string representation of *seconds* Nrz--:--:--z--:--infZInfinite<z%02i:%02i:%02iz %02i:%02i)rr)ZsecondsZ use_hoursZminutesZhoursrrr format_timeIs rcCsdjdd|jDS)N css|]}d|VqdS)z Nr).0srrr hszindent_block..)join splitlines)rrrr indent_blockgsr!N)rr)r)Z __future__rZ dnf.pycomprrrr!rrrrs   5 __pycache__/cli.cpython-36.pyc000064400000074203151030066770012164 0ustar003 g @stdZddlmZddlmZddlmZyddlmZWn ek rXddlmZYnXddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlmZdd lmZdd lmZmZddlZddlZddlZddlZddlZddl Zddl!Zddl"Zddl#Zddl$Zddl%Zddl&Zddl'Zddl(Zddl)Zddl*Zddl+Zddl,Zddl-Zddl.Zddl/Zddl0Zddl1Zddl2Zddl3Zddl4Zddl5Zddl6Zddl7Zddl8Zddl9Zddl:Zddl;ZddlZddl?Zddl@ZddlAZddlBZddlCZddlDZe jEd ZFdd dZGddZHddZIddZJGdddejKZLGdddeMZNdS)z/ Command line interface yum class and related. )print_function)absolute_import)unicode_literals)SequenceN)output)CliError)ucd_dnfcCst|jdt|jt|}t|j}t|j}xFd|fd|fd|ffD],\}}||j|d|||d7<qLWdS)zl Get the length of each pkg's column. Add that to data. This "knows" about simpleList and printVer. rnaverridrN)lennamearchZevrZ _from_repo setdefault)datapkgindentr rrdvr/usr/lib/python3.6/cli.py_add_pkg_simple_list_lens]s     rcCsiiid}x<|j|j|j|j|j|jfD]}x|D]}t||q4Wq*Wt|jdkrx*|j D] \}}t||t||d dq`W|d|d|dg}|j |d d }|d |d  |d  fS) zA Work out the dynamic size of the columns to pass to fmtColumns. )r rrr )rr rrr)Zremainder_columnz ) installed availableextras autoremoveupdatesrecentrr obsoletesobsoletesTuplesZ calcColumns)ryplrZlstrZnpkgZopkgcolumnsrrr_list_cmd_calc_columnshs   r)c Csdd}tjj|}d}x|jjj|dD]}|r>tdd}|jdkrbd|j|j |j f}nd |j|j|j |j f}|j j |j }ttd ||||jfttd |jr|jnd||jfq.WdS) NcSstjdtj|S)Nz%c)timestrftimeZgmtime)xrrr sm_ui_timezsz"print_versions..sm_ui_timeF)rr T0z%s-%s.%sz %s:%s-%s.%sz Installed: %s-%s at %sz Built : %s at %s)r sack rpmdb_sackqueryrfiltermprintZepochversionreleasertermboldrr Z installtimeZpackagerZ buildtime) pkgsbaserr-r0donerrrrrrprint_versionsys    r;cCs>td}x0|jD]$\}}tj|j||d|dqWdS)NzTThe operation would result in switching of module '{0}' stream '{1}' to stream '{2}'rr)r itemsloggerwarningformat)switchedModulesZmsg1Z moduleNameZstreamsrrrreport_module_switchsrAcseZdZdZd fdd Zfffdd ZddZd d Zd d Zd dZ fdddfddZ ddZ ggdfddZ dfdfddZ d!ddZfddZddZZS)"BaseCliz#This is the base class for yum cli.Ncs4|p tjj}tt|j|dtj||j|_dS)N)conf)r rCZConfsuperrB__init__rZOutput)selfrC) __class__rrrEszBaseCli.__init__cstjjrJ|jjsJt|jj}|rJt|t dj tj j d}tj j||j}|jj|}|rjtj||rg}g}d}xF|D]>} | jtjjkr|j| jq| jtjjkrd}|j| jqW|`|s|jj|n|jj|||s|jjs|jr|jjs|jjr|jj r:tjt dj tj j!dn(d|jj"krbtjt dj tj j!d|j#r|jj$s|jj% rt&t dntjt d d S|rD|r:tjt d y|jj'} |j(||jj)| Wn\tj j*k r8} z:tj+j j,t-| } t d d | } t.tj j| WYd d } ~ XnX|j/||jj rRd St0|t1sd|g}tj2gt3|}t4t5|j6|}|d k r|j7j8|gd}tj9jj:|j7|j;}nd }|rt.t.dj<|jj=|t.x.|D]&} | j>t?jj@krtj jt dqW|S)zTake care of package downloading, checking, user confirmation and actually running the transaction. :param display: `rpm.callback.TransactionProgress` object(s) :return: history database transaction ID or None aQIt is not possible to switch enabled streams of a module unless explicitly enabled via configuration option module_stream_switch. It is recommended to rather remove all installed content from the module, and reset the module using '{prog} module reset ' command. After you reset the module, you can install the other stream.)progTFz7{prog} will only download packages for the transaction.ZtestzP{prog} will only download packages, install gpg keys, and check the transaction.zOperation aborted.zNothing to do.NzDownloading Packages:zError downloading packages:z %sr zTransaction failed)Ar r9Z WITH_MODULESrCZmodule_stream_switchdictZ_moduleContainerZgetSwitchedStreamsrAr r?util MAIN_PROG exceptionsErrorZ transactionrZlist_transactionr=infoactionZFORWARD_ACTIONSappendrZBACKWARD_ACTIONSZ_tsZreportRemoveSizeZreportDownloadSizeZ isChangedZ_historygroupenv downloadonlyMAIN_PROG_UPPERZtsflags _promptWantedassumeno userconfirmrZdownload_callback_total_cbZdownload_packagesprogressZ DownloadErrorcliZ indent_blockr r3 gpgsigcheck isinstancerZCliTransactionDisplaylistrDrBdo_transactionhistoryoldZdbZRPMTransactionZ_transjoinZpost_transaction_outputstatelibdnfZTransactionItemState_ERROR)rFZdisplayr@msgZtransZpkg_strZ install_pkgsZrmpkgsZ install_onlyZtsiZtotal_cbeZspecificZerrstrtid)rGrrr^s              zBaseCli.do_transactionc sg}x|D]}j|\}}|dkr(q q |dkrĈjjo@jj }tj sVtjj rl| rltjj t dfdd}yj ||Wqtjj t fk r}z|j t|WYdd}~XqXq |j |q W|rx|D]} tj| qWtjj t ddS)aPerform GPG signature verification on the given packages, installing keys if possible. :param pkgs: a list of package objects to verify the GPG signatures of :raises: Will raise :class:`Error` if there's a problem rrzTRefusing to automatically import keys when running unattended. Use "-y" to override.cs jjS)N)rrX)r,yz)rFrr$sz%BaseCli.gpgsigcheck..NzGPG check FAILED)Z_sig_check_pkgrC assumeyesrWsysstdinisattyr rMrNr Z_get_key_for_package ValueErrorrQstrr=critical) rFr8Zerror_messagesporesulterrmsgZayfnrerdr)rFrr[ s&  " zBaseCli.gpgsigcheckcsXdx:|jjjd|jD]$}|tj}|rtjj|dPqWfdd|j D}|S)zBReturn list of changelogs for package newer then installed versionNrrcs$g|]}dks|dkr|qS)N timestampr).0Zchlog)newestrr =sz-BaseCli.latest_changelogs..) Z_rpmconnZ readonly_tsZdbMatchrrpmZRPMTAG_CHANGELOGTIMEdatetimeZdateZ fromtimestamp changelogs)rFpackageZmiZchangelogtimesZchlogsr)rwrlatest_changelogs3s zBaseCli.latest_changelogscCs4d|djdtjj|dtjj|df}|S)z*Return changelog formatted as in spec filez * %s %s %s ruz%a %b %d %X %YZauthortext)r+r Zi18nr )rFZ changelogZ chlog_strrrrformat_changelogAs  zBaseCli.format_changelogcCst}x&|D]}|j|jp|jgj|q Wxdt|jD]T}||}ttdj dj dd|Dx$|j |dD]}t|j |qzWq.r) rJr source_namerrQsortedkeysr3r r?rar}r)rFZpackagesZbysrpmprZ bin_packagesZchlrrrprint_changelogsIs "zBaseCli.print_changelogsTFc CsR|jd||d}|jjs |jjr@|jd||d}|j|_|j|_|rDt|j|}t|jdkri}|jj j d} | rx>t |jD]0} | j } t jj| r| jr| || j| jf<qW|jj} |jj} |jj|jdd||| | dd |r|j|jt|jdkrDttd x0t |jtjdd D]}|jj|d|d q(W|jpP|jS) z?Check updates matching given *patterns* in selected repository.Zupgrades)reponamer%rr7r r])=znot in)Z outputType highlight_nar(highlight_modeszObsoleting Packages)key)r()returnPkgListsrCr%verboser&r)rrr#r6MODErZlocalPkgospathexistsZverifyLocalPkgrrcolor_update_localcolor_update_remotelistPkgsrr3r operator itemgetterupdatesObsoletesList)rFpatternsrZprint_r{r'Ztyplr( local_pkgs highlightrqZlocalculcurobtuprrr check_updatesUs:    zBaseCli.check_updatescCsr|jj}t|dkr |jnx|D]}|j|q&W|jj|}|dkrn|jj rntd}tjj|dS)ab Upgrade or downgrade packages to match the latest versions available in the enabled repositories. :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage rz4No packages marked for distribution synchronization.N) Z_goalZ req_lengthrZ distro_syncZreq_has_distupgrade_allr r rMrN)rFZuserlistZoldcountpkg_specZcntrdrrrdistro_sync_userlist{s    zBaseCli.distro_sync_userlistc CsTd}xf|D]^}y|j||dd}Wq tjjk rf}z"tjtd|jjj |j WYdd}~Xq Xq Wx|D]}y|j ||dd}Wqrtjj k r}z$td} tj| |jjj |WYdd}~Xqrtjj k r}z"tjtd|jjj |jWYdd}~Xqrtjjk r4ds0tYqrXqrW|sPtjjtddS) aaAttempt to take the user specified list of packages or wildcards and downgrade them. If a complete version number is specified, attempt to downgrade them to the specified version :param specs: a list of names or wildcards specifying packages to downgrade :param file_pkgs: a list of pkg objects from local files F)strictTzNo match for argument: %sNzNo package %s available.z6Packages for argument %s available, but not installed.z!No packages marked for downgrade.)Zpackage_downgrader rMZ MarkingErrorr=rOr rr6r7locationZ downgrade_toZPackageNotFoundErrorZPackagesNotInstalledErrorrAssertionErrorrN) rFZspecsZ file_pkgsrrrrreargerrrdrrr downgradePkgss,   ( & "zBaseCli.downgradePkgsallc!CsDy$|jjjd}|j||||d}Wn0tjjk rT}zdt|gfSd}~XnXi}i} i} d} |dkrzt|j|} |r|j rxB|j |j |j D],} | j | jf} | |ks| || kr| || <qW|o|jrx8|jD].} | j | jf} | | ks| | | kr| | | <qW|rP|jrPx2t|jD]$}|jtjkr(|| |j |jf<q(W|jj}|jj}|jj}|jj}|jj|j td||| ||||dd}|jj}|jj}|jj}|jj }|jj|jtd || | ||||d d}|jj|j!td || d }|jj|j"td || d }|jj#}|jj$}|jj|jtd|| | ||dd}t%|j&dkr|dkrt%|j&}t'tdxLt|j(t)j*ddD]}|jj+|d| d qWn|jj|j&td|| d }|jj|j,td|| d } t%|r@| dkr@|dkr@|dkr@|dkr@|dkr@|dkr@|dkr@tjjtddS)zJOutput selection *pkgnarrow* of packages matching *patterns* and *repoid*.r7)installed_availablerrNr]zInstalled Packages)>r9 cli_commandscommandr rZZdemandZ DemandSheetdemandsregister_commandZcommandsaliasZ AliasCommandr"ZAutoremoveCommandZcheckZ CheckCommandZcleanZ CleanCommandZ distrosyncZDistroSyncCommandZdeplistZDeplistCommandZ downgradeZDowngradeCommandrRZ GroupCommandr_ZHistoryCommandZinstallZInstallCommandZ makecacheZMakeCacheCommandZmarkZ MarkCommandmoduleZ ModuleCommandZ reinstallZReinstallCommandremoveZ RemoveCommandrepolistZRepoListCommandZ repoqueryZRepoQueryCommandsearchZ SearchCommandshellZ ShellCommandZswapZ SwapCommandZ updateinfoZUpdateInfoCommandZupgradeZUpgradeCommandZupgrademinimalZUpgradeMinimalCommandZ InfoCommandZ ListCommandZProvidesCommandZCheckUpdateCommandZRepoPkgsCommandZ HelpCommand)rFr9rrrrEfsBz Cli.__init__cCs|jj||jr^xJ|jjD]<\}}|jjj||jj|gd}|j||jj |dfqW|j r|jj dd |jj dd|j Dt }yzxt|jD]j\}}|jjj|}|s|jjjr|dkrtd} tjj| ||j||dkr|jq|jqWWnFtjjk rP} z$tj| |jjtjd WYdd} ~ XnXx|D]}tjtd |qXW|jjj } | dkr|jjj!} x,| D]$} |jjj"| }|r|j#j$qW|jj%j&\} |j_'|jjj(j)| t%j*|j|jj%}|jjj(j+|dS) N)Zbaseurlenabler*disablecSsg|] }|dfqS)rr)rvrrrrrxsz(Cli._configure_repos..zUnknown repo: '%s'rzNo repository match: %s)rr),r9Zread_all_reposZ repofrompathr<reposZ add_new_reporC_configure_from_optionsZrepos_edrQrepoinsertrsetZ get_matchingrr r rMZ RepoErroraddrr ConfigErrorr=rp optparser print_helprkexitr>Z_repo_persistorZget_expired_reposrget_repoexpirerZsetup_progress_callbacksZ _ds_callbackrset_progress_barZ CliKeyImportZ_set_key_import)rFoptsZlabelrZ this_repoZnotmatchrZ operationrrdreZ expired_reposrZbarZ key_importrrr_configure_repossL            zCli._configure_reposcCsvtjdjtjjdtjjtjtj j d|j tjtj j d|j j jtjtj j d|j j jtjd|j j jdS)Nz{prog} version: %s)rHz Command: %szInstallroot: %szReleasever: %sz cachedir: %s)r=debugr?r rKrUconstVERSIONlogloggingDDEBUG cmdstringr9rC installroot releasevercachedir)rFrrr_log_essentialss      zCli._log_essentialscCs|j}|jj}|jr.tjjs.tjjt d|j rLx|j D] }d|_ q>W|j s\|jjj rd|jj_ xn|jD]}|jjtjjqpWnL|jrxD|j D]}|jjqWn(|jsx |jD]}|jjtjjqW|jr|jj|jjrdnd|jjddS)Nz[This command has to be run with superuser privileges (under the root user on most systems).TautoF)load_system_repoZload_available_repos)rr9rZ root_userr rKZ am_i_rootrMrNr r{ iter_enabledZload_metadata_other cacheonlyrCvaluesrZsetSyncStrategyrZSYNC_ONLY_CACHEfreshest_metadatarZfresh_metadataZ SYNC_LAZYZsack_activationZ fill_sackrZavailable_repos)rFrrrrrr_process_demandss.    zCli._process_demandscCs|j}|jj|}|dkr~tjtd|tjd|jj j r`tjtdj t j jt j jd|ntjtdj t j jdt|||_tjt jjd|tjt jjd |dS) z,Check that the requested CLI command exists.Nz)No such command: %s. Please use %s --helprzLIt could be a {PROG} plugin command, try: "{prog} install 'dnf-command(%s)'")rHZPROGzRIt could be a {prog} plugin command, but loading of plugins is currently disabled.)rHzBase command: %szExtra commands: %s)rrrr=rpr rkargvr9rCZpluginsr?r rKrLrUrrrr)rFrrr command_clsrrr_parse_commandss      zCli._parse_commandsNc Cstjjj}|j|}|dkr*tjjjn||_|jj|}|j rpt tj j t |jjj|j|jjtjd|jrd|_d|_|jrtj j|_|_yh|jr|jjjd|jjjtjjd|j_|jjj||j|j d|kr|j!|jj_!|jjj"Wntj#j$t%fk rF}z t&j't(d|tjdWYdd}~XnXt)k r}z:d t*t+|t,|j-f}t&j't(d|tjdWYdd}~XnX|j.dk r|j.|jj_.|jjj/ r|j0dkrt&j't(dtjd|j1s|j2r|j0dkrt&j't(dtjd|j3dk r>t4j5t6j7|j3d|jj8|j9d|jj:|j;|j<||jj8|j9d|j0s|jj=tjd||j_>|jj?d|_@x$|jj>D]}|j@d|7_@qW|jAy|jB||Wn tCk rtjdYnX|jDr$|jj=|j0tjd|jjE|j0|}|jFrN|jF|j_Gd|j_H|jIr`|jI|j_I|jJrrd|jj_K|jLrd|jj_L|j0jM|jjN|jjO|jP||jjQ|jjj||j0jR|jjj.rtjSjT|jjj.|jjj.|jjUjV_W|jjjXdkr(|jjjYjZ|jjjXdt[j\ddkrd}x,|jjUj]D]}|j^rZqJd|_^d}qJW|jjj_sd|jj__d}|rt&j`t(ddS)aParse 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 :param option_parser: a class for parsing cli options NrrrTrzConfig error: %srz%s: %sdownloadsystem-upgradereposync modulesynczb--destdir or --downloaddir must be used with --downloadonly or download or system-upgrade command.zconfig-managerz_--enable, --set-enabled and --disable, --set-disabled must be used with config-manager command.<mainZpluginrz%s r)colorz%_pkgverify_level signaturerFzWarning: Enforcing GPG signature check globally as per active RPM security policy (see 'gpgcheck' in dnf.conf(5) for how to squelch this message))rrrr)rr)ar rZaliasesZAliasesZresolve option_parserZ OptionParserrZparse_main_argsr4r3rrr;r9rCZhistory_record_packagesrrkrquietZ debuglevelZ errorlevelrZ VERBOSE_LEVELrZ _set_valueZsystem_cachedirZ PRIO_DEFAULTrr_read_conf_filerrZ_adjust_conf_optionsrMrrnr=rpr IOErrorr roreprfilenameZdestdirrTrZ set_enabledZ set_disabledZ sleeptimer*ZsleeprandomZ randrangeZ add_commandsrZ init_pluginsZ disablepluginZ enablepluginrrrHrrrrhelpZparse_command_argsZ allowerasingZ allow_erasingZ_allow_erasingrZ debugsolverZ debug_solverr%Z pre_configureZpre_configure_pluginsZ_activate_persistorrZconfigure_plugins configurerKZ ensure_dirrrZpkgdirrr6ZreinitryZ expandMacrorZgpgcheckZlocalpkg_gpgcheckr>) rFrrrrrerZforcingrrrrrs                                z Cli.configurecCsBtjjd}|jj}|jd|jd|jd}|jdtjj krht j j | rhtj jtdj||jtjjd|jd}|jdtjj krd}|j}|j||jdd|dkr|jdkrtjj|j}n|dkrtjj|}|dk r||_|jdkrtjtd xd D]}|j|qW|jjj|||S)NconfigZconfig_file_pathzConfig file "{}" does not exist)ZpriorityZreposdirvarsdir/)rzPUnable to detect release version (use '--releasever' to specify release version)rlogdir persistdir)rrr)r rZTimerr9rCZ_check_remote_fileZ_search_inside_installrootZ _get_valueZ _get_priorityZPRIO_COMMANDLINErrisfilerMrr r?readZPRIO_MAINCONFIGZ substitutionsZupdate_from_etcrryZdetect_releaseverrr=r>Zprepend_installroot_loggingZ_setup_from_dnf_conf)rFrZtimerrCrZ from_rootZsubstoptrrrrs6        zCli._read_conf_fileeqcCs|dkr|dkrdSg}|js"|r,|jd|js6|r@|jd|jsJ|rT|jd|js^|rh|jd|jj|||j|j|j |j ddS)zz :param opts: :param cmp_type: string supported "eq", "gte" :param all: :return: Nbugfix enhancement newpackagesecurity)typesadvisorybugzillacvesseverity) r rQr r r r9Zadd_security_filtersrrrr)rFrZcmp_typerrrrr _populate_update_security_filters        z$Cli._populate_update_security_filtercCs4|dk r|jjjj||dk r0|jjjj|dS)z Change minimal logger level for terminal output to stdout and stderr according to specific command requirements @param stdout: logging.INFO, logging.WARNING, ... @param stderr:logging.INFO, logging.WARNING, ... N)r9rZstdout_handlerZsetLevelZstderr_handler)rFstdoutstderrrrrredirect_loggerszCli.redirect_loggercCs.tjjj|}||jj_|jjjj|dS)N) r rZrYZMultiFileProgressMeterr9rrrr)rFZforYrrrredirect_repo_progresss zCli.redirect_repo_progresscCs|jjj}|dkrdS|jjjj|jd}|j}|jdd|}x|D]}||krL|}qLW||krtd|td|dS)N)rr )Z advisory_typez,Security: %s is an installed security updatez-Security: %s is the currently running version)r9r/Zget_running_kernelr1r2rrr3)rFZkernelqZikpkgrrrr_check_running_kernels    zCli._check_running_kernelcCs*t|jjtjjtdj||dS)Nz)argument {}: not allowed with argument {})r3rZ print_usager rMrNr r?)rFZoption_string_1Zoption_string_2rrr_option_conflicts zCli._option_conflictcCs<x6|jD],}||jkr*tjjtd|||j|<qWdS)zRegister a Command. :apizCommand "%s" already definedN)rrr rMrr )rFrrrrrrs  zCli.register_commandcCs|j|jjjr8tjtddjtt |jjj|jjj rhtjtddjtt |jjj xx|jj j D]h}|jrtjtd|j ddjtt |j|j rvtjtd|j ddjtt |j qvW|jjS)a2Call the base command, and pass it the extended commands or arguments. :return: (exit_code, [ errors ]) exit_code is:: 0 = we're done, exit 1 = we've errored, exit with error string 2 = we've got work yet to do, onto the next stage zExcludes in dnf.conf: z, zIncludes in dnf.conf: zExcludes in repo z: zIncludes in repo )rr9rCZ excludepkgsr=rr rarrZ includepkgsrridrrun)rFrrrrrs  " "(,zCli.run)N)N)r N)NN)rrrrErrrrrrrrrkrrrrrrrrrrres$3   -  r)r )OrZ __future__rrrcollections.abcr ImportError collectionsrzrrrrryrkr*rZlibdnf.transactionrcr rZdnf.clirZdnf.i18nr r r Zdnf.cli.aliasesZdnf.cli.commandsZdnf.cli.commands.aliasZdnf.cli.commands.autoremoveZdnf.cli.commands.checkZdnf.cli.commands.cleanZdnf.cli.commands.deplistZdnf.cli.commands.distrosyncZdnf.cli.commands.downgradeZdnf.cli.commands.groupZdnf.cli.commands.historyZdnf.cli.commands.installZdnf.cli.commands.makecacheZdnf.cli.commands.markZdnf.cli.commands.moduleZdnf.cli.commands.reinstallZdnf.cli.commands.removeZdnf.cli.commands.repolistZdnf.cli.commands.repoqueryZdnf.cli.commands.searchZdnf.cli.commands.shellZdnf.cli.commands.swapZdnf.cli.commands.updateinfoZdnf.cli.commands.upgradeZdnf.cli.commands.upgrademinimalZdnf.cli.demandZdnf.cli.formatZdnf.cli.option_parserZdnf.confZdnf.conf.substitutionsZ dnf.constZdnf.db.historyZdnf.exceptionsZ dnf.loggingZ dnf.persistorZ dnf.pluginZdnf.rpmZdnf.sackZdnf.transactionZdnf.utilZ dnf.yum.miscZ getLoggerr=rr)r;rAZBaserBobjectrrrrrs       O__pycache__/completion_helper.cpython-36.pyc000064400000020733151030066770015124 0ustar003 g/ @s<ddlZddlZddlZddlZddZddZGdddejjj j Z Gdd d ejjj j ZGd d d ejjjjZGd d d ejjjZGdddejjjjZGdddejjjjZGdddejjjjZGdddejjjjZddZ e!dkr8ye ej"ddWn e#k r6ej$dYnXdS)Ncstfdd|S)Ncst|jS)N)str startswith)k)kw'/usr/lib/python3.6/completion_helper.pysz#filter_list_by_kw..)filter)rZlstr)rrfilter_list_by_kwsr cCstdd|DS)NcSsg|] }t|qSr)r).0xrrr !sz%listpkg_to_setstr..)set)pkgsrrrlistpkg_to_setstr srcs,eZdZfddZddZddZZS)RemoveCompletionCommandcstt|j|dS)N)superr__init__)selfargs) __class__rrr$sz RemoveCompletionCommand.__init__cCsd|jj_d|jj_dS)NFT)clidemands root_usersack_activation)rrrr configure's z!RemoveCompletionCommand.configurecCs,x&tj|j|jjD]}tt|qWdS)N)ListCompletionCommand installedbaseopts pkg_specsprintr)rpkgrrrrun+szRemoveCompletionCommand.run)__name__ __module__ __qualname__rrr# __classcell__rr)rrr#s rcs,eZdZfddZddZddZZS)InstallCompletionCommandcstt|j|dS)N)rr(r)rr)rrrr1sz!InstallCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrravailable_reposr)rrrrr4s  z"InstallCompletionCommand.configurecCsNttj|j|jj}ttj|j|jj}x||D]}tt|q6WdS)N) rrrrrr availabler!r)rrr*r"rrrr#9s     zInstallCompletionCommand.run)r$r%r&rrr#r'rr)rrr(0s r(cs,eZdZfddZddZddZZS)ReinstallCompletionCommandcstt|j|dS)N)rr+r)rr)rrrrCsz#ReinstallCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrrr)r)rrrrrFs  z$ReinstallCompletionCommand.configurecCsNttj|j|jj}ttj|j|jj}x||@D]}tt|q6WdS)N) rrrrrr r*r!r)rrr*r"rrrr#Ks     zReinstallCompletionCommand.run)r$r%r&rrr#r'rr)rrr+Bs r+csHeZdZfddZddZeddZeddZed d ZZ S) rcstt|j|dS)N)rrr)rr)rrrrTszListCompletionCommand.__init__cCs|j}|jj}|jj}t|dkrH|d|krHtdjt|d|n|dkr`|j|j |}n||dkrx|j |j |}nd|dkr|j |j |}nLt |j |j |}t |j|j |}||B}|stdjt|d|dSx|D]}tt |qWdS)N rr*updatesr)Z pkgnarrowsrZpackagesZpackages_actionlenr!joinr rrr*r.rr)rsubcmdsractionrr*rr"rrrr#Ws& zListCompletionCommand.runcCs |jjjjdj|ddS)Nz{}*r) name__glob)sackqueryrfiltermformat)rargrrrrnszListCompletionCommand.installedcCs |jjjjdj|ddS)Nz{}*r)r3)r4r5r*r6r7)rr8rrrr*rszListCompletionCommand.availablecCs|jdj|dgddS)Nz{}*rF)Zprint_)Z check_updatesr7)rr8rrrr.vszListCompletionCommand.updates) r$r%r&rr# staticmethodrr*r.r'rr)rrrSs    rcs$eZdZfddZddZZS)RepoListCompletionCommandcstt|j|dS)N)rr:r)rr)rrrr|sz"RepoListCompletionCommand.__init__cCs|j}|jdkr>tdjt|jddd|jjjDnn|jdkrvtdjt|jddd|jjjDn6|jdkrtdjt|jdd d|jjjDdS) Nenabledr-rcSsg|] }|jqSr)id)r rrrrr sz1RepoListCompletionCommand.run..ZdisabledcSsg|]}|js|jqSr)r;r<)r r=rrrr sallcSsg|] }|jqSr)r<)r r=rrrr s) rZ repos_actionr!r0r ZreposrZ iter_enabledr>)rrrrrr#s   zRepoListCompletionCommand.run)r$r%r&rr#r'rr)rrr:{s r:cs,eZdZfddZddZddZZS)UpgradeCompletionCommandcstt|j|dS)N)rr?r)rr)rrrrsz!UpgradeCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrrr)r)rrrrrs  z"UpgradeCompletionCommand.configurecCs,x&tj|j|jjD]}tt|qWdS)N)rr.rrr r!r)rr"rrrr#szUpgradeCompletionCommand.run)r$r%r&rrr#r'rr)rrr?s r?cs,eZdZfddZddZddZZS)DowngradeCompletionCommandcstt|j|dS)N)rr@r)rr)rrrrsz#DowngradeCompletionCommand.__init__cCs"d|jj_d|jj_d|jj_dS)NFT)rrrr)r)rrrrrs  z$DowngradeCompletionCommand.configurecCs0x*tj|j|jjjD]}tt|qWdS)N)rr*rrr Z downgradesr!r)rr"rrrr#szDowngradeCompletionCommand.run)r$r%r&rrr#r'rr)rrr@s r@cs$eZdZfddZddZZS)CleanCompletionCommandcstt|j|dS)N)rrAr)rr)rrrrszCleanCompletionCommand.__init__cCs0tjjjjj}tdjt|j j d|dS)Nr-r,) dnfrcommandscleanZ _CACHE_TYPESkeysr!r0r rtype)rr1rrrr#szCleanCompletionCommand.run)r$r%r&rr#r'rr)rrrAs rAc Cstjjj}tjj|}|ddkrP|jgg|tdjt|d|jdS|jj |j t |j t |j t |j t|j t|j t|j t|j t|j|y |jWn&ttjjfk rtjdYnXdS)NrZ_cmdsr-r,)rBrZBaseCliZCliZ init_pluginsr!r0r Z cli_commandsclearZregister_commandrr(r+rr:r?r@rArr#OSError exceptionsErrorsysexit)rrrrrrmains(              rM__main__r,)%Zdnf.exceptionsrBZdnf.cliZdnf.cli.commands.cleanrKr rrrCremoveZ RemoveCommandrZinstallZInstallCommandr(Z reinstallZReinstallCommandr+Z ListCommandrZrepolistZRepoListCommandr:ZupgradeZUpgradeCommandr?Z downgradeZDowngradeCommandr@rDZ CleanCommandrArMr$argvKeyboardInterruptrLrrrrs& (  __pycache__/main.cpython-36.opt-1.pyc000064400000012241151030066770013272 0ustar003 ft`f@sPdZddlmZddlmZddlmZddlmZddlmZddl m Z ddl m Z dd l mZdd l mZdd lZdd lZdd l Zdd lZdd l Zdd lZdd lZdd lZdd lZdd lZdd lZdd lZdd lZdd lZejd Zd dZddZ eee fddZ!ddZ"ddZ#ddZ$d ddZ%e&dkrLe%ej'dd ddd S)!z4 Entrance point for the yum command line interface. )print_function)absolute_import)unicode_literals)Conf)Cli) OptionParser)ucd)show_lock_owner)_NdnfcCs&tjtjjdddtjt|dS)NT)exc_info)loggerlogr loggingSUBDEBUGcriticalr)er/usr/lib/python3.6/main.py ex_IOError2srcCs6tjtjjddd|jdk r2tjtdt|dS)Nr T)r z Error: %sr) rrr rrvaluerr r)rrrrex_Error8s rcCsy6tjjtjjj|}t||||SQRXWntjjk rr}ztj |j t |j dSd}~XnLtjj k r}ztj |j dSd}~Xntjjk r}zdSd}~Xntjjk r}zt|Sd}~Xntjk r$}ztj tdt|dSd}~Xntjjk r\}ztj tdt|dSd}~Xnbtk r}zt|Sd}~Xn>tk r}z tj djt|jtddSd}~XnXdS)Nrz Error: %sz{}: {}z Terminated.)r Zi18nZ setup_stdoutcliZBaseCli_main exceptionsZProcessLockErrorrrrr pid LockError DepsolveErrorErrorrhawkey Exceptionr rlibdnferrorIOErrorrKeyboardInterruptformattype__name__)argsZ conf_class cli_classZoption_parser_classbaserrrrmain?s4    r.cCsb|jj||}y|jttt||Wn(ttfk rV}zt|Sd}~XnXt ||S)z2Run the dnf program from a command line interface.N) Z_loggingZ _presetupZ configurelistmaprr&OSErrorrcli_run)r-r+r,Z option_parserrrrrrr\s rc,Csy td}WnFtk rR}z*|jtjkrBtjtdtjdWYdd}~Xn X|j y |j Wn@t j j k rYn(ttfk r}zt|Sd}~XnX|jjryt||}Wnt j jk r}zt|d}|jj r|jjddr|tdjd7}|jjjrN|s<|td jd 7}n|td jd 7}|jjjr|jjjd }|t jjkr|s|td jd7}n|tdjd7}|rtjdj|WYdd}~XnX|r|S|jj |jj!S)N.z8No read/execute access in current directory, moving to //r T)Z availablez?try to add '{}' to command line to replace conflicting packagesz--allowerasingz.try to add '{}' to skip uninstallable packagesz --skip-brokenz' or '{}' to skip uninstallable packagesbestz7try to add '{}' to use not only best candidate packagesz--nobestz0 or '{}' to use not only best candidate packagesz({}))"openr&errnoZEACCESrrr oschdircloseZrunr rrr1rdemands resolvingr r allow_erasingZ_goalZproblem_conflictsr(r-Zconfstrictr5Z _get_priorityZPRIO_MAINCONFIGinfocommandZrun_transactionZsuccess_exit_status)rr-frretmsgZpriorrrr2msT             r2cCs |jdkr&|j|jjtjtd|jjg}|jj dk rN|j |jj y|j |dWnt j jk r}ztjt|dSd}~Xnvt jjk r}z$x|jj|D]}tj|qWdSd}~Xn4tk r}zt|Sd}~XnXtjtddS)z9Perform the depsolve, download and RPM transaction stage.NzDependencies resolved.)Zdisplayrz Complete!r)Z transactionZresolver;r=rr?r r@Z run_resolvedZtransaction_displayappendZdo_transactionr rZCliErrorr%rrZTransactionCheckErrorZget_error_outputrr&r)rr-ZdisplaysexcerrrCrrrrr<s(   r<FcCst|}|rtj||S)apCall one of the multiple main() functions based on environment variables. :param args: command line arguments passed into yum :param exit_code: if *exit_code* is True, this function will exit python with its exit code when it has finished executing. Otherwise, it will return its exit code. :return: the exit code from dnf.yum execution )r.sysexit)r+ exit_codeZerrcoderrr user_mains  rJ__main__rT)rI)F)(__doc__Z __future__rrrZdnf.confrZ dnf.cli.clirZdnf.cli.option_parserrZdnf.i18nrZ dnf.cli.utilsr r Zdnf.clir Zdnf.exceptionsZ dnf.loggingZdnf.utilr7r"Z libdnf.errorr$rr8Zos.pathrGZ getLoggerrrrr.rr2r<rJr*argvrrrrsB          5  __pycache__/demand.cpython-36.pyc000064400000003013151030066770012634 0ustar003 ft` @s0ddlmZGdddeZGdddeZdS))unicode_literalsc@s&eZdZddZdddZddZdS) _BoolDefaultcCs ||_d|jjt|f|_dS)Nz__%s%x)default __class____name__id _storing_name)selfrr /usr/lib/python3.6/demand.py__init__sz_BoolDefault.__init__NcCs |j}|j|kr||jS|jS)N)__dict__rr)r objZobjtypeobjdictr r r __get__s  z_BoolDefault.__get__cCs8|j}|j|kr*||j}||kr*td|||j<dS)NzDemand already set.)r rAttributeError)r rvalrZ current_valr r r __set__#s   z_BoolDefault.__set__)N)r __module__ __qualname__r rrr r r r rs rc@speZdZdZedZedZedZedZedZ edZ dZ edZ edZ edZedZdZedZdS) DemandSheetzHCollection of demands that different CLI parts have on other parts. :apiFTrN)rrr__doc__rZ allow_erasingZavailable_reposZ resolvingZ root_userZsack_activationZload_system_repoZsuccess_exit_statusZ cacheonlyZfresh_metadataZfreshest_metadataZ changelogsZtransaction_displayZplugin_filtering_enabledr r r r r+srN)Z __future__robjectrrr r r r s __pycache__/progress.cpython-36.pyc000064400000010777151030066770013267 0ustar003 ft`@spddlmZddlmZmZddlmZddlmZddl m Z ddl Z ddl Z ddl Z Gddde jjZdS) )unicode_literals) format_number format_time) _term_width)unicode)timeNc@sreZdZdZejjdejjdejjdejj diZ e j dddfd d Z d d ZdddZddZddZddZdS)MultiFileProgressMeterz"Multi-file download progress meterZFAILEDZSKIPPEDZMIRRORZDRPMg333333?g?g@cCsp||_||_||_||_d|_d|_tjj|_d|_ d|_ d|_ g|_ i|_ d|_d|_d|_d|_d|_dS)zCreates a new progress meter instance update_period -- how often to update the progress bar tick_period -- how fast to cycle through concurrent downloads rate_average -- time constant for average speed calculation rN)fo update_period tick_period rate_averageunknown_progres total_drpmsysstdoutisatty done_drpm done_files done_sizeactivestate last_time last_sizerate total_files total_size)selfr r r r r/usr/lib/python3.6/progress.py__init__&s" zMultiFileProgressMeter.__init__cCstjjd||jdS)NZ write_flush)dnfutilZ_terminal_messengerr )rmsgrrrmessage?szMultiFileProgressMeter.messagercCsF||_||_||_d|_d|_d|_g|_i|_d|_d|_ d|_ dS)Nr) rrrrrrrrrrr)rrrZ total_drpmsrrrstartBszMultiFileProgressMeter.startcCst}t|}t|j}t|}||jkrD|df|j|<|jj||j|\}}||f|j|<|j||7_||j|j kr||j kr||_ |j |dS)Nr) rrint download_sizerrappendrrr r_update)rpayloaddonenowtextZtotalr$oldrrrprogressSs    zMultiFileProgressMeter.progresscCsJ|jrj||j}|j|j}|dkrj|dkrj||}|jdk rdt||jd}|||jd|}||_||_|j|_|jsdS|jt||j t |j}|j dkrd|j d}t |jdkr|d|j t |j7}d||j |f}|jo|j rt|j |j|j}nd}d|jr,t|jndt|j|f} tt | } | d d } | d kr0|j r|jd |j } t|j| d |j d \}} d |d| }d| | || f} | | d 8} nj|jd}d} |dkrdn|}d|d | }d| || f} | | d 8} |jd| kr*|jdnd|_|jd| | || fdS)Nrz%dz-%dz (%s/%d): %sz--:--z %5sB/s | %5sB %9s ETA z--- d=-z%3d%% [%-*s]%s z [%-*s]%sz%-*.*s%s)rrrrminr rrr%r lenrrrrrrdivmodr r#)rr+Z delta_timeZ delta_sizerZweightr,nZtime_etar"leftZblZpctpZbarrrrr(gsX        zMultiFileProgressMeter._updatec Cst}}t|}t|j}d}|tjjkr.n|tjjkrJ|jd7_nt||j kr|j j |\}}|j j |||8}|j d7_ |j|7_n(|tjjkr|j d7_ |j|7_|r*|tjjkr|jdkrd|j||j|j|f} nd|j||f} tt| d} d| | |f} nl|jdkrHd|j |j|f}t||d} dtt|| t|t| f} tt| } d | | || f} |j| |j r|j|dS) Nrr/z[%s %d/%d] %s: z [%s] %s: z%s%-*s z (%d/%d): %sgMbP?z %5sB/s | %5sB %9s z%-*.*s%s)rrr%r&r callback STATUS_MIRROR STATUS_DRPMrrpoprremoverrSTATUS_ALREADY_EXISTSr STATUS_2_STRrr9rmaxrfloatrr#r() rr)ZstatusZerr_msgr$r+r,sizer*r"r<ZtmrrrendsH          zMultiFileProgressMeter.endN)r)__name__ __module__ __qualname____doc__r r>Z STATUS_FAILEDrCr?r@rDrstderrrr#r$r.r(rHrrrrrs  5r)Z __future__rZdnf.cli.formatrrZ dnf.cli.termrZ dnf.pycomprrrZ dnf.callbackr Zdnf.utilr>ZDownloadProgressrrrrrs    output.py000064400000255005151030066770006472 0ustar00# Copyright 2005 Duke University # Copyright (C) 2012-2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Handle actual output from the cli.""" from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import fnmatch import hawkey import itertools import libdnf.transaction import logging import operator import pwd import re import sys import time from dnf.cli.format import format_number, format_time from dnf.i18n import _, C_, P_, ucd, fill_exact_width, textwrap_fill, exact_width, select_short_long from dnf.pycomp import xrange, basestring, long, unicode, sys_maxsize from dnf.yum.rpmtrans import TransactionDisplay from dnf.db.history import MergedTransactionWrapper import dnf.base import dnf.callback import dnf.cli.progress import dnf.cli.term import dnf.conf import dnf.crypto import dnf.i18n import dnf.transaction import dnf.util import dnf.yum.misc logger = logging.getLogger('dnf') def _spread_in_columns(cols_count, label, lst): left = itertools.chain((label,), itertools.repeat('')) lst_length = len(lst) right_count = cols_count - 1 missing_items = -lst_length % right_count if not lst_length: lst = itertools.repeat('', right_count) elif missing_items: lst.extend(('',) * missing_items) lst_iter = iter(lst) return list(zip(left, *[lst_iter] * right_count)) class Output(object): """Main output class for the yum command line.""" GRP_PACKAGE_INDENT = ' ' * 3 FILE_PROVIDE_RE = re.compile(r'^\*{0,2}/') def __init__(self, base, conf): self.conf = conf self.base = base self.term = dnf.cli.term.Term() self.progress = None def _banner(self, col_data, row): term_width = self.term.columns rule = '%s' % '=' * term_width header = self.fmtColumns(zip(row, col_data), ' ') return rule, header, rule def _col_widths(self, rows): col_data = [dict() for _ in rows[0]] for row in rows: for (i, val) in enumerate(row): col_dct = col_data[i] length = len(val) col_dct[length] = col_dct.get(length, 0) + 1 cols = self.calcColumns(col_data, None, indent=' ') # align to the left return list(map(operator.neg, cols)) def _highlight(self, highlight): hibeg = '' hiend = '' if not highlight: pass elif not isinstance(highlight, basestring) or highlight == 'bold': hibeg = self.term.MODE['bold'] elif highlight == 'normal': pass # Minor opt. else: # Turn a string into a specific output: colour, bold, etc. for high in highlight.replace(',', ' ').split(): if high == 'normal': hibeg = '' elif high in self.term.MODE: hibeg += self.term.MODE[high] elif high in self.term.FG_COLOR: hibeg += self.term.FG_COLOR[high] elif (high.startswith('fg:') and high[3:] in self.term.FG_COLOR): hibeg += self.term.FG_COLOR[high[3:]] elif (high.startswith('bg:') and high[3:] in self.term.BG_COLOR): hibeg += self.term.BG_COLOR[high[3:]] if hibeg: hiend = self.term.MODE['normal'] return (hibeg, hiend) def _sub_highlight(self, haystack, highlight, needles, **kwds): hibeg, hiend = self._highlight(highlight) return self.term.sub(haystack, hibeg, hiend, needles, **kwds) @staticmethod def _calc_columns_spaces_helps(current, data_tups, left): """ Spaces left on the current field will help how many pkgs? """ ret = 0 for tup in data_tups: if left < (tup[0] - current): break ret += tup[1] return ret @property def history(self): return self.base.history @property def sack(self): return self.base.sack def calcColumns(self, data, columns=None, remainder_column=0, total_width=None, indent=''): """Dynamically calculate the widths of the columns that the fields in data should be placed into for output. :param data: a list of dictionaries that represent the data to be output. Each dictionary in the list corresponds to a column of output. The keys of the dictionary are the lengths of the items to be output, and the value associated with a key is the number of items of that length. :param columns: a list containing the minimum amount of space that must be allocated for each row. This can be used to ensure that there is space available in a column if, for example, the actual lengths of the items being output cannot be given in *data* :param remainder_column: number of the column to receive a few extra spaces that may remain after other allocation has taken place :param total_width: the total width of the output. self.term.real_columns is used by default :param indent: string that will be prefixed to a line of output to create e.g. an indent :return: a list of the widths of the columns that the fields in data should be placed into for output """ cols = len(data) # Convert the data to ascending list of tuples, (field_length, pkgs) pdata = data data = [None] * cols # Don't modify the passed in data for d in range(0, cols): data[d] = sorted(pdata[d].items()) if total_width is None: total_width = self.term.real_columns # We start allocating 1 char to everything but the last column, and a # space between each (again, except for the last column). Because # at worst we are better with: # |one two three| # | four | # ...than: # |one two three| # | f| # |our | # ...the later being what we get if we pre-allocate the last column, and # thus. the space, due to "three" overflowing it's column by 2 chars. if columns is None: columns = [1] * (cols - 1) columns.append(0) # i'm not able to get real terminal width so i'm probably # running in non interactive terminal (pipe to grep, redirect to file...) # avoid splitting lines to enable filtering output if not total_width: full_columns = [] for d in xrange(0, cols): col = data[d] if col: full_columns.append(col[-1][0]) else: full_columns.append(columns[d] + 1) full_columns[0] += len(indent) # if possible, try to keep default width (usually 80 columns) default_width = self.term.columns if sum(full_columns) > default_width: return full_columns total_width = default_width total_width -= (sum(columns) + (cols - 1) + exact_width(indent)) if not columns[-1]: total_width += 1 while total_width > 0: # Find which field all the spaces left will help best helps = 0 val = 0 for d in xrange(0, cols): thelps = self._calc_columns_spaces_helps(columns[d], data[d], total_width) if not thelps: continue # We prefer to overflow: the last column, and then earlier # columns. This is so that in the best case (just overflow the # last) ... grep still "works", and then we make it prettier. if helps and (d == (cols - 1)) and (thelps / 2) < helps: continue if thelps < helps: continue helps = thelps val = d # If we found a column to expand, move up to the next level with # that column and start again with any remaining space. if helps: diff = data[val].pop(0)[0] - columns[val] if not columns[val] and (val == (cols - 1)): # If we are going from 0 => N on the last column, take 1 # for the space before the column. total_width -= 1 columns[val] += diff total_width -= diff continue overflowed_columns = 0 for d in xrange(0, cols): if not data[d]: continue overflowed_columns += 1 if overflowed_columns: # Split the remaining spaces among each overflowed column # equally norm = total_width // overflowed_columns for d in xrange(0, cols): if not data[d]: continue columns[d] += norm total_width -= norm # Split the remaining spaces among each column equally, except the # last one. And put the rest into the remainder column cols -= 1 norm = total_width // cols for d in xrange(0, cols): columns[d] += norm columns[remainder_column] += total_width - (cols * norm) total_width = 0 return columns @staticmethod def _fmt_column_align_width(width): """Returns tuple of (align_left, width)""" if width < 0: return (True, -width) return (False, width) def _col_data(self, col_data): assert len(col_data) == 2 or len(col_data) == 3 if len(col_data) == 2: (val, width) = col_data hibeg = hiend = '' if len(col_data) == 3: (val, width, highlight) = col_data (hibeg, hiend) = self._highlight(highlight) return (ucd(val), width, hibeg, hiend) def fmtColumns(self, columns, msg=u'', end=u''): """Return a row of data formatted into a string for output. Items can overflow their columns. :param columns: a list of tuples containing the data to output. Each tuple contains first the item to be output, then the amount of space allocated for the column, and then optionally a type of highlighting for the item :param msg: a string to begin the line of output with :param end: a string to end the line of output with :return: a row of data formatted into a string for output """ columns = list(columns) total_width = len(msg) data = [] for col_data in columns[:-1]: (val, width, hibeg, hiend) = self._col_data(col_data) if not width: # Don't count this column, invisible text msg += u"%s" data.append(val) continue (align_left, width) = self._fmt_column_align_width(width) val_width = exact_width(val) if val_width <= width: # Don't use fill_exact_width() because it sucks performance # wise for 1,000s of rows. Also allows us to use len(), when # we can. msg += u"%s%s%s%s " if align_left: data.extend([hibeg, val, " " * (width - val_width), hiend]) else: data.extend([hibeg, " " * (width - val_width), val, hiend]) else: msg += u"%s%s%s\n" + " " * (total_width + width + 1) data.extend([hibeg, val, hiend]) total_width += width total_width += 1 (val, width, hibeg, hiend) = self._col_data(columns[-1]) (align_left, width) = self._fmt_column_align_width(width) val = fill_exact_width(val, width, left=align_left, prefix=hibeg, suffix=hiend) msg += u"%%s%s" % end data.append(val) return msg % tuple(data) def simpleList(self, pkg, ui_overflow=False, indent='', highlight=False, columns=None): """Print a package as a line. :param pkg: the package to be printed :param ui_overflow: unused :param indent: string to be prefixed onto the line to provide e.g. an indent :param highlight: highlighting options for the name of the package :param columns: tuple containing the space allocated for each column of output. The columns are the package name, version, and repository """ if columns is None: columns = (-40, -22, -16) # Old default na = '%s%s.%s' % (indent, pkg.name, pkg.arch) hi_cols = [highlight, 'normal', 'normal'] columns = zip((na, pkg.evr, pkg._from_repo), columns, hi_cols) print(self.fmtColumns(columns)) def simpleEnvraList(self, pkg, ui_overflow=False, indent='', highlight=False, columns=None): """Print a package as a line, with the package itself in envra format so it can be passed to list/install/etc. :param pkg: the package to be printed :param ui_overflow: unused :param indent: string to be prefixed onto the line to provide e.g. an indent :param highlight: highlighting options for the name of the package :param columns: tuple containing the space allocated for each column of output. The columns the are the package envra and repository """ if columns is None: columns = (-63, -16) # Old default envra = '%s%s' % (indent, ucd(pkg)) hi_cols = [highlight, 'normal', 'normal'] rid = pkg.ui_from_repo columns = zip((envra, rid), columns, hi_cols) print(self.fmtColumns(columns)) def simple_name_list(self, pkg): """Print a package as a line containing its name.""" print(ucd(pkg.name)) def simple_nevra_list(self, pkg): """Print a package as a line containing its NEVRA.""" print(ucd(pkg)) def fmtKeyValFill(self, key, val): """Return a key value pair in the common two column output format. :param key: the key to be formatted :param val: the value associated with *key* :return: the key value pair formatted in two columns for output """ keylen = exact_width(key) cols = self.term.real_columns if not cols: cols = sys_maxsize elif cols < 20: cols = 20 nxt = ' ' * (keylen - 2) + ': ' if not val: # textwrap.fill in case of empty val returns empty string return key val = ucd(val) ret = textwrap_fill(val, width=cols, initial_indent=key, subsequent_indent=nxt) if ret.count("\n") > 1 and keylen > (cols // 3): # If it's big, redo it again with a smaller subsequent off ret = textwrap_fill(val, width=cols, initial_indent=key, subsequent_indent=' ...: ') return ret def fmtSection(self, name, fill='='): """Format and return a section header. The format of the header is a line with *name* centered, and *fill* repeated on either side to fill an entire line on the terminal. :param name: the name of the section :param fill: the character to repeat on either side of *name* to fill an entire line. *fill* must be a single character. :return: a string formatted to be a section header """ name = ucd(name) cols = self.term.columns - 2 name_len = exact_width(name) if name_len >= (cols - 4): beg = end = fill * 2 else: beg = fill * ((cols - name_len) // 2) end = fill * (cols - name_len - len(beg)) return "%s %s %s" % (beg, name, end) def infoOutput(self, pkg, highlight=False): """Print information about the given package. :param pkg: the package to print information about :param highlight: highlighting options for the name of the package """ def format_key_val(key, val): return " ".join([fill_exact_width(key, 12, 12), ":", str(val)]) def format_key_val_fill(key, val): return self.fmtKeyValFill(fill_exact_width(key, 12, 12) + " : ", val or "") output_list = [] (hibeg, hiend) = self._highlight(highlight) # Translators: This is abbreviated 'Name'. Should be no longer # than 12 characters. You can use the full version if it is short # enough in your language. key = select_short_long(12, C_("short", "Name"), C_("long", "Name")) output_list.append(format_key_val(key, "%s%s%s" % (hibeg, pkg.name, hiend))) if pkg.epoch: # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val(_("Epoch"), pkg.epoch)) key = select_short_long(12, C_("short", "Version"), C_("long", "Version")) output_list.append(format_key_val(key, pkg.version)) # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val(_("Release"), pkg.release)) key = select_short_long(12, C_("short", "Arch"), C_("long", "Architecture")) output_list.append(format_key_val(key, pkg.arch)) key = select_short_long(12, C_("short", "Size"), C_("long", "Size")) output_list.append(format_key_val(key, format_number(float(pkg._size)))) # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val(_("Source"), pkg.sourcerpm)) key = select_short_long(12, C_("short", "Repo"), C_("long", "Repository")) output_list.append(format_key_val(key, pkg.repoid)) if pkg._from_system: history_repo = self.history.repo(pkg) if history_repo: # Translators: This message should be no longer than 12 chars. output_list.append(format_key_val(_("From repo"), history_repo)) if self.conf.verbose: # :hawkey does not support changelog information # print(_("Committer : %s") % ucd(pkg.committer)) # print(_("Committime : %s") % time.ctime(pkg.committime)) # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val(_("Packager"), pkg.packager)) # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val(_("Buildtime"), dnf.util.normalize_time(pkg.buildtime))) if pkg.installtime: # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val(_("Install time"), dnf.util.normalize_time(pkg.installtime))) history_pkg = self.history.package_data(pkg) if history_pkg: try: uid = int(history_pkg._item.getInstalledBy()) except ValueError: # In case int() fails uid = None # Translators: This message should be no longer than 12 chars. output_list.append(format_key_val(_("Installed by"), self._pwd_ui_username(uid))) # Translators: This is abbreviated 'Summary'. Should be no longer # than 12 characters. You can use the full version if it is short # enough in your language. key = select_short_long(12, C_("short", "Summary"), C_("long", "Summary")) output_list.append(format_key_val_fill(key, pkg.summary)) if pkg.url: output_list.append(format_key_val(_("URL"), ucd(pkg.url))) # Translators: This message should be no longer than 12 characters. output_list.append(format_key_val_fill(_("License"), pkg.license)) # Translators: This is abbreviated 'Description'. Should be no longer # than 12 characters. You can use the full version if it is short # enough in your language. key = select_short_long(12, C_("short", "Description"), C_("long", "Description")) output_list.append(format_key_val_fill(key, pkg.description)) return "\n".join(output_list) def updatesObsoletesList(self, uotup, changetype, columns=None): """Print a simple string that explains the relationship between the members of an update or obsoletes tuple. :param uotup: an update or obsoletes tuple. The first member is the new package, and the second member is the old package :param changetype: a string indicating what the change between the packages is, e.g. 'updates' or 'obsoletes' :param columns: a tuple containing information about how to format the columns of output. The absolute value of each number in the tuple indicates how much space has been allocated for the corresponding column. If the number is negative, the text in the column will be left justified, and if it is positive, the text will be right justified. The columns of output are the package name, version, and repository """ (changePkg, instPkg) = uotup if columns is not None: # New style, output all info. for both old/new with old indented chi = self.conf.color_update_remote if changePkg.reponame != hawkey.SYSTEM_REPO_NAME: chi = self.conf.color_update_local self.simpleList(changePkg, columns=columns, highlight=chi) self.simpleList(instPkg, columns=columns, indent=' ' * 4, highlight=self.conf.color_update_installed) return # Old style c_compact = changePkg.compactPrint() i_compact = '%s.%s' % (instPkg.name, instPkg.arch) c_repo = changePkg.repoid print('%-35.35s [%.12s] %.10s %-20.20s' % (c_compact, c_repo, changetype, i_compact)) def listPkgs(self, lst, description, outputType, highlight_na={}, columns=None, highlight_modes={}): """Prints information about the given list of packages. :param lst: a list of packages to print information about :param description: string describing what the list of packages contains, e.g. 'Available Packages' :param outputType: The type of information to be printed. Current options:: 'list' - simple pkg list 'info' - similar to rpm -qi output 'name' - simple name list 'nevra' - simple nevra list :param highlight_na: a dictionary containing information about packages that should be highlighted in the output. The dictionary keys are (name, arch) tuples for the package, and the associated values are the package objects themselves. :param columns: a tuple containing information about how to format the columns of output. The absolute value of each number in the tuple indicates how much space has been allocated for the corresponding column. If the number is negative, the text in the column will be left justified, and if it is positive, the text will be right justified. The columns of output are the package name, version, and repository :param highlight_modes: dictionary containing information about to highlight the packages in *highlight_na*. *highlight_modes* should contain the following keys:: 'not_in' - highlighting used for packages not in *highlight_na* '=' - highlighting used when the package versions are equal '<' - highlighting used when the package has a lower version number '>' - highlighting used when the package has a higher version number :return: number of packages listed """ if outputType in ['list', 'info', 'name', 'nevra']: if len(lst) > 0: print('%s' % description) info_set = set() if outputType == 'list': unique_item_dict = {} for pkg in lst: unique_item_dict[str(pkg) + str(pkg._from_repo)] = pkg lst = unique_item_dict.values() for pkg in sorted(lst): key = (pkg.name, pkg.arch) highlight = False if key not in highlight_na: highlight = highlight_modes.get('not in', 'normal') elif pkg.evr_eq(highlight_na[key]): highlight = highlight_modes.get('=', 'normal') elif pkg.evr_lt(highlight_na[key]): highlight = highlight_modes.get('>', 'bold') else: highlight = highlight_modes.get('<', 'normal') if outputType == 'list': self.simpleList(pkg, ui_overflow=True, highlight=highlight, columns=columns) elif outputType == 'info': info_set.add(self.infoOutput(pkg, highlight=highlight) + "\n") elif outputType == 'name': self.simple_name_list(pkg) elif outputType == 'nevra': self.simple_nevra_list(pkg) else: pass if info_set: print("\n".join(sorted(info_set))) return len(lst) def userconfirm(self, msg=None, defaultyes_msg=None): """Get a yes or no from the user, and default to No :msg: String for case with [y/N] :defaultyes_msg: String for case with [Y/n] :return: True if the user selects yes, and False if the user selects no """ yui = (ucd(_('y')), ucd(_('yes'))) nui = (ucd(_('n')), ucd(_('no'))) aui = yui + nui while True: if msg is None: msg = _('Is this ok [y/N]: ') choice = '' if self.conf.defaultyes: if defaultyes_msg is None: msg = _('Is this ok [Y/n]: ') else: msg = defaultyes_msg try: choice = dnf.i18n.ucd_input(msg) except EOFError: pass except KeyboardInterrupt: choice = nui[0] choice = ucd(choice).lower() if len(choice) == 0: choice = yui[0] if self.conf.defaultyes else nui[0] if choice in aui: break # If the English one letter names don't mix with the translated # letters, allow them too: if u'y' == choice and u'y' not in aui: choice = yui[0] break if u'n' == choice and u'n' not in aui: choice = nui[0] break if choice in yui: return True return False def _pkgs2name_dict(self, sections): installed = self.sack.query().installed()._name_dict() available = self.sack.query().available()._name_dict() d = {} for pkg_name in itertools.chain(*list(zip(*sections))[1]): if pkg_name in installed: d[pkg_name] = installed[pkg_name][0] elif pkg_name in available: d[pkg_name] = available[pkg_name][0] return d def _pkgs2col_lengths(self, sections, name_dict): nevra_lengths = {} repo_lengths = {} for pkg_name in itertools.chain(*list(zip(*sections))[1]): pkg = name_dict.get(pkg_name) if pkg is None: continue nevra_l = exact_width(ucd(pkg)) + exact_width(self.GRP_PACKAGE_INDENT) repo_l = exact_width(ucd(pkg.reponame)) nevra_lengths[nevra_l] = nevra_lengths.get(nevra_l, 0) + 1 repo_lengths[repo_l] = repo_lengths.get(repo_l, 0) + 1 return (nevra_lengths, repo_lengths) def _display_packages(self, pkg_names): for name in pkg_names: print('%s%s' % (self.GRP_PACKAGE_INDENT, name)) def _display_packages_verbose(self, pkg_names, name_dict, columns): for name in pkg_names: try: pkg = name_dict[name] except KeyError: # package not in any repo -> print only package name print('%s%s' % (self.GRP_PACKAGE_INDENT, name)) continue highlight = False if not pkg._from_system: highlight = self.conf.color_list_available_install self.simpleEnvraList(pkg, ui_overflow=True, indent=self.GRP_PACKAGE_INDENT, highlight=highlight, columns=columns) def display_pkgs_in_groups(self, group): """Output information about the packages in a given group :param group: a Group object to output information about """ def names(packages): return sorted(pkg.name for pkg in packages) print('\n' + _('Group: %s') % group.ui_name) verbose = self.conf.verbose if verbose: print(_(' Group-Id: %s') % ucd(group.id)) if group.ui_description: print(_(' Description: %s') % ucd(group.ui_description) or "") if group.lang_only: print(_(' Language: %s') % group.lang_only) sections = ( (_(' Mandatory Packages:'), names(group.mandatory_packages)), (_(' Default Packages:'), names(group.default_packages)), (_(' Optional Packages:'), names(group.optional_packages)), (_(' Conditional Packages:'), names(group.conditional_packages))) if verbose: name_dict = self._pkgs2name_dict(sections) col_lengths = self._pkgs2col_lengths(sections, name_dict) columns = self.calcColumns(col_lengths) columns = (-columns[0], -columns[1]) for (section_name, packages) in sections: if len(packages) < 1: continue print(section_name) self._display_packages_verbose(packages, name_dict, columns) else: for (section_name, packages) in sections: if len(packages) < 1: continue print(section_name) self._display_packages(packages) def display_groups_in_environment(self, environment): """Output information about the packages in a given environment :param environment: an Environment object to output information about """ def names(groups): return sorted(group.name for group in groups) print(_('Environment Group: %s') % environment.ui_name) if self.conf.verbose: print(_(' Environment-Id: %s') % ucd(environment.id)) if environment.ui_description: description = ucd(environment.ui_description) or "" print(_(' Description: %s') % description) sections = ( (_(' Mandatory Groups:'), names(environment.mandatory_groups)), (_(' Optional Groups:'), names(environment.optional_groups))) for (section_name, packages) in sections: if len(packages) < 1: continue print(section_name) self._display_packages(packages) def matchcallback(self, po, values, matchfor=None, verbose=None, highlight=None): """Output search/provides type callback matches. :param po: the package object that matched the search :param values: the information associated with *po* that matched the search :param matchfor: a list of strings to be highlighted in the output :param verbose: whether to output extra verbose information :param highlight: highlighting options for the highlighted matches """ def print_highlighted_key_item(key, item, printed_headline, can_overflow=False): if not printed_headline: print(_('Matched from:')) item = ucd(item) or "" if item == "": return if matchfor: item = self._sub_highlight(item, highlight, matchfor, ignore_case=True) if can_overflow: print(self.fmtKeyValFill(key, item)) else: print(key % item) def print_file_provides(item, printed_match): if not self.FILE_PROVIDE_RE.match(item): return False key = _("Filename : %s") file_match = False for filename in po.files: if fnmatch.fnmatch(filename, item): print_highlighted_key_item( key, filename, file_match or printed_match, can_overflow=False) file_match = True return file_match if self.conf.showdupesfromrepos: msg = '%s : ' % po else: msg = '%s.%s : ' % (po.name, po.arch) msg = self.fmtKeyValFill(msg, po.summary or "") if matchfor: if highlight is None: highlight = self.conf.color_search_match msg = self._sub_highlight(msg, highlight, matchfor, ignore_case=True) print(msg) if verbose is None: verbose = self.conf.verbose if not verbose: return print(_("Repo : %s") % po.ui_from_repo) printed_match = False name_match = False for item in set(values): if po.summary == item: name_match = True continue # Skip double name/summary printing if po.description == item: key = _("Description : ") print_highlighted_key_item(key, item, printed_match, can_overflow=True) printed_match = True elif po.url == item: key = _("URL : %s") print_highlighted_key_item(key, item, printed_match, can_overflow=False) printed_match = True elif po.license == item: key = _("License : %s") print_highlighted_key_item(key, item, printed_match, can_overflow=False) printed_match = True elif print_file_provides(item, printed_match): printed_match = True else: key = _("Provide : %s") for provide in po.provides: provide = str(provide) if fnmatch.fnmatch(provide, item): print_highlighted_key_item(key, provide, printed_match, can_overflow=False) printed_match = True else: first_provide = provide.split()[0] possible = set('=<>') if any((char in possible) for char in item): item_new = item.split()[0] else: item_new = item if fnmatch.fnmatch(first_provide, item_new): print_highlighted_key_item( key, provide, printed_match, can_overflow=False) printed_match = True if not any([printed_match, name_match]): for item in set(values): key = _("Other : %s") print_highlighted_key_item(key, item, printed_match, can_overflow=False) print() def matchcallback_verbose(self, po, values, matchfor=None): """Output search/provides type callback matches. This will output more information than :func:`matchcallback`. :param po: the package object that matched the search :param values: the information associated with *po* that matched the search :param matchfor: a list of strings to be highlighted in the output """ return self.matchcallback(po, values, matchfor, verbose=True) def reportDownloadSize(self, packages, installonly=False): """Report the total download size for a set of packages :param packages: a list of package objects :param installonly: whether the transaction consists only of installations """ totsize = 0 locsize = 0 insize = 0 error = False for pkg in packages: # Just to be on the safe side, if for some reason getting # the package size fails, log the error and don't report download # size try: size = int(pkg._size) totsize += size try: if pkg.verifyLocalPkg(): locsize += size except Exception: pass if not installonly: continue try: size = int(pkg.installsize) except Exception: pass insize += size except Exception: error = True msg = _('There was an error calculating total download size') logger.error(msg) break if not error: if locsize: logger.info(_("Total size: %s"), format_number(totsize)) if locsize != totsize: logger.info(_("Total download size: %s"), format_number(totsize - locsize)) if installonly: logger.info(_("Installed size: %s"), format_number(insize)) def reportRemoveSize(self, packages): """Report the total size of packages being removed. :param packages: a list of package objects """ totsize = 0 error = False for pkg in packages: # Just to be on the safe side, if for some reason getting # the package size fails, log the error and don't report download # size try: size = pkg._size totsize += size except Exception: error = True msg = _('There was an error calculating installed size') logger.error(msg) break if not error: logger.info(_("Freed space: %s"), format_number(totsize)) def list_group_transaction(self, comps, history, diff): if not diff: return None out = [] rows = [] if diff.new_groups: out.append(_('Marking packages as installed by the group:')) for grp_id in diff.new_groups: pkgs = list(diff.added_packages(grp_id)) group_object = comps._group_by_id(grp_id) grp_name = group_object.ui_name if group_object else grp_id rows.extend(_spread_in_columns(4, "@" + grp_name, pkgs)) if diff.removed_groups: out.append(_('Marking packages as removed by the group:')) for grp_id in diff.removed_groups: pkgs = list(diff.removed_packages(grp_id)) grp_name = history.group.get(grp_id).ui_name rows.extend(_spread_in_columns(4, "@" + grp_name, pkgs)) if rows: col_data = self._col_widths(rows) for row in rows: out.append(self.fmtColumns(zip(row, col_data), ' ')) out[0:0] = self._banner(col_data, (_('Group'), _('Packages'), '', '')) return '\n'.join(out) def list_transaction(self, transaction, total_width=None): """Return a string representation of the transaction in an easy-to-read format. """ forward_actions = hawkey.UPGRADE | hawkey.UPGRADE_ALL | hawkey.DISTUPGRADE | \ hawkey.DISTUPGRADE_ALL | hawkey.DOWNGRADE | hawkey.INSTALL skipped_conflicts = set() skipped_broken = set() if transaction is None: # set empty transaction list instead of returning None # in order to display module changes when RPM transaction is empty transaction = [] list_bunch = dnf.util._make_lists(transaction) pkglist_lines = [] data = {'n' : {}, 'v' : {}, 'r' : {}} a_wid = 0 # Arch can't get "that big" ... so always use the max. def _add_line(lines, data, a_wid, po, obsoletes=[]): (n, a, e, v, r) = po.pkgtup evr = po.evr repoid = po._from_repo size = format_number(po._size) if a is None: # gpgkeys are weird a = 'noarch' # none, partial, full? if po._from_system: hi = self.conf.color_update_installed elif po._from_cmdline: hi = self.conf.color_update_local else: hi = self.conf.color_update_remote lines.append((n, a, evr, repoid, size, obsoletes, hi)) # Create a dict of field_length => number of packages, for # each field. for (d, v) in (("n", len(n)), ("v", len(evr)), ("r", len(repoid))): data[d].setdefault(v, 0) data[d][v] += 1 a_wid = max(a_wid, len(a)) return a_wid ins_group_msg = _('Installing group/module packages') if dnf.base.WITH_MODULES \ else _('Installing group packages') for (action, pkglist) in [ # TRANSLATORS: This is for a list of packages to be installed. (C_('summary', 'Installing'), list_bunch.installed), # TRANSLATORS: This is for a list of packages to be upgraded. (C_('summary', 'Upgrading'), list_bunch.upgraded), # TRANSLATORS: This is for a list of packages to be reinstalled. (C_('summary', 'Reinstalling'), list_bunch.reinstalled), (ins_group_msg, list_bunch.installed_group), (_('Installing dependencies'), list_bunch.installed_dep), (_('Installing weak dependencies'), list_bunch.installed_weak), # TRANSLATORS: This is for a list of packages to be removed. (_('Removing'), list_bunch.erased), (_('Removing dependent packages'), list_bunch.erased_dep), (_('Removing unused dependencies'), list_bunch.erased_clean), # TRANSLATORS: This is for a list of packages to be downgraded. (C_('summary', 'Downgrading'), list_bunch.downgraded)]: lines = [] # build a reverse mapping to 'replaced_by' # this is required to achieve reasonable speed replaces = {} for tsi in transaction: if tsi.action != libdnf.transaction.TransactionItemAction_OBSOLETED: continue for i in tsi._item.getReplacedBy(): replaces.setdefault(i, set()).add(tsi) for tsi in sorted(pkglist, key=lambda x: x.pkg): if tsi.action not in dnf.transaction.FORWARD_ACTIONS + [libdnf.transaction.TransactionItemAction_REMOVE]: continue # get TransactionItems obsoleted by tsi obsoleted = sorted(replaces.get(tsi._item, [])) a_wid = _add_line(lines, data, a_wid, tsi.pkg, obsoleted) pkglist_lines.append((action, lines)) installedProfiles = sorted(dict(self.base._moduleContainer.getInstalledProfiles()).items()) if installedProfiles: action = _("Installing module profiles") lines = [] for name, profiles in installedProfiles: for profile in list(profiles): lines.append(("%s/%s" % (name, profile), "", "", "", "", "", "")) pkglist_lines.append((action, lines)) removedProfiles = sorted(dict(self.base._moduleContainer.getRemovedProfiles()).items()) if removedProfiles: action = _("Disabling module profiles") lines = [] for name, profiles in removedProfiles: for profile in list(profiles): lines.append(("%s/%s" % (name, profile), "", "", "", "", "", "")) pkglist_lines.append((action, lines)) enabledStreams = sorted(dict(self.base._moduleContainer.getEnabledStreams()).items()) if enabledStreams: action = _("Enabling module streams") lines = [] for name, stream in enabledStreams: lines.append((name, "", stream, "", "", "", "")) pkglist_lines.append((action, lines)) switchedStreams = sorted(dict(self.base._moduleContainer.getSwitchedStreams()).items()) if switchedStreams: action = _("Switching module streams") lines = [] for name, stream in switchedStreams: lines.append((name, "", "%s -> %s" % (stream[0], stream[1]), "", "", "", "")) pkglist_lines.append((action, lines)) disabledModules = sorted(list(self.base._moduleContainer.getDisabledModules())) if disabledModules: action = _("Disabling modules") lines = [] for name in disabledModules: lines.append((name, "", "", "", "", "", "")) pkglist_lines.append((action, lines)) resetModules = sorted(list(self.base._moduleContainer.getResetModules())) if resetModules: action = _("Resetting modules") lines = [] for name in resetModules: lines.append((name, "", "", "", "", "", "")) pkglist_lines.append((action, lines)) if self.base._history: def format_line(group): name = group.getName() return (name if name else _(""), "", "", "", "", "", "") install_env_group = self.base._history.env._installed if install_env_group: action = _("Installing Environment Groups") lines = [] for group in install_env_group.values(): lines.append(format_line(group)) pkglist_lines.append((action, lines)) upgrade_env_group = self.base._history.env._upgraded if upgrade_env_group: action = _("Upgrading Environment Groups") lines = [] for group in upgrade_env_group.values(): lines.append(format_line(group)) pkglist_lines.append((action, lines)) remove_env_group = self.base._history.env._removed if remove_env_group: action = _("Removing Environment Groups") lines = [] for group in remove_env_group.values(): lines.append(format_line(group)) pkglist_lines.append((action, lines)) install_group = self.base._history.group._installed if install_group: action = _("Installing Groups") lines = [] for group in install_group.values(): lines.append(format_line(group)) pkglist_lines.append((action, lines)) upgrade_group = self.base._history.group._upgraded if upgrade_group: action = _("Upgrading Groups") lines = [] for group in upgrade_group.values(): lines.append(format_line(group)) pkglist_lines.append((action, lines)) remove_group = self.base._history.group._removed if remove_group: action = _("Removing Groups") lines = [] for group in remove_group.values(): lines.append(format_line(group)) pkglist_lines.append((action, lines)) # show skipped conflicting packages if not self.conf.best and self.base._goal.actions & forward_actions: lines = [] skipped_conflicts, skipped_broken = self.base._skipped_packages( report_problems=True, transaction=transaction) skipped_broken = dict((str(pkg), pkg) for pkg in skipped_broken) for pkg in sorted(skipped_conflicts): a_wid = _add_line(lines, data, a_wid, pkg, []) recommendations = ["--best"] if not self.base._allow_erasing: recommendations.append("--allowerasing") skip_str = _("Skipping packages with conflicts:\n" "(add '%s' to command line " "to force their upgrade)") % " ".join(recommendations) # remove misleading green color from the "packages with conflicts" lines lines = [i[:-1] + ("", ) for i in lines] pkglist_lines.append((skip_str, lines)) lines = [] for nevra, pkg in sorted(skipped_broken.items()): a_wid = _add_line(lines, data, a_wid, pkg, []) skip_str = _("Skipping packages with broken dependencies%s") if self.base.conf.upgrade_group_objects_upgrade: skip_str = skip_str % "" else: skip_str = skip_str % _(" or part of a group") # remove misleading green color from the "broken dependencies" lines lines = [i[:-1] + ("", ) for i in lines] pkglist_lines.append((skip_str, lines)) output_width = self.term.columns if not data['n'] and not self.base._moduleContainer.isChanged() and not \ (self.base._history and (self.base._history.group or self.base._history.env)): return u'' else: data = [data['n'], {}, data['v'], data['r'], {}] columns = [1, a_wid, 1, 1, 5] columns = self.calcColumns(data, indent=" ", columns=columns, remainder_column=2, total_width=total_width) (n_wid, a_wid, v_wid, r_wid, s_wid) = columns real_width = sum(columns) + 5 output_width = output_width if output_width >= real_width else real_width # Do not use 'Package' without context. Using context resolves # RhBug 1302935 as a side effect. msg_package = select_short_long(n_wid, # Translators: This is the short version of 'Package'. You can # use the full (unabbreviated) term 'Package' if you think that # the translation to your language is not too long and will # always fit to limited space. C_('short', 'Package'), # Translators: This is the full (unabbreviated) term 'Package'. C_('long', 'Package')) msg_arch = select_short_long(a_wid, # Translators: This is abbreviated 'Architecture', used when # we have not enough space to display the full word. C_('short', 'Arch'), # Translators: This is the full word 'Architecture', used when # we have enough space. C_('long', 'Architecture')) msg_version = select_short_long(v_wid, # Translators: This is the short version of 'Version'. You can # use the full (unabbreviated) term 'Version' if you think that # the translation to your language is not too long and will # always fit to limited space. C_('short', 'Version'), # Translators: This is the full (unabbreviated) term 'Version'. C_('long', 'Version')) msg_repository = select_short_long(r_wid, # Translators: This is abbreviated 'Repository', used when # we have not enough space to display the full word. C_('short', 'Repo'), # Translators: This is the full word 'Repository', used when # we have enough space. C_('long', 'Repository')) msg_size = select_short_long(s_wid, # Translators: This is the short version of 'Size'. It should # not be longer than 5 characters. If the term 'Size' in your # language is not longer than 5 characters then you can use it # unabbreviated. C_('short', 'Size'), # Translators: This is the full (unabbreviated) term 'Size'. C_('long', 'Size')) out = [u"%s\n%s\n%s\n" % ('=' * output_width, self.fmtColumns(((msg_package, -n_wid), (msg_arch, -a_wid), (msg_version, -v_wid), (msg_repository, -r_wid), (msg_size, s_wid)), u" "), '=' * output_width)] for (action, lines) in pkglist_lines: if lines: totalmsg = u"%s:\n" % action for (n, a, evr, repoid, size, obsoletes, hi) in lines: columns = ((n, -n_wid, hi), (a, -a_wid), (evr, -v_wid), (repoid, -r_wid), (size, s_wid)) msg = self.fmtColumns(columns, u" ", u"\n") hibeg, hiend = self._highlight(self.conf.color_update_installed) for obspo in sorted(obsoletes): appended = ' ' + _('replacing') + ' %s%s%s.%s %s\n' appended %= (hibeg, obspo.name, hiend, obspo.arch, obspo.evr) msg += appended totalmsg = totalmsg + msg if lines: out.append(totalmsg) out.append(_(""" Transaction Summary %s """) % ('=' * output_width)) summary_data = ( (_('Install'), len(list_bunch.installed) + len(list_bunch.installed_group) + len(list_bunch.installed_weak) + len(list_bunch.installed_dep), 0), (_('Upgrade'), len(list_bunch.upgraded), 0), (_('Remove'), len(list_bunch.erased) + len(list_bunch.erased_dep) + len(list_bunch.erased_clean), 0), (_('Downgrade'), len(list_bunch.downgraded), 0), (_('Skip'), len(skipped_conflicts) + len(skipped_broken), 0)) max_msg_action = 0 max_msg_count = 0 max_msg_pkgs = 0 max_msg_depcount = 0 for action, count, depcount in summary_data: if not count and not depcount: continue msg_pkgs = P_('Package', 'Packages', count) len_msg_action = exact_width(action) len_msg_count = exact_width(unicode(count)) len_msg_pkgs = exact_width(msg_pkgs) if depcount: len_msg_depcount = exact_width(unicode(depcount)) else: len_msg_depcount = 0 max_msg_action = max(len_msg_action, max_msg_action) max_msg_count = max(len_msg_count, max_msg_count) max_msg_pkgs = max(len_msg_pkgs, max_msg_pkgs) max_msg_depcount = max(len_msg_depcount, max_msg_depcount) for action, count, depcount in summary_data: msg_pkgs = P_('Package', 'Packages', count) if depcount: msg_deppkgs = P_('Dependent package', 'Dependent packages', depcount) action_msg = fill_exact_width(action, max_msg_action) if count: msg = '%s %*d %s (+%*d %s)\n' out.append(msg % (action_msg, max_msg_count, count, "%-*s" % (max_msg_pkgs, msg_pkgs), max_msg_depcount, depcount, msg_deppkgs)) else: msg = '%s %s ( %*d %s)\n' out.append(msg % (action_msg, (max_msg_count + max_msg_pkgs) * ' ', max_msg_depcount, depcount, msg_deppkgs)) elif count: msg = '%s %*d %s\n' out.append(msg % (fill_exact_width(action, max_msg_action), max_msg_count, count, msg_pkgs)) return ''.join(out) def _pto_callback(self, action, tsis): # Works a bit like calcColumns, but we never overflow a column we just # have a dynamic number of columns. def _fits_in_cols(msgs, num): """ Work out how many columns we can use to display stuff, in the post trans output. """ if len(msgs) < num: return [] left = self.term.columns - ((num - 1) + 2) if left <= 0: return [] col_lens = [0] * num col = 0 for msg in msgs: if len(msg) > col_lens[col]: diff = (len(msg) - col_lens[col]) if left <= diff: return [] left -= diff col_lens[col] = len(msg) col += 1 col %= len(col_lens) for col in range(len(col_lens)): col_lens[col] += left // num col_lens[col] *= -1 return col_lens if not tsis: return '' out = [] msgs = [] out.append('{}:'.format(action)) for tsi in tsis: msgs.append(str(tsi)) for num in (8, 7, 6, 5, 4, 3, 2): cols = _fits_in_cols(msgs, num) if cols: break if not cols: cols = [-(self.term.columns - 2)] while msgs: current_msgs = msgs[:len(cols)] out.append(' {}'.format(self.fmtColumns(zip(current_msgs, cols)))) msgs = msgs[len(cols):] return out def post_transaction_output(self, transaction): """ Return a human-readable summary of the transaction. Packages in sections are arranged to columns. """ return dnf.util._post_transaction_output(self.base, transaction, self._pto_callback) def setup_progress_callbacks(self): """Set up the progress callbacks and various output bars based on debug level. """ progressbar = None if self.conf.debuglevel >= 2: progressbar = dnf.cli.progress.MultiFileProgressMeter(fo=sys.stdout) self.progress = dnf.cli.progress.MultiFileProgressMeter(fo=sys.stdout) # setup our depsolve progress callback return (progressbar, DepSolveProgressCallBack()) def download_callback_total_cb(self, remote_size, download_start_timestamp): """Outputs summary information about the download process. :param remote_size: the total amount of information that was downloaded, in bytes :param download_start_timestamp: the time when the download process started, in seconds since the epoch """ if remote_size <= 0: return width = self.term.columns logger.info("-" * width) dl_time = max(0.01, time.time() - download_start_timestamp) msg = ' %5sB/s | %5sB %9s ' % ( format_number(remote_size // dl_time), format_number(remote_size), format_time(dl_time)) msg = fill_exact_width(_("Total"), width - len(msg)) + msg logger.info(msg) def _history_uiactions(self, hpkgs): actions = set() actions_short = set() count = 0 for pkg in hpkgs: if pkg.action in (libdnf.transaction.TransactionItemAction_UPGRADED, libdnf.transaction.TransactionItemAction_DOWNGRADED): # skip states we don't want to display in user input continue actions.add(pkg.action_name) actions_short.add(pkg.action_short) count += 1 if len(actions) > 1: return count, ", ".join(sorted(actions_short)) # So empty transactions work, although that "shouldn't" really happen return count, "".join(list(actions)) def _pwd_ui_username(self, uid, limit=None): if isinstance(uid, list): return [self._pwd_ui_username(u, limit) for u in uid] # loginuid is set to -1 (0xFFFF_FFFF) on init, in newer kernels. # loginuid is set to INT_MAX (0x7FFF_FFFF) on init, in older kernels. if uid is None or uid in (0xFFFFFFFF, 0x7FFFFFFF): loginid = _("") name = _("System") + " " + loginid if limit is not None and len(name) > limit: name = loginid return ucd(name) def _safe_split_0(text, *args): """ Split gives us a [0] for everything _but_ '', this function returns '' in that case. """ ret = text.split(*args) if not ret: return '' return ret[0] try: user = pwd.getpwuid(int(uid)) fullname = _safe_split_0(ucd(user.pw_gecos), ';', 2) user_name = ucd(user.pw_name) name = "%s <%s>" % (fullname, user_name) if limit is not None and len(name) > limit: name = "%s ... <%s>" % (_safe_split_0(fullname), user_name) if len(name) > limit: name = "<%s>" % user_name return name except KeyError: return ucd(uid) def historyListCmd(self, tids, reverse=False): """Output a list of information about the history of yum transactions. :param tids: transaction Ids; lists all transactions if empty """ transactions = self.history.old(tids) if self.conf.history_list_view == 'users': uids = [1, 2] elif self.conf.history_list_view == 'commands': uids = [1] else: assert self.conf.history_list_view == 'single-user-commands' uids = set() done = 0 blanks = 0 for transaction in transactions: done += 1 if transaction.cmdline is None: blanks += 1 uids.add(transaction.loginuid) fmt = "%s | %s | %s | %s | %s" if len(uids) == 1: name = _("Command line") real_cols = self.term.real_columns if real_cols is None: # if output is redirected in `less` the columns # detected are None value, to detect terminal size # use stdin file descriptor real_cols = dnf.cli.term._real_term_width(0) if real_cols is None: # if even stdin fd fails use 24 to fit to 80 cols real_cols = 24 name_width = real_cols - 55 if real_cols > 79 else 24 else: # TRANSLATORS: user names who executed transaction in history command output name = _("User name") name_width = 24 print(fmt % (fill_exact_width(_("ID"), 6, 6), fill_exact_width(name, name_width, name_width), fill_exact_width(_("Date and time"), 16, 16), fill_exact_width(_("Action(s)"), 14, 14), fill_exact_width(_("Altered"), 7, 7))) # total table width: each column length +3 (padding and separator between columns) table_width = 6 + 3 + name_width + 3 + 16 + 3 + 14 + 3 + 7 print("-" * table_width) fmt = "%6u | %s | %-16.16s | %s | %4u" if reverse is True: transactions = reversed(transactions) for transaction in transactions: if len(uids) == 1: name = transaction.cmdline or '' else: name = self._pwd_ui_username(transaction.loginuid, 24) name = ucd(name) tm = time.strftime("%Y-%m-%d %H:%M", time.localtime(transaction.beg_timestamp)) num, uiacts = self._history_uiactions(transaction.data()) name = fill_exact_width(name, name_width, name_width) uiacts = fill_exact_width(uiacts, 14, 14) rmark = lmark = ' ' if transaction.return_code is None: rmark = lmark = '*' elif transaction.return_code: rmark = lmark = '#' # We don't check .errors, because return_code will be non-0 elif transaction.is_output: rmark = lmark = 'E' if transaction.altered_lt_rpmdb: rmark = '<' if transaction.altered_gt_rpmdb: lmark = '>' print(fmt % (transaction.tid, name, tm, uiacts, num), "%s%s" % (lmark, rmark)) def historyInfoCmd(self, tids, pats=[], mtids=set()): """Output information about a transaction in history :param tids: transaction Ids; prints info for the last transaction if empty :raises dnf.exceptions.Error in case no transactions were found """ tids = set(tids) last = self.history.last() if last is None: logger.critical(_('No transactions')) raise dnf.exceptions.Error(_('Failed history info')) lasttid = last.tid lastdbv = last.end_rpmdb_version transactions = [] if not tids: last = self.history.last(complete_transactions_only=False) if last is not None: tids.add(last.tid) transactions.append(last) else: transactions = self.history.old(tids) if not tids: logger.critical(_('No transaction ID, or package, given')) raise dnf.exceptions.Error(_('Failed history info')) bmtid, emtid = -1, -1 mobj = None done = False if mtids: mtids = sorted(mtids) bmtid, emtid = mtids.pop() for trans in transactions: if lastdbv is not None and trans.tid == lasttid: # If this is the last transaction, is good and it doesn't # match the current rpmdb ... then mark it as bad. rpmdbv = self.sack._rpmdb_version() trans.compare_rpmdbv(str(rpmdbv)) lastdbv = None merged = False if trans.tid >= bmtid and trans.tid <= emtid: if mobj is None: mobj = MergedTransactionWrapper(trans) else: mobj.merge(trans) merged = True elif mobj is not None: if done: print("-" * 79) done = True self._historyInfoCmd(mobj) mobj = None if mtids: bmtid, emtid = mtids.pop() if trans.tid >= bmtid and trans.tid <= emtid: mobj = trans merged = True if not merged: if done: print("-" * 79) done = True self._historyInfoCmd(trans, pats) if mobj is not None: if done: print("-" * 79) self._historyInfoCmd(mobj) def _historyInfoCmd(self, old, pats=[]): loginuid = old.loginuid if isinstance(loginuid, int): loginuid = [loginuid] name = [self._pwd_ui_username(uid) for uid in loginuid] _pkg_states_installed = {'i' : _('Installed'), 'e' : _('Erased'), 'o' : _('Upgraded'), 'n' : _('Downgraded')} _pkg_states_available = {'i' : _('Installed'), 'e' : _('Not installed'), 'o' : _('Older'), 'n' : _('Newer')} maxlen = max([len(x) for x in (list(_pkg_states_installed.values()) + list(_pkg_states_available.values()))]) _pkg_states_installed['maxlen'] = maxlen _pkg_states_available['maxlen'] = maxlen def _simple_pkg(pkg, prefix_len, was_installed=False, highlight=False, pkg_max_len=0, show_repo=True): prefix = " " * prefix_len if was_installed: _pkg_states = _pkg_states_installed else: _pkg_states = _pkg_states_available state = _pkg_states['i'] # get installed packages with name = pkg.name ipkgs = self.sack.query().installed().filterm(name=pkg.name).run() if not ipkgs: state = _pkg_states['e'] else: # get latest installed package from software database inst_pkg = self.history.package(ipkgs[0]) if inst_pkg: res = pkg.compare(inst_pkg) # res is: # 0 if inst_pkg == pkg # > 0 when inst_pkg > pkg # < 0 when inst_pkg < pkg if res == 0: pass # installed elif res > 0: state = _pkg_states['o'] # updated else: state = _pkg_states['n'] # downgraded if highlight: (hibeg, hiend) = self._highlight('bold') else: (hibeg, hiend) = self._highlight('normal') state = fill_exact_width(state, _pkg_states['maxlen']) ui_repo = '' if show_repo: ui_repo = pkg.ui_from_repo() print("%s%s%s%s %-*s %s" % (prefix, hibeg, state, hiend, pkg_max_len, str(pkg), ui_repo)) tids = old.tids() if len(tids) > 1: print(_("Transaction ID :"), "%u..%u" % (tids[0], tids[-1])) else: print(_("Transaction ID :"), tids[0]) begt = float(old.beg_timestamp) begtm = time.strftime("%c", time.localtime(begt)) print(_("Begin time :"), begtm) if old.beg_rpmdb_version is not None: if old.altered_lt_rpmdb: print(_("Begin rpmdb :"), old.beg_rpmdb_version, "**") else: print(_("Begin rpmdb :"), old.beg_rpmdb_version) if old.end_timestamp is not None: endt = old.end_timestamp endtm = time.strftime("%c", time.localtime(endt)) diff = endt - begt if diff < 5 * 60: diff = _("(%u seconds)") % diff elif diff < 5 * 60 * 60: diff = _("(%u minutes)") % (diff // 60) elif diff < 5 * 60 * 60 * 24: diff = _("(%u hours)") % (diff // (60 * 60)) else: diff = _("(%u days)") % (diff // (60 * 60 * 24)) print(_("End time :"), endtm, diff) if old.end_rpmdb_version is not None: if old.altered_gt_rpmdb: print(_("End rpmdb :"), old.end_rpmdb_version, "**") else: print(_("End rpmdb :"), old.end_rpmdb_version) if isinstance(name, (list, tuple)): seen = set() for i in name: if i in seen: continue seen.add(i) print(_("User :"), i) else: print(_("User :"), name) if isinstance(old.return_code, (list, tuple)): codes = old.return_code if codes[0] is None: print(_("Return-Code :"), "**", _("Aborted"), "**") codes = codes[1:] elif not all(codes): print(_("Return-Code :"), _("Success")) elif codes: print(_("Return-Code :"), _("Failures:"), ", ".join([str(i) for i in codes])) elif old.return_code is None: print(_("Return-Code :"), "**", _("Aborted"), "**") elif old.return_code: print(_("Return-Code :"), _("Failure:"), old.return_code) else: print(_("Return-Code :"), _("Success")) if isinstance(old.releasever, (list, tuple)): seen = set() for i in old.releasever: if i in seen: continue seen.add(i) print(_("Releasever :"), i) else: print(_("Releasever :"), old.releasever) if old.cmdline is not None: if isinstance(old.cmdline, (list, tuple)): for cmdline in old.cmdline: print(_("Command Line :"), cmdline) else: print(_("Command Line :"), old.cmdline) if old.comment is not None: if isinstance(old.comment, (list, tuple)): for comment in old.comment: print(_("Comment :"), comment) else: print(_("Comment :"), old.comment) perf_with = old.performed_with() if perf_with: print(_("Transaction performed with:")) max_len = 0 for with_pkg in perf_with: str_len = len(str(with_pkg)) if str_len > max_len: max_len = str_len for with_pkg in perf_with: _simple_pkg(with_pkg, 4, was_installed=True, pkg_max_len=max_len) print(_("Packages Altered:")) self.historyInfoCmdPkgsAltered(old, pats) t_out = old.output() if t_out: print(_("Scriptlet output:")) num = 0 for line in t_out: num += 1 print("%4d" % num, line) t_err = old.error() if t_err: print(_("Errors:")) num = 0 for line in t_err: num += 1 print("%4d" % num, line) # TODO: remove _history_state2uistate = {'True-Install' : _('Install'), 'Install' : _('Install'), 'Dep-Install' : _('Dep-Install'), 'Obsoleted' : _('Obsoleted'), 'Obsoleting' : _('Obsoleting'), 'Erase' : _('Erase'), 'Reinstall' : _('Reinstall'), 'Downgrade' : _('Downgrade'), 'Downgraded' : _('Downgraded'), 'Update' : _('Upgrade'), 'Updated' : _('Upgraded'), } def historyInfoCmdPkgsAltered(self, old, pats=[]): """Print information about how packages are altered in a transaction. :param old: the :class:`DnfSwdbTrans` to print information about :param pats: a list of patterns. Packages that match a patten in *pats* will be highlighted in the output """ # Note that these don't use _simple_pkg() because we are showing what # happened to them in the transaction ... not the difference between the # version in the transaction and now. all_uistates = self._history_state2uistate maxlen = 0 pkg_max_len = 0 packages = old.packages() for pkg in packages: uistate = all_uistates.get(pkg.action_name, pkg.action_name) if maxlen < len(uistate): maxlen = len(uistate) pkg_len = len(str(pkg)) if pkg_max_len < pkg_len: pkg_max_len = pkg_len for pkg in packages: prefix = " " * 4 if pkg.state != libdnf.transaction.TransactionItemState_DONE: prefix = " ** " highlight = 'normal' if pats: if any([pkg.match(pat) for pat in pats]): highlight = 'bold' (hibeg, hiend) = self._highlight(highlight) uistate = all_uistates.get(pkg.action_name, pkg.action_name) uistate = fill_exact_width(ucd(uistate), maxlen) print("%s%s%s%s %-*s %s" % (prefix, hibeg, uistate, hiend, pkg_max_len, str(pkg), pkg.ui_from_repo())) class DepSolveProgressCallBack(dnf.callback.Depsolve): """Provides text output callback functions for Dependency Solver callback.""" def pkg_added(self, pkg, mode): """Print information about a package being added to the transaction set. :param pkgtup: tuple containing the package name, arch, version, and repository :param mode: a short string indicating why the package is being added to the transaction set. Valid current values for *mode* are:: i = the package will be installed u = the package will be an update e = the package will be erased r = the package will be reinstalled d = the package will be a downgrade o = the package will be obsoleting another package ud = the package will be updated od = the package will be obsoleted """ output = None if mode == 'i': output = _('---> Package %s.%s %s will be installed') elif mode == 'u': output = _('---> Package %s.%s %s will be an upgrade') elif mode == 'e': output = _('---> Package %s.%s %s will be erased') elif mode == 'r': output = _('---> Package %s.%s %s will be reinstalled') elif mode == 'd': output = _('---> Package %s.%s %s will be a downgrade') elif mode == 'o': output = _('---> Package %s.%s %s will be obsoleting') elif mode == 'ud': output = _('---> Package %s.%s %s will be upgraded') elif mode == 'od': output = _('---> Package %s.%s %s will be obsoleted') if output: logger.debug(output, pkg.name, pkg.arch, pkg.evr) def start(self): """Perform setup at the beginning of the dependency solving process. """ logger.debug(_('--> Starting dependency resolution')) def end(self): """Output a message stating that dependency resolution has finished.""" logger.debug(_('--> Finished dependency resolution')) class CliKeyImport(dnf.callback.KeyImport): def __init__(self, base, output): self.base = base self.output = output def _confirm(self, id, userid, fingerprint, url, timestamp): def short_id(id): rj = '0' if dnf.pycomp.PY3 else b'0' return id[-8:].rjust(8, rj) msg = (_('Importing GPG key 0x%s:\n' ' Userid : "%s"\n' ' Fingerprint: %s\n' ' From : %s') % (short_id(id), userid, dnf.crypto._printable_fingerprint(fingerprint), url.replace("file://", ""))) logger.critical("%s", msg) if self.base.conf.assumeyes: return True if self.base.conf.assumeno: return False return self.output.userconfirm() class CliTransactionDisplay(TransactionDisplay): """A YUM specific callback class for RPM operations.""" width = property(lambda self: dnf.cli.term._term_width()) def __init__(self): super(CliTransactionDisplay, self).__init__() self.lastmsg = "" self.lastpackage = None # name of last package we looked at self.output = True # for a progress bar self.mark = "=" self.marks = 22 def progress(self, package, action, ti_done, ti_total, ts_done, ts_total): """Output information about an rpm operation. This may include a text progress bar. :param package: the package involved in the event :param action: the type of action that is taking place. Valid values are given by :func:`rpmtrans.TransactionDisplay.action.keys()` :param ti_done: a number representing the amount of work already done in the current transaction :param ti_total: a number representing the total amount of work to be done in the current transaction :param ts_done: the number of the current transaction in transaction set :param ts_total: the total number of transactions in the transaction set """ action_str = dnf.transaction.ACTIONS.get(action) if action_str is None: return wid1 = self._max_action_width() pkgname = ucd(package) self.lastpackage = package if ti_total == 0: percent = 0 else: percent = (ti_done*long(100))//ti_total self._out_progress(ti_done, ti_total, ts_done, ts_total, percent, action_str, pkgname, wid1) def _max_action_width(self): if not hasattr(self, '_max_action_wid_cache'): wid1 = 0 for val in dnf.transaction.ACTIONS.values(): wid_val = exact_width(val) if wid1 < wid_val: wid1 = wid_val self._max_action_wid_cache = wid1 wid1 = self._max_action_wid_cache return wid1 def _out_progress(self, ti_done, ti_total, ts_done, ts_total, percent, process, pkgname, wid1): if self.output and (sys.stdout.isatty() or ti_done == ti_total): (fmt, wid1, wid2) = self._makefmt(percent, ts_done, ts_total, progress=sys.stdout.isatty(), pkgname=pkgname, wid1=wid1) pkgname = ucd(pkgname) msg = fmt % (fill_exact_width(process, wid1, wid1), fill_exact_width(pkgname, wid2, wid2)) if msg != self.lastmsg: dnf.util._terminal_messenger('write_flush', msg, sys.stdout) self.lastmsg = msg if ti_done == ti_total: print(" ") def _makefmt(self, percent, ts_done, ts_total, progress=True, pkgname=None, wid1=15): l = len(str(ts_total)) size = "%s.%s" % (l, l) fmt_done = "%" + size + "s/%" + size + "s" done = fmt_done % (ts_done, ts_total) # This should probably use TerminLine, but we don't want to dep. on # that. So we kind do an ok job by hand ... at least it's dynamic now. if pkgname is None: pnl = 22 else: pnl = exact_width(pkgname) overhead = (2 * l) + 2 # Length of done, above overhead += 2 + wid1 +2 # Length of beginning (" " action " :") overhead += 1 # Space between pn and done overhead += 2 # Ends for progress overhead += 1 # Space for end width = self.width if width < overhead: width = overhead # Give up width -= overhead if pnl > width // 2: pnl = width // 2 marks = self.width - (overhead + pnl) width = "%s.%s" % (marks, marks) fmt_bar = "[%-" + width + "s]" # pnl = str(28 + marks + 1) full_pnl = pnl + marks + 1 if progress and percent == 100: # Don't chop pkg name on 100% fmt = "\r %s: %s " + done wid2 = full_pnl elif progress: if marks > 5: bar = fmt_bar % (self.mark * int(marks * (percent / 100.0)), ) else: bar = "" fmt = "\r %s: %s " + bar + " " + done wid2 = pnl elif percent == 100: fmt = " %s: %s " + done wid2 = full_pnl else: if marks > 5: bar = fmt_bar % (self.mark * marks, ) else: bar = "" fmt = " %s: %s " + bar + " " + done wid2 = pnl return fmt, wid1, wid2 def progressbar(current, total, name=None): """Output the current status to the terminal using a simple text progress bar consisting of 50 # marks. :param current: a number representing the amount of work already done :param total: a number representing the total amount of work to be done :param name: a name to label the progress bar with """ mark = '#' if not sys.stdout.isatty(): return if current == 0: percent = 0 else: if total != 0: percent = float(current) / total else: percent = 0 width = dnf.cli.term._term_width() if name is None and current == total: name = '-' end = ' %d/%d' % (current, total) width -= len(end) + 1 if width < 0: width = 0 if name is None: width -= 2 if width < 0: width = 0 hashbar = mark * int(width * percent) output = '\r[%-*s]%s' % (width, hashbar, end) elif current == total: # Don't chop name on 100% output = '\r%s%s' % (fill_exact_width(name, width, width), end) else: width -= 4 if width < 0: width = 0 nwid = width // 2 if nwid > exact_width(name): nwid = exact_width(name) width -= nwid hashbar = mark * int(width * percent) output = '\r%s: [%-*s]%s' % (fill_exact_width(name, nwid, nwid), width, hashbar, end) if current <= total: dnf.util._terminal_messenger('write', output, sys.stdout) if current == total: dnf.util._terminal_messenger('write', '\n', sys.stdout) dnf.util._terminal_messenger('flush', out=sys.stdout) commands/module.py000064400000040731151030066770010216 0ustar00# supplies the 'module' command. # # Copyright (C) 2014-2017 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import print_function from dnf.cli import commands, CliError from dnf.i18n import _ from dnf.module.exceptions import NoModuleException from dnf.util import logger import dnf.util import sys import os import hawkey import libdnf import dnf.module.module_base import dnf.exceptions class ModuleCommand(commands.Command): class SubCommand(commands.Command): def __init__(self, cli): super(ModuleCommand.SubCommand, self).__init__(cli) self.module_base = dnf.module.module_base.ModuleBase(self.base) def _get_modules_from_name_stream_specs(self): modules_from_specs = set() for module_spec in self.opts.module_spec: __, nsvcap = self.module_base._get_modules(module_spec) # When there is no match, the problem was already reported by module_base.remove() if nsvcap is None: continue name = nsvcap.name if nsvcap.name else "" stream = nsvcap.stream if nsvcap.stream else "" if (nsvcap.version and nsvcap.version != -1) or nsvcap.context: logger.info(_("Only module name, stream, architecture or profile is used. " "Ignoring unneeded information in argument: '{}'").format( module_spec)) arch = nsvcap.arch if nsvcap.arch else "" modules = self.base._moduleContainer.query(name, stream, "", "", arch) modules_from_specs.update(modules) return modules_from_specs def _get_module_artifact_names(self, use_modules, skip_modules): artifacts = set() pkg_names = set() for module in use_modules: if module not in skip_modules: if self.base._moduleContainer.isModuleActive(module): artifacts.update(module.getArtifacts()) for artifact in artifacts: subj = hawkey.Subject(artifact) for nevra_obj in subj.get_nevra_possibilities( forms=[hawkey.FORM_NEVRA]): if nevra_obj.name: pkg_names.add(nevra_obj.name) return pkg_names, artifacts class ListSubCommand(SubCommand): aliases = ('list',) summary = _('list all module streams, profiles and states') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True def run_on_module(self): mods = self.module_base if self.opts.enabled: output = mods._get_brief_description( self.opts.module_spec, libdnf.module.ModulePackageContainer.ModuleState_ENABLED) elif self.opts.disabled: output = mods._get_brief_description( self.opts.module_spec, libdnf.module.ModulePackageContainer.ModuleState_DISABLED) elif self.opts.installed: output = mods._get_brief_description( self.opts.module_spec, libdnf.module.ModulePackageContainer.ModuleState_INSTALLED) else: output = mods._get_brief_description( self.opts.module_spec, libdnf.module.ModulePackageContainer.ModuleState_UNKNOWN) if output: print(output) return if self.opts.module_spec: msg = _('No matching Modules to list') raise dnf.exceptions.Error(msg) class InfoSubCommand(SubCommand): aliases = ('info',) summary = _('print detailed information about a module') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True def run_on_module(self): if self.opts.verbose: output = self.module_base._get_full_info(self.opts.module_spec) elif self.opts.profile: output = self.module_base._get_info_profiles(self.opts.module_spec) else: output = self.module_base._get_info(self.opts.module_spec) if output: print(output) else: raise dnf.exceptions.Error(_('No matching Modules to list')) class EnableSubCommand(SubCommand): aliases = ('enable',) summary = _('enable a module stream') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def run_on_module(self): try: self.module_base.enable(self.opts.module_spec) except dnf.exceptions.MarkingErrors as e: if self.base.conf.strict: if e.no_match_group_specs or e.error_group_specs: raise e if e.module_depsolv_errors and e.module_depsolv_errors[1] != \ libdnf.module.ModulePackageContainer.ModuleErrorType_ERROR_IN_DEFAULTS: raise e logger.error(str(e)) class DisableSubCommand(SubCommand): aliases = ('disable',) summary = _('disable a module with all its streams') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def run_on_module(self): try: self.module_base.disable(self.opts.module_spec) except dnf.exceptions.MarkingErrors as e: if self.base.conf.strict: if e.no_match_group_specs or e.error_group_specs: raise e if e.module_depsolv_errors and e.module_depsolv_errors[1] != \ libdnf.module.ModulePackageContainer.ModuleErrorType_ERROR_IN_DEFAULTS: raise e logger.error(str(e)) class ResetSubCommand(SubCommand): aliases = ('reset',) summary = _('reset a module') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def run_on_module(self): try: self.module_base.reset(self.opts.module_spec) except dnf.exceptions.MarkingErrors as e: if self.base.conf.strict: if e.no_match_group_specs: raise e logger.error(str(e)) class InstallSubCommand(SubCommand): aliases = ('install',) summary = _('install a module profile including its packages') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def run_on_module(self): try: self.module_base.install(self.opts.module_spec, self.base.conf.strict) except dnf.exceptions.MarkingErrors as e: if self.base.conf.strict: if e.no_match_group_specs or e.error_group_specs: raise e logger.error(str(e)) class UpdateSubCommand(SubCommand): aliases = ('update',) summary = _('update packages associated with an active stream') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def run_on_module(self): module_specs = self.module_base.upgrade(self.opts.module_spec) if module_specs: raise NoModuleException(", ".join(module_specs)) class RemoveSubCommand(SubCommand): aliases = ('remove', 'erase',) summary = _('remove installed module profiles and their packages') def configure(self): demands = self.cli.demands demands.allow_erasing = True demands.available_repos = True demands.fresh_metadata = False demands.resolving = True demands.root_user = True demands.sack_activation = True def run_on_module(self): skipped_groups = self.module_base.remove(self.opts.module_spec) if self.opts.all: modules_from_specs = self._get_modules_from_name_stream_specs() remove_names_from_spec, __ = self._get_module_artifact_names( modules_from_specs, set()) keep_names, __ = self._get_module_artifact_names( self.base._moduleContainer.getModulePackages(), modules_from_specs) remove_query = self.base.sack.query().installed().filterm( name=remove_names_from_spec) keep_query = self.base.sack.query().installed().filterm(name=keep_names) for pkg in remove_query: if pkg in keep_query: msg = _("Package {} belongs to multiple modules, skipping").format(pkg) logger.info(msg) else: self.base.goal.erase( pkg, clean_deps=self.base.conf.clean_requirements_on_remove) if not skipped_groups: return logger.error(dnf.exceptions.MarkingErrors(no_match_group_specs=skipped_groups)) class SwitchToSubCommand(SubCommand): aliases = ('switch-to',) summary = _('switch a module to a stream and distrosync rpm packages') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True self.base.conf.module_stream_switch = True def run_on_module(self): try: self.module_base.switch_to(self.opts.module_spec, strict=self.base.conf.strict) except dnf.exceptions.MarkingErrors as e: if self.base.conf.strict: if e.no_match_group_specs or e.error_group_specs: raise e logger.error(str(e)) class ProvidesSubCommand(SubCommand): aliases = ("provides", ) summary = _('list modular packages') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True def run_on_module(self): output = self.module_base._what_provides(self.opts.module_spec) if output: print(output) class RepoquerySubCommand(SubCommand): aliases = ("repoquery", ) summary = _('list packages belonging to a module') def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True def run_on_module(self): modules_from_specs = set() for module_spec in self.opts.module_spec: modules, __ = self.module_base._get_modules(module_spec) modules_from_specs.update(modules) names_from_spec, spec_artifacts = self._get_module_artifact_names( modules_from_specs, set()) package_strings = set() if self.opts.available or not self.opts.installed: query = self.base.sack.query().available().filterm(nevra_strict=spec_artifacts) for pkg in query: package_strings.add(str(pkg)) if self.opts.installed: query = self.base.sack.query().installed().filterm(name=names_from_spec) for pkg in query: package_strings.add(str(pkg)) output = "\n".join(sorted(package_strings)) print(output) SUBCMDS = {ListSubCommand, InfoSubCommand, EnableSubCommand, DisableSubCommand, ResetSubCommand, InstallSubCommand, UpdateSubCommand, RemoveSubCommand, SwitchToSubCommand, ProvidesSubCommand, RepoquerySubCommand} SUBCMDS_NOT_REQUIRED_ARG = {ListSubCommand} aliases = ("module",) summary = _("Interact with Modules.") def __init__(self, cli): super(ModuleCommand, self).__init__(cli) subcmd_objs = (subcmd(cli) for subcmd in self.SUBCMDS) self.subcmd = None self._subcmd_name2obj = { alias: subcmd for subcmd in subcmd_objs for alias in subcmd.aliases} def set_argparser(self, parser): narrows = parser.add_mutually_exclusive_group() narrows.add_argument('--enabled', dest='enabled', action='store_true', help=_("show only enabled modules")) narrows.add_argument('--disabled', dest='disabled', action='store_true', help=_("show only disabled modules")) narrows.add_argument('--installed', dest='installed', action='store_true', help=_("show only installed modules or packages")) narrows.add_argument('--profile', dest='profile', action='store_true', help=_("show profile content")) parser.add_argument('--available', dest='available', action='store_true', help=_("show only available packages")) narrows.add_argument('--all', dest='all', action='store_true', help=_("remove all modular packages")) subcommand_choices = [] subcommand_help = [] for subcmd in sorted(self.SUBCMDS, key=lambda x: x.aliases[0]): subcommand_choices.append(subcmd.aliases[0]) subcommand_help.append('{}: {}'.format(subcmd.aliases[0], subcmd.summary or '')) parser.add_argument('subcmd', nargs=1, choices=subcommand_choices, metavar='', help='\n'.join(subcommand_help)) parser.add_argument('module_spec', metavar='module-spec', nargs='*', help=_("Module specification")) def configure(self): try: self.subcmd = self._subcmd_name2obj[self.opts.subcmd[0]] except (CliError, KeyError): self.cli.optparser.print_usage() raise CliError self.subcmd.opts = self.opts self.subcmd.configure() def run(self): self.check_required_argument() self.subcmd.run_on_module() def check_required_argument(self): not_required_argument = [alias for subcmd in self.SUBCMDS_NOT_REQUIRED_ARG for alias in subcmd.aliases] if self.opts.subcmd[0] not in not_required_argument: if not self.opts.module_spec: raise CliError( _("{} {} {}: too few arguments").format(dnf.util.MAIN_PROG, self.opts.command, self.opts.subcmd[0])) commands/reinstall.py000064400000010135151030066770010721 0ustar00# reinstall.py # Reinstall CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import _ import dnf.exceptions import logging logger = logging.getLogger('dnf') class ReinstallCommand(commands.Command): """A class containing methods needed by the cli to execute the reinstall command. """ aliases = ('reinstall', 'rei') summary = _('reinstall a package') @staticmethod def set_argparser(parser): parser.add_argument('packages', nargs='+', help=_('Package to reinstall'), action=OptionParser.ParseSpecGroupFileCallback, metavar=_('PACKAGE')) def configure(self): """Verify that conditions are met so that this command can run. These include that the program is being run by the root user, that there are enabled repositories with gpg keys, and that this command is called with appropriate arguments. """ demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True commands._checkGPGKey(self.base, self.cli) if not self.opts.filenames: commands._checkEnabledRepo(self.base) def run(self): # Reinstall files. done = False for pkg in self.base.add_remote_rpms(self.opts.filenames, strict=False, progress=self.base.output.progress): try: self.base.package_reinstall(pkg) except dnf.exceptions.MarkingError: logger.info(_('No match for argument: %s'), self.base.output.term.bold(pkg.location)) else: done = True # Reinstall packages. for pkg_spec in self.opts.pkg_specs + ['@' + x for x in self.opts.grp_specs]: try: self.base.reinstall(pkg_spec) except dnf.exceptions.PackagesNotInstalledError as err: for pkg in err.packages: logger.info(_('Package %s available, but not installed.'), self.output.term.bold(pkg.name)) break logger.info(_('No match for argument: %s'), self.base.output.term.bold(pkg_spec)) except dnf.exceptions.PackagesNotAvailableError as err: for pkg in err.packages: xmsg = '' pkgrepo = self.base.history.repo(pkg) if pkgrepo: xmsg = _(' (from %s)') % pkgrepo msg = _('Installed package %s%s not available.') logger.info(msg, self.base.output.term.bold(pkg), xmsg) except dnf.exceptions.MarkingError: assert False, 'Only the above marking errors are expected.' else: done = True if not done: raise dnf.exceptions.Error(_('No packages marked for reinstall.')) commands/mark.py000064400000006720151030066770007663 0ustar00# mark.py # Mark CLI command. # # Copyright (C) 2015-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import print_function from __future__ import unicode_literals import libdnf.transaction from dnf.i18n import _ from dnf.cli import commands import dnf import functools import logging logger = logging.getLogger("dnf") class MarkCommand(commands.Command): aliases = ('mark',) summary = _('mark or unmark installed packages as installed by user.') @staticmethod def set_argparser(parser): parser.add_argument('mark', nargs=1, choices=['install', 'remove', 'group'], help=_("install: mark as installed by user\n" "remove: unmark as installed by user\n" "group: mark as installed by group")) parser.add_argument('package', nargs='+', metavar="PACKAGE", help=_("Package specification")) def _mark_install(self, pkg): self.base.history.set_reason(pkg, libdnf.transaction.TransactionItemReason_USER) logger.info(_('%s marked as user installed.'), str(pkg)) def _mark_remove(self, pkg): self.base.history.set_reason(pkg, libdnf.transaction.TransactionItemReason_DEPENDENCY) logger.info(_('%s unmarked as user installed.'), str(pkg)) def _mark_group(self, pkg): self.base.history.set_reason(pkg, libdnf.transaction.TransactionItemReason_GROUP) logger.info(_('%s marked as group installed.'), str(pkg)) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.root_user = True demands.available_repos = False demands.resolving = False def run(self): cmd = self.opts.mark[0] pkgs = self.opts.package mark_func = functools.partial(getattr(self, '_mark_' + cmd)) notfound = [] for pkg in pkgs: subj = dnf.subject.Subject(pkg) q = subj.get_best_query(self.base.sack) for pkg in q: mark_func(pkg) if len(q) == 0: notfound.append(pkg) if notfound: logger.error(_('Error:')) for pkg in notfound: logger.error(_('Package %s is not installed.'), pkg) raise dnf.cli.CliError old = self.base.history.last() if old is None: rpmdb_version = self.sack._rpmdb_version() else: rpmdb_version = old.end_rpmdb_version self.base.history.beg(rpmdb_version, [], []) self.base.history.end(rpmdb_version) commands/repoquery.py000064400000103331151030066770010760 0ustar00# # Copyright (C) 2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from dnf.i18n import _ from dnf.cli import commands from dnf.cli.option_parser import OptionParser import argparse import datetime import logging import re import sys import dnf import dnf.cli import dnf.exceptions import dnf.subject import dnf.util import hawkey logger = logging.getLogger('dnf') QFORMAT_DEFAULT = '%{name}-%{epoch}:%{version}-%{release}.%{arch}' # matches %[-][dd]{attr} QFORMAT_MATCH = re.compile(r'%(-?\d*?){([:.\w]+?)}') QUERY_TAGS = """\ name, arch, epoch, version, release, reponame (repoid), from_repo, evr, debug_name, source_name, source_debug_name, installtime, buildtime, size, downloadsize, installsize, provides, requires, obsoletes, conflicts, sourcerpm, description, summary, license, url, reason""" OPTS_MAPPING = { 'conflicts': 'conflicts', 'enhances': 'enhances', 'obsoletes': 'obsoletes', 'provides': 'provides', 'recommends': 'recommends', 'requires': 'requires', 'requires-pre': 'requires_pre', 'suggests': 'suggests', 'supplements': 'supplements' } def rpm2py_format(queryformat): """Convert a rpm like QUERYFMT to an python .format() string.""" def fmt_repl(matchobj): fill = matchobj.groups()[0] key = matchobj.groups()[1] if fill: if fill[0] == '-': fill = '>' + fill[1:] else: fill = '<' + fill fill = ':' + fill return '{0.' + key.lower() + fill + "}" def brackets(txt): return txt.replace('{', '{{').replace('}', '}}') queryformat = queryformat.replace("\\n", "\n").replace("\\t", "\t") for key, value in OPTS_MAPPING.items(): queryformat = queryformat.replace(key, value) fmt = "" spos = 0 for item in QFORMAT_MATCH.finditer(queryformat): fmt += brackets(queryformat[spos:item.start()]) fmt += fmt_repl(item) spos = item.end() fmt += brackets(queryformat[spos:]) return fmt class _CommaSplitCallback(OptionParser._SplitCallback): SPLITTER = r'\s*,\s*' class RepoQueryCommand(commands.Command): """A class containing methods needed by the cli to execute the repoquery command. """ nevra_forms = {'repoquery-n': hawkey.FORM_NAME, 'repoquery-na': hawkey.FORM_NA, 'repoquery-nevra': hawkey.FORM_NEVRA} aliases = ('repoquery', 'rq') + tuple(nevra_forms.keys()) summary = _('search for packages matching keyword') @staticmethod def filter_repo_arch(opts, query): """Filter query by repoid and arch options""" if opts.repo: query.filterm(reponame=opts.repo) if opts.arches: query.filterm(arch=opts.arches) return query @staticmethod def set_argparser(parser): parser.add_argument('-a', '--all', dest='queryall', action='store_true', help=_("Query all packages (shorthand for repoquery '*' " "or repoquery without argument)")) parser.add_argument('--show-duplicates', action='store_true', help=_("Query all versions of packages (default)")) parser.add_argument('--arch', '--archlist', dest='arches', default=[], action=_CommaSplitCallback, metavar='[arch]', help=_('show only results from this ARCH')) parser.add_argument('-f', '--file', metavar='FILE', nargs='+', help=_('show only results that owns FILE')) parser.add_argument('--whatconflicts', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that conflict REQ')) parser.add_argument('--whatdepends', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('shows results that requires, suggests, supplements, enhances,' 'or recommends package provides and files REQ')) parser.add_argument('--whatobsoletes', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that obsolete REQ')) parser.add_argument('--whatprovides', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that provide REQ')) parser.add_argument('--whatrequires', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('shows results that requires package provides and files REQ')) parser.add_argument('--whatrecommends', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that recommend REQ')) parser.add_argument('--whatenhances', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that enhance REQ')) parser.add_argument('--whatsuggests', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that suggest REQ')) parser.add_argument('--whatsupplements', default=[], action=_CommaSplitCallback, metavar='REQ', help=_('show only results that supplement REQ')) whatrequiresform = parser.add_mutually_exclusive_group() whatrequiresform.add_argument("--alldeps", action="store_true", help=_("check non-explicit dependencies (files and Provides); default")) whatrequiresform.add_argument("--exactdeps", action="store_true", help=_('check dependencies exactly as given, opposite of --alldeps')) parser.add_argument("--recursive", action="store_true", help=_( 'used with --whatrequires, and --requires --resolve, query packages recursively.')) parser.add_argument('--deplist', action='store_true', help=_( "show a list of all dependencies and what packages provide them")) parser.add_argument('--resolve', action='store_true', help=_('resolve capabilities to originating package(s)')) parser.add_argument("--tree", action="store_true", help=_('show recursive tree for package(s)')) parser.add_argument('--srpm', action='store_true', help=_('operate on corresponding source RPM')) parser.add_argument("--latest-limit", dest='latest_limit', type=int, help=_('show N latest packages for a given name.arch' ' (or latest but N if N is negative)')) parser.add_argument("--disable-modular-filtering", action="store_true", help=_("list also packages of inactive module streams")) outform = parser.add_mutually_exclusive_group() outform.add_argument('-i', "--info", dest='queryinfo', default=False, action='store_true', help=_('show detailed information about the package')) outform.add_argument('-l', "--list", dest='queryfilelist', default=False, action='store_true', help=_('show list of files in the package')) outform.add_argument('-s', "--source", dest='querysourcerpm', default=False, action='store_true', help=_('show package source RPM name')) outform.add_argument('--changelogs', dest='querychangelogs', default=False, action='store_true', help=_('show changelogs of the package')) outform.add_argument('--qf', "--queryformat", dest='queryformat', default=QFORMAT_DEFAULT, help=_('display format for listing packages: ' '"%%{name} %%{version} ...", ' 'use --querytags to view full tag list')) parser.add_argument('--querytags', action='store_true', help=_('show available tags to use with ' '--queryformat')) outform.add_argument("--nevra", dest='queryformat', const=QFORMAT_DEFAULT, action='store_const', help=_('use name-epoch:version-release.architecture format for ' 'displaying found packages (default)')) outform.add_argument("--nvr", dest='queryformat', const='%{name}-%{version}-%{release}', action='store_const', help=_('use name-version-release format for ' 'displaying found packages ' '(rpm query default)')) outform.add_argument("--envra", dest='queryformat', const='%{epoch}:%{name}-%{version}-%{release}.%{arch}', action='store_const', help=_('use epoch:name-version-release.architecture format for ' 'displaying found packages')) outform.add_argument('--groupmember', action="store_true", help=_( 'Display in which comps groups are presented selected packages')) pkgfilter = parser.add_mutually_exclusive_group() pkgfilter.add_argument("--duplicates", dest='pkgfilter', const='duplicated', action='store_const', help=_('limit the query to installed duplicate ' 'packages')) pkgfilter.add_argument("--duplicated", dest='pkgfilter', const='duplicated', action='store_const', help=argparse.SUPPRESS) pkgfilter.add_argument("--installonly", dest='pkgfilter', const='installonly', action='store_const', help=_('limit the query to installed installonly packages')) pkgfilter.add_argument("--unsatisfied", dest='pkgfilter', const='unsatisfied', action='store_const', help=_('limit the query to installed packages with unsatisfied dependencies')) parser.add_argument('--location', action='store_true', help=_('show a location from where packages can be downloaded')) package_attribute = parser.add_mutually_exclusive_group() help_msgs = { 'conflicts': _('Display capabilities that the package conflicts with.'), 'depends': _('Display capabilities that the package can depend on, enhance, recommend,' ' suggest, and supplement.'), 'enhances': _('Display capabilities that the package can enhance.'), 'provides': _('Display capabilities provided by the package.'), 'recommends': _('Display capabilities that the package recommends.'), 'requires': _('Display capabilities that the package depends on.'), 'requires-pre': _('If the package is not installed display capabilities that it depends on for ' 'running %%pre and %%post scriptlets. If the package is installed display ' 'capabilities that is depends for %%pre, %%post, %%preun and %%postun.'), 'suggests': _('Display capabilities that the package suggests.'), 'supplements': _('Display capabilities that the package can supplement.') } for arg, help_msg in help_msgs.items(): name = '--%s' % arg package_attribute.add_argument(name, dest='packageatr', action='store_const', const=arg, help=help_msg) parser.add_argument('--available', action="store_true", help=_('Display only available packages.')) help_list = { 'installed': _('Display only installed packages.'), 'extras': _('Display only packages that are not present in any of available repositories.'), 'upgrades': _('Display only packages that provide an upgrade for some already installed package.'), 'unneeded': _('Display only packages that can be removed by "{prog} autoremove" ' 'command.').format(prog=dnf.util.MAIN_PROG), 'userinstalled': _('Display only packages that were installed by user.') } list_group = parser.add_mutually_exclusive_group() for list_arg, help_arg in help_list.items(): switch = '--%s' % list_arg list_group.add_argument(switch, dest='list', action='store_const', const=list_arg, help=help_arg) # make --autoremove hidden compatibility alias for --unneeded list_group.add_argument( '--autoremove', dest='list', action='store_const', const="unneeded", help=argparse.SUPPRESS) parser.add_argument('--recent', action="store_true", help=_('Display only recently edited packages')) parser.add_argument('key', nargs='*', metavar="KEY", help=_('the key to search for')) def pre_configure(self): if not self.opts.quiet: self.cli.redirect_logger(stdout=logging.WARNING, stderr=logging.INFO) def configure(self): if not self.opts.quiet: self.cli.redirect_repo_progress() demands = self.cli.demands if self.opts.obsoletes: if self.opts.packageatr: self.cli._option_conflict("--obsoletes", "--" + self.opts.packageatr) else: self.opts.packageatr = "obsoletes" if self.opts.querytags: return if self.opts.resolve and not self.opts.packageatr: raise dnf.cli.CliError( _("Option '--resolve' has to be used together with one of the " "'--conflicts', '--depends', '--enhances', '--provides', '--recommends', " "'--requires', '--requires-pre', '--suggests' or '--supplements' options")) if self.opts.recursive: if self.opts.exactdeps: self.cli._option_conflict("--recursive", "--exactdeps") if not any([self.opts.whatrequires, (self.opts.packageatr == "requires" and self.opts.resolve)]): raise dnf.cli.CliError( _("Option '--recursive' has to be used with '--whatrequires ' " "(optionally with '--alldeps', but not with '--exactdeps'), or with " "'--requires --resolve'")) if self.opts.alldeps or self.opts.exactdeps: if not (self.opts.whatrequires or self.opts.whatdepends): raise dnf.cli.CliError( _("argument {} requires --whatrequires or --whatdepends option".format( '--alldeps' if self.opts.alldeps else '--exactdeps'))) if self.opts.srpm: self.base.repos.enable_source_repos() if (self.opts.list not in ["installed", "userinstalled"] and self.opts.pkgfilter != "installonly") or self.opts.available: demands.available_repos = True demands.sack_activation = True if self.opts.querychangelogs: demands.changelogs = True def build_format_fn(self, opts, pkg): if opts.querychangelogs: out = [] out.append('Changelog for %s' % str(pkg)) for chlog in pkg.changelogs: dt = chlog['timestamp'] out.append('* %s %s\n%s\n' % (dt.strftime("%a %b %d %Y"), dnf.i18n.ucd(chlog['author']), dnf.i18n.ucd(chlog['text']))) return '\n'.join(out) try: po = PackageWrapper(pkg) if opts.queryinfo: return self.base.output.infoOutput(pkg) elif opts.queryfilelist: filelist = po.files if not filelist: print(_('Package {} contains no files').format(pkg), file=sys.stderr) return filelist elif opts.querysourcerpm: return po.sourcerpm else: return rpm2py_format(opts.queryformat).format(po) except AttributeError as e: # catch that the user has specified attributes # there don't exist on the dnf Package object. raise dnf.exceptions.Error(str(e)) def _resolve_nevras(self, nevras, base_query): resolved_nevras_query = self.base.sack.query().filterm(empty=True) for nevra in nevras: resolved_nevras_query = resolved_nevras_query.union(base_query.intersection( dnf.subject.Subject(nevra).get_best_query( self.base.sack, with_provides=False, with_filenames=False ) )) return resolved_nevras_query def _do_recursive_deps(self, query_in, query_select, done=None): done = done if done else query_select query_required = query_in.filter(requires=query_select) query_select = query_required.difference(done) done = query_required.union(done) if query_select: done = self._do_recursive_deps(query_in, query_select, done=done) return done def by_all_deps(self, names, query, all_dep_types=False): # in case of arguments being NEVRAs, resolve them to packages resolved_nevras_query = self._resolve_nevras(names, query) # filter the arguments directly as reldeps depquery = query.filter(requires__glob=names) # filter the resolved NEVRAs as packages depquery = depquery.union(query.filter(requires=resolved_nevras_query)) if all_dep_types: # TODO this is very inefficient, as it resolves the `names` glob to # reldeps four more times, which in a reasonably wide glob like # `dnf repoquery --whatdepends "libdnf*"` can take roughly 50% of # the total execution time. depquery = depquery.union(query.filter(recommends__glob=names)) depquery = depquery.union(query.filter(enhances__glob=names)) depquery = depquery.union(query.filter(supplements__glob=names)) depquery = depquery.union(query.filter(suggests__glob=names)) depquery = depquery.union(query.filter(recommends=resolved_nevras_query)) depquery = depquery.union(query.filter(enhances=resolved_nevras_query)) depquery = depquery.union(query.filter(supplements=resolved_nevras_query)) depquery = depquery.union(query.filter(suggests=resolved_nevras_query)) if self.opts.recursive: depquery = self._do_recursive_deps(query, depquery) return depquery def _get_recursive_providers_query(self, query_in, providers, done=None): done = done if done else self.base.sack.query().filterm(empty=True) t = self.base.sack.query().filterm(empty=True) for pkg in providers.run(): t = t.union(query_in.filter(provides=pkg.requires)) query_select = t.difference(done) if query_select: done = self._get_recursive_providers_query(query_in, query_select, done=t.union(done)) return t.union(done) def _add_add_remote_packages(self): rpmnames = [] remote_packages = [] for key in self.opts.key: schemes = dnf.pycomp.urlparse.urlparse(key)[0] if key.endswith('.rpm'): rpmnames.append(key) elif schemes and schemes in ('http', 'ftp', 'file', 'https'): rpmnames.append(key) if rpmnames: remote_packages = self.base.add_remote_rpms( rpmnames, strict=False, progress=self.base.output.progress) return remote_packages def run(self): if self.opts.querytags: print(QUERY_TAGS) return self.cli._populate_update_security_filter(self.opts) q = self.base.sack.query( flags=hawkey.IGNORE_MODULAR_EXCLUDES if self.opts.disable_modular_filtering else hawkey.APPLY_EXCLUDES ) if self.opts.key: remote_packages = self._add_add_remote_packages() kwark = {} if self.opts.command in self.nevra_forms: kwark["forms"] = [self.nevra_forms[self.opts.command]] pkgs = [] query_results = q.filter(empty=True) if remote_packages: query_results = query_results.union( self.base.sack.query().filterm(pkg=remote_packages)) for key in self.opts.key: query_results = query_results.union( dnf.subject.Subject(key, ignore_case=True).get_best_query( self.base.sack, with_provides=False, query=q, **kwark)) q = query_results if self.opts.recent: q = q._recent(self.base.conf.recent) if self.opts.available: if self.opts.list and self.opts.list != "installed": print(self.cli.optparser.print_usage()) raise dnf.exceptions.Error(_("argument {}: not allowed with argument {}".format( "--available", "--" + self.opts.list))) elif self.opts.list == "unneeded": q = q._unneeded(self.base.history.swdb) elif self.opts.list and self.opts.list != 'userinstalled': q = getattr(q, self.opts.list)() if self.opts.pkgfilter == "duplicated": installonly = self.base._get_installonly_query(q) q = q.difference(installonly).duplicated() elif self.opts.pkgfilter == "installonly": q = self.base._get_installonly_query(q) elif self.opts.pkgfilter == "unsatisfied": rpmdb = dnf.sack.rpmdb_sack(self.base) rpmdb._configure(self.base.conf.installonlypkgs, self.base.conf.installonly_limit) goal = dnf.goal.Goal(rpmdb) goal.protect_running_kernel = False solved = goal.run(verify=True) if not solved: print(dnf.util._format_resolve_problems(goal.problem_rules())) return elif not self.opts.list: # do not show packages from @System repo q = q.available() # filter repo and arch q = self.filter_repo_arch(self.opts, q) orquery = q if self.opts.file: q.filterm(file__glob=self.opts.file) if self.opts.whatconflicts: rels = q.filter(conflicts__glob=self.opts.whatconflicts) q = rels.union(q.filter(conflicts=self._resolve_nevras(self.opts.whatconflicts, q))) if self.opts.whatobsoletes: q.filterm(obsoletes=self.opts.whatobsoletes) if self.opts.whatprovides: query_for_provide = q.filter(provides__glob=self.opts.whatprovides) if query_for_provide: q = query_for_provide else: q.filterm(file__glob=self.opts.whatprovides) if self.opts.whatrequires: if (self.opts.exactdeps): q.filterm(requires__glob=self.opts.whatrequires) else: q = self.by_all_deps(self.opts.whatrequires, q) if self.opts.whatdepends: if (self.opts.exactdeps): dependsquery = q.filter(requires__glob=self.opts.whatdepends) dependsquery = dependsquery.union(q.filter(recommends__glob=self.opts.whatdepends)) dependsquery = dependsquery.union(q.filter(enhances__glob=self.opts.whatdepends)) dependsquery = dependsquery.union(q.filter(supplements__glob=self.opts.whatdepends)) q = dependsquery.union(q.filter(suggests__glob=self.opts.whatdepends)) else: q = self.by_all_deps(self.opts.whatdepends, q, True) if self.opts.whatrecommends: rels = q.filter(recommends__glob=self.opts.whatrecommends) q = rels.union(q.filter(recommends=self._resolve_nevras(self.opts.whatrecommends, q))) if self.opts.whatenhances: rels = q.filter(enhances__glob=self.opts.whatenhances) q = rels.union(q.filter(enhances=self._resolve_nevras(self.opts.whatenhances, q))) if self.opts.whatsupplements: rels = q.filter(supplements__glob=self.opts.whatsupplements) q = rels.union(q.filter(supplements=self._resolve_nevras(self.opts.whatsupplements, q))) if self.opts.whatsuggests: rels = q.filter(suggests__glob=self.opts.whatsuggests) q = rels.union(q.filter(suggests=self._resolve_nevras(self.opts.whatsuggests, q))) if self.opts.latest_limit: q = q.latest(self.opts.latest_limit) # reduce a query to security upgrades if they are specified q = self.base._merge_update_filters(q, warning=False) if self.opts.srpm: pkg_list = [] for pkg in q: srcname = pkg.source_name if srcname is not None: tmp_query = self.base.sack.query().filterm(name=srcname, evr=pkg.evr, arch='src') pkg_list += tmp_query.run() q = self.base.sack.query().filterm(pkg=pkg_list) if self.opts.tree: if not self.opts.whatrequires and self.opts.packageatr not in ( 'conflicts', 'enhances', 'obsoletes', 'provides', 'recommends', 'requires', 'suggests', 'supplements'): raise dnf.exceptions.Error( _("No valid switch specified\nusage: {prog} repoquery [--conflicts|" "--enhances|--obsoletes|--provides|--recommends|--requires|" "--suggest|--supplements|--whatrequires] [key] [--tree]\n\n" "description:\n For the given packages print a tree of the" "packages.").format(prog=dnf.util.MAIN_PROG)) self.tree_seed(q, orquery, self.opts) return pkgs = set() if self.opts.packageatr: rels = set() for pkg in q.run(): if self.opts.list != 'userinstalled' or self.base.history.user_installed(pkg): if self.opts.packageatr == 'depends': rels.update(pkg.requires + pkg.enhances + pkg.suggests + pkg.supplements + pkg.recommends) else: rels.update(getattr(pkg, OPTS_MAPPING[self.opts.packageatr])) if self.opts.resolve: # find the providing packages and show them if self.opts.list == "installed": query = self.filter_repo_arch(self.opts, self.base.sack.query()) else: query = self.filter_repo_arch(self.opts, self.base.sack.query().available()) providers = query.filter(provides=rels) if self.opts.recursive: providers = providers.union( self._get_recursive_providers_query(query, providers)) pkgs = set() for pkg in providers.latest().run(): pkgs.add(self.build_format_fn(self.opts, pkg)) else: pkgs.update(str(rel) for rel in rels) elif self.opts.location: for pkg in q.run(): location = pkg.remote_location() if location is not None: pkgs.add(location) elif self.opts.deplist: pkgs = [] for pkg in sorted(set(q.run())): if self.opts.list != 'userinstalled' or self.base.history.user_installed(pkg): deplist_output = [] deplist_output.append('package: ' + str(pkg)) for req in sorted([str(req) for req in pkg.requires]): deplist_output.append(' dependency: ' + req) subject = dnf.subject.Subject(req) query = subject.get_best_query(self.base.sack) query = self.filter_repo_arch( self.opts, query.available()) if not self.opts.verbose: query = query.latest() for provider in query.run(): deplist_output.append(' provider: ' + str(provider)) pkgs.append('\n'.join(deplist_output)) if pkgs: print('\n\n'.join(pkgs)) return elif self.opts.groupmember: self._group_member_report(q) return else: for pkg in q.run(): if self.opts.list != 'userinstalled' or self.base.history.user_installed(pkg): pkgs.add(self.build_format_fn(self.opts, pkg)) if pkgs: if self.opts.queryinfo: print("\n\n".join(sorted(pkgs))) else: print("\n".join(sorted(pkgs))) def _group_member_report(self, query): package_conf_dict = {} for group in self.base.comps.groups: package_conf_dict[group.id] = set([pkg.name for pkg in group.packages_iter()]) group_package_dict = {} pkg_not_in_group = [] for pkg in query.run(): group_id_list = [] for group_id, package_name_set in package_conf_dict.items(): if pkg.name in package_name_set: group_id_list.append(group_id) if group_id_list: group_package_dict.setdefault( '$'.join(sorted(group_id_list)), []).append(str(pkg)) else: pkg_not_in_group.append(str(pkg)) output = [] for key, package_list in sorted(group_package_dict.items()): output.append( '\n'.join(sorted(package_list) + sorted([' @' + id for id in key.split('$')]))) output.append('\n'.join(sorted(pkg_not_in_group))) if output: print('\n'.join(output)) def grow_tree(self, level, pkg, opts): pkg_string = self.build_format_fn(opts, pkg) if level == -1: print(pkg_string) return spacing = " " for x in range(0, level): spacing += "| " requires = [] for requirepkg in pkg.requires: requires.append(str(requirepkg)) reqstr = "[" + str(len(requires)) + ": " + ", ".join(requires) + "]" print(spacing + r"\_ " + pkg_string + " " + reqstr) def tree_seed(self, query, aquery, opts, level=-1, usedpkgs=None): for pkg in sorted(set(query.run()), key=lambda p: p.name): usedpkgs = set() if usedpkgs is None or level == -1 else usedpkgs if pkg.name.startswith("rpmlib") or pkg.name.startswith("solvable"): return self.grow_tree(level, pkg, opts) if pkg not in usedpkgs: usedpkgs.add(pkg) if opts.packageatr: strpkg = getattr(pkg, opts.packageatr) ar = {} for name in set(strpkg): pkgquery = self.base.sack.query().filterm(provides=name) for querypkg in pkgquery: ar[querypkg.name + "." + querypkg.arch] = querypkg pkgquery = self.base.sack.query().filterm(pkg=list(ar.values())) else: pkgquery = self.by_all_deps((pkg.name, ), aquery) if opts.alldeps \ else aquery.filter(requires__glob=pkg.name) self.tree_seed(pkgquery, aquery, opts, level + 1, usedpkgs) class PackageWrapper(object): """Wrapper for dnf.package.Package, so we can control formatting.""" def __init__(self, pkg): self._pkg = pkg def __getattr__(self, attr): atr = getattr(self._pkg, attr) if atr is None: return "(none)" if isinstance(atr, list): return '\n'.join(sorted({dnf.i18n.ucd(reldep) for reldep in atr})) return dnf.i18n.ucd(atr) @staticmethod def _get_timestamp(timestamp): if timestamp > 0: dt = datetime.datetime.utcfromtimestamp(timestamp) return dt.strftime("%Y-%m-%d %H:%M") else: return '' @property def buildtime(self): return self._get_timestamp(self._pkg.buildtime) @property def installtime(self): return self._get_timestamp(self._pkg.installtime) commands/autoremove.py000064400000005746151030066770011126 0ustar00# autoremove.py # Autoremove CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import _ import dnf.exceptions import hawkey import logging logger = logging.getLogger("dnf") class AutoremoveCommand(commands.Command): nevra_forms = {'autoremove-n': hawkey.FORM_NAME, 'autoremove-na': hawkey.FORM_NA, 'autoremove-nevra': hawkey.FORM_NEVRA} aliases = ('autoremove',) + tuple(nevra_forms.keys()) summary = _('remove all unneeded packages that were originally installed ' 'as dependencies') @staticmethod def set_argparser(parser): parser.add_argument('packages', nargs='*', help=_('Package to remove'), action=OptionParser.ParseSpecGroupFileCallback, metavar=_('PACKAGE')) def configure(self): demands = self.cli.demands demands.resolving = True demands.root_user = True demands.sack_activation = True if any([self.opts.grp_specs, self.opts.pkg_specs, self.opts.filenames]): self.base.conf.clean_requirements_on_remove = True demands.allow_erasing = True # disable all available repos to delete whole dependency tree # instead of replacing removable package with available packages demands.available_repos = False else: demands.available_repos = True demands.fresh_metadata = False def run(self): if any([self.opts.grp_specs, self.opts.pkg_specs, self.opts.filenames]): forms = [] if self.opts.command in self.nevra_forms: forms = [self.nevra_forms[self.opts.command]] self.base.autoremove(forms, self.opts.pkg_specs, self.opts.grp_specs, self.opts.filenames) else: self.base.autoremove() commands/check.py000064400000016077151030066770010014 0ustar00# # Copyright (C) 2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.i18n import _ from dnf.cli import commands import argparse import dnf.exceptions class CheckCommand(commands.Command): """A class containing methods needed by the cli to execute the check command. """ aliases = ('check',) summary = _('check for problems in the packagedb') @staticmethod def set_argparser(parser): parser.add_argument('--all', dest='check_types', action='append_const', const='all', help=_('show all problems; default')) parser.add_argument('--dependencies', dest='check_types', action='append_const', const='dependencies', help=_('show dependency problems')) parser.add_argument('--duplicates', dest='check_types', action='append_const', const='duplicates', help=_('show duplicate problems')) parser.add_argument('--obsoleted', dest='check_types', action='append_const', const='obsoleted', help=_('show obsoleted packages')) parser.add_argument('--provides', dest='check_types', action='append_const', const='provides', help=_('show problems with provides')) # Add compatibility with yum but invisible in help # In choices [] allows to return empty list if no argument otherwise it fails parser.add_argument('check_yum_types', nargs='*', choices=[ 'all', 'dependencies', 'duplicates', 'obsoleted', 'provides', []], help=argparse.SUPPRESS) def configure(self): self.cli.demands.sack_activation = True if self.opts.check_yum_types: if self.opts.check_types: self.opts.check_types = self.opts.check_types + \ self.opts.check_yum_types else: self.opts.check_types = self.opts.check_yum_types if not self.opts.check_types: self.opts.check_types = {'all'} else: self.opts.check_types = set(self.opts.check_types) self.base.conf.disable_excludes += ["all"] def run(self): output_set = set() q = self.base.sack.query().installed() if self.opts.check_types.intersection({'all', 'dependencies'}): sack = None for pkg in q: for require in set(pkg.regular_requires) | set(set(pkg.requires_pre) - set(pkg.prereq_ignoreinst)): if str(require).startswith('rpmlib'): continue if not len(q.filter(provides=[require])): if str(require).startswith('('): # rich deps can be only tested by solver if sack is None: sack = dnf.sack.rpmdb_sack(self.base) selector = dnf.selector.Selector(sack) selector.set(provides=str(require)) goal = dnf.goal.Goal(sack) goal.protect_running_kernel = self.base.conf.protect_running_kernel goal.install(select=selector, optional=False) solved = goal.run() # there ase only @system repo in sack, therefore solved is only in case # when rich deps doesn't require any additional package if solved: continue msg = _("{} has missing requires of {}") output_set.add(msg.format( self.base.output.term.bold(pkg), self.base.output.term.bold(require))) for conflict in pkg.conflicts: conflicted = q.filter(provides=[conflict], name=str(conflict).split()[0]) for conflict_pkg in conflicted: msg = '{} has installed conflict "{}": {}' output_set.add(msg.format( self.base.output.term.bold(pkg), self.base.output.term.bold(conflict), self.base.output.term.bold(conflict_pkg))) if self.opts.check_types.intersection({'all', 'duplicates'}): installonly = self.base._get_installonly_query(q) dups = q.duplicated().difference(installonly)._name_dict() for name, pkgs in dups.items(): pkgs.sort() for dup in pkgs[1:]: msg = _("{} is a duplicate with {}").format( self.base.output.term.bold(pkgs[0]), self.base.output.term.bold(dup)) output_set.add(msg) if self.opts.check_types.intersection({'all', 'obsoleted'}): for pkg in q: for obsolete in pkg.obsoletes: obsoleted = q.filter(provides=[obsolete], name=str(obsolete).split()[0]) if len(obsoleted): msg = _("{} is obsoleted by {}").format( self.base.output.term.bold(obsoleted[0]), self.base.output.term.bold(pkg)) output_set.add(msg) if self.opts.check_types.intersection({'all', 'provides'}): for pkg in q: for provide in pkg.provides: if pkg not in q.filter(provides=[provide]): msg = _("{} provides {} but it cannot be found") output_set.add(msg.format( self.base.output.term.bold(pkg), self.base.output.term.bold(provide))) for msg in sorted(output_set): print(msg) if output_set: raise dnf.exceptions.Error( 'Check discovered {} problem(s)'.format(len(output_set))) commands/updateinfo.py000064400000045062151030066770011071 0ustar00# updateinfo.py # UpdateInfo CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # """UpdateInfo CLI command.""" from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import collections import fnmatch import hawkey from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import _, exact_width from dnf.pycomp import unicode def _maxlen(iterable): """Return maximum length of items in a non-empty iterable.""" return max(exact_width(item) for item in iterable) class UpdateInfoCommand(commands.Command): """Implementation of the UpdateInfo command.""" TYPE2LABEL = {hawkey.ADVISORY_BUGFIX: _('bugfix'), hawkey.ADVISORY_ENHANCEMENT: _('enhancement'), hawkey.ADVISORY_SECURITY: _('security'), hawkey.ADVISORY_UNKNOWN: _('unknown'), hawkey.ADVISORY_NEWPACKAGE: _('newpackage')} SECURITY2LABEL = {'Critical': _('Critical/Sec.'), 'Important': _('Important/Sec.'), 'Moderate': _('Moderate/Sec.'), 'Low': _('Low/Sec.')} direct_commands = {'list-updateinfo' : 'list', 'list-security' : 'list', 'list-sec' : 'list', 'info-updateinfo' : 'info', 'info-security' : 'info', 'info-sec' : 'info', 'summary-updateinfo' : 'summary'} aliases = ['updateinfo'] + list(direct_commands.keys()) summary = _('display advisories about packages') availability_default = 'available' availabilities = ['installed', 'updates', 'all', availability_default] def __init__(self, cli): """Initialize the command.""" super(UpdateInfoCommand, self).__init__(cli) self._installed_query = None @staticmethod def set_argparser(parser): availability = parser.add_mutually_exclusive_group() availability.add_argument( "--available", dest='_availability', const='available', action='store_const', help=_("advisories about newer versions of installed packages (default)")) availability.add_argument( "--installed", dest='_availability', const='installed', action='store_const', help=_("advisories about equal and older versions of installed packages")) availability.add_argument( "--updates", dest='_availability', const='updates', action='store_const', help=_("advisories about newer versions of those installed packages " "for which a newer version is available")) availability.add_argument( "--all", dest='_availability', const='all', action='store_const', help=_("advisories about any versions of installed packages")) cmds = ['summary', 'list', 'info'] output_format = parser.add_mutually_exclusive_group() output_format.add_argument("--summary", dest='_spec_action', const='summary', action='store_const', help=_('show summary of advisories (default)')) output_format.add_argument("--list", dest='_spec_action', const='list', action='store_const', help=_('show list of advisories')) output_format.add_argument("--info", dest='_spec_action', const='info', action='store_const', help=_('show info of advisories')) parser.add_argument("--with-cve", dest='with_cve', default=False, action='store_true', help=_('show only advisories with CVE reference')) parser.add_argument("--with-bz", dest='with_bz', default=False, action='store_true', help=_('show only advisories with bugzilla reference')) parser.add_argument('spec', nargs='*', metavar='SPEC', choices=cmds, default=cmds[0], action=OptionParser.PkgNarrowCallback, help=_("Package specification")) def configure(self): """Do any command-specific configuration based on command arguments.""" self.cli.demands.available_repos = True self.cli.demands.sack_activation = True if self.opts.command in self.direct_commands: # we were called with direct command self.opts.spec_action = self.direct_commands[self.opts.command] else: if self.opts._spec_action: self.opts.spec_action = self.opts._spec_action if self.opts._availability: self.opts.availability = self.opts._availability else: # yum compatibility - search for all|available|installed|updates in spec[0] if not self.opts.spec or self.opts.spec[0] not in self.availabilities: self.opts.availability = self.availability_default else: self.opts.availability = self.opts.spec.pop(0) # filtering by advisory types (security/bugfix/enhancement/newpackage) self.opts._advisory_types = set() if self.opts.bugfix: self.opts._advisory_types.add(hawkey.ADVISORY_BUGFIX) if self.opts.enhancement: self.opts._advisory_types.add(hawkey.ADVISORY_ENHANCEMENT) if self.opts.newpackage: self.opts._advisory_types.add(hawkey.ADVISORY_NEWPACKAGE) if self.opts.security: self.opts._advisory_types.add(hawkey.ADVISORY_SECURITY) # yum compatibility - yum accepts types also as positional arguments if self.opts.spec: spec = self.opts.spec.pop(0) if spec == 'bugfix': self.opts._advisory_types.add(hawkey.ADVISORY_BUGFIX) elif spec == 'enhancement': self.opts._advisory_types.add(hawkey.ADVISORY_ENHANCEMENT) elif spec in ('security', 'sec'): self.opts._advisory_types.add(hawkey.ADVISORY_SECURITY) elif spec == 'newpackage': self.opts._advisory_types.add(hawkey.ADVISORY_NEWPACKAGE) elif spec in ('bugzillas', 'bzs'): self.opts.with_bz = True elif spec == 'cves': self.opts.with_cve = True else: self.opts.spec.insert(0, spec) if self.opts.advisory: self.opts.spec.extend(self.opts.advisory) def run(self): """Execute the command with arguments.""" if self.opts.availability == 'installed': apkg_adv_insts = self.installed_apkg_adv_insts(self.opts.spec) description = _('installed') elif self.opts.availability == 'updates': apkg_adv_insts = self.updating_apkg_adv_insts(self.opts.spec) description = _('updates') elif self.opts.availability == 'all': apkg_adv_insts = self.all_apkg_adv_insts(self.opts.spec) description = _('all') else: apkg_adv_insts = self.available_apkg_adv_insts(self.opts.spec) description = _('available') if self.opts.spec_action == 'list': self.display_list(apkg_adv_insts) elif self.opts.spec_action == 'info': self.display_info(apkg_adv_insts) else: self.display_summary(apkg_adv_insts, description) def _newer_equal_installed(self, apackage): if self._installed_query is None: self._installed_query = self.base.sack.query().installed().apply() q = self._installed_query.filter(name=apackage.name, evr__gte=apackage.evr) return len(q) > 0 def _advisory_matcher(self, advisory): if not self.opts._advisory_types \ and not self.opts.spec \ and not self.opts.severity \ and not self.opts.bugzilla \ and not self.opts.cves \ and not self.opts.with_cve \ and not self.opts.with_bz: return True if advisory.type in self.opts._advisory_types: return True if any(fnmatch.fnmatchcase(advisory.id, pat) for pat in self.opts.spec): return True if self.opts.severity and advisory.severity in self.opts.severity: return True if self.opts.bugzilla and any([advisory.match_bug(bug) for bug in self.opts.bugzilla]): return True if self.opts.cves and any([advisory.match_cve(cve) for cve in self.opts.cves]): return True if self.opts.with_cve: if any([ref.type == hawkey.REFERENCE_CVE for ref in advisory.references]): return True if self.opts.with_bz: if any([ref.type == hawkey.REFERENCE_BUGZILLA for ref in advisory.references]): return True return False def _apackage_advisory_installed(self, pkgs_query, cmptype, specs): """Return (adv. package, advisory, installed) triplets.""" for apackage in pkgs_query.get_advisory_pkgs(cmptype): advisory = apackage.get_advisory(self.base.sack) advisory_match = self._advisory_matcher(advisory) apackage_match = any(fnmatch.fnmatchcase(apackage.name, pat) for pat in self.opts.spec) if advisory_match or apackage_match: installed = self._newer_equal_installed(apackage) yield apackage, advisory, installed def running_kernel_pkgs(self): """Return query containing packages of currently running kernel""" sack = self.base.sack q = sack.query().filterm(empty=True) kernel = sack.get_running_kernel() if kernel: q = q.union(sack.query().filterm(sourcerpm=kernel.sourcerpm)) return q def available_apkg_adv_insts(self, specs): """Return available (adv. package, adv., inst.) triplets""" # check advisories for the latest installed packages q = self.base.sack.query().installed().latest(1) # plus packages of the running kernel q = q.union(self.running_kernel_pkgs().installed()) return self._apackage_advisory_installed(q, hawkey.GT, specs) def installed_apkg_adv_insts(self, specs): """Return installed (adv. package, adv., inst.) triplets""" return self._apackage_advisory_installed( self.base.sack.query().installed(), hawkey.LT | hawkey.EQ, specs) def updating_apkg_adv_insts(self, specs): """Return updating (adv. package, adv., inst.) triplets""" return self._apackage_advisory_installed( self.base.sack.query().filterm(upgradable=True), hawkey.GT, specs) def all_apkg_adv_insts(self, specs): """Return installed (adv. package, adv., inst.) triplets""" return self._apackage_advisory_installed( self.base.sack.query().installed(), hawkey.LT | hawkey.EQ | hawkey.GT, specs) def _summary(self, apkg_adv_insts): """Make the summary of advisories.""" # Remove duplicate advisory IDs. We assume that the ID is unique within # a repository and two advisories with the same IDs in different # repositories must have the same type. id2type = {} for (apkg, advisory, installed) in apkg_adv_insts: id2type[advisory.id] = advisory.type if advisory.type == hawkey.ADVISORY_SECURITY: id2type[(advisory.id, advisory.severity)] = (advisory.type, advisory.severity) return collections.Counter(id2type.values()) 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_list(self, apkg_adv_insts): """Display the list of advisories.""" def inst2mark(inst): if not self.opts.availability == 'all': return '' elif inst: return 'i ' else: return ' ' def type2label(typ, sev): if typ == hawkey.ADVISORY_SECURITY: return self.SECURITY2LABEL.get(sev, _('Unknown/Sec.')) else: return self.TYPE2LABEL.get(typ, _('unknown')) nevra_inst_dict = dict() for apkg, advisory, installed in apkg_adv_insts: nevra = '%s-%s.%s' % (apkg.name, apkg.evr, apkg.arch) if self.opts.with_cve or self.opts.with_bz: for ref in advisory.references: if ref.type == hawkey.REFERENCE_BUGZILLA and not self.opts.with_bz: continue elif ref.type == hawkey.REFERENCE_CVE and not self.opts.with_cve: continue nevra_inst_dict.setdefault((nevra, installed, advisory.updated), dict())[ref.id] = ( advisory.type, advisory.severity) else: nevra_inst_dict.setdefault((nevra, installed, advisory.updated), dict())[advisory.id] = ( advisory.type, advisory.severity) advlist = [] # convert types to labels, find max len of advisory IDs and types idw = tlw = nw = 0 for (nevra, inst, aupdated), id2type in sorted(nevra_inst_dict.items(), key=lambda x: x[0]): nw = max(nw, len(nevra)) for aid, atypesev in id2type.items(): idw = max(idw, len(aid)) label = type2label(*atypesev) tlw = max(tlw, len(label)) advlist.append((inst2mark(inst), aid, label, nevra, aupdated)) for (inst, aid, label, nevra, aupdated) in advlist: if self.base.conf.verbose: print('%s%-*s %-*s %-*s %s' % (inst, idw, aid, tlw, label, nw, nevra, aupdated)) else: print('%s%-*s %-*s %s' % (inst, idw, aid, tlw, label, nevra)) def display_info(self, apkg_adv_insts): """Display the details about available advisories.""" arches = self.base.sack.list_arches() verbose = self.base.conf.verbose labels = (_('Update ID'), _('Type'), _('Updated'), _('Bugs'), _('CVEs'), _('Description'), _('Severity'), _('Rights'), _('Files'), _('Installed')) 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 self.opts.availability == 'all': 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(key) lines.append('%*s%s: %s' % (key_padding, "", key, line)) return '\n'.join(lines) advisories = set() for apkg, advisory, installed in apkg_adv_insts: advisories.add(advisory2info(advisory, installed)) print("\n\n".join(sorted(advisories, key=lambda x: x.lower()))) commands/upgrade.py000064400000011176151030066770010361 0ustar00# upgrade.py # Upgrade CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals import logging import dnf.exceptions import dnf.base from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import _ logger = logging.getLogger('dnf') class UpgradeCommand(commands.Command): """A class containing methods needed by the cli to execute the update command. """ aliases = ('upgrade', 'update', 'upgrade-to', 'update-to', 'localupdate', 'up') summary = _('upgrade a package or packages on your system') @staticmethod def set_argparser(parser): parser.add_argument('packages', nargs='*', help=_('Package to upgrade'), action=OptionParser.ParseSpecGroupFileCallback, metavar=_('PACKAGE')) def configure(self): """Verify that conditions are met so that this command can run. These include that there are enabled repositories with gpg keys, and that this command is being run by the root user. """ demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True commands._checkGPGKey(self.base, self.cli) if not self.opts.filenames: commands._checkEnabledRepo(self.base) self.upgrade_minimal = None self.all_security = None self.skipped_grp_specs = None def run(self): cmp_type = "eq" if self.upgrade_minimal else "gte" self.cli._populate_update_security_filter(self.opts, cmp_type=cmp_type, all=self.all_security) if self.opts.filenames or self.opts.pkg_specs or self.opts.grp_specs: result = False result |= self._update_modules() result |= self._update_files() result |= self._update_packages() result |= self._update_groups() if result: return else: self.base.upgrade_all() return raise dnf.exceptions.Error(_('No packages marked for upgrade.')) def _update_modules(self): group_specs_num = len(self.opts.grp_specs) if dnf.base.WITH_MODULES: module_base = dnf.module.module_base.ModuleBase(self.base) self.skipped_grp_specs = module_base.upgrade(self.opts.grp_specs) else: self.skipped_grp_specs = self.opts.grp_specs return len(self.skipped_grp_specs) != group_specs_num def _update_files(self): success = False if self.opts.filenames: for pkg in self.base.add_remote_rpms(self.opts.filenames, strict=False, progress=self.base.output.progress): try: self.base.package_upgrade(pkg) success = True except dnf.exceptions.MarkingError as e: logger.info(_('No match for argument: %s'), self.base.output.term.bold(pkg.location)) return success def _update_packages(self): success = False for pkg_spec in self.opts.pkg_specs: try: self.base.upgrade(pkg_spec) success = True except dnf.exceptions.MarkingError as e: logger.info(_('No match for argument: %s'), self.base.output.term.bold(pkg_spec)) return success def _update_groups(self): if self.skipped_grp_specs: self.base.env_group_upgrade(self.skipped_grp_specs) return True return False commands/repolist.py000064400000031172151030066770010571 0ustar00# repolist.py # repolist CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.i18n import _, ucd, fill_exact_width, exact_width from dnf.cli.option_parser import OptionParser import dnf.cli.format import dnf.pycomp import dnf.util import fnmatch import hawkey import logging import operator logger = logging.getLogger('dnf') def _expire_str(repo, md): last = dnf.util.normalize_time(repo._repo.getTimestamp()) if md else _("unknown") if repo.metadata_expire <= -1: return _("Never (last: %s)") % last elif not repo.metadata_expire: return _("Instant (last: %s)") % last else: num = _num2ui_num(repo.metadata_expire) return _("%s second(s) (last: %s)") % (num, last) def _num2ui_num(num): return ucd(dnf.pycomp.format("%d", num, True)) def _repo_match(repo, patterns): rid = repo.id.lower() rnm = repo.name.lower() for pat in patterns: if fnmatch.fnmatch(rid, pat): return True if fnmatch.fnmatch(rnm, pat): return True return False def _repo_size(sack, repo): ret = 0 for pkg in sack.query(flags=hawkey.IGNORE_EXCLUDES).filterm(reponame__eq=repo.id): ret += pkg._size return dnf.cli.format.format_number(ret) class RepoListCommand(commands.Command): """A class containing methods needed by the cli to execute the repolist command. """ aliases = ('repolist', 'repoinfo') summary = _('display the configured software repositories') @staticmethod def set_argparser(parser): repolimit = parser.add_mutually_exclusive_group() repolimit.add_argument('--all', dest='_repos_action', action='store_const', const='all', default=None, help=_("show all repos")) repolimit.add_argument('--enabled', dest='_repos_action', action='store_const', const='enabled', help=_("show enabled repos (default)")) repolimit.add_argument('--disabled', dest='_repos_action', action='store_const', const='disabled', help=_("show disabled repos")) parser.add_argument('repos', nargs='*', default='enabled-default', metavar="REPOSITORY", choices=['all', 'enabled', 'disabled'], action=OptionParser.PkgNarrowCallback, help=_("Repository specification")) def pre_configure(self): if not self.opts.quiet: self.cli.redirect_logger(stdout=logging.WARNING, stderr=logging.INFO) def configure(self): if not self.opts.quiet: self.cli.redirect_repo_progress() demands = self.cli.demands if self.base.conf.verbose or self.opts.command == 'repoinfo': demands.available_repos = True demands.sack_activation = True if self.opts._repos_action: self.opts.repos_action = self.opts._repos_action def run(self): arg = self.opts.repos_action extcmds = [x.lower() for x in self.opts.repos] verbose = self.base.conf.verbose repos = list(self.base.repos.values()) repos.sort(key=operator.attrgetter('id')) term = self.output.term on_ehibeg = term.FG_COLOR['green'] + term.MODE['bold'] on_dhibeg = term.FG_COLOR['red'] on_hiend = term.MODE['normal'] tot_num = 0 cols = [] if not repos: logger.warning(_('No repositories available')) return include_status = arg == 'all' or (arg == 'enabled-default' and extcmds) repoinfo_output = [] for repo in repos: if len(extcmds) and not _repo_match(repo, extcmds): continue (ehibeg, dhibeg, hiend) = '', '', '' ui_enabled = '' ui_endis_wid = 0 ui_excludes_num = '' if include_status: (ehibeg, dhibeg, hiend) = (on_ehibeg, on_dhibeg, on_hiend) if repo.enabled: enabled = True if arg == 'disabled': continue if include_status or verbose or self.opts.command == 'repoinfo': ui_enabled = ehibeg + _('enabled') + hiend ui_endis_wid = exact_width(_('enabled')) if verbose or self.opts.command == 'repoinfo': ui_size = _repo_size(self.base.sack, repo) else: enabled = False if arg == 'enabled' or (arg == 'enabled-default' and not extcmds): continue ui_enabled = dhibeg + _('disabled') + hiend ui_endis_wid = exact_width(_('disabled')) if not (verbose or self.opts.command == 'repoinfo'): rid = ucd(repo.id) cols.append((rid, repo.name, (ui_enabled, ui_endis_wid))) else: if enabled: md = repo.metadata else: md = None out = [self.output.fmtKeyValFill(_("Repo-id : "), repo.id), self.output.fmtKeyValFill(_("Repo-name : "), repo.name)] if include_status: out += [self.output.fmtKeyValFill(_("Repo-status : "), ui_enabled)] if md and repo._repo.getRevision(): out += [self.output.fmtKeyValFill(_("Repo-revision : "), repo._repo.getRevision())] if md and repo._repo.getContentTags(): tags = repo._repo.getContentTags() out += [self.output.fmtKeyValFill(_("Repo-tags : "), ", ".join(sorted(tags)))] if md and repo._repo.getDistroTags(): distroTagsDict = {k: v for (k, v) in repo._repo.getDistroTags()} for (distro, tags) in distroTagsDict.items(): out += [self.output.fmtKeyValFill( _("Repo-distro-tags : "), "[%s]: %s" % (distro, ", ".join(sorted(tags))))] if md: num = len(self.base.sack.query(flags=hawkey.IGNORE_EXCLUDES).filterm( reponame__eq=repo.id)) num_available = len(self.base.sack.query().filterm(reponame__eq=repo.id)) ui_num = _num2ui_num(num) ui_num_available = _num2ui_num(num_available) tot_num += num out += [ self.output.fmtKeyValFill( _("Repo-updated : "), dnf.util.normalize_time(repo._repo.getMaxTimestamp())), self.output.fmtKeyValFill(_("Repo-pkgs : "), ui_num), self.output.fmtKeyValFill(_("Repo-available-pkgs: "), ui_num_available), self.output.fmtKeyValFill(_("Repo-size : "), ui_size)] if repo.metalink: out += [self.output.fmtKeyValFill(_("Repo-metalink : "), repo.metalink)] if enabled: ts = repo._repo.getTimestamp() out += [self.output.fmtKeyValFill( _(" Updated : "), dnf.util.normalize_time(ts))] elif repo.mirrorlist: out += [self.output.fmtKeyValFill(_("Repo-mirrors : "), repo.mirrorlist)] baseurls = repo.baseurl if baseurls: out += [self.output.fmtKeyValFill(_("Repo-baseurl : "), ", ".join(baseurls))] elif enabled: mirrors = repo._repo.getMirrors() if mirrors: url = "%s (%d more)" % (mirrors[0], len(mirrors) - 1) out += [self.output.fmtKeyValFill(_("Repo-baseurl : "), url)] expire = _expire_str(repo, md) out += [self.output.fmtKeyValFill(_("Repo-expire : "), expire)] if repo.excludepkgs: # TRANSLATORS: Packages that are excluded - their names like (dnf systemd) out += [self.output.fmtKeyValFill(_("Repo-exclude : "), ", ".join(repo.excludepkgs))] if repo.includepkgs: out += [self.output.fmtKeyValFill(_("Repo-include : "), ", ".join(repo.includepkgs))] if ui_excludes_num: # TRANSLATORS: Number of packages that where excluded (5) out += [self.output.fmtKeyValFill(_("Repo-excluded : "), ui_excludes_num)] if repo.repofile: out += [self.output.fmtKeyValFill(_("Repo-filename : "), repo.repofile)] repoinfo_output.append("\n".join(map(ucd, out))) if repoinfo_output: print("\n\n".join(repoinfo_output)) if not verbose and cols: # Work out the first (id) and last (enabled/disabled/count), # then chop the middle (name)... id_len = exact_width(_('repo id')) nm_len = 0 st_len = 0 for (rid, rname, (ui_enabled, ui_endis_wid)) in cols: if id_len < exact_width(rid): id_len = exact_width(rid) if nm_len < exact_width(rname): nm_len = exact_width(rname) if st_len < ui_endis_wid: st_len = ui_endis_wid # Need this as well as above for: fill_exact_width() if include_status: if exact_width(_('status')) > st_len: left = term.columns - (id_len + len(_('status')) + 2) else: left = term.columns - (id_len + st_len + 2) else: # Don't output a status column. left = term.columns - (id_len + 1) if left < nm_len: # Name gets chopped nm_len = left else: # Share the extra... left -= nm_len id_len += left // 2 nm_len += left - (left // 2) txt_rid = fill_exact_width(_('repo id'), id_len) if include_status: txt_rnam = fill_exact_width(_('repo name'), nm_len, nm_len) else: txt_rnam = _('repo name') if not include_status: # Don't output a status column. print("%s %s" % (txt_rid, txt_rnam)) else: print("%s %s %s" % (txt_rid, txt_rnam, _('status'))) for (rid, rname, (ui_enabled, ui_endis_wid)) in cols: if not include_status: # Don't output a status column. print("%s %s" % (fill_exact_width(rid, id_len), rname)) continue print("%s %s %s" % (fill_exact_width(rid, id_len), fill_exact_width(rname, nm_len, nm_len), ui_enabled)) if verbose or self.opts.command == 'repoinfo': msg = _('Total packages: {}') print(msg.format(_num2ui_num(tot_num))) commands/group.py000064400000035235151030066770010070 0ustar00# group.py # Group CLI command. # # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.comps import CompsQuery from dnf.cli import commands from dnf.i18n import _, ucd import libdnf.transaction import dnf.cli import dnf.exceptions import dnf.util import logging logger = logging.getLogger("dnf") class GroupCommand(commands.Command): """ Single sub-command interface for most groups interaction. """ direct_commands = {'grouplist' : 'list', 'groupinstall' : 'install', 'groupupdate' : 'install', 'groupremove' : 'remove', 'grouperase' : 'remove', 'groupinfo' : 'info'} aliases = ('group', 'groups', 'grp') + tuple(direct_commands.keys()) summary = _('display, or use, the groups information') _CMD_ALIASES = {'update' : 'upgrade', 'erase' : 'remove'} _MARK_CMDS = ('install', 'remove') _GROUP_SUBCOMMANDS = ('summary', 'list', 'info', 'remove', 'install', 'upgrade', 'mark') def _canonical(self): # were we called with direct command? direct = self.direct_commands.get(self.opts.command) if direct: # canonize subcmd and args if self.opts.subcmd is not None: self.opts.args.insert(0, self.opts.subcmd) self.opts.subcmd = direct if self.opts.subcmd is None: self.opts.subcmd = 'summary' self.opts.subcmd = self._CMD_ALIASES.get(self.opts.subcmd, self.opts.subcmd) def __init__(self, cli): super(GroupCommand, self).__init__(cli) self._remark = False def _assert_comps(self): msg = _('No group data available for configured repositories.') if not len(self.base.comps): raise dnf.exceptions.CompsError(msg) def _environment_lists(self, patterns): def available_pred(env): env_found = self.base.history.env.get(env.id) return not(env_found) self._assert_comps() if patterns is None: envs = self.base.comps.environments else: envs = self.base.comps.environments_by_pattern(",".join(patterns)) return dnf.util.mapall(list, dnf.util.partition(available_pred, envs)) def _group_lists(self, uservisible, patterns): def installed_pred(group): group_found = self.base.history.group.get(group.id) if group_found: return True return False installed = [] available = [] self._assert_comps() if patterns is None: grps = self.base.comps.groups else: grps = self.base.comps.groups_by_pattern(",".join(patterns)) for grp in grps: tgt_list = available if installed_pred(grp): tgt_list = installed if not uservisible or grp.uservisible: tgt_list.append(grp) return installed, available def _info(self, userlist): for strng in userlist: group_matched = False for env in self.base.comps.environments_by_pattern(strng): self.output.display_groups_in_environment(env) group_matched = True for group in self.base.comps.groups_by_pattern(strng): self.output.display_pkgs_in_groups(group) group_matched = True if not group_matched: logger.error(_('Warning: Group %s does not exist.'), strng) return 0, [] def _list(self, userlist): uservisible = 1 showinstalled = 0 showavailable = 0 print_ids = self.base.conf.verbose or self.opts.ids while userlist: if userlist[0] == 'hidden': uservisible = 0 userlist.pop(0) elif userlist[0] == 'installed': showinstalled = 1 userlist.pop(0) elif userlist[0] == 'available': showavailable = 1 userlist.pop(0) elif userlist[0] == 'ids': print_ids = True userlist.pop(0) else: break if self.opts.hidden: uservisible = 0 if self.opts.installed: showinstalled = 1 if self.opts.available: showavailable = 1 if not userlist: userlist = None # Match everything... errs = False if userlist is not None: for group in userlist: comps = self.base.comps in_group = len(comps.groups_by_pattern(group)) > 0 in_environment = len(comps.environments_by_pattern(group)) > 0 if not in_group and not in_environment: logger.error(_('Warning: No groups match:') + '\n %s', group) errs = True if errs: return 0, [] env_inst, env_avail = self._environment_lists(userlist) installed, available = self._group_lists(uservisible, userlist) def _out_grp(sect, group): if not done: print(sect) msg = ' %s' % (group.ui_name if group.ui_name is not None else _("")) if print_ids: msg += ' (%s)' % group.id if group.lang_only: msg += ' [%s]' % group.lang_only print('{}'.format(msg)) def _out_env(sect, envs): if envs: print(sect) for e in envs: msg = ' %s' % (e.ui_name if e.ui_name is not None else _("")) if print_ids: msg += ' (%s)' % e.id print(msg) if not showinstalled: _out_env(_('Available Environment Groups:'), env_avail) if not showavailable: _out_env(_('Installed Environment Groups:'), env_inst) if not showavailable: done = False for group in installed: if group.lang_only: continue _out_grp(_('Installed Groups:'), group) done = True done = False for group in installed: if not group.lang_only: continue _out_grp(_('Installed Language Groups:'), group) done = True if showinstalled: return 0, [] done = False for group in available: if group.lang_only: continue _out_grp(_('Available Groups:'), group) done = True done = False for group in available: if not group.lang_only: continue _out_grp(_('Available Language Groups:'), group) done = True return 0, [] def _mark_install(self, patterns): q = CompsQuery(self.base.comps, self.base.history, CompsQuery.GROUPS | CompsQuery.ENVIRONMENTS, CompsQuery.AVAILABLE | CompsQuery.INSTALLED) solver = self.base._build_comps_solver() res = q.get(*patterns) if self.opts.with_optional: types = tuple(self.base.conf.group_package_types + ['optional']) else: types = tuple(self.base.conf.group_package_types) pkg_types = libdnf.transaction.listToCompsPackageType(types) for env_id in res.environments: solver._environment_install(env_id, pkg_types) for group_id in res.groups: solver._group_install(group_id, pkg_types) def _mark_remove(self, patterns): q = CompsQuery(self.base.comps, self.base.history, CompsQuery.GROUPS | CompsQuery.ENVIRONMENTS, CompsQuery.INSTALLED) solver = self.base._build_comps_solver() res = q.get(*patterns) for env_id in res.environments: assert dnf.util.is_string_type(env_id) solver._environment_remove(env_id) for grp_id in res.groups: assert dnf.util.is_string_type(grp_id) solver._group_remove(grp_id) def _mark_subcmd(self, extcmds): if extcmds[0] in self._MARK_CMDS: return extcmds[0], extcmds[1:] return 'install', extcmds def _summary(self, userlist): uservisible = 1 if len(userlist) > 0: if userlist[0] == 'hidden': uservisible = 0 userlist.pop(0) if self.opts.hidden: uservisible = 0 if not userlist: userlist = None # Match everything... installed, available = self._group_lists(uservisible, userlist) def _out_grp(sect, num): if not num: return logger.info('%s %u', sect, num) done = 0 for group in installed: if group.lang_only: continue done += 1 _out_grp(_('Installed Groups:'), done) done = 0 for group in installed: if not group.lang_only: continue done += 1 _out_grp(_('Installed Language Groups:'), done) done = False for group in available: if group.lang_only: continue done += 1 _out_grp(_('Available Groups:'), done) done = False for group in available: if not group.lang_only: continue done += 1 _out_grp(_('Available Language Groups:'), done) return 0, [] @staticmethod def set_argparser(parser): parser.add_argument('--with-optional', action='store_true', help=_("include optional packages from group")) grpparser = parser.add_mutually_exclusive_group() grpparser.add_argument('--hidden', action='store_true', help=_("show also hidden groups")) grpparser.add_argument('--installed', action='store_true', help=_("show only installed groups")) grpparser.add_argument('--available', action='store_true', help=_("show only available groups")) grpparser.add_argument('--ids', action='store_true', help=_("show also ID of groups")) parser.add_argument('subcmd', nargs='?', metavar='COMMAND', help=_('available subcommands: {} (default), {}').format( GroupCommand._GROUP_SUBCOMMANDS[0], ', '.join(GroupCommand._GROUP_SUBCOMMANDS[1:]))) parser.add_argument('args', nargs='*', metavar='COMMAND_ARG', help=_('argument for group subcommand')) def configure(self): self._canonical() cmd = self.opts.subcmd args = self.opts.args if cmd not in self._GROUP_SUBCOMMANDS: logger.critical(_('Invalid groups sub-command, use: %s.'), ", ".join(self._GROUP_SUBCOMMANDS)) raise dnf.cli.CliError if cmd in ('install', 'remove', 'mark', 'info') and not args: self.cli.optparser.print_help(self) raise dnf.cli.CliError demands = self.cli.demands demands.sack_activation = True if cmd in ('install', 'mark', 'remove', 'upgrade'): demands.root_user = True demands.resolving = True if cmd == 'remove': demands.allow_erasing = True demands.available_repos = False else: demands.available_repos = True if cmd not in ('remove'): commands._checkEnabledRepo(self.base) if cmd in ('install', 'upgrade'): commands._checkGPGKey(self.base, self.cli) def run(self): cmd = self.opts.subcmd extcmds = self.opts.args if cmd == 'summary': return self._summary(extcmds) if cmd == 'list': return self._list(extcmds) if cmd == 'info': return self._info(extcmds) if cmd == 'mark': (subcmd, extcmds) = self._mark_subcmd(extcmds) if subcmd == 'remove': return self._mark_remove(extcmds) else: assert subcmd == 'install' return self._mark_install(extcmds) if cmd == 'install': if self.opts.with_optional: types = tuple(self.base.conf.group_package_types + ['optional']) else: types = tuple(self.base.conf.group_package_types) self._remark = True try: return self.base.env_group_install(extcmds, types, self.base.conf.strict) except dnf.exceptions.MarkingError as e: msg = _('No package %s available.') logger.info(msg, self.base.output.term.bold(e)) raise dnf.exceptions.PackagesNotAvailableError( _("Unable to find a mandatory group package.")) if cmd == 'upgrade': return self.base.env_group_upgrade(extcmds) if cmd == 'remove': for arg in extcmds: try: self.base.env_group_remove([arg]) except dnf.exceptions.Error: pass def run_transaction(self): if not self._remark: return goal = self.base._goal history = self.base.history names = goal.group_members for pkg in self.base.sack.query().installed().filterm(name=names): reason = history.rpm.get_reason(pkg) history.set_reason(pkg, goal.group_reason(pkg, reason)) commands/clean.py000064400000010564151030066770010014 0ustar00# clean.py # Clean CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.i18n import _, P_ from dnf.yum import misc import dnf.cli import dnf.exceptions import dnf.lock import dnf.logging import dnf.repo import logging import os import re import time logger = logging.getLogger("dnf") # Dict mapping cmdline arguments to actual data types to be cleaned up _CACHE_TYPES = { 'metadata': ['metadata', 'dbcache', 'expire-cache'], 'packages': ['packages'], 'dbcache': ['dbcache'], 'expire-cache': ['expire-cache'], 'all': ['metadata', 'packages', 'dbcache'], } def _tree(dirpath): """Traverse dirpath recursively and yield relative filenames.""" for root, dirs, files in os.walk(dirpath): base = os.path.relpath(root, dirpath) for f in files: path = os.path.join(base, f) yield os.path.normpath(path) def _filter(files, patterns): """Yield those filenames that match any of the patterns.""" return (f for f in files for p in patterns if re.match(p, f)) def _clean(dirpath, files): """Remove the given filenames from dirpath.""" count = 0 for f in files: path = os.path.join(dirpath, f) logger.log(dnf.logging.DDEBUG, _('Removing file %s'), path) misc.unlink_f(path) count += 1 return count def _cached_repos(files): """Return the repo IDs that have some cached metadata around.""" metapat = dnf.repo.CACHE_FILES['metadata'] matches = (re.match(metapat, f) for f in files) return set(m.group('repoid') for m in matches if m) class CleanCommand(commands.Command): """A class containing methods needed by the cli to execute the clean command. """ aliases = ('clean',) summary = _('remove cached data') @staticmethod def set_argparser(parser): parser.add_argument('type', nargs='+', choices=_CACHE_TYPES.keys(), help=_('Metadata type to clean')) def run(self): cachedir = self.base.conf.cachedir md_lock = dnf.lock.build_metadata_lock(cachedir, True) download_lock = dnf.lock.build_download_lock(cachedir, True) rpmdb_lock = dnf.lock.build_rpmdb_lock(self.base.conf.persistdir, True) while True: try: with md_lock and download_lock and rpmdb_lock: types = set(t for c in self.opts.type for t in _CACHE_TYPES[c]) files = list(_tree(cachedir)) logger.debug(_('Cleaning data: ' + ' '.join(types))) if 'expire-cache' in types: expired = _cached_repos(files) self.base._repo_persistor.expired_to_add.update(expired) types.remove('expire-cache') logger.info(_('Cache was expired')) patterns = [dnf.repo.CACHE_FILES[t] for t in types] count = _clean(cachedir, _filter(files, patterns)) logger.info(P_('%d file removed', '%d files removed', count) % count) return except dnf.exceptions.LockError as e: if not self.base.conf.exit_on_lock: msg = _('Waiting for process with pid %d to finish.') % (e.pid) logger.info(msg) time.sleep(3) else: raise e commands/downgrade.py000064400000004425151030066770010703 0ustar00# downgrade.py # Downgrade CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import _ class DowngradeCommand(commands.Command): """A class containing methods needed by the cli to execute the downgrade command. """ aliases = ('downgrade', 'dg') summary = _("Downgrade a package") @staticmethod def set_argparser(parser): parser.add_argument('package', nargs='*', help=_('Package to downgrade'), action=OptionParser.ParseSpecGroupFileCallback) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True commands._checkGPGKey(self.base, self.cli) if not self.opts.filenames: commands._checkEnabledRepo(self.base) def run(self): file_pkgs = self.base.add_remote_rpms(self.opts.filenames, strict=False, progress=self.base.output.progress) return self.base.downgradePkgs( specs=self.opts.pkg_specs + ['@' + x for x in self.opts.grp_specs], file_pkgs=file_pkgs, strict=self.base.conf.strict) commands/history.py000064400000043045151030066770010433 0ustar00# Copyright 2006 Duke University # Copyright (C) 2012-2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import libdnf import hawkey from dnf.i18n import _, ucd from dnf.cli import commands from dnf.transaction_sr import TransactionReplay, serialize_transaction import dnf.cli import dnf.exceptions import dnf.transaction import dnf.util import json import logging import os logger = logging.getLogger('dnf') class HistoryCommand(commands.Command): """A class containing methods needed by the cli to execute the history command. """ aliases = ('history', 'hist') summary = _('display, or use, the transaction history') _CMDS = ['list', 'info', 'redo', 'replay', 'rollback', 'store', 'undo', 'userinstalled'] def __init__(self, *args, **kw): super(HistoryCommand, self).__init__(*args, **kw) self._require_one_transaction_id = False @staticmethod def set_argparser(parser): parser.add_argument('transactions_action', nargs='?', metavar="COMMAND", help="Available commands: {} (default), {}".format( HistoryCommand._CMDS[0], ", ".join(HistoryCommand._CMDS[1:]))) parser.add_argument('--reverse', action='store_true', help="display history list output reversed") parser.add_argument("-o", "--output", default=None, help=_("For the store command, file path to store the transaction to")) parser.add_argument("--ignore-installed", action="store_true", help=_("For the replay command, don't check for installed packages matching " "those in transaction")) parser.add_argument("--ignore-extras", action="store_true", help=_("For the replay command, don't check for extra packages pulled " "into the transaction")) parser.add_argument("--skip-unavailable", action="store_true", help=_("For the replay command, skip packages that are not available or have " "missing dependencies")) parser.add_argument('transactions', nargs='*', metavar="TRANSACTION", help="For commands working with history transactions, " "Transaction ID (, 'last' or 'last-' " "for one transaction, .. " "for a range)") parser.add_argument('transaction_filename', nargs='?', metavar="TRANSACTION_FILE", help="For the replay command, path to the stored " "transaction file to replay") def configure(self): if not self.opts.transactions_action: # no positional argument given self.opts.transactions_action = self._CMDS[0] elif self.opts.transactions_action not in self._CMDS: # first positional argument is not a command self.opts.transactions.insert(0, self.opts.transactions_action) self.opts.transactions_action = self._CMDS[0] self._require_one_transaction_id_msg = _("Found more than one transaction ID.\n" "'{}' requires one transaction ID or package name." ).format(self.opts.transactions_action) demands = self.cli.demands if self.opts.transactions_action == 'replay': if not self.opts.transactions: raise dnf.cli.CliError(_('No transaction file name given.')) if len(self.opts.transactions) > 1: raise dnf.cli.CliError(_('More than one argument given as transaction file name.')) # in case of replay, copy over the file name to it's appropriate variable # (the arg parser can't distinguish here) self.opts.transaction_filename = os.path.abspath(self.opts.transactions[0]) self.opts.transactions = [] demands.available_repos = True demands.resolving = True demands.root_user = True # Override configuration options that affect how the transaction is resolved self.base.conf.clean_requirements_on_remove = False self.base.conf.install_weak_deps = False dnf.cli.commands._checkGPGKey(self.base, self.cli) elif self.opts.transactions_action == 'store': self._require_one_transaction_id = True if not self.opts.transactions: raise dnf.cli.CliError(_('No transaction ID or package name given.')) elif self.opts.transactions_action in ['redo', 'undo', 'rollback']: demands.available_repos = True demands.resolving = True demands.root_user = True self._require_one_transaction_id = True if not self.opts.transactions: msg = _('No transaction ID or package name given.') logger.critical(msg) raise dnf.cli.CliError(msg) elif len(self.opts.transactions) > 1: logger.critical(self._require_one_transaction_id_msg) raise dnf.cli.CliError(self._require_one_transaction_id_msg) demands.available_repos = True dnf.cli.commands._checkGPGKey(self.base, self.cli) else: demands.fresh_metadata = False demands.sack_activation = True if self.base.history.path != ":memory:" and not os.access(self.base.history.path, os.R_OK): msg = _("You don't have access to the history DB: %s" % self.base.history.path) logger.critical(msg) raise dnf.cli.CliError(msg) def get_error_output(self, error): """Get suggestions for resolving the given error.""" if isinstance(error, dnf.exceptions.TransactionCheckError): if self.opts.transactions_action == 'undo': id_, = self.opts.transactions return (_('Cannot undo transaction %s, doing so would result ' 'in an inconsistent package database.') % id_,) elif self.opts.transactions_action == 'rollback': id_, = (self.opts.transactions if self.opts.transactions[0] != 'force' else self.opts.transactions[1:]) return (_('Cannot rollback transaction %s, doing so would ' 'result in an inconsistent package database.') % id_,) return dnf.cli.commands.Command.get_error_output(self, error) def _hcmd_redo(self, extcmds): old = self._history_get_transaction(extcmds) data = serialize_transaction(old) self.replay = TransactionReplay( self.base, data=data, ignore_installed=True, ignore_extras=True, skip_unavailable=self.opts.skip_unavailable ) self.replay.run() def _history_get_transactions(self, extcmds): if not extcmds: raise dnf.cli.CliError(_('No transaction ID given')) old = self.base.history.old(extcmds) if not old: raise dnf.cli.CliError(_('Transaction ID "{0}" not found.').format(extcmds[0])) return old def _history_get_transaction(self, extcmds): old = self._history_get_transactions(extcmds) if len(old) > 1: raise dnf.cli.CliError(_('Found more than one transaction ID!')) return old[0] def _hcmd_undo(self, extcmds): old = self._history_get_transaction(extcmds) self._revert_transaction(old) def _hcmd_rollback(self, extcmds): old = self._history_get_transaction(extcmds) last = self.base.history.last() merged_trans = None if old.tid != last.tid: # history.old([]) returns all transactions and we don't want that # so skip merging the transactions when trying to rollback to the last transaction # which is the current system state and rollback is not applicable for trans in self.base.history.old(list(range(old.tid + 1, last.tid + 1))): if trans.altered_lt_rpmdb: logger.warning(_('Transaction history is incomplete, before %u.'), trans.tid) elif trans.altered_gt_rpmdb: logger.warning(_('Transaction history is incomplete, after %u.'), trans.tid) if merged_trans is None: merged_trans = dnf.db.history.MergedTransactionWrapper(trans) else: merged_trans.merge(trans) self._revert_transaction(merged_trans) def _revert_transaction(self, trans): action_map = { "Install": "Removed", "Removed": "Install", "Upgrade": "Downgraded", "Upgraded": "Downgrade", "Downgrade": "Upgraded", "Downgraded": "Upgrade", "Reinstalled": "Reinstall", "Reinstall": "Reinstalled", "Obsoleted": "Install", "Obsolete": "Obsoleted", "Reason Change": "Reason Change", } data = serialize_transaction(trans) # revert actions in the serialized transaction data to perform rollback/undo for content_type in ("rpms", "groups", "environments"): for ti in data.get(content_type, []): ti["action"] = action_map[ti["action"]] if ti["action"] == "Install" and ti.get("reason", None) == "clean": ti["reason"] = "dependency" if ti["action"] == "Reason Change" and "nevra" in ti: subj = hawkey.Subject(ti["nevra"]) nevra = subj.get_nevra_possibilities(forms=[hawkey.FORM_NEVRA])[0] reason = self.output.history.swdb.resolveRPMTransactionItemReason( nevra.name, nevra.arch, trans.tids()[0] - 1 ) ti["reason"] = libdnf.transaction.TransactionItemReasonToString(reason) if ti.get("repo_id") == hawkey.SYSTEM_REPO_NAME: # erase repo_id, because it's not possible to perform forward actions from the @System repo ti["repo_id"] = None self.replay = TransactionReplay( self.base, data=data, ignore_installed=True, ignore_extras=True, skip_unavailable=self.opts.skip_unavailable ) self.replay.run() def _hcmd_userinstalled(self): """Execute history userinstalled command.""" pkgs = tuple(self.base.iter_userinstalled()) n_listed = self.output.listPkgs(pkgs, 'Packages installed by user', 'nevra') if n_listed == 0: raise dnf.cli.CliError(_('No packages to list')) def _args2transaction_ids(self): """Convert commandline arguments to transaction ids""" def str2transaction_id(s): if s == 'last': s = '0' elif s.startswith('last-'): s = s[4:] transaction_id = int(s) if transaction_id <= 0: transaction_id += self.output.history.last().tid return transaction_id tids = set() merged_tids = set() for t in self.opts.transactions: if '..' in t: try: begin_transaction_id, end_transaction_id = t.split('..', 2) except ValueError: logger.critical( _("Invalid transaction ID range definition '{}'.\n" "Use '..'." ).format(t)) raise dnf.cli.CliError cant_convert_msg = _("Can't convert '{}' to transaction ID.\n" "Use '', 'last', 'last-'.") try: begin_transaction_id = str2transaction_id(begin_transaction_id) except ValueError: logger.critical(_(cant_convert_msg).format(begin_transaction_id)) raise dnf.cli.CliError try: end_transaction_id = str2transaction_id(end_transaction_id) except ValueError: logger.critical(_(cant_convert_msg).format(end_transaction_id)) raise dnf.cli.CliError if self._require_one_transaction_id and begin_transaction_id != end_transaction_id: logger.critical(self._require_one_transaction_id_msg) raise dnf.cli.CliError if begin_transaction_id > end_transaction_id: begin_transaction_id, end_transaction_id = \ end_transaction_id, begin_transaction_id merged_tids.add((begin_transaction_id, end_transaction_id)) tids.update(range(begin_transaction_id, end_transaction_id + 1)) else: try: tids.add(str2transaction_id(t)) except ValueError: # not a transaction id, assume it's package name transact_ids_from_pkgname = self.output.history.search([t]) if transact_ids_from_pkgname: tids.update(transact_ids_from_pkgname) else: msg = _("No transaction which manipulates package '{}' was found." ).format(t) if self._require_one_transaction_id: logger.critical(msg) raise dnf.cli.CliError else: logger.info(msg) return sorted(tids, reverse=True), merged_tids def run(self): vcmd = self.opts.transactions_action if vcmd == 'replay': self.replay = TransactionReplay( self.base, filename=self.opts.transaction_filename, ignore_installed = self.opts.ignore_installed, ignore_extras = self.opts.ignore_extras, skip_unavailable = self.opts.skip_unavailable ) self.replay.run() else: tids, merged_tids = self._args2transaction_ids() if vcmd == 'list' and (tids or not self.opts.transactions): self.output.historyListCmd(tids, reverse=self.opts.reverse) elif vcmd == 'info' and (tids or not self.opts.transactions): self.output.historyInfoCmd(tids, self.opts.transactions, merged_tids) elif vcmd == 'undo': self._hcmd_undo(tids) elif vcmd == 'redo': self._hcmd_redo(tids) elif vcmd == 'rollback': self._hcmd_rollback(tids) elif vcmd == 'userinstalled': self._hcmd_userinstalled() elif vcmd == 'store': tid = self._history_get_transaction(tids) data = serialize_transaction(tid) try: filename = self.opts.output if self.opts.output is not None else "transaction.json" # it is absolutely possible for both assumeyes and assumeno to be True, go figure if (self.base.conf.assumeno or not self.base.conf.assumeyes) and os.path.isfile(filename): msg = _("{} exists, overwrite?").format(filename) if self.base.conf.assumeno or not self.base.output.userconfirm( msg='\n{} [y/N]: '.format(msg), defaultyes_msg='\n{} [Y/n]: '.format(msg)): print(_("Not overwriting {}, exiting.").format(filename)) return with open(filename, "w") as f: json.dump(data, f, indent=4, sort_keys=True) f.write("\n") print(_("Transaction saved to {}.").format(filename)) except OSError as e: raise dnf.cli.CliError(_('Error storing transaction: {}').format(str(e))) def run_resolved(self): if self.opts.transactions_action not in ("replay", "redo", "rollback", "undo"): return self.replay.post_transaction() def run_transaction(self): if self.opts.transactions_action not in ("replay", "redo", "rollback", "undo"): return warnings = self.replay.get_warnings() if warnings: logger.log( dnf.logging.WARNING, _("Warning, the following problems occurred while running a transaction:") ) for w in warnings: logger.log(dnf.logging.WARNING, " " + w) commands/remove.py000064400000014752151030066770010232 0ustar00# remove_command.py # Remove CLI command. # # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.i18n import _ from dnf.cli.option_parser import OptionParser import dnf.base import argparse import hawkey import dnf.exceptions import logging logger = logging.getLogger("dnf") class RemoveCommand(commands.Command): """Remove command.""" nevra_forms = {'remove-n': hawkey.FORM_NAME, 'remove-na': hawkey.FORM_NA, 'remove-nevra': hawkey.FORM_NEVRA, 'erase-n': hawkey.FORM_NAME, 'erase-na': hawkey.FORM_NA, 'erase-nevra': hawkey.FORM_NEVRA} aliases = ('remove', 'erase', 'rm') + tuple(nevra_forms.keys()) summary = _('remove a package or packages from your system') @staticmethod def set_argparser(parser): mgroup = parser.add_mutually_exclusive_group() mgroup.add_argument('--duplicates', action='store_true', dest='duplicated', help=_('remove duplicated packages')) mgroup.add_argument('--duplicated', action='store_true', help=argparse.SUPPRESS) mgroup.add_argument('--oldinstallonly', action='store_true', help=_( 'remove installonly packages over the limit')) parser.add_argument('packages', nargs='*', help=_('Package to remove'), action=OptionParser.ParseSpecGroupFileCallback, metavar=_('PACKAGE')) def configure(self): demands = self.cli.demands # disable all available repos to delete whole dependency tree # instead of replacing removable package with available packages demands.resolving = True demands.root_user = True demands.sack_activation = True if self.opts.duplicated: demands.available_repos = True elif dnf.base.WITH_MODULES and self.opts.grp_specs: demands.available_repos = True demands.fresh_metadata = False demands.allow_erasing = True else: demands.allow_erasing = True demands.available_repos = False def run(self): forms = [] if self.opts.command in self.nevra_forms: forms = [self.nevra_forms[self.opts.command]] # local pkgs not supported in erase command self.opts.pkg_specs += self.opts.filenames done = False if self.opts.duplicated: q = self.base.sack.query() instonly = self.base._get_installonly_query(q.installed()) dups = q.duplicated().difference(instonly) if not dups: raise dnf.exceptions.Error(_('No duplicated packages found for removal.')) for (name, arch), pkgs_list in dups._na_dict().items(): if len(pkgs_list) < 2: continue pkgs_list.sort(reverse=True) try: self.base.reinstall(str(pkgs_list[0])) except dnf.exceptions.PackagesNotAvailableError: xmsg = '' msg = _('Installed package %s%s not available.') logger.warning(msg, self.base.output.term.bold(str(pkgs_list[0])), xmsg) for pkg in pkgs_list[1:]: self.base.package_remove(pkg) return if self.opts.oldinstallonly: q = self.base.sack.query() instonly = self.base._get_installonly_query(q.installed()).latest(-1) # also remove running kernel from the set kernel = self.base.sack.get_running_kernel() if kernel is not None: running_installonly = instonly.filter( epoch=kernel.epoch, version=kernel.version, release=kernel.release) if running_installonly: instonly = instonly.difference(running_installonly) if instonly: for pkg in instonly: self.base.package_remove(pkg) else: raise dnf.exceptions.Error( _('No old installonly packages found for removal.')) return # Remove groups. if self.opts.grp_specs and forms: for grp_spec in self.opts.grp_specs: msg = _('Not a valid form: %s') logger.warning(msg, self.base.output.term.bold(grp_spec)) elif self.opts.grp_specs: if dnf.base.WITH_MODULES: module_base = dnf.module.module_base.ModuleBase(self.base) skipped_grps = module_base.remove(self.opts.grp_specs) if len(self.opts.grp_specs) != len(skipped_grps): done = True else: skipped_grps = self.opts.grp_specs if skipped_grps: for group in skipped_grps: try: if self.base.env_group_remove([group]): done = True except dnf.exceptions.Error: pass for pkg_spec in self.opts.pkg_specs: try: self.base.remove(pkg_spec, forms=forms) except dnf.exceptions.MarkingError as e: msg = '{}: {}'.format(e.value, self.base.output.term.bold(pkg_spec)) logger.info(msg) else: done = True if not done: logger.warning(_('No packages marked for removal.')) commands/alias.py000064400000015660151030066770010025 0ustar00# alias.py # Alias CLI command. # # Copyright (C) 2018 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import logging import os.path import dnf.cli import dnf.cli.aliases from dnf.cli import commands import dnf.conf import dnf.exceptions from dnf.i18n import _ logger = logging.getLogger('dnf') class AliasCommand(commands.Command): aliases = ('alias',) summary = _('List or create command aliases') @staticmethod def set_argparser(parser): enable_group = parser.add_mutually_exclusive_group() enable_group.add_argument( '--enable-resolving', default=False, action='store_true', help=_('enable aliases resolving')) enable_group.add_argument( '--disable-resolving', default=False, action='store_true', help=_('disable aliases resolving')) parser.add_argument("subcommand", nargs='?', default='list', choices=['add', 'list', 'delete'], help=_("action to do with aliases")) parser.add_argument("alias", nargs="*", metavar="command[=result]", help=_("alias definition")) def configure(self): demands = self.cli.demands if self.opts.subcommand in ('add', 'delete'): demands.root_user = True self.aliases_base = dnf.cli.aliases.Aliases() self.aliases_base._load_aliases() self.resolving_enabled = self.aliases_base.enabled self._update_config_from_options() def _update_config_from_options(self): enabled = None if self.opts.enable_resolving: enabled = True logger.info(_("Aliases are now enabled")) if self.opts.disable_resolving: enabled = False logger.info(_("Aliases are now disabled")) if enabled is not None: if not os.path.exists(dnf.cli.aliases.ALIASES_CONF_PATH): open(dnf.cli.aliases.ALIASES_CONF_PATH, 'w').close() dnf.conf.BaseConfig.write_raw_configfile( dnf.cli.aliases.ALIASES_CONF_PATH, 'main', None, {'enabled': enabled}) if not self.aliases_base._disabled_by_environ(): self.aliases_base.enabled = enabled def _parse_option_alias(self): new_aliases = {} for alias in self.opts.alias: alias = alias.split('=', 1) cmd = alias[0].strip() if len(cmd.split()) != 1: logger.warning(_("Invalid alias key: %s"), cmd) continue if cmd.startswith('-'): logger.warning(_("Invalid alias key: %s"), cmd) continue if len(alias) == 1: logger.warning(_("Alias argument has no value: %s"), cmd) continue new_aliases[cmd] = alias[1].split() return new_aliases def _load_user_aliases(self): if not os.path.exists(dnf.cli.aliases.ALIASES_USER_PATH): open(dnf.cli.aliases.ALIASES_USER_PATH, 'w').close() try: conf = dnf.cli.aliases.AliasesConfig( dnf.cli.aliases.ALIASES_USER_PATH) except dnf.exceptions.ConfigError as e: logger.warning(_('Config error: %s'), e) return None return conf def _store_user_aliases(self, user_aliases, enabled): fileobj = open(dnf.cli.aliases.ALIASES_USER_PATH, 'w') output = "[main]\n" output += "enabled = {}\n\n".format(enabled) output += "[aliases]\n" for key, value in user_aliases.items(): output += "{} = {}\n".format(key, ' '.join(value)) fileobj.write(output) def add_aliases(self, aliases): conf = self._load_user_aliases() user_aliases = conf.aliases if user_aliases is None: return user_aliases.update(aliases) self._store_user_aliases(user_aliases, conf.enabled) logger.info(_("Aliases added: %s"), ', '.join(aliases.keys())) def remove_aliases(self, cmds): conf = self._load_user_aliases() user_aliases = conf.aliases if user_aliases is None: return valid_cmds = [] for cmd in cmds: try: del user_aliases[cmd] valid_cmds.append(cmd) except KeyError: logger.info(_("Alias not found: %s"), cmd) self._store_user_aliases(user_aliases, conf.enabled) logger.info(_("Aliases deleted: %s"), ', '.join(valid_cmds)) def list_alias(self, cmd): args = [cmd] try: args = self.aliases_base._resolve(args) except dnf.exceptions.Error as e: logger.error( _('%s, alias %s="%s"'), e, cmd, (' ').join(self.aliases_base.aliases[cmd])) else: print(_("Alias %s='%s'") % (cmd, " ".join(args))) def run(self): if not self.aliases_base.enabled: logger.warning(_("Aliases resolving is disabled.")) if self.opts.subcommand == 'add': # Add new alias aliases = self._parse_option_alias() if not aliases: raise dnf.exceptions.Error(_("No aliases specified.")) self.add_aliases(aliases) return if self.opts.subcommand == 'delete': # Remove alias cmds = self.opts.alias if cmds == []: raise dnf.exceptions.Error(_("No alias specified.")) self.remove_aliases(cmds) return if not self.opts.alias: # List all aliases if not self.aliases_base.aliases: logger.info(_("No aliases defined.")) return for cmd in self.aliases_base.aliases: self.list_alias(cmd) else: # List alias by key for cmd in self.opts.alias: if cmd not in self.aliases_base.aliases: logger.info(_("No match for alias: %s") % cmd) continue self.list_alias(cmd) commands/install.py000064400000017123151030066770010376 0ustar00# install.py # Install CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals import logging from itertools import chain import hawkey import dnf.exceptions from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import _ logger = logging.getLogger('dnf') class InstallCommand(commands.Command): """A class containing methods needed by the cli to execute the install command. """ nevra_forms = {'install-n': hawkey.FORM_NAME, 'install-na': hawkey.FORM_NA, 'install-nevra': hawkey.FORM_NEVRA} alternatives_provide = 'alternative-for({})' aliases = ('install', 'localinstall', 'in') + tuple(nevra_forms.keys()) summary = _('install a package or packages on your system') @staticmethod def set_argparser(parser): parser.add_argument('package', nargs='+', metavar=_('PACKAGE'), action=OptionParser.ParseSpecGroupFileCallback, help=_('Package to install')) def configure(self): """Verify that conditions are met so that this command can run. That there are enabled repositories with gpg keys, and that this command is called with appropriate arguments. """ demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True commands._checkGPGKey(self.base, self.cli) if not self.opts.filenames: commands._checkEnabledRepo(self.base) def run(self): err_pkgs = [] errs = [] error_module_specs = [] nevra_forms = self._get_nevra_forms_from_command() self.cli._populate_update_security_filter(self.opts) if self.opts.command == 'localinstall' and (self.opts.grp_specs or self.opts.pkg_specs): self._log_not_valid_rpm_file_paths(self.opts.grp_specs) if self.base.conf.strict: raise dnf.exceptions.Error(_('Nothing to do.')) skipped_grp_specs = [] if self.opts.grp_specs and self.opts.command != 'localinstall': if dnf.base.WITH_MODULES: try: module_base = dnf.module.module_base.ModuleBase(self.base) module_base.install(self.opts.grp_specs, strict=self.base.conf.strict) except dnf.exceptions.MarkingErrors as e: if e.no_match_group_specs: for e_spec in e.no_match_group_specs: skipped_grp_specs.append(e_spec) if e.error_group_specs: for e_spec in e.error_group_specs: error_module_specs.append("@" + e_spec) module_depsolv_errors = e.module_depsolv_errors if module_depsolv_errors: logger.error(dnf.module.module_base.format_modular_solver_errors( module_depsolv_errors[0])) else: skipped_grp_specs = self.opts.grp_specs if self.opts.filenames and nevra_forms: self._inform_not_a_valid_combination(self.opts.filenames) if self.base.conf.strict: raise dnf.exceptions.Error(_('Nothing to do.')) else: err_pkgs = self._install_files() if skipped_grp_specs and nevra_forms: self._inform_not_a_valid_combination(skipped_grp_specs) if self.base.conf.strict: raise dnf.exceptions.Error(_('Nothing to do.')) elif skipped_grp_specs and self.opts.command != 'localinstall': self._install_groups(skipped_grp_specs) if self.opts.command != 'localinstall': errs = self._install_packages(nevra_forms) if (len(errs) != 0 or len(err_pkgs) != 0 or error_module_specs) and self.base.conf.strict: raise dnf.exceptions.PackagesNotAvailableError(_("Unable to find a match"), pkg_spec=' '.join(errs), packages=err_pkgs) def _get_nevra_forms_from_command(self): if self.opts.command in self.nevra_forms: return [self.nevra_forms[self.opts.command]] else: return [] def _log_not_valid_rpm_file_paths(self, grp_specs): group_names = map(lambda g: '@' + g, grp_specs) for pkg in chain(self.opts.pkg_specs, group_names): msg = _('Not a valid rpm file path: %s') logger.info(msg, self.base.output.term.bold(pkg)) def _inform_not_a_valid_combination(self, forms): for form in forms: msg = _('Not a valid form: %s') logger.warning(msg, self.base.output.term.bold(form)) def _install_files(self): err_pkgs = [] strict = self.base.conf.strict for pkg in self.base.add_remote_rpms(self.opts.filenames, strict=strict, progress=self.base.output.progress): try: self.base.package_install(pkg, strict=strict) except dnf.exceptions.MarkingError: msg = _('No match for argument: %s') logger.info(msg, self.base.output.term.bold(pkg.location)) err_pkgs.append(pkg) return err_pkgs def _install_groups(self, grp_specs): try: self.base.env_group_install(grp_specs, tuple(self.base.conf.group_package_types), strict=self.base.conf.strict) except dnf.exceptions.Error: if self.base.conf.strict: raise def _report_alternatives(self, pkg_spec): query = self.base.sack.query().filterm( provides=self.alternatives_provide.format(pkg_spec)) if query: msg = _('There are following alternatives for "{0}": {1}') logger.info(msg.format( pkg_spec, ', '.join(sorted(set([alt.name for alt in query]))))) def _install_packages(self, nevra_forms): errs = [] strict = self.base.conf.strict for pkg_spec in self.opts.pkg_specs: try: self.base.install(pkg_spec, strict=strict, forms=nevra_forms) except dnf.exceptions.MarkingError as e: msg = '{}: {}'.format(e.value, self.base.output.term.bold(pkg_spec)) logger.info(msg) self.base._report_icase_hint(pkg_spec) self._report_alternatives(pkg_spec) errs.append(pkg_spec) return errs commands/search.py000064400000014242151030066770010174 0ustar00# search.py # Search CLI command. # # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import collections from dnf.cli import commands from dnf.cli.option_parser import OptionParser from dnf.i18n import ucd, _, C_ import dnf.i18n import dnf.match_counter import dnf.util import hawkey import logging logger = logging.getLogger('dnf') class SearchCommand(commands.Command): """A class containing methods needed by the cli to execute the search command. """ aliases = ('search', 'se') summary = _('search package details for the given string') @staticmethod def set_argparser(parser): parser.add_argument('--all', action='store_true', help=_("search also package description and URL")) parser.add_argument('query_string', nargs='+', metavar=_('KEYWORD'), choices=['all'], default=None, action=OptionParser.PkgNarrowCallback, help=_("Keyword to search for")) def _search(self, args): """Search for simple text tags in a package object.""" TRANS_TBL = collections.OrderedDict(( ('name', C_('long', 'Name')), ('summary', C_('long', 'Summary')), ('description', C_('long', 'Description')), ('url', _('URL')), )) def _translate_attr(attr): try: return TRANS_TBL[attr] except: return attr def _print_section_header(exact_match, attrs, keys): trans_attrs = map(_translate_attr, attrs) # TRANSLATORS: separator used between package attributes (eg. Name & Summary & URL) trans_attrs_str = _(' & ').join(trans_attrs) if exact_match: # TRANSLATORS: %s - translated package attributes, # %%s - found keys (in listed attributes) section_text = _('%s Exactly Matched: %%s') % trans_attrs_str else: # TRANSLATORS: %s - translated package attributes, # %%s - found keys (in listed attributes) section_text = _('%s Matched: %%s') % trans_attrs_str formatted = self.base.output.fmtSection(section_text % ", ".join(keys)) print(ucd(formatted)) counter = dnf.match_counter.MatchCounter() for arg in args: self._search_counted(counter, 'name', arg) self._search_counted(counter, 'summary', arg) if self.opts.all: for arg in args: self._search_counted(counter, 'description', arg) self._search_counted(counter, 'url', arg) else: needles = len(args) pkgs = list(counter.keys()) for pkg in pkgs: if len(counter.matched_needles(pkg)) != needles: del counter[pkg] used_attrs = None matched_needles = None exact_match = False print_section_header = False limit = None if not self.base.conf.showdupesfromrepos: limit = self.base.sack.query().filterm(pkg=counter.keys()).latest() seen = set() for pkg in counter.sorted(reverse=True, limit_to=limit): if not self.base.conf.showdupesfromrepos: if pkg.name + pkg.arch in seen: continue seen.add(pkg.name + pkg.arch) if used_attrs != counter.matched_keys(pkg): used_attrs = counter.matched_keys(pkg) print_section_header = True if matched_needles != counter.matched_needles(pkg): matched_needles = counter.matched_needles(pkg) print_section_header = True if exact_match != (counter.matched_haystacks(pkg) == matched_needles): exact_match = counter.matched_haystacks(pkg) == matched_needles print_section_header = True if print_section_header: _print_section_header(exact_match, used_attrs, matched_needles) print_section_header = False self.base.output.matchcallback(pkg, counter.matched_haystacks(pkg), args) if len(counter) == 0: logger.info(_('No matches found.')) def _search_counted(self, counter, attr, needle): fdict = {'%s__substr' % attr : needle} if dnf.util.is_glob_pattern(needle): fdict = {'%s__glob' % attr : needle} q = self.base.sack.query().filterm(hawkey.ICASE, **fdict) for pkg in q.run(): counter.add(pkg, attr, needle) return counter def pre_configure(self): if not self.opts.quiet: self.cli.redirect_logger(stdout=logging.WARNING, stderr=logging.INFO) def configure(self): if not self.opts.quiet: self.cli.redirect_repo_progress() demands = self.cli.demands demands.available_repos = True demands.fresh_metadata = False demands.sack_activation = True self.opts.all = self.opts.all or self.opts.query_string_action def run(self): logger.debug(_('Searching Packages: ')) return self._search(self.opts.query_string) commands/distrosync.py000064400000003637151030066770011136 0ustar00# distrosync.py # distro-sync CLI command. # # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from dnf.cli import commands from dnf.i18n import _ class DistroSyncCommand(commands.Command): """A class containing methods needed by the cli to execute the distro-synch command. """ aliases = ('distro-sync', 'distrosync', 'distribution-synchronization', 'dsync') summary = _('synchronize installed packages to the latest available versions') @staticmethod def set_argparser(parser): parser.add_argument('package', nargs='*', help=_('Package to synchronize')) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True commands._checkGPGKey(self.base, self.cli) commands._checkEnabledRepo(self.base, self.opts.package) def run(self): return self.base.distro_sync_userlist(self.opts.package) commands/shell.py000064400000023154151030066770010040 0ustar00# shell.py # Shell CLI command. # # Copyright (C) 2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from dnf.cli import commands from dnf.i18n import _, ucd import dnf.util import cmd import copy import dnf import logging import shlex import sys logger = logging.getLogger('dnf') # only demands we'd like to override class ShellDemandSheet(object): available_repos = True resolving = True root_user = True sack_activation = True class ShellCommand(commands.Command, cmd.Cmd): aliases = ('shell', 'sh') summary = _('run an interactive {prog} shell').format(prog=dnf.util.MAIN_PROG_UPPER) MAPPING = {'repo': 'repo', 'repository': 'repo', 'exit': 'quit', 'quit': 'quit', 'run': 'ts_run', 'ts': 'transaction', 'transaction': 'transaction', 'config': 'config', 'resolvedep': 'resolve', 'help': 'help' } def __init__(self, cli): commands.Command.__init__(self, cli) cmd.Cmd.__init__(self) self.prompt = '> ' @staticmethod def set_argparser(parser): parser.add_argument('script', nargs='?', metavar=_('SCRIPT'), help=_('Script to run in {prog} shell').format( prog=dnf.util.MAIN_PROG_UPPER)) def configure(self): # append to ShellDemandSheet missing demands from # dnf.cli.demand.DemandSheet with their default values. default_demands = self.cli.demands self.cli.demands = ShellDemandSheet() for attr in dir(default_demands): if attr.startswith('__'): continue try: getattr(self.cli.demands, attr) except AttributeError: setattr(self.cli.demands, attr, getattr(default_demands, attr)) def run(self): if self.opts.script: self._run_script(self.opts.script) else: self.cmdloop() def _clean(self): self.base._finalize_base() self.base._transaction = None self.base.fill_sack() def onecmd(self, line): if not line or line == '\n': return if line == 'EOF': line = 'quit' try: s_line = shlex.split(line) except: self._help() return # reset option parser before each command, keep usage information self.cli.optparser.__init__(reset_usage=False) opts = self.cli.optparser.parse_main_args(s_line) # Disable shell recursion. if opts.command == 'shell': return if opts.command in self.MAPPING: getattr(self, '_' + self.MAPPING[opts.command])(s_line[1::]) else: cmd_cls = self.cli.cli_commands.get(opts.command) if cmd_cls is not None: cmd = cmd_cls(self.cli) try: opts = self.cli.optparser.parse_command_args(cmd, s_line) except SystemExit: # argparse.ArgumentParser prints usage information and executes # sys.exit() on problems with parsing command line arguments return try: cmd.cli.demands = copy.deepcopy(self.cli.demands) cmd.configure() cmd.run() except dnf.exceptions.Error as e: logger.error(_("Error:") + " " + ucd(e)) return else: self._help() def _config(self, args=None): def print_or_set(key, val, conf): if val: setattr(conf, key, val) else: try: print('{}: {}'.format(key, getattr(conf, str(key)))) except: logger.warning(_('Unsupported key value.')) if not args or len(args) > 2: self._help('config') return key = args[0] val = args[1] if len(args) == 2 else None period = key.find('.') if period != -1: repo_name = key[:period] key = key[period+1:] repos = self.base.repos.get_matching(repo_name) for repo in repos: print_or_set(key, val, repo) if not repos: logger.warning(_('Could not find repository: %s'), repo_name) else: print_or_set(key, val, self.base.conf) def _help(self, args=None): """Output help information. :param args: the command to output help information about. If *args* is an empty, general help will be output. """ arg = args[0] if isinstance(args, list) and len(args) > 0 else args msg = None if arg: if arg == 'config': msg = _("""{} arg [value] arg: debuglevel, errorlevel, obsoletes, gpgcheck, assumeyes, exclude, repo_id.gpgcheck, repo_id.exclude If no value is given it prints the current value. If value is given it sets that value.""").format(arg) elif arg == 'help': msg = _("""{} [command] print help""").format(arg) elif arg in ['repo', 'repository']: msg = _("""{} arg [option] list: lists repositories and their status. option = [all | id | glob] enable: enable repositories. option = repository id disable: disable repositories. option = repository id""").format(arg) elif arg == 'resolvedep': msg = _("""{} resolve the transaction set""").format(arg) elif arg in ['transaction', 'ts']: msg = _("""{} arg list: lists the contents of the transaction reset: reset (zero-out) the transaction run: run the transaction""").format(arg) elif arg == 'run': msg = _("""{} run the transaction""").format(arg) elif arg in ['exit', 'quit']: msg = _("""{} exit the shell""").format(arg) if not msg: self.cli.optparser.print_help() msg = _("""Shell specific arguments: config set config options help print help repository (or repo) enable, disable or list repositories resolvedep resolve the transaction set transaction (or ts) list, reset or run the transaction set run resolve and run the transaction set exit (or quit) exit the shell""") print('\n' + msg) def _repo(self, args=None): cmd = args[0] if args else None if cmd in ['list', None]: self.onecmd('repolist ' + ' '.join(args[1:])) elif cmd in ['enable', 'disable']: repos = self.cli.base.repos fill_sack = False for repo in args[1::]: r = repos.get_matching(repo) if r: getattr(r, cmd)() fill_sack = True else: logger.critical(_("Error:") + " " + _("Unknown repo: '%s'"), self.base.output.term.bold(repo)) if fill_sack: self.base.fill_sack() # reset base._comps, as it has changed due to changing the repos self.base._comps = None else: self._help('repo') def _resolve(self, args=None): try: self.cli.base.resolve(self.cli.demands.allow_erasing) except dnf.exceptions.DepsolveError as e: print(e) def _run_script(self, file): try: with open(file, 'r') as fd: lines = fd.readlines() for line in lines: if not line.startswith('#'): self.onecmd(line) except IOError: logger.info(_('Error: Cannot open %s for reading'), self.base.output.term.bold(file)) sys.exit(1) def _transaction(self, args=None): cmd = args[0] if args else None if cmd == 'reset': self._clean() return self._resolve() if cmd in ['list', None]: if self.base._transaction: out = self.base.output.list_transaction(self.base._transaction) logger.info(out) elif cmd == 'run': try: self.base.do_transaction() except dnf.exceptions.Error as e: logger.error(_("Error:") + " " + ucd(e)) else: logger.info(_("Complete!")) self._clean() else: self._help('transaction') def _ts_run(self, args=None): self._transaction(['run']) def _quit(self, args=None): logger.info(_('Leaving Shell')) sys.exit(0) commands/makecache.py000064400000003555151030066770010635 0ustar00# makecache.py # Makecache CLI command. # # Copyright (C) 2014-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.cli import commands from dnf.i18n import _ import argparse import dnf.cli import dnf.exceptions import dnf.util import logging logger = logging.getLogger("dnf") class MakeCacheCommand(commands.Command): aliases = ('makecache', 'mc') summary = _('generate the metadata cache') @staticmethod def set_argparser(parser): parser.add_argument('--timer', action='store_true', dest="timer_opt") # compatibility with dnf < 2.0 parser.add_argument('timer', nargs='?', choices=['timer'], metavar='timer', help=argparse.SUPPRESS) def run(self): timer = self.opts.timer is not None or self.opts.timer_opt msg = _("Making cache files for all metadata files.") logger.debug(msg) return self.base.update_cache(timer) commands/__pycache__/install.cpython-36.opt-1.pyc000064400000013703151030066770015621 0ustar003 ft`S@sddlmZddlmZddlZddlmZddlZddlZddl m Z ddl m Z ddl mZejdZGd d d e jZdS) )absolute_import)unicode_literalsN)chain)commands) OptionParser)_dnfc@seZdZdZejejejdZdZ de ej Z e dZedd Zd d Zd d ZddZddZddZddZddZddZddZdS)InstallCommandzUA class containing methods needed by the cli to execute the install command. )z install-nz install-naz install-nevrazalternative-for({})install localinstallinz,install a package or packages on your systemcCs"|jddtdtjtdddS)Npackage+ZPACKAGEzPackage to install)nargsmetavaractionhelp) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/install.py set_argparser1szInstallCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jdS)zVerify that conditions are met so that this command can run. That there are enabled repositories with gpg keys, and that this command is called with appropriate arguments. TN) clidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepo)selfrrrr configure7szInstallCommand.configurec CsPg}g}g}|j}|jj|j|jjdkrf|jjs>|jjrf|j|jj|jj j rft j j tdg}|jjo||jjdkrTt jjrLy,t jjj|j}|j|jj|jj j dWnt j jk rH}zp|jrx|jD]}|j|qW|jrx|jD]}|jd|qW|j} | r8tjt jjj| dWYdd}~XnXn|jj}|jjr|r|j|jj|jj j rt j j tdn|j}|r|r|j||jj j rt j j tdn|r|jjdkr|j||jjdkr|j |}t!|dks$t!|dks$|rL|jj j rLt j j"tddj#||ddS) Nr zNothing to do.)strict@rzUnable to find a match )pkg_specZpackages)$_get_nevra_forms_from_commandrZ _populate_update_security_filterrcommand grp_specs pkg_specs_log_not_valid_rpm_file_pathsrconfrr exceptionsErrorrZ WITH_MODULESmodule module_baseZ ModuleBaser Z MarkingErrorsZno_match_group_specsappendZerror_group_specsmodule_depsolv_errorsloggererrorZformat_modular_solver_errorsr_inform_not_a_valid_combination_install_files_install_groups_install_packageslenZPackagesNotAvailableErrorjoin) rerr_pkgserrsZerror_module_specs nevra_formsZskipped_grp_specsr,eZe_specr.rrrrunEsX            . zInstallCommand.runcCs&|jj|jkr|j|jjgSgSdS)N)rr$r9)rrrrr#zsz,InstallCommand._get_nevra_forms_from_commandcCsJtdd|}x6t|jj|D]$}td}tj||jjj j |qWdS)NcSsd|S)Nr r)grrrsz>InstallCommand._log_not_valid_rpm_file_paths..zNot a valid rpm file path: %s) maprrr&rr/inforoutputtermbold)rr%Z group_namespkgmsgrrrr'sz,InstallCommand._log_not_valid_rpm_file_pathscCs2x,|D]$}td}tj||jjjj|qWdS)NzNot a valid form: %s)rr/Zwarningrr@rArB)rformsZformrDrrrr1s z.InstallCommand._inform_not_a_valid_combinationc Csg}|jjj}x~|jj|jj||jjjdD]^}y|jj||dWq,t j j k rt d}t j||jjjj|j|j|Yq,Xq,W|S)N)rprogress)rzNo match for argument: %s)rr(rZadd_remote_rpmsrrr@rFZpackage_installrr) MarkingErrorrr/r?rArBlocationr-)rr7rrCrDrrrr2s zInstallCommand._install_filesc CsPy&|jj|t|jjj|jjjdWn$tjjk rJ|jjjrFYnXdS)N)r) rZenv_group_installtupler(Zgroup_package_typesrrr)r*)rr%rrrr3s  zInstallCommand._install_groupscCsV|jjjj|jj|d}|rRtd}tj|j|dj t t dd|DdS)N)Zprovidesz/There are following alternatives for "{0}": {1}z, cSsg|] }|jqSr)name).0Zaltrrr sz7InstallCommand._report_alternatives..) rZsackqueryZfiltermalternatives_provideformatrr/r?r6sortedset)rr"rMrDrrr_report_alternativess z#InstallCommand._report_alternativescCsg}|jjj}x|jjD]}y|jj|||dWqtjjk r}zJdj |j |jj j j |}tj||jj||j||j|WYdd}~XqXqW|S)N)rrEz{}: {})rr(rrr&r rr)rGrOvaluer@rArBr/r?Z_report_icase_hintrRr-)rr9r8rr"r:rDrrrr4s     z InstallCommand._install_packagesN)r r r )__name__ __module__ __qualname____doc__hawkeyZ FORM_NAMEZFORM_NAZ FORM_NEVRAr9rNrIkeysaliasesrZsummary staticmethodrrr;r#r'r1r2r3rRr4rrrrr %s"  5  r )Z __future__rrZlogging itertoolsrrXZdnf.exceptionsrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZ getLoggerr/ZCommandr rrrrs       commands/__pycache__/reinstall.cpython-36.opt-1.pyc000064400000005625151030066770016154 0ustar003 ft`]@slddlmZddlmZddlmZddlmZddlmZddl Z ddl Z e j dZ Gdd d ejZdS) )absolute_import)unicode_literals)commands) OptionParser)_Ndnfc@s8eZdZdZd ZedZeddZddZ d d Z d S) ReinstallCommandzSA class containing methods needed by the cli to execute the reinstall command. reinstallreizreinstall a packagecCs"|jddtdtjtdddS)Npackages+zPackage to reinstallZPACKAGE)nargshelpactionmetavar) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/reinstall.py set_argparser(szReinstallCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jdS)a Verify that conditions are met so that this command can run. These include that the program is being run by the root user, that there are enabled repositories with gpg keys, and that this command is called with appropriate arguments. TN) ZclidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepo)selfrrrr configure.szReinstallCommand.configurecCsd}xp|jj|jjd|jjjdD]P}y|jj|Wn6tjj k rlt j t d|jjj j|jYq"Xd}q"WxD|jjdd|jjDD]$}y|jj|Wntjjk r}zPx,|jD]"}t j t d|jj j|jPqWt j t d|jjj j|WYdd}~Xqtjjk r}z^xV|jD]L}d}|jjj|}|rdt d |}t d }t j ||jjj j||qLsz(ReinstallCommand.run..z(Package %s available, but not installed.z (from %s)z%Installed package %s%s not available.z!No packages marked for reinstall.)rZadd_remote_rpmsrroutputrZpackage_reinstallr exceptionsZ MarkingErrorloggerinforZtermZboldlocationZ pkg_specsZ grp_specsr ZPackagesNotInstalledErrorr nameZPackagesNotAvailableErrorhistoryZrepoError)rdoneZpkgZpkg_specerrZxmsgZpkgrepomsgrrrrun=sB $   "  zReinstallCommand.runN)r r ) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrrr.rrrrr!s  r)Z __future__rrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZdnf.exceptionsrZloggingZ getLoggerr%ZCommandrrrrrs      commands/__pycache__/makecache.cpython-36.pyc000064400000002357151030066770015120 0ustar003 ft`m@sxddlmZddlmZddlmZddlmZddlZddlZddl Zddl Zddl Z e j dZ GdddejZdS) )absolute_import)unicode_literals)commands)_Ndnfc@s,eZdZd ZedZeddZddZdS) MakeCacheCommand makecachemczgenerate the metadata cachecCs,|jdddd|jdddgdtjddS)Nz--timer store_true timer_opt)actiondesttimer?)nargschoicesmetavarhelp) add_argumentargparseZSUPPRESS)parserr/usr/lib/python3.6/makecache.py set_argparser's zMakeCacheCommand.set_argparsercCs2|jjdk p|jj}td}tj||jj|S)Nz*Making cache files for all metadata files.)Zoptsrr rloggerdebugbaseZ update_cache)selfrmsgrrrrun.s zMakeCacheCommand.runN)rr ) __name__ __module__ __qualname__aliasesrZsummary staticmethodrrrrrrr#s r)Z __future__rrZdnf.clirZdnf.i18nrrrZdnf.exceptionsZdnf.utilZloggingZ getLoggerrZCommandrrrrrs     commands/__pycache__/shell.cpython-36.pyc000064400000017277151030066770014335 0ustar003 ft`l&@sddlmZddlmZmZddlZddlZddlZddlZddl Z ddl Z ddl Z e j dZ GdddeZGdddejejZdS) )commands)_ucdNdnfc@seZdZdZdZdZdZdS)ShellDemandSheetTN)__name__ __module__ __qualname__Zavailable_reposZ resolvingZ root_userZsack_activationr r /usr/lib/python3.6/shell.pyr%src @seZdZd*ZedjejjdZ dddddddd d d d Z d dZ e ddZ ddZddZddZddZd+ddZd,ddZd-ddZd.d d!Zd"d#Zd/d$d%Zd0d&d'Zd1d(d)ZdS)2 ShellCommandshellshzrun an interactive {prog} shell)progrepoquitZts_run transactionconfigresolvehelp) r repositoryexitrruntsrr resolvedeprcCs$tjj||tjj|d|_dS)Nz> )rCommand__init__cmdCmdprompt)selfclir r r r=s zShellCommand.__init__cCs*|jddtdtdjtjjdddS)Nscript?ZSCRIPTzScript to run in {prog} shell)r)nargsmetavarr) add_argumentrformatrutilMAIN_PROG_UPPER)parserr r r set_argparserBszShellCommand.set_argparserc Csr|jj}t|j_xZt|D]N}|jdr,qyt|jj|Wqtk rht|jj|t||YqXqWdS)N__)r!demandsrdir startswithgetattrAttributeErrorsetattr)r Zdefault_demandsattrr r r configureHs  zShellCommand.configurecCs$|jjr|j|jjn|jdS)N)optsr" _run_scriptZcmdloop)r r r r rUszShellCommand.runcCs |jjd|j_|jjdS)N)baseZ_finalize_base _transaction fill_sack)r r r r _clean[s zShellCommand._cleancCs`| s|dkrdS|dkrd}ytj|}Wn|jdS|jjjdd|jjj|}|jdkrldS|j|jkrt |d|j|j|ddn|jj j |j}|dk rT||j}y|jjj ||}Wnt k rdSXy&tj|jj|j_|j|jWn@tjjk rP}ztjtd d t|dSd}~XnXn|jdS) N ZEOFrF)Z reset_usager rzError: )shlexsplit_helpr! optparserrZparse_main_argsZcommandMAPPINGr0Z cli_commandsgetZparse_command_args SystemExitcopydeepcopyr-r4rr exceptionsErrorloggererrorrr)r lineZs_liner5Zcmd_clsrer r r onecmd`s<  $   zShellCommand.onecmdNc Csdd}| st|dkr(|jddS|d}t|dkrD|dnd}|jd}|d kr|d|}||dd}|jjj|}x|D]}||||qW|stjtd|n||||jj dS) Nc SsP|rt|||n:ytdj|t|t|WntjtdYnXdS)Nz{}: {}zUnsupported key value.)r2printr'r0strrIwarningr)keyvalconfr r r print_or_sets z*ShellCommand._config..print_or_setrrr<.zCould not find repository: %s) lenr@findr7repos get_matchingrIrPrrS) r argsrTrQrRZperiodZ repo_namerZrr r r _configs"      zShellCommand._configcCst|trt|dkr|dn|}d}|r|dkrBtdj|}n|dkrZtdj|}nv|dkrrtd j|}n^|d krtd j|}nF|dkrtdj|}n.|dkrtdj|}n|dkrtdj|}|s|jjjtd}td|dS)zOutput help information. :param args: the command to output help information about. If *args* is an empty, general help will be output. rNrz{} arg [value] arg: debuglevel, errorlevel, obsoletes, gpgcheck, assumeyes, exclude, repo_id.gpgcheck, repo_id.exclude If no value is given it prints the current value. If value is given it sets that value.rz{} [command] print helprrz{} arg [option] list: lists repositories and their status. option = [all | id | glob] enable: enable repositories. option = repository id disable: disable repositories. option = repository idrz"{} resolve the transaction setrrzy{} arg list: lists the contents of the transaction reset: reset (zero-out) the transaction run: run the transactionrz{} run the transactionrrz{} exit the shellaShell specific arguments: config set config options help print help repository (or repo) enable, disable or list repositories resolvedep resolve the transaction set transaction (or ts) list, reset or run the transaction set run resolve and run the transaction set exit (or quit) exit the shellr;)rr)rr)rr) isinstancelistrXrr'r!rAZ print_helprN)r r\argmsgr r r r@s:"  zShellCommand._helpcCs|r |dnd}|d kr6|jddj|ddn|dkr|jjj}d}x\|ddD]L}|j|}|r~t||d }qZtjt d dt d |jj j j |qZW|r|jj d|j_n |jd dS)Nrr_z repolist r=r<enabledisableFTzError:zUnknown repo: '%s'r)r_N)rbrc)rMjoinr!r7rZr[r0rIZcriticalroutputtermboldr9Z_compsr@)r r\rrZr9rrr r r _repos"     zShellCommand._repocCsLy|jjj|jjjWn.tjjk rF}zt|WYdd}~XnXdS)N) r!r7rr-Z allow_erasingrrGZ DepsolveErrorrN)r r\rLr r r _resolveszShellCommand._resolvecCsyDt|d0}|j}x |D]}|jds|j|qWWdQRXWn:tk r~tjtd|jj j j |t j dYnXdS)Nrh#z!Error: Cannot open %s for readingr<)open readlinesr/rMIOErrorrIinforr7rerfrgsysr)r filefdlinesrKr r r r6s   zShellCommand._run_scriptcCs|r |dnd}|dkr$|jdS|j|d krZ|jjr|jjj|jj}tj|nz|dkry|jjWn@t j j k r}z tj t ddt|WYdd}~XnXtjt d|jn |jddS) Nrresetr_rzError:r=z Complete!r)r_N)r:rjr7r8reZlist_transactionrIroZdo_transactionrrGrHrJrrr@)r r\routrLr r r r8 s" , zShellCommand._transactioncCs|jdgdS)Nr)r8)r r\r r r _ts_run"szShellCommand._ts_runcCstjtdtjddS)Nz Leaving Shellr)rIrorrpr)r r\r r r _quit%szShellCommand._quit)r r)N)N)N)N)N)N)N)rrr aliasesrr'rr(r)ZsummaryrBr staticmethodr+r4rr:rMr]r@rirjr6r8rvrwr r r r r ,s4  &  ;    r )Zdnf.clirZdnf.i18nrrZdnf.utilrrrEZloggingr>rpZ getLoggerrIobjectrrrr r r r r s  commands/__pycache__/history.cpython-36.pyc000064400000026342151030066770014720 0ustar003 g%F@sddlmZddlmZddlmZddlZddlZddlmZmZddl m Z ddl m Z m Z ddl ZddlZddlZddlZddlZddlZddlZejdZGd d d e jZdS) )absolute_import)print_function)unicode_literalsN)_ucd)commands)TransactionReplayserialize_transactiondnfcseZdZdZd+ZedZddddd d d d gZfd dZe ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*ZZS),HistoryCommandzUA class containing methods needed by the cli to execute the history command. historyhistz(display, or use, the transaction historylistinforedoreplayrollbackstoreundo userinstalledcstt|j||d|_dS)NF)superr __init___require_one_transaction_id)selfargskw) __class__/usr/lib/python3.6/history.pyr4szHistoryCommand.__init__c Cs|jddddjtjddjtjddd|jd d d d |jd ddtdd|jdd tdd |jdd tdd |jdd tdd |jddddd|jddddddS)Ntransactions_action?ZCOMMANDz$Available commands: {} (default), {}rz, )nargsmetavarhelpz --reverse store_truez$display history list output reversed)actionr$z-oz--outputz, 'last' or 'last-' for one transaction, .. for a range)transaction_filenameZTRANSACTION_FILEzEFor the replay command, path to the stored transaction file to replay) add_argumentformatr _CMDSjoinr)parserrrr set_argparser9s$        zHistoryCommand.set_argparsercCs.|jjs|jd|j_n0|jj|jkrH|jjjd|jj|jd|j_tdj|jj|_|jj }|jjdkr|jjst jj tdt |jjdkrt jj tdt jj|jjd|j_g|j_d|_d|_d|_d|jj_d|jj_t jjj|j|jn|jjd kr6d|_|jjst jj td n|jjdkrd|_d|_d|_d|_|jjstd }tj|t jj |n,t |jjdkrtj|jt jj |jd|_t jjj|j|jnd|_d|_|jjjdkr*t j |jjjt j! r*td|jjj}tj|t jj |dS)NrzUFound more than one transaction ID. '{}' requires one transaction ID or package name.rzNo transaction file name given.r!z6More than one argument given as transaction file name.TFrz(No transaction ID or package name given.rrrz:memory:z+You don't have access to the history DB: %s)rrr)"optsrr-r(insertrr,_require_one_transaction_id_msgclidemandsr CliErrorlenospathabspathr*Zavailable_reposZ resolvingZ root_userbaseconfZclean_requirements_on_removeZinstall_weak_depsrZ _checkGPGKeyrloggercriticalZfresh_metadataZsack_activationr accessR_OK)rr5msgrrr configureUsZ       ( zHistoryCommand.configurecCst|tjjrv|jjdkr2|jj\}td|fS|jjdkrv|jjddkrV|jjn|jjdd\}td|fStjj j j ||S) z.Get suggestions for resolving the given error.rzVCannot undo transaction %s, doing so would result in an inconsistent package database.rrforcer!NzZCannot rollback transaction %s, doing so would result in an inconsistent package database.) isinstancer exceptionsZTransactionCheckErrorr1rr(rr4rCommandget_error_output)rerrorZid_rrrrGs   zHistoryCommand.get_error_outputcCs:|j|}t|}t|j|dd|jjd|_|jjdS)NT)dataignore_installed ignore_extrasskip_unavailable)_history_get_transactionr rr;r1rLrrun)rextcmdsoldrIrrr _hcmd_redos zHistoryCommand._hcmd_redocCsD|stjjtd|jjj|}|s@tjjtdj|d|S)NzNo transaction ID givenzTransaction ID "{0}" not found.r)r r4r6rr;r rPr,)rrOrPrrr_history_get_transactionss z(HistoryCommand._history_get_transactionscCs.|j|}t|dkr&tjjtd|dS)Nr!z#Found more than one transaction ID!r)rRr7r r4r6r)rrOrPrrrrMs  z'HistoryCommand._history_get_transactioncCs|j|}|j|dS)N)rM_revert_transaction)rrOrPrrr _hcmd_undos zHistoryCommand._hcmd_undocCs|j|}|jjj}d}|j|jkrx|jjjtt|jd|jdD]X}|jrjt j t d|jn|j rt j t d|j|dkrt jjj|}qL|j|qLW|j|dS)Nr!z-Transaction history is incomplete, before %u.z,Transaction history is incomplete, after %u.)rMr;r lasttidrPrrangeZaltered_lt_rpmdbr=ZwarningrZaltered_gt_rpmdbr ZdbZMergedTransactionWrappermergerS)rrOrPrUZ merged_transtransrrr_hcmd_rollbacks   *zHistoryCommand._hcmd_rollbackc Cs&dddddddddd d d }t|}xdD]}x|j|gD]}||d|d<|ddkrt|jdddkrtd|d<|dd krd|krtj|d}|jtjgdd}|jjjj |j |j |j dd}t jj||d<|jdtjkr.str2transaction_idz..zWInvalid transaction ID range definition '{}'. Use '..'.zNCan't convert '{}' to transaction ID. Use '', 'last', 'last-'.r!z8No transaction which manipulates package '{}' was found.T)reverse)setr1r(split ValueErrorr=r>rr,r r4r6rr3addupdaterWrkr searchrsorted) rrvrm merged_tidstZbegin_transaction_idZend_transaction_idZcant_convert_msgZtransact_ids_from_pkgnamerAr)rr_args2transaction_ids sV          z$HistoryCommand._args2transaction_idsc Cs@|jj}|dkrDt|j|jj|jj|jj|jjd|_|jj n|j \}}|dkr~|sf|jj r~|j j ||jjdn|dkr|s|jj r|j j||jj |n|dkr|j|nz|dkr|j|nd|dkr|j|nN|d kr|jn8|d kr<|j|}t|}y|jj dk r8|jj nd }|jjjsV|jjj rtjj|rtd j|}|jjjs|jj jd j|dj|d rttdj|dSt |d"}t!j"||ddd|j#dWdQRXttdj|Wn>t$k r:} z t%j&j'tdjt(| WYdd} ~ XnXdS)Nr)filenamerJrKrLr)rxrrrrrrztransaction.jsonz{} exists, overwrite?z {} [y/N]: z {} [Y/n]: )rAZdefaultyes_msgzNot overwriting {}, exiting.wrrT)indentZ sort_keys zTransaction saved to {}.zError storing transaction: {}))r1rrr;r*rJrKrLrrNrr(rkZhistoryListCmdrxZhistoryInfoCmdrTrQrZrprMr r<ZassumenoZ assumeyesr8r9isfilerr,Z userconfirmprintopenjsondumpwriteOSErrorr r4r6str) rZvcmdrmrrVrIrrAferrrrNMsN     ( zHistoryCommand.runcCs|jjdkrdS|jjdS)Nrrrr)rrrr)r1rrZpost_transaction)rrrr run_resolveds zHistoryCommand.run_resolvedcCsX|jjdkrdS|jj}|rTtjtjjt dx |D]}tjtjjd|q8WdS)NrrrrzEWarning, the following problems occurred while running a transaction:z )rrrr) r1rrZ get_warningsr=logr loggingZWARNINGr)rwarningsrrrrrun_transactions    zHistoryCommand.run_transaction)r r )__name__ __module__ __qualname____doc__aliasesrZsummaryr-r staticmethodr0rBrGrQrRrMrTrZrSrprrNrr __classcell__rr)rrr *s&  =  0@2r )Z __future__rrrrnrjZdnf.i18nrrZdnf.clirZdnf.transaction_srrr r Zdnf.exceptionsZdnf.transactionZdnf.utilrrr8Z getLoggerr=rFr rrrrs     commands/__pycache__/autoremove.cpython-36.opt-1.pyc000064400000003572151030066770016344 0ustar003 ft` @stddlmZddlmZddlmZddlmZddlmZddl Z ddl Z ddl Z e j dZGdd d ejZdS) )absolute_import)unicode_literals)commands) OptionParser)_Ndnfc@sReZdZejejejdZd eej Z e dZ e ddZddZdd Zd S) AutoremoveCommand)z autoremove-nz autoremove-nazautoremove-nevra autoremovezKremove all unneeded packages that were originally installed as dependenciescCs"|jddtdtjtdddS)NZpackages*zPackage to removeZPACKAGE)nargshelpactionmetavar) add_argumentrrZParseSpecGroupFileCallback)parserr /usr/lib/python3.6/autoremove.py set_argparser,szAutoremoveCommand.set_argparsercCs\|jj}d|_d|_d|_t|jj|jj|jj grLd|j j _ d|_ d|_n d|_d|_dS)NTF)ZclidemandsZ resolvingZ root_userZsack_activationanyopts grp_specs pkg_specs filenamesbaseZconfZclean_requirements_on_removeZ allow_erasingZavailable_reposZfresh_metadata)selfrrrr configure2s zAutoremoveCommand.configurecCsjt|jj|jj|jjgr\g}|jj|jkr<|j|jjg}|jj||jj|jj|jjn |jjdS)N) rrrrrZcommand nevra_formsrr )rZformsrrrrunBs zAutoremoveCommand.runN)r )__name__ __module__ __qualname__hawkeyZ FORM_NAMEZFORM_NAZ FORM_NEVRArtuplekeysaliasesrZsummary staticmethodrrrrrrrr"s  r)Z __future__rrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZdnf.exceptionsrr"ZloggingZ getLoggerZloggerZCommandrrrrrs      commands/__pycache__/deplist.cpython-36.pyc000064400000001571151030066770014660 0ustar003 ft`@sPddlmZddlmZddlmZddlmZddlmZGdddeZdS) )print_function)absolute_import)unicode_literals)_)RepoQueryCommandc@s$eZdZdZdZedZddZdS)DeplistCommandz< The command is alias for 'dnf repoquery --deplist' deplistz`[deprecated, use repoquery --deplist] List package's dependencies and what packages provide themcCstj|d|j_dS)NT)r configureZoptsr)selfr /usr/lib/python3.6/deplist.pyr "s zDeplistCommand.configureN)r)__name__ __module__ __qualname____doc__aliasesrZsummaryr r r r r rsrN) Z __future__rrrZdnf.i18nrZdnf.cli.commands.repoqueryrrr r r r s     commands/__pycache__/remove.cpython-36.pyc000064400000007521151030066770014512 0ustar003 ft`@sddlmZddlmZddlmZddlmZddlmZddl Z ddl Z ddl Z ddl Z ddlZejdZGdd d ejZdS) )absolute_import)unicode_literals)commands)_) OptionParserNdnfc@sbeZdZdZejejejejejejdZde ej Z e dZ eddZd d Zd d Zd S) RemoveCommandzRemove command.)zremove-nz remove-naz remove-nevrazerase-nzerase-naz erase-nevraremoveerasermz-remove a package or packages from your systemcCsf|j}|jdddtdd|jddtjd|jddtd d|jd d td tjtd ddS)Nz --duplicates store_true duplicatedzremove duplicated packages)actiondesthelpz --duplicated)rrz--oldinstallonlyz*remove installonly packages over the limitZpackages*zPackage to removeZPACKAGE)nargsrrmetavar)Zadd_mutually_exclusive_group add_argumentrargparseZSUPPRESSrZParseSpecGroupFileCallback)parserZmgroupr/usr/lib/python3.6/remove.py set_argparser0s   zRemoveCommand.set_argparsercCs^|jj}d|_d|_d|_|jjr*d|_n0tj j rN|jj rNd|_d|_ d|_ n d|_ d|_dS)NTF)ZclidemandsZ resolvingZ root_userZsack_activationoptsr Zavailable_reposrbase WITH_MODULES grp_specsZfresh_metadataZ allow_erasing)selfrrrr configure?szRemoveCommand.configurecCs\g}|jj|jkr"|j|jjg}|jj|jj7_d}|jjrD|jjj}|jj |j }|jj |}|st j jtdx|jjD]\\}}}t|dkrq|jddy|jjt|dWnHt j jk rd} td} tj| |jjjjt|d| YnXx"|d dD]} |jj| q&WqWdS|jjr|jjj}|jj |j jd}|jjj} | dk r|j | j!| j"| j#d } | r|j | }|rx,|D]} |jj| qWnt j jtd dS|jj$r*|r*x|jj$D]&}td } tj| |jjjj|qWn|jj$rt jj%rxt j&j'j(|j}|j)|jj$}t|jj$t|krd}n|jj$}|rxB|D]:}y|jj*|grd}Wnt j jk rYnXqWxx|jjD]l}y|jj)||d WnLt j j+k r8}z*dj,|j-|jjjj|} tj.| WYdd}~XnXd}qW|sXtjtddS)NFz)No duplicated packages found for removal.T)reverserz%Installed package %s%s not available.)epochversionreleasez.No old installonly packages found for removal.zNot a valid form: %s)formsz{}: {}zNo packages marked for removal.)/rZcommand nevra_formsZ pkg_specs filenamesr rZsackZqueryZ_get_installonly_queryZ installed differencer exceptionsErrorrZ_na_dictitemslensortZ reinstallstrZPackagesNotAvailableErrorloggerZwarningoutputZtermZboldZpackage_removeZoldinstallonlyZlatestZget_running_kernelfilterr%r&r'rrmodule module_baseZ ModuleBaser Zenv_group_removeZ MarkingErrorformatvalueinfo)rr(doneqZinstonlyZdupsnameZarchZ pkgs_listZxmsgmsgZpkgZkernelZrunning_installonlyZgrp_specr7Z skipped_grpsgroupZpkg_specerrrrunPs    (             zRemoveCommand.runN)r r r )__name__ __module__ __qualname____doc__hawkeyZ FORM_NAMEZFORM_NAZ FORM_NEVRAr*tuplekeysaliasesrZsummary staticmethodrr rArrrrr#s  r)Z __future__rrZdnf.clirZdnf.i18nrZdnf.cli.option_parserrZdnf.baserrrFZdnf.exceptionsZloggingZ getLoggerr3ZCommandrrrrrs      commands/__pycache__/history.cpython-36.opt-1.pyc000064400000026342151030066770015657 0ustar003 g%F@sddlmZddlmZddlmZddlZddlZddlmZmZddl m Z ddl m Z m Z ddl ZddlZddlZddlZddlZddlZddlZejdZGd d d e jZdS) )absolute_import)print_function)unicode_literalsN)_ucd)commands)TransactionReplayserialize_transactiondnfcseZdZdZd+ZedZddddd d d d gZfd dZe ddZ ddZ ddZ ddZ ddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*ZZS),HistoryCommandzUA class containing methods needed by the cli to execute the history command. historyhistz(display, or use, the transaction historylistinforedoreplayrollbackstoreundo userinstalledcstt|j||d|_dS)NF)superr __init___require_one_transaction_id)selfargskw) __class__/usr/lib/python3.6/history.pyr4szHistoryCommand.__init__c Cs|jddddjtjddjtjddd|jd d d d |jd ddtdd|jdd tdd |jdd tdd |jdd tdd |jddddd|jddddddS)Ntransactions_action?ZCOMMANDz$Available commands: {} (default), {}rz, )nargsmetavarhelpz --reverse store_truez$display history list output reversed)actionr$z-oz--outputz, 'last' or 'last-' for one transaction, .. for a range)transaction_filenameZTRANSACTION_FILEzEFor the replay command, path to the stored transaction file to replay) add_argumentformatr _CMDSjoinr)parserrrr set_argparser9s$        zHistoryCommand.set_argparsercCs.|jjs|jd|j_n0|jj|jkrH|jjjd|jj|jd|j_tdj|jj|_|jj }|jjdkr|jjst jj tdt |jjdkrt jj tdt jj|jjd|j_g|j_d|_d|_d|_d|jj_d|jj_t jjj|j|jn|jjd kr6d|_|jjst jj td n|jjdkrd|_d|_d|_d|_|jjstd }tj|t jj |n,t |jjdkrtj|jt jj |jd|_t jjj|j|jnd|_d|_|jjjdkr*t j |jjjt j! r*td|jjj}tj|t jj |dS)NrzUFound more than one transaction ID. '{}' requires one transaction ID or package name.rzNo transaction file name given.r!z6More than one argument given as transaction file name.TFrz(No transaction ID or package name given.rrrz:memory:z+You don't have access to the history DB: %s)rrr)"optsrr-r(insertrr,_require_one_transaction_id_msgclidemandsr CliErrorlenospathabspathr*Zavailable_reposZ resolvingZ root_userbaseconfZclean_requirements_on_removeZinstall_weak_depsrZ _checkGPGKeyrloggercriticalZfresh_metadataZsack_activationr accessR_OK)rr5msgrrr configureUsZ       ( zHistoryCommand.configurecCst|tjjrv|jjdkr2|jj\}td|fS|jjdkrv|jjddkrV|jjn|jjdd\}td|fStjj j j ||S) z.Get suggestions for resolving the given error.rzVCannot undo transaction %s, doing so would result in an inconsistent package database.rrforcer!NzZCannot rollback transaction %s, doing so would result in an inconsistent package database.) isinstancer exceptionsZTransactionCheckErrorr1rr(rr4rCommandget_error_output)rerrorZid_rrrrGs   zHistoryCommand.get_error_outputcCs:|j|}t|}t|j|dd|jjd|_|jjdS)NT)dataignore_installed ignore_extrasskip_unavailable)_history_get_transactionr rr;r1rLrrun)rextcmdsoldrIrrr _hcmd_redos zHistoryCommand._hcmd_redocCsD|stjjtd|jjj|}|s@tjjtdj|d|S)NzNo transaction ID givenzTransaction ID "{0}" not found.r)r r4r6rr;r rPr,)rrOrPrrr_history_get_transactionss z(HistoryCommand._history_get_transactionscCs.|j|}t|dkr&tjjtd|dS)Nr!z#Found more than one transaction ID!r)rRr7r r4r6r)rrOrPrrrrMs  z'HistoryCommand._history_get_transactioncCs|j|}|j|dS)N)rM_revert_transaction)rrOrPrrr _hcmd_undos zHistoryCommand._hcmd_undocCs|j|}|jjj}d}|j|jkrx|jjjtt|jd|jdD]X}|jrjt j t d|jn|j rt j t d|j|dkrt jjj|}qL|j|qLW|j|dS)Nr!z-Transaction history is incomplete, before %u.z,Transaction history is incomplete, after %u.)rMr;r lasttidrPrrangeZaltered_lt_rpmdbr=ZwarningrZaltered_gt_rpmdbr ZdbZMergedTransactionWrappermergerS)rrOrPrUZ merged_transtransrrr_hcmd_rollbacks   *zHistoryCommand._hcmd_rollbackc Cs&dddddddddd d d }t|}xdD]}x|j|gD]}||d|d<|ddkrt|jdddkrtd|d<|dd krd|krtj|d}|jtjgdd}|jjjj |j |j |j dd}t jj||d<|jdtjkr.str2transaction_idz..zWInvalid transaction ID range definition '{}'. Use '..'.zNCan't convert '{}' to transaction ID. Use '', 'last', 'last-'.r!z8No transaction which manipulates package '{}' was found.T)reverse)setr1r(split ValueErrorr=r>rr,r r4r6rr3addupdaterWrkr searchrsorted) rrvrm merged_tidstZbegin_transaction_idZend_transaction_idZcant_convert_msgZtransact_ids_from_pkgnamerAr)rr_args2transaction_ids sV          z$HistoryCommand._args2transaction_idsc Cs@|jj}|dkrDt|j|jj|jj|jj|jjd|_|jj n|j \}}|dkr~|sf|jj r~|j j ||jjdn|dkr|s|jj r|j j||jj |n|dkr|j|nz|dkr|j|nd|dkr|j|nN|d kr|jn8|d kr<|j|}t|}y|jj dk r8|jj nd }|jjjsV|jjj rtjj|rtd j|}|jjjs|jj jd j|dj|d rttdj|dSt |d"}t!j"||ddd|j#dWdQRXttdj|Wn>t$k r:} z t%j&j'tdjt(| WYdd} ~ XnXdS)Nr)filenamerJrKrLr)rxrrrrrrztransaction.jsonz{} exists, overwrite?z {} [y/N]: z {} [Y/n]: )rAZdefaultyes_msgzNot overwriting {}, exiting.wrrT)indentZ sort_keys zTransaction saved to {}.zError storing transaction: {}))r1rrr;r*rJrKrLrrNrr(rkZhistoryListCmdrxZhistoryInfoCmdrTrQrZrprMr r<ZassumenoZ assumeyesr8r9isfilerr,Z userconfirmprintopenjsondumpwriteOSErrorr r4r6str) rZvcmdrmrrVrIrrAferrrrNMsN     ( zHistoryCommand.runcCs|jjdkrdS|jjdS)Nrrrr)rrrr)r1rrZpost_transaction)rrrr run_resolveds zHistoryCommand.run_resolvedcCsX|jjdkrdS|jj}|rTtjtjjt dx |D]}tjtjjd|q8WdS)NrrrrzEWarning, the following problems occurred while running a transaction:z )rrrr) r1rrZ get_warningsr=logr loggingZWARNINGr)rwarningsrrrrrun_transactions    zHistoryCommand.run_transaction)r r )__name__ __module__ __qualname____doc__aliasesrZsummaryr-r staticmethodr0rBrGrQrRrMrTrZrSrprrNrr __classcell__rr)rrr *s&  =  0@2r )Z __future__rrrrnrjZdnf.i18nrrZdnf.clirZdnf.transaction_srrr r Zdnf.exceptionsZdnf.transactionZdnf.utilrrr8Z getLoggerr=rFr rrrrs     commands/__pycache__/deplist.cpython-36.opt-1.pyc000064400000001571151030066770015617 0ustar003 ft`@sPddlmZddlmZddlmZddlmZddlmZGdddeZdS) )print_function)absolute_import)unicode_literals)_)RepoQueryCommandc@s$eZdZdZdZedZddZdS)DeplistCommandz< The command is alias for 'dnf repoquery --deplist' deplistz`[deprecated, use repoquery --deplist] List package's dependencies and what packages provide themcCstj|d|j_dS)NT)r configureZoptsr)selfr /usr/lib/python3.6/deplist.pyr "s zDeplistCommand.configureN)r)__name__ __module__ __qualname____doc__aliasesrZsummaryr r r r r rsrN) Z __future__rrrZdnf.i18nrZdnf.cli.commands.repoqueryrrr r r r s     commands/__pycache__/distrosync.cpython-36.pyc000064400000002640151030066770015413 0ustar003 ft`@s:ddlmZddlmZddlmZGdddejZdS))absolute_import)commands)_c@s8eZdZdZdZedZeddZd d Z d d Z d S)DistroSyncCommandzZA class containing methods needed by the cli to execute the distro-synch command. distro-sync distrosyncdistribution-synchronizationdsyncz?synchronize installed packages to the latest available versionscCs|jddtdddS)Npackage*zPackage to synchronize)nargshelp) add_argumentr)parserr /usr/lib/python3.6/distrosync.py set_argparser"szDistroSyncCommand.set_argparsercCsF|jj}d|_d|_d|_d|_tj|j|jtj |j|j j dS)NT) ZclidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseZ_checkEnabledRepooptsr )selfrrrr configure&szDistroSyncCommand.configurecCs|jj|jjS)N)rZdistro_sync_userlistrr )rrrrrun/szDistroSyncCommand.runN)rrrr ) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrrrrrrrrs   rN)Z __future__rZdnf.clirZdnf.i18nrZCommandrrrrrs   commands/__pycache__/__init__.cpython-36.pyc000064400000064016151030066770014756 0ustar003 ft`{}@sdZddlmZddlmZddlmZddlmZddlZ ddl Z ddl Z ddl Z ddl Z ddlZe jdZedd Zed d Zed Zd dZffddZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZdS)z< Classes for subcommands of the yum command line interface. )print_function)unicode_literals) OptionParser)_Ndnfz+To diagnose the problem, try running: '%s'.zrpm -Va --nofiles --nodigestzDYou probably have corrupted RPMDB, running '%s' might fix the issue.zrpm --rebuilddba You have enabled checking of packages via GPG keys. This is a good thing. However, you do not have any GPG public keys installed. You need to download the keys for packages you wish to install and install them. You can do that by running the command: rpm --import public.gpg.key Alternatively you can specify the url to the key you would like to use for a repository in the 'gpgkey' option in a repository section and {prog} will install it for you. For more information contact your distribution or package provider.cCsp|jjs dS|jslxV|jjD]H}|js0|jr |j r tjdt j t j j dtjtd|t jjq WdS)zVerify that there are gpg keys for the enabled repositories in the rpm database. :param base: a :class:`dnf.Base` object. :raises: :class:`cli.CliError` Nz %s )progzProblem repository: %s)confZgpgcheckZ_gpg_key_checkreposZ iter_enabledZ repo_gpgcheckZgpgkeyloggerZcriticalgpg_msgformatrutilMAIN_PROG_UPPERrcliCliError)baserrepor/usr/lib/python3.6/__init__.py _checkGPGKey:srcCs||jjrdSxD|D]<}|jdr2tjj|r2dStjjj|d}|d krdSqWt dj d j |j j }tjj|dS) zVerify that there is at least one enabled repo. :param base: a :class:`dnf.Base` object. :param possible_local_files: the list of strings that could be a local rpms :raises: :class:`cli.CliError`: Nz.rpmrhttpftpfilehttpsz*There are no enabled repositories in "{}".z", ")rrrr)r Z _any_enabledendswithospathexistsrZpycompZurlparserr joinrZreposdirrr)rZpossible_local_filesZlfileschememsgrrr_checkEnabledRepoKs  r!c@seZdZdZgZdZdZddZeddZ edd Z ed d Z d d Z ddZ ddZddZddZddZddZdS)Commandz%Abstract base class for CLI commands.NcCs ||_dS)N)r)selfrrrr__init__fszCommand.__init__cCs|jjS)N)rr)r$rrrrjsz Command.basecCs |jdS)Nr)aliases)r$rrr_basecmdoszCommand._basecmdcCs |jjjS)N)rroutput)r$rrrr(sszCommand.outputcCsdS)z4Define command specific options and arguments. #:apiNr)r$parserrrr set_argparserwszCommand.set_argparsercCsdS)z*Do any command-specific pre-configuration.Nr)r$rrr pre_configure{szCommand.pre_configurecCsdS)z&Do any command-specific configuration.Nr)r$rrr configureszCommand.configurecCs&t|tjjrttfStd|dS)z.Get suggestions for resolving the given error.zerror not supported yet: %sN) isinstancer exceptionsZTransactionCheckError _RPM_VERIFY_RPM_REBUILDDBNotImplementedError)r$errorrrrget_error_outputszCommand.get_error_outputcCsdS)zExecute the command.Nr)r$rrrrunsz Command.runcCsdS)z$Finalize operation after resolvementNr)r$rrr run_resolvedszCommand.run_resolvedcCsdS)z%Finalize operations post-transaction.Nr)r$rrrrun_transactionszCommand.run_transaction)__name__ __module__ __qualname____doc__r&summaryoptsr%propertyrr'r(r*r+r,r3r4r5r6rrrrr"_s   r"c @sReZdZdZdZedZdZddddd d d d eh Ze d dZ ddZ ddZ dS) InfoCommandzRA class containing methods needed by the cli to execute the info command. infoz4display details about a package or group of packagesall available installedextrasupdatesupgrades autoremoverecent obsoletesc Cs|j}|jdddddtdd|jddddtd d |jd ddd td d |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddtd|j|jtjtdddS) Nz--all_packages_action store_constr@zshow all packages (default))destactionconstdefaulthelpz --availablerAzshow only available packages)rKrLrMrOz --installedrBzshow only installed packagesz--extrasrCzshow only extras packagesz --updatesrEzshow only upgrades packagesz --upgradesz --autoremoverFzshow only autoremove packagesz--recentrGz#show only recently changed packagespackages*PACKAGEzPackage name specification)nargsmetavarchoicesrNrLrO)add_mutually_exclusive_group add_argumentr pkgnarrowsDEFAULT_PKGNARROWrPkgNarrowCallback)clsr)narrowsrrrr*s:        zInfoCommand.set_argparsercCs||jj}d|_|jjr"|jj|j_|jjdkr4d|_|jjrd|jjr\|jjdd|jjnd|j_|jjdkrxd|j_dS)NTrBz --obsoletesz--rHrDrE) rdemandssack_activationr<rIpackages_actionavailable_reposrH_option_conflict)r$r]rrrr,s   zInfoCommand.configurecCs&|jj|j|jjd|jj|jjS)Nr?)r _populate_update_security_filterr<routput_packagesr_rP)r$rrrr4szInfoCommand.runN)r?) r7r8r9r:r&rr;rYrX classmethodr*r,r4rrrrr>s   r>c@s$eZdZdZdZedZddZdS) ListCommandzRA class containing methods needed by the cli to execute the list command. listlsz$list a package or groups of packagescCs&|jj|j|jjd|jj|jjS)Nrf)rrbr<rrcr_rP)r$rrrr4szListCommand.runN)rfrg)r7r8r9r:r&rr;r4rrrrresrec@s8eZdZdZd ZedZeddZdd Z d d Z d S)ProvidesCommandzVA class containing methods needed by the cli to execute the provides command. provides whatprovidesprovz*find what package provides the given valuecCs|jddtdtdddS)N dependency+ZPROVIDEz#Provide specification to search for)rSrTrO)rWr)r)rrrr*szProvidesCommand.set_argparsercCs|jj}d|_d|_d|_dS)NTF)rr]r`Zfresh_metadatar^)r$r]rrrr,szProvidesCommand.configurecCstjtd|jj|jjS)NzSearching Packages: )r debugrrrir<rl)r$rrrr4szProvidesCommand.runN)rirjrk) r7r8r9r:r&rr; staticmethodr*r,r4rrrrrhs  rhc@s8eZdZdZd ZedZeddZddZ d d Z d S) CheckUpdateCommandzZA class containing methods needed by the cli to execute the check-update command. check-update check-upgradez$check for available package upgradescCs0|jddddtdd|jddtd d dS) Nz --changelogs changelogsF store_truezshow changelogs before update)rKrNrLrOrPrQrR)rSrT)rWr)r)rrrr*s z CheckUpdateCommand.set_argparsercCs6|jj}d|_d|_d|_|jjr(d|_t|jdS)NT) rr]r^r`Zplugin_filtering_enabledr<rsr!r)r$r]rrrr, szCheckUpdateCommand.configurecCsR|jj|jdd|jj|jjd|jjd}|r:d|jj_|jj j rN|jj dS)NZgte)Zcmp_typeT)print_rsd) rrbr<r check_updatesrPrsr]success_exit_statusrZautocheck_running_kernelZ_check_running_kernel)r$foundrrrr4s   zCheckUpdateCommand.runN)rqrr) r7r8r9r:r&rr;ror*r,r4rrrrrps   rpc seZdZdZGdddeZGdddeZGdddeZGdd d eZGd d d eZ Gd d d eZ GdddeZ GdddeZ GdddeZ GdddeZGdddeZeeeee e e e e eeh Zd%ZedZfddZdd Zd!d"Zd#d$ZZS)&RepoPkgsCommandz2Implementation of the repository-packages command.c@s$eZdZdZdZddZddZdS) z%RepoPkgsCommand.CheckUpdateSubCommandz'Implementation of the info sub-command. check-updatecCs|jj}d|_d|_dS)NT)rr]r`r^)r$r]rrrr,(sz/RepoPkgsCommand.CheckUpdateSubCommand.configurecCs*|jj|jj|jdd}|r&d|jj_dS)z?Execute the command with respect to given arguments *cli_args*.T)rurvN)rrwr< pkg_specsreponamerr]rx)r$ryrrr run_on_repo-s  z1RepoPkgsCommand.CheckUpdateSubCommand.run_on_repoN)r{)r7r8r9r:r&r,r~rrrrCheckUpdateSubCommand#src@s$eZdZdZdZddZddZdS) zRepoPkgsCommand.InfoSubCommandz'Implementation of the info sub-command.r?cCsh|jj}d|_|jjr"|jj|j_|jjdkr4d|_|jjrd|jjr\|jjdd|jjnd|j_dS)NTrBz --obsoletesz--rH) rr]r^r<_pkg_specs_actionpkg_specs_actionr`rHra)r$r]rrrr,9s  z(RepoPkgsCommand.InfoSubCommand.configurecCs.|jj|j|jjd|jj|jj|jdS)z?Execute the command with respect to given arguments *cli_args*.r?N)rrbr<rrcrr|r})r$rrrr~Fsz*RepoPkgsCommand.InfoSubCommand.run_on_repoN)r?)r7r8r9r:r&r,r~rrrrInfoSubCommand4s rc@s$eZdZdZdZddZddZdS) z!RepoPkgsCommand.InstallSubCommandz*Implementation of the install sub-command.installcCs$|jj}d|_d|_d|_d|_dS)NT)rr]r`r^ resolving root_user)r$r]rrrr,Qs z+RepoPkgsCommand.InstallSubCommand.configurecCs|jj|jt|j|jd}|jjsjy|jjd|jWn&tj j k rbt j t dYqXd}nvxt|jjD]h}y|jj||jWnJtj j k r}z*dj|j|jjjj|}t j |WYdd}~XqtXd}qtW|stj jt ddS)NFrQzNo package available.Tz{}: {}zNo packages marked for install.)rrbr<rrr|rr}rr. MarkingErrorr r?rr valuer(termboldError)r$donepkg_specer rrrr~Xs$z-RepoPkgsCommand.InstallSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrInstallSubCommandLsrc@seZdZdZdZddZdS)zRepoPkgsCommand.ListSubCommandz'Implementation of the list sub-command.rfcCs.|jj|j|jjd|jj|jj|jdS)z?Execute the command with respect to given arguments *cli_args*.rfN)rrbr<rrcrr|r})r$rrrr~zsz*RepoPkgsCommand.ListSubCommand.run_on_repoN)rf)r7r8r9r:r&r~rrrrListSubCommandusrc@s$eZdZdZdZddZddZdS) z RepoPkgsCommand.MoveToSubCommandz*Implementation of the move-to sub-command.move-tocCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,s z*RepoPkgsCommand.MoveToSubCommand.configurecCst|j|jd}|jjsy|jjd|jdWnltjj k rVt j t dYnLtjj k rzt j t dYn(tjjk rdstdYnXd}nx|jjD]}y|jj||jdWntjj k rt d}t j ||Yqtjj k rp}z\xT|jD]J}d }|jjj|}|r:t d |}t d }t j ||jjj||qWWYd d }~Xqtjjk rdstdYqXd}qW|stjjt d d S)z?Execute the command with respect to given arguments *cli_args*.FrQ)Z new_reponamezNo package installed.zNo package available.z+Only the above marking errors are expected.TzNo match for argument: %sr#z (from %s)z%Installed package %s%s not available.NzNothing to do.)rrrr<r| reinstallr}rr.PackagesNotInstalledErrorr r?rPackagesNotAvailableErrorrAssertionErrorrPhistoryrr(rrr)r$rrr errpkgxmsgpkgreporrrr~s@  . z,RepoPkgsCommand.MoveToSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrMoveToSubCommandsrc@s$eZdZdZdZddZddZdS) z&RepoPkgsCommand.ReinstallOldSubCommandz0Implementation of the reinstall-old sub-command. reinstall-oldcCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,s z0RepoPkgsCommand.ReinstallOldSubCommand.configurecCst|j|jd}|jjsy|jjd|j|jWnptjj k r\t d}t j |YnLtjj k rt j t dYn(tjjk rdstdYnXd}nx|jjD]}y|jj||j|jWntjj k rt d}t j ||Yqtjj k rx}z\xT|jD]J}d}|jjj|}|rBt d |}t d }t j ||jjj||qWWYd d }~Xqtjjk rdstdYqXd}qW|stjjt d d S) z?Execute the command with respect to given arguments *cli_args*.FrQz)No package installed from the repository.zNo package available.z+Only the above marking errors are expected.TzNo match for argument: %sr#z (from %s)z%Installed package %s%s not available.NzNothing to do.)rrrr<r|rr}rr.rrr r?rrrrPrrr(rrr)r$rr rrrrrrrrr~sD    . z2RepoPkgsCommand.ReinstallOldSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrReinstallOldSubCommandsrcs4eZdZdZd ZfddZddZddZZS) z#RepoPkgsCommand.ReinstallSubCommandz,Implementation of the reinstall sub-command.rcs,ttj|j|tj|tj|f|_dS)zInitialize the command.N)superrzReinstallSubCommandr%rrwrapped_commands)r$r) __class__rrr%sz,RepoPkgsCommand.ReinstallSubCommand.__init__cCs6d|jj_x&|jD]}|j|_|j|_|jqWdS)NT)rr]r`rr<r}r,)r$commandrrrr,s   z-RepoPkgsCommand.ReinstallSubCommand.configurec Cs\t|j|jxH|jD].}y |jWntjjk r@wYqXPqWtjjtddS)z?Execute the command with respect to given arguments *cli_args*.z!No packages marked for reinstall.N) rrrrr~rr.rr)r$rrrrr~s  z/RepoPkgsCommand.ReinstallSubCommand.run_on_repo)r) r7r8r9r:r&r%r,r~ __classcell__rr)rrrs  rc@s,eZdZdZd ZddZddZddZd S) z,RepoPkgsCommand.RemoveOrDistroSyncSubCommandz8Implementation of the remove-or-distro-sync sub-command.remove-or-distro-synccCs$|jj}d|_d|_d|_d|_dS)NT)rr]r`r^rr)r$r]rrrr,s z6RepoPkgsCommand.RemoveOrDistroSyncSubCommand.configurec s|jjjjtjj|}|j|jjj}|jjjfdd|j D}|s`tj j d||j }|jjj j}xD|D]<}|j|j|jdr|jjjj|qz|jjjj||dqzWdS)z;Synchronize a package with another repository or remove it.csg|]}j|kr|qSr)r).0r)rr}rr #szIRepoPkgsCommand.RemoveOrDistroSyncSubCommand._replace..zno package matched)namearch) clean_depsN)rrZsackZ disable_reporsubjectZSubjectZget_best_queryrrBr.rrArZclean_requirements_on_removefilterrrZ_goalZ distupgradeZerase) r$rr}rZmatchesrBrArpackager)rr}r_replaces    z5RepoPkgsCommand.RemoveOrDistroSyncSubCommand._replacec Cst|j|jd}|jjs^y|jd|jWn*tjj k rVt d}t j |YqXd}nVxT|jjD]H}y|j||jWn,tjj k rt d}t j ||YqhXd}qhW|stjj t ddS)z?Execute the command with respect to given arguments *cli_args*.FrQz)No package installed from the repository.TzNo match for argument: %szNothing to do.N)rrrr<r|rr}rr.rrr r?r)r$rr rrrrr~0s$z8RepoPkgsCommand.RemoveOrDistroSyncSubCommand.run_on_repoN)r)r7r8r9r:r&r,rr~rrrrRemoveOrDistroSyncSubCommands rc@s$eZdZdZdZddZddZdS) z+RepoPkgsCommand.RemoveOrReinstallSubCommandz6Implementation of the remove-or-reinstall sub-command.remove-or-reinstallcCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,Rs z5RepoPkgsCommand.RemoveOrReinstallSubCommand.configurec Cs*t|j|jd}|jjsy|jjd|j|jddWnLtjj k r`t d}t j |Yn(tjj k rds~tdYnXd}nx|jjD]x}y|jj||j|jddWnRtjj k rt d}t j ||Yqtjj k rdstdYqXd}qW|s&tjjt dd S) z?Execute the command with respect to given arguments *cli_args*.FrQT)Z old_reponameZnew_reponame_neqZ remove_naz)No package installed from the repository.z)Only the above marking error is expected.zNo match for argument: %szNothing to do.N)rrrr<r|rr}rr.rrr r?rrr)r$rr rrrrr~Ys4  z7RepoPkgsCommand.RemoveOrReinstallSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrRemoveOrReinstallSubCommandMsrc@s$eZdZdZdZddZddZdS) z RepoPkgsCommand.RemoveSubCommandz)Implementation of the remove sub-command.removecCs*|jj}d|_d|_d|_d|_d|_dS)NTF)rr]r^Z allow_erasingr`rr)r$r]rrrr,s z*RepoPkgsCommand.RemoveSubCommand.configurecCsd}|jjsRy|jjd|jWn*tjjk rJtd}t j |YqXd}n`x^|jjD]R}y|jj||jWn4tjjk r}zt j t |WYdd}~Xq\Xd}q\W|st j tddS)z?Execute the command with respect to given arguments *cli_args*.FrQz)No package installed from the repository.TNzNo packages marked for removal.) r<r|rrr}rr.rrr r?strZwarning)r$rr rrrrrr~s  z,RepoPkgsCommand.RemoveSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrRemoveSubCommand~src@s$eZdZdZd ZddZddZdS) z!RepoPkgsCommand.UpgradeSubCommandz*Implementation of the upgrade sub-command.upgrade upgrade-tocCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,s z+RepoPkgsCommand.UpgradeSubCommand.configurec Cst|j|jd}|jjs.|jj|jd}nTxR|jjD]F}y|jj||jWn(tj j k rxt j t d|Yq8Xd}q8W|stj jt ddS)z?Execute the command with respect to given arguments *cli_args*.FTzNo match for argument: %szNo packages marked for upgrade.N)rrrr<r|Z upgrade_allr}rrr.rr r?rr)r$rrrrrr~sz-RepoPkgsCommand.UpgradeSubCommand.run_on_repoN)rr)r7r8r9r:r&r,r~rrrrUpgradeSubCommandsrrepository-packages repo-pkgs repo-packagesrepository-pkgsz7run commands on top of all packages in given repositorycs>tt|jfdd|jD}d|_dd|D|_dS)zInitialize the command.c3s|]}|VqdS)Nr)rsubcmd)rrr sz+RepoPkgsCommand.__init__..NcSsi|]}|jD] }||qqSr)r&)rraliasrrr sz,RepoPkgsCommand.__init__..)rrzr%SUBCMDSr_subcmd_name2obj)r$rZ subcmd_objs)r)rrr%s zRepoPkgsCommand.__init__c Cs`|j}|jdddddtdd|jddddtd d |jd ddd td d |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddtjtdtddd d!|jD}d"d!|jD}|jd#dd$|d%j|d&d}|d dddd'ddh}|jd(d)td*||tjtd+d,dS)-Nz--allrrJr@zshow all packages (default))rKrLrMrNrOz --availablerAzshow only available packages)rKrLrMrOz --installedrBzshow only installed packagesz--extrasrCzshow only extras packagesz --updatesrEzshow only upgrades packagesz --upgradesz --autoremoverFzshow only autoremove packagesz--recentrGz#show only recently changed packagesr}ZREPOIDz Repository ID)rSrLrTrOcSsg|]}|jdqS)r)r&)rrrrrrsz1RepoPkgsCommand.set_argparser..cSsg|]}|jD]}|qqSr)r&)rrrrrrrsrZ SUBCOMMANDz, )rSrTrUrOrHr|rQrRzPackage specification)rSrTrUrNrLrO)rVrWrrZ_RepoCallbackEnablerrrZ)r$r)r\Zsubcommand_choicesZsubcommand_choices_allrYrXrrrr*sP         zRepoPkgsCommand.set_argparsercCsy|j|jjd|_Wn>tjjtfk rV}z|jjjtjjWYdd}~XnX|j|j_|jj d|j_ |jj dS)z8Verify whether the command can run with given arguments.rN) rr<rrrrKeyError optparserZ print_usager}r,)r$rrrrr,s  zRepoPkgsCommand.configurecCs|jjdS)z>Execute the command with respect to given arguments *extcmds*.N)rr~)r$rrrr4szRepoPkgsCommand.run)rrrr)r7r8r9r:r"rrrrrrrrrrrrr&rr;r%r*r,r4rrr)rrrz s0) 79>1(# + rzc@s0eZdZdZd ZedZeddZddZ dS) HelpCommandzRA class containing methods needed by the cli to execute the help command. rOzdisplay a helpful usage messagecCs*|jddtdtdjtjjdddS)Ncmd?ZCOMMANDz{prog} command to get help for)r)rSrTrO)rWrr rr r)r)rrrr*szHelpCommand.set_argparsercCsN|jj s|jj|jjkr(|jjjn"|jj|jj}|jjj||dS)N)r<rrZ cli_commandsrZ print_help)r$rrrrr4$s  zHelpCommand.runN)rO) r7r8r9r:r&rr;ror*r4rrrrrs  r)r:Z __future__rrZdnf.cli.option_parserrZdnf.i18nrZdnf.clirZdnf.exceptionsZ dnf.pycompZdnf.utilZloggingrZ getLoggerr r/r0r rr!objectr"r>rerhrprzrrrrrs:       9?$ycommands/__pycache__/__init__.cpython-36.opt-1.pyc000064400000063433151030066770015717 0ustar003 ft`{}@sdZddlmZddlmZddlmZddlmZddlZ ddl Z ddl Z ddl Z ddl Z ddlZe jdZedd Zed d Zed Zd dZffddZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZGdddeZdS)z< Classes for subcommands of the yum command line interface. )print_function)unicode_literals) OptionParser)_Ndnfz+To diagnose the problem, try running: '%s'.zrpm -Va --nofiles --nodigestzDYou probably have corrupted RPMDB, running '%s' might fix the issue.zrpm --rebuilddba You have enabled checking of packages via GPG keys. This is a good thing. However, you do not have any GPG public keys installed. You need to download the keys for packages you wish to install and install them. You can do that by running the command: rpm --import public.gpg.key Alternatively you can specify the url to the key you would like to use for a repository in the 'gpgkey' option in a repository section and {prog} will install it for you. For more information contact your distribution or package provider.cCsp|jjs dS|jslxV|jjD]H}|js0|jr |j r tjdt j t j j dtjtd|t jjq WdS)zVerify that there are gpg keys for the enabled repositories in the rpm database. :param base: a :class:`dnf.Base` object. :raises: :class:`cli.CliError` Nz %s )progzProblem repository: %s)confZgpgcheckZ_gpg_key_checkreposZ iter_enabledZ repo_gpgcheckZgpgkeyloggerZcriticalgpg_msgformatrutilMAIN_PROG_UPPERrcliCliError)baserrepor/usr/lib/python3.6/__init__.py _checkGPGKey:srcCs||jjrdSxD|D]<}|jdr2tjj|r2dStjjj|d}|d krdSqWt dj d j |j j }tjj|dS) zVerify that there is at least one enabled repo. :param base: a :class:`dnf.Base` object. :param possible_local_files: the list of strings that could be a local rpms :raises: :class:`cli.CliError`: Nz.rpmrhttpftpfilehttpsz*There are no enabled repositories in "{}".z", ")rrrr)r Z _any_enabledendswithospathexistsrZpycompZurlparserr joinrZreposdirrr)rZpossible_local_filesZlfileschememsgrrr_checkEnabledRepoKs  r!c@seZdZdZgZdZdZddZeddZ edd Z ed d Z d d Z ddZ ddZddZddZddZddZdS)Commandz%Abstract base class for CLI commands.NcCs ||_dS)N)r)selfrrrr__init__fszCommand.__init__cCs|jjS)N)rr)r$rrrrjsz Command.basecCs |jdS)Nr)aliases)r$rrr_basecmdoszCommand._basecmdcCs |jjjS)N)rroutput)r$rrrr(sszCommand.outputcCsdS)z4Define command specific options and arguments. #:apiNr)r$parserrrr set_argparserwszCommand.set_argparsercCsdS)z*Do any command-specific pre-configuration.Nr)r$rrr pre_configure{szCommand.pre_configurecCsdS)z&Do any command-specific configuration.Nr)r$rrr configureszCommand.configurecCs&t|tjjrttfStd|dS)z.Get suggestions for resolving the given error.zerror not supported yet: %sN) isinstancer exceptionsZTransactionCheckError _RPM_VERIFY_RPM_REBUILDDBNotImplementedError)r$errorrrrget_error_outputszCommand.get_error_outputcCsdS)zExecute the command.Nr)r$rrrrunsz Command.runcCsdS)z$Finalize operation after resolvementNr)r$rrr run_resolvedszCommand.run_resolvedcCsdS)z%Finalize operations post-transaction.Nr)r$rrrrun_transactionszCommand.run_transaction)__name__ __module__ __qualname____doc__r&summaryoptsr%propertyrr'r(r*r+r,r3r4r5r6rrrrr"_s   r"c @sReZdZdZdZedZdZddddd d d d eh Ze d dZ ddZ ddZ dS) InfoCommandzRA class containing methods needed by the cli to execute the info command. infoz4display details about a package or group of packagesall available installedextrasupdatesupgrades autoremoverecent obsoletesc Cs|j}|jdddddtdd|jddddtd d |jd ddd td d |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddtd|j|jtjtdddS) Nz--all_packages_action store_constr@zshow all packages (default))destactionconstdefaulthelpz --availablerAzshow only available packages)rKrLrMrOz --installedrBzshow only installed packagesz--extrasrCzshow only extras packagesz --updatesrEzshow only upgrades packagesz --upgradesz --autoremoverFzshow only autoremove packagesz--recentrGz#show only recently changed packagespackages*PACKAGEzPackage name specification)nargsmetavarchoicesrNrLrO)add_mutually_exclusive_group add_argumentr pkgnarrowsDEFAULT_PKGNARROWrPkgNarrowCallback)clsr)narrowsrrrr*s:        zInfoCommand.set_argparsercCs||jj}d|_|jjr"|jj|j_|jjdkr4d|_|jjrd|jjr\|jjdd|jjnd|j_|jjdkrxd|j_dS)NTrBz --obsoletesz--rHrDrE) rdemandssack_activationr<rIpackages_actionavailable_reposrH_option_conflict)r$r]rrrr,s   zInfoCommand.configurecCs&|jj|j|jjd|jj|jjS)Nr?)r _populate_update_security_filterr<routput_packagesr_rP)r$rrrr4szInfoCommand.runN)r?) r7r8r9r:r&rr;rYrX classmethodr*r,r4rrrrr>s   r>c@s$eZdZdZdZedZddZdS) ListCommandzRA class containing methods needed by the cli to execute the list command. listlsz$list a package or groups of packagescCs&|jj|j|jjd|jj|jjS)Nrf)rrbr<rrcr_rP)r$rrrr4szListCommand.runN)rfrg)r7r8r9r:r&rr;r4rrrrresrec@s8eZdZdZd ZedZeddZdd Z d d Z d S)ProvidesCommandzVA class containing methods needed by the cli to execute the provides command. provides whatprovidesprovz*find what package provides the given valuecCs|jddtdtdddS)N dependency+ZPROVIDEz#Provide specification to search for)rSrTrO)rWr)r)rrrr*szProvidesCommand.set_argparsercCs|jj}d|_d|_d|_dS)NTF)rr]r`Zfresh_metadatar^)r$r]rrrr,szProvidesCommand.configurecCstjtd|jj|jjS)NzSearching Packages: )r debugrrrir<rl)r$rrrr4szProvidesCommand.runN)rirjrk) r7r8r9r:r&rr; staticmethodr*r,r4rrrrrhs  rhc@s8eZdZdZd ZedZeddZddZ d d Z d S) CheckUpdateCommandzZA class containing methods needed by the cli to execute the check-update command. check-update check-upgradez$check for available package upgradescCs0|jddddtdd|jddtd d dS) Nz --changelogs changelogsF store_truezshow changelogs before update)rKrNrLrOrPrQrR)rSrT)rWr)r)rrrr*s z CheckUpdateCommand.set_argparsercCs6|jj}d|_d|_d|_|jjr(d|_t|jdS)NT) rr]r^r`Zplugin_filtering_enabledr<rsr!r)r$r]rrrr, szCheckUpdateCommand.configurecCsR|jj|jdd|jj|jjd|jjd}|r:d|jj_|jj j rN|jj dS)NZgte)Zcmp_typeT)print_rsd) rrbr<r check_updatesrPrsr]success_exit_statusrZautocheck_running_kernelZ_check_running_kernel)r$foundrrrr4s   zCheckUpdateCommand.runN)rqrr) r7r8r9r:r&rr;ror*r,r4rrrrrps   rpc seZdZdZGdddeZGdddeZGdddeZGdd d eZGd d d eZ Gd d d eZ GdddeZ GdddeZ GdddeZ GdddeZGdddeZeeeee e e e e eeh Zd%ZedZfddZdd Zd!d"Zd#d$ZZS)&RepoPkgsCommandz2Implementation of the repository-packages command.c@s$eZdZdZdZddZddZdS) z%RepoPkgsCommand.CheckUpdateSubCommandz'Implementation of the info sub-command. check-updatecCs|jj}d|_d|_dS)NT)rr]r`r^)r$r]rrrr,(sz/RepoPkgsCommand.CheckUpdateSubCommand.configurecCs*|jj|jj|jdd}|r&d|jj_dS)z?Execute the command with respect to given arguments *cli_args*.T)rurvN)rrwr< pkg_specsreponamerr]rx)r$ryrrr run_on_repo-s  z1RepoPkgsCommand.CheckUpdateSubCommand.run_on_repoN)r{)r7r8r9r:r&r,r~rrrrCheckUpdateSubCommand#src@s$eZdZdZdZddZddZdS) zRepoPkgsCommand.InfoSubCommandz'Implementation of the info sub-command.r?cCsh|jj}d|_|jjr"|jj|j_|jjdkr4d|_|jjrd|jjr\|jjdd|jjnd|j_dS)NTrBz --obsoletesz--rH) rr]r^r<_pkg_specs_actionpkg_specs_actionr`rHra)r$r]rrrr,9s  z(RepoPkgsCommand.InfoSubCommand.configurecCs.|jj|j|jjd|jj|jj|jdS)z?Execute the command with respect to given arguments *cli_args*.r?N)rrbr<rrcrr|r})r$rrrr~Fsz*RepoPkgsCommand.InfoSubCommand.run_on_repoN)r?)r7r8r9r:r&r,r~rrrrInfoSubCommand4s rc@s$eZdZdZdZddZddZdS) z!RepoPkgsCommand.InstallSubCommandz*Implementation of the install sub-command.installcCs$|jj}d|_d|_d|_d|_dS)NT)rr]r`r^ resolving root_user)r$r]rrrr,Qs z+RepoPkgsCommand.InstallSubCommand.configurecCs|jj|jt|j|jd}|jjsjy|jjd|jWn&tj j k rbt j t dYqXd}nvxt|jjD]h}y|jj||jWnJtj j k r}z*dj|j|jjjj|}t j |WYdd}~XqtXd}qtW|stj jt ddS)NFrQzNo package available.Tz{}: {}zNo packages marked for install.)rrbr<rrr|rr}rr. MarkingErrorr r?rr valuer(termboldError)r$donepkg_specer rrrr~Xs$z-RepoPkgsCommand.InstallSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrInstallSubCommandLsrc@seZdZdZdZddZdS)zRepoPkgsCommand.ListSubCommandz'Implementation of the list sub-command.rfcCs.|jj|j|jjd|jj|jj|jdS)z?Execute the command with respect to given arguments *cli_args*.rfN)rrbr<rrcrr|r})r$rrrr~zsz*RepoPkgsCommand.ListSubCommand.run_on_repoN)rf)r7r8r9r:r&r~rrrrListSubCommandusrc@s$eZdZdZdZddZddZdS) z RepoPkgsCommand.MoveToSubCommandz*Implementation of the move-to sub-command.move-tocCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,s z*RepoPkgsCommand.MoveToSubCommand.configurecCst|j|jd}|jjsy|jjd|jdWn`tjj k rVt j t dYn@tjj k rzt j t dYntjjk rYnXd}nx|jjD]}y|jj||jdWntjj k rt d}t j ||Yqtjj k rd}z\xT|jD]J}d}|jjj|}|r.t d |}t d }t j ||jjj||qWWYd d }~Xqtjjk r|YqXd}qW|stjjt d d S) z?Execute the command with respect to given arguments *cli_args*.FrQ)Z new_reponamezNo package installed.zNo package available.TzNo match for argument: %sr#z (from %s)z%Installed package %s%s not available.NzNothing to do.)rrrr<r| reinstallr}rr.PackagesNotInstalledErrorr r?rPackagesNotAvailableErrorrrPhistoryrr(rrr)r$rrr errpkgxmsgpkgreporrrr~s>  .z,RepoPkgsCommand.MoveToSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrMoveToSubCommandsrc@s$eZdZdZdZddZddZdS) z&RepoPkgsCommand.ReinstallOldSubCommandz0Implementation of the reinstall-old sub-command. reinstall-oldcCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,s z0RepoPkgsCommand.ReinstallOldSubCommand.configurecCst|j|jd}|jjsy|jjd|j|jWndtjj k r\t d}t j |Yn@tjj k rt j t dYntjjk rYnXd}nx|jjD]}y|jj||j|jWntjj k rt d}t j ||Yqtjj k rl}z\xT|jD]J}d}|jjj|}|r6t d|}t d }t j ||jjj||qWWYd d }~Xqtjjk rYqXd}qW|stjjt d d S) z?Execute the command with respect to given arguments *cli_args*.FrQz)No package installed from the repository.zNo package available.TzNo match for argument: %sr#z (from %s)z%Installed package %s%s not available.NzNothing to do.)rrrr<r|rr}rr.rrr r?rrrPrrr(rrr)r$rr rrrrrrrrr~sB    .z2RepoPkgsCommand.ReinstallOldSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrReinstallOldSubCommandsrcs4eZdZdZd ZfddZddZddZZS) z#RepoPkgsCommand.ReinstallSubCommandz,Implementation of the reinstall sub-command.rcs,ttj|j|tj|tj|f|_dS)zInitialize the command.N)superrzReinstallSubCommandr%rrwrapped_commands)r$r) __class__rrr%sz,RepoPkgsCommand.ReinstallSubCommand.__init__cCs6d|jj_x&|jD]}|j|_|j|_|jqWdS)NT)rr]r`rr<r}r,)r$commandrrrr,s   z-RepoPkgsCommand.ReinstallSubCommand.configurec Cs\t|j|jxH|jD].}y |jWntjjk r@wYqXPqWtjjtddS)z?Execute the command with respect to given arguments *cli_args*.z!No packages marked for reinstall.N) rrrrr~rr.rr)r$rrrrr~s  z/RepoPkgsCommand.ReinstallSubCommand.run_on_repo)r) r7r8r9r:r&r%r,r~ __classcell__rr)rrrs  rc@s,eZdZdZd ZddZddZddZd S) z,RepoPkgsCommand.RemoveOrDistroSyncSubCommandz8Implementation of the remove-or-distro-sync sub-command.remove-or-distro-synccCs$|jj}d|_d|_d|_d|_dS)NT)rr]r`r^rr)r$r]rrrr,s z6RepoPkgsCommand.RemoveOrDistroSyncSubCommand.configurec s|jjjjtjj|}|j|jjj}|jjjfdd|j D}|s`tj j d||j }|jjj j}xD|D]<}|j|j|jdr|jjjj|qz|jjjj||dqzWdS)z;Synchronize a package with another repository or remove it.csg|]}j|kr|qSr)r).0r)rr}rr #szIRepoPkgsCommand.RemoveOrDistroSyncSubCommand._replace..zno package matched)namearch) clean_depsN)rrZsackZ disable_reporsubjectZSubjectZget_best_queryrrBr.rrArZclean_requirements_on_removefilterrrZ_goalZ distupgradeZerase) r$rr}rZmatchesrBrArpackager)rr}r_replaces    z5RepoPkgsCommand.RemoveOrDistroSyncSubCommand._replacec Cst|j|jd}|jjs^y|jd|jWn*tjj k rVt d}t j |YqXd}nVxT|jjD]H}y|j||jWn,tjj k rt d}t j ||YqhXd}qhW|stjj t ddS)z?Execute the command with respect to given arguments *cli_args*.FrQz)No package installed from the repository.TzNo match for argument: %szNothing to do.N)rrrr<r|rr}rr.rrr r?r)r$rr rrrrr~0s$z8RepoPkgsCommand.RemoveOrDistroSyncSubCommand.run_on_repoN)r)r7r8r9r:r&r,rr~rrrrRemoveOrDistroSyncSubCommands rc@s$eZdZdZdZddZddZdS) z+RepoPkgsCommand.RemoveOrReinstallSubCommandz6Implementation of the remove-or-reinstall sub-command.remove-or-reinstallcCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,Rs z5RepoPkgsCommand.RemoveOrReinstallSubCommand.configurec Cst|j|jd}|jjs~y|jjd|j|jddWn@tjj k r`t d}t j |Yqtjj k rvYqXd}nvxt|jjD]h}y|jj||j|jddWnBtjj k rt d}t j ||Yqtjj k rYqXd}qW|s tjjt ddS) z?Execute the command with respect to given arguments *cli_args*.FrQT)Z old_reponameZnew_reponame_neqZ remove_naz)No package installed from the repository.zNo match for argument: %szNothing to do.N)rrrr<r|rr}rr.rrr r?rr)r$rr rrrrr~Ys4  z7RepoPkgsCommand.RemoveOrReinstallSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrRemoveOrReinstallSubCommandMsrc@s$eZdZdZdZddZddZdS) z RepoPkgsCommand.RemoveSubCommandz)Implementation of the remove sub-command.removecCs*|jj}d|_d|_d|_d|_d|_dS)NTF)rr]r^Z allow_erasingr`rr)r$r]rrrr,s z*RepoPkgsCommand.RemoveSubCommand.configurecCsd}|jjsRy|jjd|jWn*tjjk rJtd}t j |YqXd}n`x^|jjD]R}y|jj||jWn4tjjk r}zt j t |WYdd}~Xq\Xd}q\W|st j tddS)z?Execute the command with respect to given arguments *cli_args*.FrQz)No package installed from the repository.TNzNo packages marked for removal.) r<r|rrr}rr.rrr r?strZwarning)r$rr rrrrrr~s  z,RepoPkgsCommand.RemoveSubCommand.run_on_repoN)r)r7r8r9r:r&r,r~rrrrRemoveSubCommand~src@s$eZdZdZd ZddZddZdS) z!RepoPkgsCommand.UpgradeSubCommandz*Implementation of the upgrade sub-command.upgrade upgrade-tocCs$|jj}d|_d|_d|_d|_dS)NT)rr]r^r`rr)r$r]rrrr,s z+RepoPkgsCommand.UpgradeSubCommand.configurec Cst|j|jd}|jjs.|jj|jd}nTxR|jjD]F}y|jj||jWn(tj j k rxt j t d|Yq8Xd}q8W|stj jt ddS)z?Execute the command with respect to given arguments *cli_args*.FTzNo match for argument: %szNo packages marked for upgrade.N)rrrr<r|Z upgrade_allr}rrr.rr r?rr)r$rrrrrr~sz-RepoPkgsCommand.UpgradeSubCommand.run_on_repoN)rr)r7r8r9r:r&r,r~rrrrUpgradeSubCommandsrrepository-packages repo-pkgs repo-packagesrepository-pkgsz7run commands on top of all packages in given repositorycs>tt|jfdd|jD}d|_dd|D|_dS)zInitialize the command.c3s|]}|VqdS)Nr)rsubcmd)rrr sz+RepoPkgsCommand.__init__..NcSsi|]}|jD] }||qqSr)r&)rraliasrrr sz,RepoPkgsCommand.__init__..)rrzr%SUBCMDSr_subcmd_name2obj)r$rZ subcmd_objs)r)rrr%s zRepoPkgsCommand.__init__c Cs`|j}|jdddddtdd|jddddtd d |jd ddd td d |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddddtdd |jddtjtdtddd d!|jD}d"d!|jD}|jd#dd$|d%j|d&d}|d dddd'ddh}|jd(d)td*||tjtd+d,dS)-Nz--allrrJr@zshow all packages (default))rKrLrMrNrOz --availablerAzshow only available packages)rKrLrMrOz --installedrBzshow only installed packagesz--extrasrCzshow only extras packagesz --updatesrEzshow only upgrades packagesz --upgradesz --autoremoverFzshow only autoremove packagesz--recentrGz#show only recently changed packagesr}ZREPOIDz Repository ID)rSrLrTrOcSsg|]}|jdqS)r)r&)rrrrrrsz1RepoPkgsCommand.set_argparser..cSsg|]}|jD]}|qqSr)r&)rrrrrrrsrZ SUBCOMMANDz, )rSrTrUrOrHr|rQrRzPackage specification)rSrTrUrNrLrO)rVrWrrZ_RepoCallbackEnablerrrZ)r$r)r\Zsubcommand_choicesZsubcommand_choices_allrYrXrrrr*sP         zRepoPkgsCommand.set_argparsercCsy|j|jjd|_Wn>tjjtfk rV}z|jjjtjjWYdd}~XnX|j|j_|jj d|j_ |jj dS)z8Verify whether the command can run with given arguments.rN) rr<rrrrKeyError optparserZ print_usager}r,)r$rrrrr,s  zRepoPkgsCommand.configurecCs|jjdS)z>Execute the command with respect to given arguments *extcmds*.N)rr~)r$rrrr4szRepoPkgsCommand.run)rrrr)r7r8r9r:r"rrrrrrrrrrrrr&rr;r%r*r,r4rrr)rrrz s0) 79>1(# + rzc@s0eZdZdZd ZedZeddZddZ dS) HelpCommandzRA class containing methods needed by the cli to execute the help command. rOzdisplay a helpful usage messagecCs*|jddtdtdjtjjdddS)Ncmd?ZCOMMANDz{prog} command to get help for)r)rSrTrO)rWrr rr r)r)rrrr*szHelpCommand.set_argparsercCsN|jj s|jj|jjkr(|jjjn"|jj|jj}|jjj||dS)N)r<rrZ cli_commandsrZ print_help)r$rrrrr4$s  zHelpCommand.runN)rO) r7r8r9r:r&rr;ror*r4rrrrrs  r)r:Z __future__rrZdnf.cli.option_parserrZdnf.i18nrZdnf.clirZdnf.exceptionsZ dnf.pycompZdnf.utilZloggingrZ getLoggerr r/r0r rr!objectr"r>rerhrprzrrrrrs:       9?$ycommands/__pycache__/distrosync.cpython-36.opt-1.pyc000064400000002640151030066770016352 0ustar003 ft`@s:ddlmZddlmZddlmZGdddejZdS))absolute_import)commands)_c@s8eZdZdZdZedZeddZd d Z d d Z d S)DistroSyncCommandzZA class containing methods needed by the cli to execute the distro-synch command. distro-sync distrosyncdistribution-synchronizationdsyncz?synchronize installed packages to the latest available versionscCs|jddtdddS)Npackage*zPackage to synchronize)nargshelp) add_argumentr)parserr /usr/lib/python3.6/distrosync.py set_argparser"szDistroSyncCommand.set_argparsercCsF|jj}d|_d|_d|_d|_tj|j|jtj |j|j j dS)NT) ZclidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseZ_checkEnabledRepooptsr )selfrrrr configure&szDistroSyncCommand.configurecCs|jj|jjS)N)rZdistro_sync_userlistrr )rrrrrun/szDistroSyncCommand.runN)rrrr ) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrrrrrrrrs   rN)Z __future__rZdnf.clirZdnf.i18nrZCommandrrrrrs   commands/__pycache__/upgrademinimal.cpython-36.pyc000064400000002117151030066770016207 0ustar003 ft`@sDddlmZddlmZddlmZddlmZGdddeZdS))absolute_import)unicode_literals)_)UpgradeCommandc@s$eZdZdZd ZedZddZdS) UpgradeMinimalCommandzSA class containing methods needed by the cli to execute the check command. upgrade-minimalupdate-minimalup-minzWupgrade, but only 'newest' package match which fixes a problem that affects your systemc CsRtj|d|_t|jj|jj|jj|jj|jj |jj |jj |jj gsNd|_ dS)NT)r configureZupgrade_minimalanyZoptsZbugfixZ enhancementZ newpackageZsecurityZadvisoryZbugzillaZcvesZseverityZ all_security)selfr $/usr/lib/python3.6/upgrademinimal.pyr "s  zUpgradeMinimalCommand.configureN)rrr )__name__ __module__ __qualname____doc__aliasesrZsummaryr r r r rrsrN)Z __future__rrZdnf.i18nrZdnf.cli.commands.upgraderrr r r rs    commands/__pycache__/repoquery.cpython-36.pyc000064400000053431151030066770015251 0ustar003 ft`ن @sddlmZddlmZddlmZddlmZddlmZddlm Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZe jdZd Ze jd Zd Zd d dddddddd ZddZGddde jZGdddejZGddde Z!dS))absolute_import)print_function)unicode_literals)_)commands) OptionParserNdnfz.%{name}-%{epoch}:%{version}-%{release}.%{arch}z%(-?\d*?){([:.\w]+?)}a name, arch, epoch, version, release, reponame (repoid), from_repo, evr, debug_name, source_name, source_debug_name, installtime, buildtime, size, downloadsize, installsize, provides, requires, obsoletes, conflicts, sourcerpm, description, summary, license, url, reason conflictsenhances obsoletesprovides recommendsrequiresZ requires_presuggests supplements) r r r r r rz requires-prerrcCsdd}dd}|jddjdd}x tjD]\}}|j||}q.Wd }d }x>tj|D]0}|||||j7}|||7}|j}qZW||||d 7}|S) z:Convert a rpm like QUERYFMT to an python .format() string.cSs^|jd}|jd}|rJ|ddkr:d|dd}nd|}d|}d|j|dS) Nr-><:z{0.})groupslower)ZmatchobjZfillkeyr/usr/lib/python3.6/repoquery.pyfmt_replDs   zrpm2py_format..fmt_replcSs|jddjddS)N{z{{rz}})replace)ZtxtrrrbracketsOszrpm2py_format..bracketsz\n z\t rN)r OPTS_MAPPINGitems QFORMAT_MATCHfinditerstartend) queryformatrrrvalueZfmtspositemrrr rpm2py_formatBs   r-c@seZdZdZdS)_CommaSplitCallbackz\s*,\s*N)__name__ __module__ __qualname__ZSPLITTERrrrrr._sr.c@seZdZdZejejejdZd%e ej Z e dZ eddZedd Zd d Zd d ZddZddZd&ddZd'ddZd(ddZddZddZddZd d!Zd*d#d$ZdS)+RepoQueryCommandzSA class containing methods needed by the cli to execute the repoquery command. )z repoquery-nz repoquery-nazrepoquery-nevra repoqueryrqz$search for packages matching keywordcCs,|jr|j|jd|jr(|j|jd|S)z'Filter query by repoid and arch options)Zreponame)arch)Zrepofiltermarches)optsqueryrrrfilter_repo_archms z!RepoQueryCommand.filter_repo_archc Cs|jddddtdd|jddtdd |jd d d gtd tdd|jddddtdd|jdgtdtdd|jdgtdtdd|jdgtdtdd|jdgtdtdd|jd gtdtd!d|jd"gtdtd#d|jd$gtdtd%d|jd&gtdtd'd|jd(gtdtd)d|j}|jd*dtd+d |jd,dtd-d |jd.dtd/d |jd0dtd1d |jd2dtd3d |jd4dtd5d |jd6dtd7d |jd8d9ttd:d;|jdd?d@dAdtdBdC|jdDdEdFdAdtdGdC|jdHdIdJdAdtdKdC|jdLdMdAdtdNdC|jdOdPdQttdRdS|jdTdtdUd |jdVdQtdWtdXdY|jdZdQd[dWtd\dY|jd]dQd^dWtd_dY|jd`dtdad |j}|jdbdcdddWtdedY|jdfdcdddWtjdY|jdgdcdhdWtdidY|jdjdcdkdWtdldY|jdmdtdnd |j}tdotdptdqtdrtdstdttdutdvtdwdx }x2|jD]&\}}dy|}|j|dzdW||d{qW|jd|dtd}d td~tdtdtdj t j j dtdd} |j} x2| jD]&\} } dy| } | j| ddW| | d{q4W| jdddWdtjd{|jddtdd |jdddtdddS)Nz-az--allZqueryall store_truezNQuery all packages (shorthand for repoquery '*' or repoquery without argument))destactionhelpz--show-duplicatesz(Query all versions of packages (default))r=r>z--archz --archlistr7z[arch]z show only results from this ARCH)r<defaultr=metavarr>z-fz--fileFILE+z show only results that owns FILE)r@nargsr>z--whatconflictsZREQz#show only results that conflict REQ)r?r=r@r>z --whatdependszishows results that requires, suggests, supplements, enhances,or recommends package provides and files REQz--whatobsoletesz#show only results that obsolete REQz--whatprovidesz"show only results that provide REQz--whatrequiresz:shows results that requires package provides and files REQz--whatrecommendsz$show only results that recommend REQz--whatenhancesz"show only results that enhance REQz--whatsuggestsz"show only results that suggest REQz--whatsupplementsz%show only results that supplement REQz --alldepsz=check non-explicit dependencies (files and Provides); defaultz --exactdepsz:check dependencies exactly as given, opposite of --alldepsz --recursivezOused with --whatrequires, and --requires --resolve, query packages recursively.z --deplistz>show a list of all dependencies and what packages provide themz --resolvez.resolve capabilities to originating package(s)z--treez"show recursive tree for package(s)z--srpmz#operate on corresponding source RPMz--latest-limit latest_limitzOshow N latest packages for a given name.arch (or latest but N if N is negative))r<typer>z--disable-modular-filteringz-list also packages of inactive module streamsz-iz--info queryinfoFz+show detailed information about the package)r<r?r=r>z-lz--list queryfilelistz!show list of files in the packagez-sz--sourcequerysourcerpmzshow package source RPM namez --changelogsquerychangelogszshow changelogs of the packagez--qfz --queryformatr)zfdisplay format for listing packages: "%%{name} %%{version} ...", use --querytags to view full tag list)r<r?r>z --querytagsz-show available tags to use with --queryformatz--nevra store_constzZuse name-epoch:version-release.architecture format for displaying found packages (default))r<constr=r>z--nvrz%{name}-%{version}-%{release}zQuse name-version-release format for displaying found packages (rpm query default)z--envraz.%{epoch}:%{name}-%{version}-%{release}.%{arch}zPuse epoch:name-version-release.architecture format for displaying found packagesz --groupmemberz=Display in which comps groups are presented selected packagesz --duplicates pkgfilter duplicatedz/limit the query to installed duplicate packagesz --duplicatedz --installonly installonlyz1limit the query to installed installonly packagesz --unsatisfied unsatisfiedzClimit the query to installed packages with unsatisfied dependenciesz --locationz5show a location from where packages can be downloadedz5Display capabilities that the package conflicts with.zaDisplay capabilities that the package can depend on, enhance, recommend, suggest, and supplement.z2Display capabilities that the package can enhance.z-Display capabilities provided by the package.z1Display capabilities that the package recommends.z1Display capabilities that the package depends on.zIf the package is not installed display capabilities that it depends on for running %%pre and %%post scriptlets. If the package is installed display capabilities that is depends for %%pre, %%post, %%preun and %%postun.z/Display capabilities that the package suggests.z5Display capabilities that the package can supplement.) r dependsr r r rz requires-prerrz--%s packageatr)r<r=rKr>z --availablez Display only available packages.z Display only installed packages.zLDisplay only packages that are not present in any of available repositories.zQDisplay only packages that provide an upgrade for some already installed package.zIDisplay only packages that can be removed by "{prog} autoremove" command.)progz2Display only packages that were installed by user.) installedZextrasZupgradesunneeded userinstalledlistz --autoremoverTz--recentz%Display only recently edited packagesr*ZKEYzthe key to search for)rCr@r>) add_argumentrr.Zadd_mutually_exclusive_groupintQFORMAT_DEFAULTargparseZSUPPRESSr$formatrutil MAIN_PROG)parserZwhatrequiresformZoutformrLZpackage_attributeZ help_msgsargZhelp_msgnameZ help_listZ list_groupZlist_argZhelp_argZswitchrrr set_argparservs                                                                 zRepoQueryCommand.set_argparsercCs |jjs|jjtjtjddS)N)stdoutstderr)r8quietcliZredirect_loggerloggingZWARNINGINFO)selfrrr pre_configureszRepoQueryCommand.pre_configurecCsj|jjs|jj|jj}|jjrJ|jjrB|jjdd|jjnd|j_|jjrVdS|jj rx|jj rxt jj t d|jj r|jjr|jjddt|jj|jjdko|jj gst jj t d|jjs|jjr|jjp|jjst jj t d j|jjrd nd|jjr$|jjj|jjdkr@|jjd ksJ|jjrPd|_d|_|jjrfd|_dS)Nz --obsoletesz--r zOption '--resolve' has to be used together with one of the '--conflicts', '--depends', '--enhances', '--provides', '--recommends', '--requires', '--requires-pre', '--suggests' or '--supplements' optionsz --recursivez --exactdepsrzOption '--recursive' has to be used with '--whatrequires ' (optionally with '--alldeps', but not with '--exactdeps'), or with '--requires --resolve'z;argument {} requires --whatrequires or --whatdepends optionz --alldepsrSrUrNT)rSrU)r8rerfZredirect_repo_progressdemandsr rQZ_option_conflict querytagsresolverZCliErrorr recursive exactdepsany whatrequiresalldeps whatdependsr\srpmbaseZreposZenable_source_reposrVrL availableZavailable_reposZsack_activationrI changelogs)rirkrrr configures@      zRepoQueryCommand.configurec Cs|jrpg}|jdt|xH|jD]>}|d}|jd|jdtjj|dtjj|dfq$Wdj|Syht |}|j r|j j j |S|jr|j}|sttdj|tjd |S|jr|jSt|jj|SWn4tk r }ztjjt|WYdd}~XnXdS) NzChangelog for %s timestampz * %s %s %s z %a %b %d %YZauthortextr zPackage {} contains no files)file)rIappendstrrwstrftimeri18nucdjoinPackageWrapperrFruoutputZ infoOutputrGfilesprintrr\sysrdrHZ sourcerpmr-r)AttributeError exceptionsError) rir8pkgoutZchlogdtZpoZfilelisterrrbuild_format_fnGs.  z RepoQueryCommand.build_format_fncCsN|jjjjdd}x4|D],}|j|jtjj|j |jjddd}qW|S)NT)emptyF) with_providesZwith_filenames) rusackr9r6union intersectionrsubjectSubjectget_best_query)riZnevrasZ base_queryresolved_nevras_queryZnevrarrr_resolve_nevrascs  z RepoQueryCommand._resolve_nevrasNcCsD|r|n|}|j|d}|j|}|j|}|r@|j|||d}|S)N)r)done)filter differencer_do_recursive_deps)riquery_in query_selectrZquery_requiredrrrrps    z#RepoQueryCommand._do_recursive_depsFcCs|j||}|j|d}|j|j|d}|r|j|j|d}|j|j|d}|j|j|d}|j|j|d}|j|j|d}|j|j|d}|j|j|d }|j|j|d }|jjr|j||}|S) N)requires__glob)r)recommends__glob)enhances__glob)supplements__glob)suggests__glob)r )r )r)r)rrrr8rnr)rinamesr9Z all_dep_typesrZdepqueryrrr by_all_deps}s   zRepoQueryCommand.by_all_depscCs|r|n|jjjjdd}|jjjjdd}x$|jD]}|j|j|jd}q:W|j|}|rz|j |||j|d}|j|S)NT)r)r )r) rurr9r6runrrrr_get_recursive_providers_query)rir providersrtrrrrrrs z/RepoQueryCommand._get_recursive_providers_querycCsxg}g}xN|jjD]B}tjjj|d}|jdr>|j|q|r|d kr|j|qW|rt|jj|d|jj j d}|S) Nrz.rpmhttpftpr{httpsF)strictprogress)rrr{r) r8rrZpycompZurlparseendswithr|ruZadd_remote_rpmsrr)riZrpmnamesremote_packagesrZschemesrrr_add_add_remote_packagess   z)RepoQueryCommand._add_add_remote_packagesc Cs|jjrttdS|jj|j|jjj|jj r8t j nt j d}|jj r|j}i}|jj|jkrx|j|jjg|d<g}|jdd}|r|j|jjjj|d}x>|jj D]2}|jtjj|ddj|jjfd|d|}qW|}|jjr|j|jjj}|jjrX|jjr|jjd krt|jjjtjj t!d j"d d |jjnH|jjd krx|j#|jj$j%}n(|jjr|jjdkrt&||jj}|jj'dkr|jj(|}|j)|j*}n|jj'dkr|jj(|}n|jj'dkrVtjj+|j}|j,|jjj-|jjj.tj/j0|} d| _1| j2dd} | sRttj3j4| j5dS|jjsh|j}|j6|j|}|} |jj7r|j|jj7d|jj8r|j|jj8d} | j|j|j9|jj8|d}|jj:r|j|jj:d|jj;r|j|jj;d} | r | }n|j|jj;d|jj<rR|jj=rB|j|jj|jj<|}|jj?r|jj=r|j|jj?d}|j|j|jj?d}|j|j|jj?d}|j|j|jj?d}|j|j|jj?d}n|j>|jj?|d}|jj@r|j|jj@d} | j|j|j9|jj@|d}|jjArR|j|jjAd} | j|j|j9|jjA|d}|jjBr|j|jjBd} | j|j|j9|jjB|d}|jjCr|j|jjCd} | j|j|j9|jjC|d }|jjDr|jE|jjD}|jjF|dd!}|jjGrRg}xD|D]<}|jH}|dk r|jjjj||jId"d#}||j27}qW|jjjj|d}|jjJr|jj< r|jjKd9krtjj t!d,j"tj3jLd-|jM|| |jdStN}|jjKrtN} x||j2D]p}|jjdks|jj$jO|r|jjKd.kr| jP|jQ|jR|jS|jT|jUn| jPt&|tV|jjKqW|jjWr|jjd krj|j6|j|jjj}n|j6|j|jjjj}|j| d/}|jjXr|j|jY||}tN}x@|jEj2D]}|jZ|j[|j|qWn|jPd0d1| Dn|jj\r6x.|j2D]"}|j]}|dk r |jZ|q Wnv|jj^rNg}xt_tN|j2D]}|jjdksx|jj$jO|rVg}|j`d2ta|xt_d3d4|jQDD]x}|j`d5|tjj|}|j|jj}|j6|j|j}|jjbs|jE}x$|j2D]}|j`d6ta|qWqW|j`d7jc|qVW|rJtd8jc|dS|jjdrf|je|dSxD|j2D]8}|jjdks|jj$jO|rp|jZ|j[|j|qpW|r|jjfrtd8jct_|ntd7jct_|dS):N)flagsZformsT)r)r)Z ignore_caseF)rr9rSz)argument {}: not allowed with argument {}z --availablez--rTrUrMrNrO)Zverify)Z file__glob)Zconflicts__glob)r )r )Zprovides__glob)r)r)r)r)r)r )r )r)r)Zwarningsrc)raevrr5r r r r r rrrzNo valid switch specified usage: {prog} repoquery [--conflicts|--enhances|--obsoletes|--provides|--recommends|--requires|--suggest|--supplements|--whatrequires] [key] [--tree] description: For the given packages print a tree of thepackages.)rRrP)r css|]}t|VqdS)N)r}).0Zrelrrr Qsz'RepoQueryCommand.run..z package: cSsg|] }t|qSr)r})rreqrrr ]sz(RepoQueryCommand.run..z dependency: z provider: r z )r r r r r rrr)gr8rlr QUERY_TAGSrfZ _populate_update_security_filterrurr9Zdisable_modular_filteringhawkeyZIGNORE_MODULAR_EXCLUDESZAPPLY_EXCLUDESrrZcommand nevra_formsrrr6rrrrZrecentZ_recentZconfrvrVZ optparserZ print_usagerrrr\Z _unneededhistoryZswdbgetattrrLZ_get_installonly_queryrrMZ rpmdb_sackZ _configureZinstallonlypkgsZinstallonly_limitgoalZGoalZprotect_running_kernelrr]Z_format_resolve_problemsZ problem_rulesr:r{Z whatconflictsrZ whatobsoletesZ whatprovidesrqrorrsZwhatrecommendsZ whatenhancesZwhatsupplementsZ whatsuggestsrDZlatestZ_merge_update_filtersrtZ source_namerZtreerQr^ tree_seedsetZuser_installedupdaterr rrr r#rmrnraddrlocationZremote_locationZdeplistsortedr|r}verboserZ groupmember_group_member_reportrF)riqrZkwarkZpkgsZ query_resultsrrNZrpmdbrZsolvedZorqueryZrelsZquery_for_provideZ dependsqueryZpkg_listrZsrcnameZ tmp_queryr9rrZdeplist_outputrrZproviderrrrrsH                           "           zRepoQueryCommand.runc Cs&i}x.|jjjD] }tdd|jD||j<qWi}g}xr|jD]f}g}x(|jD]\}} |j| krX|j |qXW|r|j dj t |gj t |qF|j t |qFWg} xDt |jD]4\} } | j dj t | t dd| jdDqW| j dj t || r"tdj | dS)NcSsg|] }|jqSr)ra)rrrrrr}sz9RepoQueryCommand._group_member_report..$r cSsg|] }d|qS)z @r)ridrrrrs)rucompsrrZ packages_iterrrr$rar| setdefaultrrr}splitr) rir9Zpackage_conf_dictgroupZgroup_package_dictZpkg_not_in_grouprZ group_id_listZgroup_idZpackage_name_setrrZ package_listrrrrzs*  ,z%RepoQueryCommand._group_member_reportc Cs|j||}|d kr t|dSd}xtd|D] }|d7}q0Wg}x|jD]}|jt|qLWdtt|ddj|d} t|d |d| dS) Nr rz| [z: z, ]z\_ )rrrangerr|r}lenr) rilevelrr8Z pkg_stringZspacingxrZ requirepkgZreqstrrrr grow_trees   "zRepoQueryCommand.grow_treerc Cs8x0tt|jdddD]}|dks2|d kr8tn|}|jjdsT|jjdrXdS|j|||||kr|j||jrt||j}i}xFt|D]:} |j j j j | d} x | D]} | || jd| j <qWqW|j j j j t|jd } n&|jr |j|jf|n |j|jd } |j| |||d|qWdS) NcSs|jS)N)ra)prrrsz,RepoQueryCommand.tree_seed..)rrZrpmlibZsolvable)r .)r)rr)rrrra startswithrrrQrrurr9r6r5rVvaluesrrrrr) rir9Zaqueryr8rZusedpkgsrZstrpkgarraZpkgqueryZquerypkgrrrrs$"   zRepoQueryCommand.tree_seed)r3r4)N)F)Nr)rN)r/r0r1__doc__rZ FORM_NAMEZFORM_NAZ FORM_NEVRArtuplekeysaliasesrZsummary staticmethodr:rbrjrxrrrrrrrrrrrrrrr2cs,  0  Hr2c@sDeZdZdZddZddZeddZedd Z ed d Z d S) rz>Wrapper for dnf.package.Package, so we can control formatting.cCs ||_dS)N)_pkg)rirrrr__init__szPackageWrapper.__init__cCsFt|j|}|dkrdSt|tr:djtdd|DStjj|S)Nz(none)r cSsh|]}tjj|qSr)rrr)rZreldeprrr sz-PackageWrapper.__getattr__..) rr isinstancerVrrrrr)riattrZatrrrr __getattr__s   zPackageWrapper.__getattr__cCs&|dkrtjj|}|jdSdSdS)Nrz%Y-%m-%d %H:%Mr")datetimeZutcfromtimestampr~)ryrrrr_get_timestamps  zPackageWrapper._get_timestampcCs|j|jjS)N)rr buildtime)rirrrrszPackageWrapper.buildtimecCs|j|jjS)N)rr installtime)rirrrrszPackageWrapper.installtimeN) r/r0r1rrrrrpropertyrrrrrrrs   r)"Z __future__rrrZdnf.i18nrZdnf.clirZdnf.cli.option_parserrr[rrgrerrZdnf.exceptionsZ dnf.subjectZdnf.utilrZ getLoggerZloggerrZcompiler%rr#r-Z_SplitCallbackr.ZCommandr2objectrrrrrsJ        Wcommands/__pycache__/group.cpython-36.pyc000064400000024356151030066770014356 0ustar003 g:@sddlmZddlmZddlmZddlmZddlmZm Z ddl Z ddlZ ddl Z ddlZ ddlZejdZGdd d ejZdS) )absolute_import)unicode_literals) CompsQuery)commands)_ucdNdnfcseZdZdZdddddddZd-eejZed Z d dd Z d.Z d/Z ddZ fddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zed%d&Zd'd(Zd)d*Zd+d,ZZS)0 GroupCommandz; Single sub-command interface for most groups interaction. listinstallremoveinfo)Z grouplistZ groupinstallZ groupupdateZ groupremoveZ grouperaseZ groupinfogroupgroupsgrpz'display, or use, the groups informationupgrade)updateZerasesummarymarkcCsn|jj|jj}|r<|jjdk r4|jjjd|jj||j_|jjdkrPd|j_|jj|jj|jj|j_dS)Nrr)direct_commandsgetoptsZcommandsubcmdargsinsert _CMD_ALIASES)selfZdirectr/usr/lib/python3.6/group.py _canonical6s   zGroupCommand._canonicalcstt|j|d|_dS)NF)superr __init___remark)rcli) __class__rrr!CszGroupCommand.__init__cCs$td}t|jjs tjj|dS)Nz4No group data available for configured repositories.)rlenbasecompsr exceptionsZ CompsError)rmsgrrr _assert_compsGs zGroupCommand._assert_compscsTfdd}j|dkr(jjj}njjjdj|}tjjt tjj ||S)Ncsjjjj|j}| S)N)r&historyenvrid)r,Z env_found)rrravailable_predMsz7GroupCommand._environment_lists..available_pred,) r*r&r' environmentsenvironments_by_patternjoinrutilZmapallr partition)rpatternsr.envsr)rr_environment_listsLs   zGroupCommand._environment_listsc sfdd}g}g}j|dkr0jjj}njjjdj|}x2|D]*}|}||r^|}| sj|jrJ|j|qJW||fS)Ncsjjjj|j}|rdSdS)NTF)r&r+rrr-)rZ group_found)rrrinstalled_predZsz1GroupCommand._group_lists..installed_predr/)r*r&r'rgroups_by_patternr2 uservisibleappend) rr:r5r8 installed availableZgrpsrZtgt_listr)rr _group_listsYs    zGroupCommand._group_listscCs~xt|D]l}d}x&|jjj|D]}|jj|d}qWx&|jjj|D]}|jj|d}qFW|stjt d|qWdgfS)NFTz!Warning: Group %s does not exist.r) r&r'r1outputZdisplay_groups_in_environmentr9Zdisplay_pkgs_in_groupsloggererrorr)ruserlistZstrngZ group_matchedr,rrrr_infoqs   zGroupCommand._infocsd}d}d}|jjjp|jjxz|r|ddkr@d}|jdq |ddkr\d}|jdq |ddkrxd}|jdq |ddkrd|jdq Pq W|jjrd}|jjrd}|jjrd}|sd}d}|dk r@x\|D]T}|jj }t |j |dk}t |j |dk} | r| rt jtd d |d}qW|r@dgfS|j|\} } |j||\} } fd d }fd d}|s|td| |s|td| |s dx,| D]$}|jrq|td|dqWdx,| D]$}|jsq|td|dqW|rdgfSdx,| D]$}|jr2q"|td|dq"Wdx,| D]$}|jsdqT|td|dqTWdgfS)Nrhiddenr<r=idsTFzWarning: No groups match:z %scs`s t|d|jdk r|jntd}r:|d|j7}|jrN|d|j7}tdj|dS)Nz %sz z (%s)z [%s]z{})printui_namerr- lang_onlyformat)sectrr))done print_idsrr_out_grpsz$GroupCommand._list.._out_grpcsT|r t|xB|D]:}d|jdk r(|jntd}rD|d|j7}t|qWdS)Nz %sz z (%s))rGrHrr-)rKr6er))rMrr_out_envs z$GroupCommand._list.._out_envzAvailable Environment Groups:zInstalled Environment Groups:zInstalled Groups:zInstalled Language Groups:zAvailable Groups:zAvailable Language Groups:)r&confverboserrFpoprEr<r=r'r%r9r1r@rArr7r>rI)rrBr:Z showinstalledZ showavailableZerrsrr'Zin_groupZin_environmentZenv_instZ env_availr<r=rNrPr)rLrMr_lists                    zGroupCommand._listc Cst|jj|jjtjtjBtjtjB}|jj}|j |}|j j rXt |jj jdg}nt |jj j}tjj|}x|jD]}|j||qzWx|jD]}|j||qWdS)Noptional)rr&r'r+GROUPS ENVIRONMENTSZ AVAILABLE INSTALLED_build_comps_solverrr with_optionaltuplerQgroup_package_typeslibdnfZ transactionZlistToCompsPackageTyper0Z_environment_installrZ_group_install) rr5qsolverrestypesZ pkg_typesenv_idZgroup_idrrr _mark_installs      zGroupCommand._mark_installcCst|jj|jjtjtjBtj}|jj}|j|}x(|j D]}t j j |sPt |j|qd}|j||\}}dd}d}x|D]}|jrlq`|d7}q`W|td|d}x|D]}|jsq|d7}qW|td|d}x|D]}|jrq|d7}qW|td |d}x|D]}|jsq|d7}qW|td |dgfS) NrDrrEcSs|sdStjd||dS)Nz%s %u)r@r )rKZnumrrrrNsz'GroupCommand._summary.._out_grpzInstalled Groups:zInstalled Language Groups:FzAvailable Groups:zAvailable Language Groups:)r%rSrrEr>rIr)rrBr:r<r=rNrLrrrr_summary sH           zGroupCommand._summaryc Cs|jddtdd|j}|jddtdd|jddtdd|jd dtd d|jd dtd d|jd ddtdjtjddjtjddd|jdddtdddS)Nz--with-optional store_truez$include optional packages from group)actionhelpz--hiddenzshow also hidden groupsz --installedzshow only installed groupsz --availablezshow only available groupsz--idszshow also ID of groupsr?ZCOMMANDz'available subcommands: {} (default), {}rz, rD)nargsmetavarrlr*Z COMMAND_ARGzargument for group subcommand) add_argumentrZadd_mutually_exclusive_grouprJr _GROUP_SUBCOMMANDSr2)parserZ grpparserrrr set_argparser<s"       zGroupCommand.set_argparsercCs|j|jj}|jj}||jkrBtjtddj|jt j j |d krf| rf|j j j |t j j |j j}d|_|d krd|_d|_|dkrd|_d |_nd|_|dkrtj|j|d krtj|j|j dS) Nz$Invalid groups sub-command, use: %s.z, r r rr TrF)r r rr )r rr r)r r)rrrrrrr@Zcriticalrr2rr#ZCliErrorZ optparserZ print_helpdemandsZsack_activationZ root_userZ resolvingZ allow_erasingZavailable_reposrZ_checkEnabledRepor&Z _checkGPGKey)rcmdrrurrr configurePs.   zGroupCommand.configurecCs|jj}|jj}|dkr"|j|S|dkr4|j|S|dkrF|j|S|dkr|j|\}}|dkrn|j|S|dkszt|j |S|dkr0|jj rt |j j jdg}nt |j j j}d|_y|j j|||j j jStjjk r.}z6td }tj||j jjj|tjjtd WYdd}~XnX|d krF|j j|S|dkrx<|D]4}y|j j|gWntjjk rYnXqVWdS) Nrr r rr r rUTzNo package %s available.z)Unable to find a mandatory group package.r)rrrrirTrCrhrerdrcrZr[r&rQr\r"Zenv_group_installstrictrr(Z MarkingErrorrr@r r?ZtermZboldZPackagesNotAvailableErrorZenv_group_upgradeZenv_group_removeError)rrvrgrrarOr)argrrrrunosF             zGroupCommand.runcCsf|js dS|jj}|jj}|j}x@|jjjjj|dD]$}|j j |}|j ||j ||q:WdS)N)name) r"r&Z_goalr+Z group_membersZsackZqueryr<ZfiltermZrpmZ get_reasonZ set_reasonZ group_reason)rZgoalr+namesZpkgreasonrrrrun_transactions zGroupCommand.run_transaction)rrr)r r )rr r r r rr)__name__ __module__ __qualname____doc__rr[keysaliasesrrrrfrrrr!r*r7r>rCrTrcrerhri staticmethodrtrwr{r __classcell__rr)r$rr $s8  h / *r )Z __future__rrZ dnf.compsrZdnf.clirZdnf.i18nrrZlibdnf.transactionr]rZdnf.exceptionsZdnf.utilZloggingZ getLoggerr@ZCommandr rrrrs     commands/__pycache__/repoquery.cpython-36.opt-1.pyc000064400000053431151030066770016210 0ustar003 ft`ن @sddlmZddlmZddlmZddlmZddlmZddlm Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZe jdZd Ze jd Zd Zd d dddddddd ZddZGddde jZGdddejZGddde Z!dS))absolute_import)print_function)unicode_literals)_)commands) OptionParserNdnfz.%{name}-%{epoch}:%{version}-%{release}.%{arch}z%(-?\d*?){([:.\w]+?)}a name, arch, epoch, version, release, reponame (repoid), from_repo, evr, debug_name, source_name, source_debug_name, installtime, buildtime, size, downloadsize, installsize, provides, requires, obsoletes, conflicts, sourcerpm, description, summary, license, url, reason conflictsenhances obsoletesprovides recommendsrequiresZ requires_presuggests supplements) r r r r r rz requires-prerrcCsdd}dd}|jddjdd}x tjD]\}}|j||}q.Wd }d }x>tj|D]0}|||||j7}|||7}|j}qZW||||d 7}|S) z:Convert a rpm like QUERYFMT to an python .format() string.cSs^|jd}|jd}|rJ|ddkr:d|dd}nd|}d|}d|j|dS) Nr-><:z{0.})groupslower)ZmatchobjZfillkeyr/usr/lib/python3.6/repoquery.pyfmt_replDs   zrpm2py_format..fmt_replcSs|jddjddS)N{z{{rz}})replace)ZtxtrrrbracketsOszrpm2py_format..bracketsz\n z\t rN)r OPTS_MAPPINGitems QFORMAT_MATCHfinditerstartend) queryformatrrrvalueZfmtspositemrrr rpm2py_formatBs   r-c@seZdZdZdS)_CommaSplitCallbackz\s*,\s*N)__name__ __module__ __qualname__ZSPLITTERrrrrr._sr.c@seZdZdZejejejdZd%e ej Z e dZ eddZedd Zd d Zd d ZddZddZd&ddZd'ddZd(ddZddZddZddZd d!Zd*d#d$ZdS)+RepoQueryCommandzSA class containing methods needed by the cli to execute the repoquery command. )z repoquery-nz repoquery-nazrepoquery-nevra repoqueryrqz$search for packages matching keywordcCs,|jr|j|jd|jr(|j|jd|S)z'Filter query by repoid and arch options)Zreponame)arch)Zrepofiltermarches)optsqueryrrrfilter_repo_archms z!RepoQueryCommand.filter_repo_archc Cs|jddddtdd|jddtdd |jd d d gtd tdd|jddddtdd|jdgtdtdd|jdgtdtdd|jdgtdtdd|jdgtdtdd|jd gtdtd!d|jd"gtdtd#d|jd$gtdtd%d|jd&gtdtd'd|jd(gtdtd)d|j}|jd*dtd+d |jd,dtd-d |jd.dtd/d |jd0dtd1d |jd2dtd3d |jd4dtd5d |jd6dtd7d |jd8d9ttd:d;|jdd?d@dAdtdBdC|jdDdEdFdAdtdGdC|jdHdIdJdAdtdKdC|jdLdMdAdtdNdC|jdOdPdQttdRdS|jdTdtdUd |jdVdQtdWtdXdY|jdZdQd[dWtd\dY|jd]dQd^dWtd_dY|jd`dtdad |j}|jdbdcdddWtdedY|jdfdcdddWtjdY|jdgdcdhdWtdidY|jdjdcdkdWtdldY|jdmdtdnd |j}tdotdptdqtdrtdstdttdutdvtdwdx }x2|jD]&\}}dy|}|j|dzdW||d{qW|jd|dtd}d td~tdtdtdj t j j dtdd} |j} x2| jD]&\} } dy| } | j| ddW| | d{q4W| jdddWdtjd{|jddtdd |jdddtdddS)Nz-az--allZqueryall store_truezNQuery all packages (shorthand for repoquery '*' or repoquery without argument))destactionhelpz--show-duplicatesz(Query all versions of packages (default))r=r>z--archz --archlistr7z[arch]z show only results from this ARCH)r<defaultr=metavarr>z-fz--fileFILE+z show only results that owns FILE)r@nargsr>z--whatconflictsZREQz#show only results that conflict REQ)r?r=r@r>z --whatdependszishows results that requires, suggests, supplements, enhances,or recommends package provides and files REQz--whatobsoletesz#show only results that obsolete REQz--whatprovidesz"show only results that provide REQz--whatrequiresz:shows results that requires package provides and files REQz--whatrecommendsz$show only results that recommend REQz--whatenhancesz"show only results that enhance REQz--whatsuggestsz"show only results that suggest REQz--whatsupplementsz%show only results that supplement REQz --alldepsz=check non-explicit dependencies (files and Provides); defaultz --exactdepsz:check dependencies exactly as given, opposite of --alldepsz --recursivezOused with --whatrequires, and --requires --resolve, query packages recursively.z --deplistz>show a list of all dependencies and what packages provide themz --resolvez.resolve capabilities to originating package(s)z--treez"show recursive tree for package(s)z--srpmz#operate on corresponding source RPMz--latest-limit latest_limitzOshow N latest packages for a given name.arch (or latest but N if N is negative))r<typer>z--disable-modular-filteringz-list also packages of inactive module streamsz-iz--info queryinfoFz+show detailed information about the package)r<r?r=r>z-lz--list queryfilelistz!show list of files in the packagez-sz--sourcequerysourcerpmzshow package source RPM namez --changelogsquerychangelogszshow changelogs of the packagez--qfz --queryformatr)zfdisplay format for listing packages: "%%{name} %%{version} ...", use --querytags to view full tag list)r<r?r>z --querytagsz-show available tags to use with --queryformatz--nevra store_constzZuse name-epoch:version-release.architecture format for displaying found packages (default))r<constr=r>z--nvrz%{name}-%{version}-%{release}zQuse name-version-release format for displaying found packages (rpm query default)z--envraz.%{epoch}:%{name}-%{version}-%{release}.%{arch}zPuse epoch:name-version-release.architecture format for displaying found packagesz --groupmemberz=Display in which comps groups are presented selected packagesz --duplicates pkgfilter duplicatedz/limit the query to installed duplicate packagesz --duplicatedz --installonly installonlyz1limit the query to installed installonly packagesz --unsatisfied unsatisfiedzClimit the query to installed packages with unsatisfied dependenciesz --locationz5show a location from where packages can be downloadedz5Display capabilities that the package conflicts with.zaDisplay capabilities that the package can depend on, enhance, recommend, suggest, and supplement.z2Display capabilities that the package can enhance.z-Display capabilities provided by the package.z1Display capabilities that the package recommends.z1Display capabilities that the package depends on.zIf the package is not installed display capabilities that it depends on for running %%pre and %%post scriptlets. If the package is installed display capabilities that is depends for %%pre, %%post, %%preun and %%postun.z/Display capabilities that the package suggests.z5Display capabilities that the package can supplement.) r dependsr r r rz requires-prerrz--%s packageatr)r<r=rKr>z --availablez Display only available packages.z Display only installed packages.zLDisplay only packages that are not present in any of available repositories.zQDisplay only packages that provide an upgrade for some already installed package.zIDisplay only packages that can be removed by "{prog} autoremove" command.)progz2Display only packages that were installed by user.) installedZextrasZupgradesunneeded userinstalledlistz --autoremoverTz--recentz%Display only recently edited packagesr*ZKEYzthe key to search for)rCr@r>) add_argumentrr.Zadd_mutually_exclusive_groupintQFORMAT_DEFAULTargparseZSUPPRESSr$formatrutil MAIN_PROG)parserZwhatrequiresformZoutformrLZpackage_attributeZ help_msgsargZhelp_msgnameZ help_listZ list_groupZlist_argZhelp_argZswitchrrr set_argparservs                                                                 zRepoQueryCommand.set_argparsercCs |jjs|jjtjtjddS)N)stdoutstderr)r8quietcliZredirect_loggerloggingZWARNINGINFO)selfrrr pre_configureszRepoQueryCommand.pre_configurecCsj|jjs|jj|jj}|jjrJ|jjrB|jjdd|jjnd|j_|jjrVdS|jj rx|jj rxt jj t d|jj r|jjr|jjddt|jj|jjdko|jj gst jj t d|jjs|jjr|jjp|jjst jj t d j|jjrd nd|jjr$|jjj|jjdkr@|jjd ksJ|jjrPd|_d|_|jjrfd|_dS)Nz --obsoletesz--r zOption '--resolve' has to be used together with one of the '--conflicts', '--depends', '--enhances', '--provides', '--recommends', '--requires', '--requires-pre', '--suggests' or '--supplements' optionsz --recursivez --exactdepsrzOption '--recursive' has to be used with '--whatrequires ' (optionally with '--alldeps', but not with '--exactdeps'), or with '--requires --resolve'z;argument {} requires --whatrequires or --whatdepends optionz --alldepsrSrUrNT)rSrU)r8rerfZredirect_repo_progressdemandsr rQZ_option_conflict querytagsresolverZCliErrorr recursive exactdepsany whatrequiresalldeps whatdependsr\srpmbaseZreposZenable_source_reposrVrL availableZavailable_reposZsack_activationrI changelogs)rirkrrr configures@      zRepoQueryCommand.configurec Cs|jrpg}|jdt|xH|jD]>}|d}|jd|jdtjj|dtjj|dfq$Wdj|Syht |}|j r|j j j |S|jr|j}|sttdj|tjd |S|jr|jSt|jj|SWn4tk r }ztjjt|WYdd}~XnXdS) NzChangelog for %s timestampz * %s %s %s z %a %b %d %YZauthortextr zPackage {} contains no files)file)rIappendstrrwstrftimeri18nucdjoinPackageWrapperrFruoutputZ infoOutputrGfilesprintrr\sysrdrHZ sourcerpmr-r)AttributeError exceptionsError) rir8pkgoutZchlogdtZpoZfilelisterrrbuild_format_fnGs.  z RepoQueryCommand.build_format_fncCsN|jjjjdd}x4|D],}|j|jtjj|j |jjddd}qW|S)NT)emptyF) with_providesZwith_filenames) rusackr9r6union intersectionrsubjectSubjectget_best_query)riZnevrasZ base_queryresolved_nevras_queryZnevrarrr_resolve_nevrascs  z RepoQueryCommand._resolve_nevrasNcCsD|r|n|}|j|d}|j|}|j|}|r@|j|||d}|S)N)r)done)filter differencer_do_recursive_deps)riquery_in query_selectrZquery_requiredrrrrps    z#RepoQueryCommand._do_recursive_depsFcCs|j||}|j|d}|j|j|d}|r|j|j|d}|j|j|d}|j|j|d}|j|j|d}|j|j|d}|j|j|d}|j|j|d }|j|j|d }|jjr|j||}|S) N)requires__glob)r)recommends__glob)enhances__glob)supplements__glob)suggests__glob)r )r )r)r)rrrr8rnr)rinamesr9Z all_dep_typesrZdepqueryrrr by_all_deps}s   zRepoQueryCommand.by_all_depscCs|r|n|jjjjdd}|jjjjdd}x$|jD]}|j|j|jd}q:W|j|}|rz|j |||j|d}|j|S)NT)r)r )r) rurr9r6runrrrr_get_recursive_providers_query)rir providersrtrrrrrrs z/RepoQueryCommand._get_recursive_providers_querycCsxg}g}xN|jjD]B}tjjj|d}|jdr>|j|q|r|d kr|j|qW|rt|jj|d|jj j d}|S) Nrz.rpmhttpftpr{httpsF)strictprogress)rrr{r) r8rrZpycompZurlparseendswithr|ruZadd_remote_rpmsrr)riZrpmnamesremote_packagesrZschemesrrr_add_add_remote_packagess   z)RepoQueryCommand._add_add_remote_packagesc Cs|jjrttdS|jj|j|jjj|jj r8t j nt j d}|jj r|j}i}|jj|jkrx|j|jjg|d<g}|jdd}|r|j|jjjj|d}x>|jj D]2}|jtjj|ddj|jjfd|d|}qW|}|jjr|j|jjj}|jjrX|jjr|jjd krt|jjjtjj t!d j"d d |jjnH|jjd krx|j#|jj$j%}n(|jjr|jjdkrt&||jj}|jj'dkr|jj(|}|j)|j*}n|jj'dkr|jj(|}n|jj'dkrVtjj+|j}|j,|jjj-|jjj.tj/j0|} d| _1| j2dd} | sRttj3j4| j5dS|jjsh|j}|j6|j|}|} |jj7r|j|jj7d|jj8r|j|jj8d} | j|j|j9|jj8|d}|jj:r|j|jj:d|jj;r|j|jj;d} | r | }n|j|jj;d|jj<rR|jj=rB|j|jj|jj<|}|jj?r|jj=r|j|jj?d}|j|j|jj?d}|j|j|jj?d}|j|j|jj?d}|j|j|jj?d}n|j>|jj?|d}|jj@r|j|jj@d} | j|j|j9|jj@|d}|jjArR|j|jjAd} | j|j|j9|jjA|d}|jjBr|j|jjBd} | j|j|j9|jjB|d}|jjCr|j|jjCd} | j|j|j9|jjC|d }|jjDr|jE|jjD}|jjF|dd!}|jjGrRg}xD|D]<}|jH}|dk r|jjjj||jId"d#}||j27}qW|jjjj|d}|jjJr|jj< r|jjKd9krtjj t!d,j"tj3jLd-|jM|| |jdStN}|jjKrtN} x||j2D]p}|jjdks|jj$jO|r|jjKd.kr| jP|jQ|jR|jS|jT|jUn| jPt&|tV|jjKqW|jjWr|jjd krj|j6|j|jjj}n|j6|j|jjjj}|j| d/}|jjXr|j|jY||}tN}x@|jEj2D]}|jZ|j[|j|qWn|jPd0d1| Dn|jj\r6x.|j2D]"}|j]}|dk r |jZ|q Wnv|jj^rNg}xt_tN|j2D]}|jjdksx|jj$jO|rVg}|j`d2ta|xt_d3d4|jQDD]x}|j`d5|tjj|}|j|jj}|j6|j|j}|jjbs|jE}x$|j2D]}|j`d6ta|qWqW|j`d7jc|qVW|rJtd8jc|dS|jjdrf|je|dSxD|j2D]8}|jjdks|jj$jO|rp|jZ|j[|j|qpW|r|jjfrtd8jct_|ntd7jct_|dS):N)flagsZformsT)r)r)Z ignore_caseF)rr9rSz)argument {}: not allowed with argument {}z --availablez--rTrUrMrNrO)Zverify)Z file__glob)Zconflicts__glob)r )r )Zprovides__glob)r)r)r)r)r)r )r )r)r)Zwarningsrc)raevrr5r r r r r rrrzNo valid switch specified usage: {prog} repoquery [--conflicts|--enhances|--obsoletes|--provides|--recommends|--requires|--suggest|--supplements|--whatrequires] [key] [--tree] description: For the given packages print a tree of thepackages.)rRrP)r css|]}t|VqdS)N)r}).0Zrelrrr Qsz'RepoQueryCommand.run..z package: cSsg|] }t|qSr)r})rreqrrr ]sz(RepoQueryCommand.run..z dependency: z provider: r z )r r r r r rrr)gr8rlr QUERY_TAGSrfZ _populate_update_security_filterrurr9Zdisable_modular_filteringhawkeyZIGNORE_MODULAR_EXCLUDESZAPPLY_EXCLUDESrrZcommand nevra_formsrrr6rrrrZrecentZ_recentZconfrvrVZ optparserZ print_usagerrrr\Z _unneededhistoryZswdbgetattrrLZ_get_installonly_queryrrMZ rpmdb_sackZ _configureZinstallonlypkgsZinstallonly_limitgoalZGoalZprotect_running_kernelrr]Z_format_resolve_problemsZ problem_rulesr:r{Z whatconflictsrZ whatobsoletesZ whatprovidesrqrorrsZwhatrecommendsZ whatenhancesZwhatsupplementsZ whatsuggestsrDZlatestZ_merge_update_filtersrtZ source_namerZtreerQr^ tree_seedsetZuser_installedupdaterr rrr r#rmrnraddrlocationZremote_locationZdeplistsortedr|r}verboserZ groupmember_group_member_reportrF)riqrZkwarkZpkgsZ query_resultsrrNZrpmdbrZsolvedZorqueryZrelsZquery_for_provideZ dependsqueryZpkg_listrZsrcnameZ tmp_queryr9rrZdeplist_outputrrZproviderrrrrsH                           "           zRepoQueryCommand.runc Cs&i}x.|jjjD] }tdd|jD||j<qWi}g}xr|jD]f}g}x(|jD]\}} |j| krX|j |qXW|r|j dj t |gj t |qF|j t |qFWg} xDt |jD]4\} } | j dj t | t dd| jdDqW| j dj t || r"tdj | dS)NcSsg|] }|jqSr)ra)rrrrrr}sz9RepoQueryCommand._group_member_report..$r cSsg|] }d|qS)z @r)ridrrrrs)rucompsrrZ packages_iterrrr$rar| setdefaultrrr}splitr) rir9Zpackage_conf_dictgroupZgroup_package_dictZpkg_not_in_grouprZ group_id_listZgroup_idZpackage_name_setrrZ package_listrrrrzs*  ,z%RepoQueryCommand._group_member_reportc Cs|j||}|d kr t|dSd}xtd|D] }|d7}q0Wg}x|jD]}|jt|qLWdtt|ddj|d} t|d |d| dS) Nr rz| [z: z, ]z\_ )rrrangerr|r}lenr) rilevelrr8Z pkg_stringZspacingxrZ requirepkgZreqstrrrr grow_trees   "zRepoQueryCommand.grow_treerc Cs8x0tt|jdddD]}|dks2|d kr8tn|}|jjdsT|jjdrXdS|j|||||kr|j||jrt||j}i}xFt|D]:} |j j j j | d} x | D]} | || jd| j <qWqW|j j j j t|jd } n&|jr |j|jf|n |j|jd } |j| |||d|qWdS) NcSs|jS)N)ra)prrrsz,RepoQueryCommand.tree_seed..)rrZrpmlibZsolvable)r .)r)rr)rrrra startswithrrrQrrurr9r6r5rVvaluesrrrrr) rir9Zaqueryr8rZusedpkgsrZstrpkgarraZpkgqueryZquerypkgrrrrs$"   zRepoQueryCommand.tree_seed)r3r4)N)F)Nr)rN)r/r0r1__doc__rZ FORM_NAMEZFORM_NAZ FORM_NEVRArtuplekeysaliasesrZsummary staticmethodr:rbrjrxrrrrrrrrrrrrrrr2cs,  0  Hr2c@sDeZdZdZddZddZeddZedd Z ed d Z d S) rz>Wrapper for dnf.package.Package, so we can control formatting.cCs ||_dS)N)_pkg)rirrrr__init__szPackageWrapper.__init__cCsFt|j|}|dkrdSt|tr:djtdd|DStjj|S)Nz(none)r cSsh|]}tjj|qSr)rrr)rZreldeprrr sz-PackageWrapper.__getattr__..) rr isinstancerVrrrrr)riattrZatrrrr __getattr__s   zPackageWrapper.__getattr__cCs&|dkrtjj|}|jdSdSdS)Nrz%Y-%m-%d %H:%Mr")datetimeZutcfromtimestampr~)ryrrrr_get_timestamps  zPackageWrapper._get_timestampcCs|j|jjS)N)rr buildtime)rirrrrszPackageWrapper.buildtimecCs|j|jjS)N)rr installtime)rirrrrszPackageWrapper.installtimeN) r/r0r1rrrrrpropertyrrrrrrrs   r)"Z __future__rrrZdnf.i18nrZdnf.clirZdnf.cli.option_parserrr[rrgrerrZdnf.exceptionsZ dnf.subjectZdnf.utilrZ getLoggerZloggerrZcompiler%rr#r-Z_SplitCallbackr.ZCommandr2objectrrrrrsJ        Wcommands/__pycache__/remove.cpython-36.opt-1.pyc000064400000007521151030066770015451 0ustar003 ft`@sddlmZddlmZddlmZddlmZddlmZddl Z ddl Z ddl Z ddl Z ddlZejdZGdd d ejZdS) )absolute_import)unicode_literals)commands)_) OptionParserNdnfc@sbeZdZdZejejejejejejdZde ej Z e dZ eddZd d Zd d Zd S) RemoveCommandzRemove command.)zremove-nz remove-naz remove-nevrazerase-nzerase-naz erase-nevraremoveerasermz-remove a package or packages from your systemcCsf|j}|jdddtdd|jddtjd|jddtd d|jd d td tjtd ddS)Nz --duplicates store_true duplicatedzremove duplicated packages)actiondesthelpz --duplicated)rrz--oldinstallonlyz*remove installonly packages over the limitZpackages*zPackage to removeZPACKAGE)nargsrrmetavar)Zadd_mutually_exclusive_group add_argumentrargparseZSUPPRESSrZParseSpecGroupFileCallback)parserZmgroupr/usr/lib/python3.6/remove.py set_argparser0s   zRemoveCommand.set_argparsercCs^|jj}d|_d|_d|_|jjr*d|_n0tj j rN|jj rNd|_d|_ d|_ n d|_ d|_dS)NTF)ZclidemandsZ resolvingZ root_userZsack_activationoptsr Zavailable_reposrbase WITH_MODULES grp_specsZfresh_metadataZ allow_erasing)selfrrrr configure?szRemoveCommand.configurecCs\g}|jj|jkr"|j|jjg}|jj|jj7_d}|jjrD|jjj}|jj |j }|jj |}|st j jtdx|jjD]\\}}}t|dkrq|jddy|jjt|dWnHt j jk rd} td} tj| |jjjjt|d| YnXx"|d dD]} |jj| q&WqWdS|jjr|jjj}|jj |j jd}|jjj} | dk r|j | j!| j"| j#d } | r|j | }|rx,|D]} |jj| qWnt j jtd dS|jj$r*|r*x|jj$D]&}td } tj| |jjjj|qWn|jj$rt jj%rxt j&j'j(|j}|j)|jj$}t|jj$t|krd}n|jj$}|rxB|D]:}y|jj*|grd}Wnt j jk rYnXqWxx|jjD]l}y|jj)||d WnLt j j+k r8}z*dj,|j-|jjjj|} tj.| WYdd}~XnXd}qW|sXtjtddS)NFz)No duplicated packages found for removal.T)reverserz%Installed package %s%s not available.)epochversionreleasez.No old installonly packages found for removal.zNot a valid form: %s)formsz{}: {}zNo packages marked for removal.)/rZcommand nevra_formsZ pkg_specs filenamesr rZsackZqueryZ_get_installonly_queryZ installed differencer exceptionsErrorrZ_na_dictitemslensortZ reinstallstrZPackagesNotAvailableErrorloggerZwarningoutputZtermZboldZpackage_removeZoldinstallonlyZlatestZget_running_kernelfilterr%r&r'rrmodule module_baseZ ModuleBaser Zenv_group_removeZ MarkingErrorformatvalueinfo)rr(doneqZinstonlyZdupsnameZarchZ pkgs_listZxmsgmsgZpkgZkernelZrunning_installonlyZgrp_specr7Z skipped_grpsgroupZpkg_specerrrrunPs    (             zRemoveCommand.runN)r r r )__name__ __module__ __qualname____doc__hawkeyZ FORM_NAMEZFORM_NAZ FORM_NEVRAr*tuplekeysaliasesrZsummary staticmethodrr rArrrrr#s  r)Z __future__rrZdnf.clirZdnf.i18nrZdnf.cli.option_parserrZdnf.baserrrFZdnf.exceptionsZloggingZ getLoggerr3ZCommandrrrrrs      commands/__pycache__/repolist.cpython-36.pyc000064400000016402151030066770015054 0ustar003 ft`z2@sddlmZddlmZddlmZddlmZmZmZm Z ddl m Z ddl Z ddlZ ddlZ ddlZddlZddlZddlZejdZdd Zd d Zd d ZddZGdddejZdS))absolute_import)unicode_literals)commands)_ucdfill_exact_width exact_width) OptionParserNdnfcCsd|rtjj|jjntd}|jdkr4td|S|jsFtd|St|j}td||fSdS)NunknownzNever (last: %s)zInstant (last: %s)z%s second(s) (last: %s))r utilnormalize_time_repo getTimestamprZmetadata_expire _num2ui_num)repomdZlastnumr/usr/lib/python3.6/repolist.py _expire_str%s    rcCsttjjd|dS)Nz%dT)rr Zpycompformat)rrrrr0srcCsF|jj}|jj}x,|D]$}tj||r.dStj||rdSqWdS)NTF)idlowernamefnmatch)rZpatternsridZrnmZpatrrr _repo_match4s     rcCs>d}x*|jtjdj|jdD]}||j7}qWtjjj |S)Nr)flags) reponame__eq) queryhawkeyIGNORE_EXCLUDESfiltermrZ_sizer clirZ format_number)sackrretZpkgrrr _repo_size?sr)c@s@eZdZdZdZedZeddZddZ d d Z d d Z d S)RepoListCommandzVA class containing methods needed by the cli to execute the repolist command. repolistrepoinfoz,display the configured software repositoriesc Csz|j}|jdddddtdd|jddddtd d |jd ddd td d |jddddddd gtjtdddS)Nz--all _repos_action store_constallzshow all repos)destactionconstdefaulthelpz --enabledenabledzshow enabled repos (default))r0r1r2r4z --disableddisabledzshow disabled reposrepos*zenabled-defaultZ REPOSITORYzRepository specification)nargsr3metavarchoicesr1r4)Zadd_mutually_exclusive_group add_argumentrr ZPkgNarrowCallback)parserZ repolimitrrr set_argparserNs    zRepoListCommand.set_argparsercCs |jjs|jjtjtjddS)N)stdoutstderr)optsquietr&Zredirect_loggerloggingZWARNINGINFO)selfrrr pre_configure_szRepoListCommand.pre_configurecCsT|jjs|jj|jj}|jjjs0|jjdkrpsz'RepoListCommand.run..r)keyZgreenZboldZredZnormalrzNo repositories availabler/zenabled-defaultTr6r,r5FzRepo-id : zRepo-name : zRepo-status : zRepo-revision : zRepo-tags : z, cSsi|]\}}||qSrr)rNkvrrr sz'RepoListCommand.run..zRepo-distro-tags : z[%s]: %s)r )r!zRepo-updated : zRepo-pkgs : zRepo-available-pkgs: zRepo-size : zRepo-metalink : z Updated : zRepo-mirrors : zRepo-baseurl : z %s (%d more)r zRepo-expire : zRepo-exclude : zRepo-include : zRepo-excluded : zRepo-filename :  z zrepo idZstatusz repo namez%s %sz%s %s %szTotal packages: {})rRrRrR)=rArLr7rHrIrJlistvaluessortoperator attrgetteroutputtermZFG_COLORZMODEloggerZwarningrlenrr5rKrr)r'rrappendrZmetadataZ fmtKeyValFillrZ getRevisionZgetContentTagsjoinsortedZ getDistroTagsitemsr"r#r$r%rr rrZgetMaxTimestampZmetalinkrZ mirrorlistZbaseurlZ getMirrorsrZ excludepkgsZ includepkgsZrepofilemapprintcolumnsrr)-rEargZextcmdsrJr7r^Z on_ehibegZ on_dhibegZon_hiendZtot_numZcolsZinclude_statusZrepoinfo_outputrZehibegZdhibegZhiendZ ui_enabledZ ui_endis_widZui_excludes_numr5Zui_sizerroutZtagsZdistroTagsDictZdistrorZ num_availableZui_numZui_num_availableZtsZbaseurlsZmirrorsZurlZexpireZid_lenZnm_lenZst_lenZrnameleftZtxt_ridZtxt_rnammsgrrrrunns.          "               zRepoListCommand.runN)r+r,) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodr>rFrMrlrrrrr*Fs  r*)Z __future__rrZdnf.clirZdnf.i18nrrrrZdnf.cli.option_parserr Zdnf.cli.formatr Z dnf.pycompZdnf.utilrr#rCr[Z getLoggerr_rrrr)ZCommandr*rrrrs"       commands/__pycache__/alias.cpython-36.pyc000064400000012322151030066770014301 0ustar003 ft`@sddlmZddlmZddlmZddlZddlZddlZddl Zddlm Z ddl Zddl Zddl mZejdZGdd d e jZdS) )absolute_import)print_function)unicode_literalsN)commands)_dnfc@sleZdZdZedZeddZddZddZ d d Z d d Z d dZ ddZ ddZddZddZdS) AliasCommandaliaszList or create command aliasescCsl|j}|jdddtdd|jdddtdd|jdd d d d d gtd d|jdddtdddS)Nz--enable-resolvingF store_truezenable aliases resolving)defaultactionhelpz--disable-resolvingzdisable aliases resolving subcommand?listadddeletezaction to do with aliases)nargsr choicesr r *zcommand[=result]zalias definition)rmetavarr )Zadd_mutually_exclusive_group add_argumentr)parserZ enable_groupr/usr/lib/python3.6/alias.py set_argparser*s     zAliasCommand.set_argparsercCsH|jj}|jjdkrd|_tjjj|_|jj |jj |_ |j dS)NrrT)rr) clidemandsoptsrZ root_userraliasesZAliases aliases_baseZ _load_aliasesenabledZresolving_enabled_update_config_from_options)selfrrrr configure9s   zAliasCommand.configurecCsd}|jjrd}tjtd|jjr8d}tjtd|dk rtjjt j j j sft t j j j djt jjjt j j j ddd|i|jjs||j_dS)NTzAliases are now enabledFzAliases are now disabledwmainr!)rZenable_resolvingloggerinforZdisable_resolvingospathexistsrrrZALIASES_CONF_PATHopencloseconfZ BaseConfigZwrite_raw_configfiler Z_disabled_by_environr!)r#r!rrrr"Bs z(AliasCommand._update_config_from_optionscCsi}x|jjD]}|jdd}|dj}t|jdkrLtjtd|q|jdrhtjtd|qt|dkrtjtd|q|dj||<qW|S)N=rzInvalid alias key: %s-zAlias argument has no value: %s) rr splitstriplenr'warningr startswith)r#Z new_aliasesr cmdrrr_parse_option_aliasTs    z AliasCommand._parse_option_aliascCsxtjjtjjjs&ttjjjdjytjjj tjjj}Wn4tj j k rr}zt j td|dSd}~XnX|S)Nr%zConfig error: %s)r)r*r+rrrALIASES_USER_PATHr,r-Z AliasesConfig exceptionsZ ConfigErrorr'r5r)r#r.errr_load_user_aliaseseszAliasCommand._load_user_aliasescCsdttjjjd}d}|dj|7}|d7}x*|jD]\}}|dj|dj|7}q4W|j|dS)Nr%z[main] zenabled = {} z [aliases] z{} = {}  ) r,rrrr9formatitemsjoinwrite)r# user_aliasesr!Zfileobjoutputkeyvaluerrr_store_user_aliasespsz AliasCommand._store_user_aliasescCsP|j}|j}|dkrdS|j||j||jtjtddj|j dS)NzAliases added: %sz, ) r<rupdaterFr!r'r(rr@keys)r#rr.rBrrr add_aliasesys zAliasCommand.add_aliasesc Cs|j}|j}|dkrdSg}xF|D]>}y||=|j|Wq$tk r`tjtd|Yq$Xq$W|j||jtjtddj |dS)NzAlias not found: %szAliases deleted: %sz, ) r<rappendKeyErrorr'r(rrFr!r@)r#cmdsr.rBZ valid_cmdsr7rrrremove_aliasess zAliasCommand.remove_aliasescCs~|g}y|jj|}WnHtjjk r^}z(tjtd||dj|jj |WYdd}~XnXt td|dj|fdS)Nz%s, alias %s="%s"r=z Alias %s='%s') r Z_resolverr:Errorr'errorrr@rprint)r#r7argsr;rrr list_aliass0zAliasCommand.list_aliascCs|jjstjtd|jjdkrL|j}|s>tj j td|j |dS|jjdkr|jj }|gkrxtj j td|j |dS|jj s|jjstjtddSxX|jjD]}|j|qWns      commands/__pycache__/clean.cpython-36.pyc000064400000010011151030066770014263 0ustar003 ft`t@sddlmZddlmZddlmZddlmZmZddlm Z ddlZ ddl Z ddl Z ddl Z ddlZ ddlZddlZddlZddlZejdZdd d gd gd gd gdd d gd Zd dZddZddZddZGdddejZdS))absolute_import)unicode_literals)commands)_P_)miscNdnfmetadatadbcachez expire-cachepackages)r r r z expire-cacheallccsVxPtj|D]B\}}}tjj||}x(|D] }tjj||}tjj|Vq*Wq WdS)z:Traverse dirpath recursively and yield relative filenames.N)oswalkpathrelpathjoinnormpath)dirpathrootdirsfilesbasefrr/usr/lib/python3.6/clean.py_tree1s  rcsfdd|DS)z5Yield those filenames that match any of the patterns.c3s(|] }D]}tj||r |Vq qdS)N)rematch).0rp)patternsrr <sz_filter..r)rr r)r r_filter:sr"cCsLd}xB|D]:}tjj||}tjtjjtd|t j ||d7}q W|S)z(Remove the given filenames from dirpath.rzRemoving file %s) r rrloggerlogrloggingZDDEBUGrrZunlink_f)rrcountrrrrr_clean?s   r(cs0tjjdfdd|D}tdd|DS)z:Return the repo IDs that have some cached metadata around.r c3s|]}tj|VqdS)N)rr)rr)metapatrrr!Msz _cached_repos..css|]}|r|jdVqdS)ZrepoidN)group)rmrrrr!Ns)rrepo CACHE_FILESset)rZmatchesr)r)r _cached_reposJs r/c@s0eZdZdZd ZedZeddZddZ dS) CleanCommandzSA class containing methods needed by the cli to execute the clean command. cleanzremove cached datacCs|jddtjtdddS)Ntype+zMetadata type to clean)nargschoiceshelp) add_argument _CACHE_TYPESkeysr)parserrrr set_argparserYszCleanCommand.set_argparserc Csf|jjj}tjj|d}tjj|d}tjj|jjjd}x$y|oJ|oJ|t dd|j j D}t t |}tjtddj|d|krt|}|jjjj||jdtjtddd |D}t|t||} tjtd d | | dSQRXWq>tjjk r\} z:|jjjsHtd | j} tj| tj d n| WYdd} ~ Xq>Xq>WdS)NTcss |]}t|D] }|VqqdS)N)r8)rctrrrr!gsz#CleanCommand.run..zCleaning data:  z expire-cachezCache was expiredcSsg|]}tjj|qSr)rr,r-)rr=rrr qsz$CleanCommand.run..z%d file removedz%d files removedz*Waiting for process with pid %d to finish.)!rZconfcachedirrlockZbuild_metadata_lockZbuild_download_lockZbuild_rpmdb_lockZ persistdirr.Zoptsr2listrr$debugrrr/Z_repo_persistorZexpired_to_addupdateremoveinfor(r"r exceptionsZ LockErrorZ exit_on_lockpidtimeZsleep) selfrAZmd_lockZ download_lockZ rpmdb_locktypesrZexpiredr r'emsgrrrrun_s2      zCleanCommand.runN)r1) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodr;rOrrrrr0Qs  r0)Z __future__rrZdnf.clirZdnf.i18nrrZdnf.yumrrZdnf.exceptionsZdnf.lockZ dnf.loggingZdnf.repor&r rrJZ getLoggerr$r8rr"r(r/ZCommandr0rrrrs0       commands/__pycache__/upgrademinimal.cpython-36.opt-1.pyc000064400000002117151030066770017146 0ustar003 ft`@sDddlmZddlmZddlmZddlmZGdddeZdS))absolute_import)unicode_literals)_)UpgradeCommandc@s$eZdZdZd ZedZddZdS) UpgradeMinimalCommandzSA class containing methods needed by the cli to execute the check command. upgrade-minimalupdate-minimalup-minzWupgrade, but only 'newest' package match which fixes a problem that affects your systemc CsRtj|d|_t|jj|jj|jj|jj|jj |jj |jj |jj gsNd|_ dS)NT)r configureZupgrade_minimalanyZoptsZbugfixZ enhancementZ newpackageZsecurityZadvisoryZbugzillaZcvesZseverityZ all_security)selfr $/usr/lib/python3.6/upgrademinimal.pyr "s  zUpgradeMinimalCommand.configureN)rrr )__name__ __module__ __qualname____doc__aliasesrZsummaryr r r r rrsrN)Z __future__rrZdnf.i18nrZdnf.cli.commands.upgraderrr r r rs    commands/__pycache__/swap.cpython-36.opt-1.pyc000064400000003537151030066770015131 0ustar003 ft`s @s`ddlmZddlmZddlmZddlmZddlZddl Z e j dZ Gdddej Z dS) )absolute_import)unicode_literals)_)commandsNdnfc@sLeZdZdZdZedjejj dZ e ddZ ddZ d d Zd d Zd S) SwapCommandzNA class containing methods needed by the cli to execute the swap command. swapz=run an interactive {prog} mod for remove and install one spec)progcCs,|jddtdd|jddtdddS)N remove_specZstorezThe specs that will be removed)actionhelp install_specz The specs that will be installed) add_argumentr)parserr/usr/lib/python3.6/swap.py set_argparser&s zSwapCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|jtj |j|j j gdS)NT) clidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseZ_checkEnabledRepooptsr )selfrrrr configure,szSwapCommand.configurecCs@|jjj|}|dk r<||j}|jjj|||g|jdS)N)rZ cli_commandsgetZ optparserZparse_command_argsrun)rZcmd_strspecZcmd_clscmdrrr_perform5s  zSwapCommand._performcCs$|jd|jj|jd|jjdS)NremoveZinstall)rrr r )rrrrr<szSwapCommand.runN)r)__name__ __module__ __qualname____doc__aliasesrformatrutilZMAIN_PROG_UPPERZsummary staticmethodrrrrrrrrrs   r)Z __future__rrZdnf.i18nrZdnf.clirZdnf.utilrZloggingZ getLoggerZloggerZCommandrrrrrs     commands/__pycache__/shell.cpython-36.opt-1.pyc000064400000017277151030066770015274 0ustar003 ft`l&@sddlmZddlmZmZddlZddlZddlZddlZddl Z ddl Z ddl Z e j dZ GdddeZGdddejejZdS) )commands)_ucdNdnfc@seZdZdZdZdZdZdS)ShellDemandSheetTN)__name__ __module__ __qualname__Zavailable_reposZ resolvingZ root_userZsack_activationr r /usr/lib/python3.6/shell.pyr%src @seZdZd*ZedjejjdZ dddddddd d d d Z d dZ e ddZ ddZddZddZddZd+ddZd,ddZd-ddZd.d d!Zd"d#Zd/d$d%Zd0d&d'Zd1d(d)ZdS)2 ShellCommandshellshzrun an interactive {prog} shell)progrepoquitZts_run transactionconfigresolvehelp) r repositoryexitrruntsrr resolvedeprcCs$tjj||tjj|d|_dS)Nz> )rCommand__init__cmdCmdprompt)selfclir r r r=s zShellCommand.__init__cCs*|jddtdtdjtjjdddS)Nscript?ZSCRIPTzScript to run in {prog} shell)r)nargsmetavarr) add_argumentrformatrutilMAIN_PROG_UPPER)parserr r r set_argparserBszShellCommand.set_argparserc Csr|jj}t|j_xZt|D]N}|jdr,qyt|jj|Wqtk rht|jj|t||YqXqWdS)N__)r!demandsrdir startswithgetattrAttributeErrorsetattr)r Zdefault_demandsattrr r r configureHs  zShellCommand.configurecCs$|jjr|j|jjn|jdS)N)optsr" _run_scriptZcmdloop)r r r r rUszShellCommand.runcCs |jjd|j_|jjdS)N)baseZ_finalize_base _transaction fill_sack)r r r r _clean[s zShellCommand._cleancCs`| s|dkrdS|dkrd}ytj|}Wn|jdS|jjjdd|jjj|}|jdkrldS|j|jkrt |d|j|j|ddn|jj j |j}|dk rT||j}y|jjj ||}Wnt k rdSXy&tj|jj|j_|j|jWn@tjjk rP}ztjtd d t|dSd}~XnXn|jdS) N ZEOFrF)Z reset_usager rzError: )shlexsplit_helpr! optparserrZparse_main_argsZcommandMAPPINGr0Z cli_commandsgetZparse_command_args SystemExitcopydeepcopyr-r4rr exceptionsErrorloggererrorrr)r lineZs_liner5Zcmd_clsrer r r onecmd`s<  $   zShellCommand.onecmdNc Csdd}| st|dkr(|jddS|d}t|dkrD|dnd}|jd}|d kr|d|}||dd}|jjj|}x|D]}||||qW|stjtd|n||||jj dS) Nc SsP|rt|||n:ytdj|t|t|WntjtdYnXdS)Nz{}: {}zUnsupported key value.)r2printr'r0strrIwarningr)keyvalconfr r r print_or_sets z*ShellCommand._config..print_or_setrrr<.zCould not find repository: %s) lenr@findr7repos get_matchingrIrPrrS) r argsrTrQrRZperiodZ repo_namerZrr r r _configs"      zShellCommand._configcCst|trt|dkr|dn|}d}|r|dkrBtdj|}n|dkrZtdj|}nv|dkrrtd j|}n^|d krtd j|}nF|dkrtdj|}n.|dkrtdj|}n|dkrtdj|}|s|jjjtd}td|dS)zOutput help information. :param args: the command to output help information about. If *args* is an empty, general help will be output. rNrz{} arg [value] arg: debuglevel, errorlevel, obsoletes, gpgcheck, assumeyes, exclude, repo_id.gpgcheck, repo_id.exclude If no value is given it prints the current value. If value is given it sets that value.rz{} [command] print helprrz{} arg [option] list: lists repositories and their status. option = [all | id | glob] enable: enable repositories. option = repository id disable: disable repositories. option = repository idrz"{} resolve the transaction setrrzy{} arg list: lists the contents of the transaction reset: reset (zero-out) the transaction run: run the transactionrz{} run the transactionrrz{} exit the shellaShell specific arguments: config set config options help print help repository (or repo) enable, disable or list repositories resolvedep resolve the transaction set transaction (or ts) list, reset or run the transaction set run resolve and run the transaction set exit (or quit) exit the shellr;)rr)rr)rr) isinstancelistrXrr'r!rAZ print_helprN)r r\argmsgr r r r@s:"  zShellCommand._helpcCs|r |dnd}|d kr6|jddj|ddn|dkr|jjj}d}x\|ddD]L}|j|}|r~t||d }qZtjt d dt d |jj j j |qZW|r|jj d|j_n |jd dS)Nrr_z repolist r=r<enabledisableFTzError:zUnknown repo: '%s'r)r_N)rbrc)rMjoinr!r7rZr[r0rIZcriticalroutputtermboldr9Z_compsr@)r r\rrZr9rrr r r _repos"     zShellCommand._repocCsLy|jjj|jjjWn.tjjk rF}zt|WYdd}~XnXdS)N) r!r7rr-Z allow_erasingrrGZ DepsolveErrorrN)r r\rLr r r _resolveszShellCommand._resolvecCsyDt|d0}|j}x |D]}|jds|j|qWWdQRXWn:tk r~tjtd|jj j j |t j dYnXdS)Nrh#z!Error: Cannot open %s for readingr<)open readlinesr/rMIOErrorrIinforr7rerfrgsysr)r filefdlinesrKr r r r6s   zShellCommand._run_scriptcCs|r |dnd}|dkr$|jdS|j|d krZ|jjr|jjj|jj}tj|nz|dkry|jjWn@t j j k r}z tj t ddt|WYdd}~XnXtjt d|jn |jddS) Nrresetr_rzError:r=z Complete!r)r_N)r:rjr7r8reZlist_transactionrIroZdo_transactionrrGrHrJrrr@)r r\routrLr r r r8 s" , zShellCommand._transactioncCs|jdgdS)Nr)r8)r r\r r r _ts_run"szShellCommand._ts_runcCstjtdtjddS)Nz Leaving Shellr)rIrorrpr)r r\r r r _quit%szShellCommand._quit)r r)N)N)N)N)N)N)N)rrr aliasesrr'rr(r)ZsummaryrBr staticmethodr+r4rr:rMr]r@rirjr6r8rvrwr r r r r ,s4  &  ;    r )Zdnf.clirZdnf.i18nrrZdnf.utilrrrEZloggingr>rpZ getLoggerrIobjectrrrr r r r r s  commands/__pycache__/module.cpython-36.pyc000064400000035164151030066770014506 0ustar003 ft`A@sddlmZddlmZmZddlmZddlmZddl m Z ddl Z ddl Z ddl Z ddlZddlZddlZ ddlZ GdddejZdS) )print_function)commandsCliError)_)NoModuleException)loggerNc s*eZdZGdddejZGdddeZGdddeZGdddeZGd d d eZ Gd d d eZ Gd ddeZ GdddeZ GdddeZ GdddeZGdddeZGdddeZeeee e e e e eeeh ZehZd%ZedZfddZddZdd Zd!d"Zd#d$ZZS)& ModuleCommandcs,eZdZfddZddZddZZS)zModuleCommand.SubCommandcs(ttj|j|tjjj|j|_dS)N) superr SubCommand__init__dnfmodule module_baseZ ModuleBasebase)selfcli) __class__/usr/lib/python3.6/module.pyr (sz!ModuleCommand.SubCommand.__init__c Cst}x|jjD]}|jj|\}}|dkr.q|jr:|jnd}|jrJ|jnd}|jr^|jdksd|jrxt j t dj ||j r|j nd}|jjj||dd|}|j|qW|S)NzjOnly module name, stream, architecture or profile is used. Ignoring unneeded information in argument: '{}')setopts module_specr _get_modulesnamestreamversioncontextrinforformatarchr_moduleContainerqueryupdate) rmodules_from_specsr__Znsvcaprrr"modulesrrr#_get_modules_from_name_stream_specs,s zs   z3ModuleCommand.SubCommand._get_module_artifact_names)__name__ __module__ __qualname__r r)r, __classcell__rr)rrr &s r c@s(eZdZdZedZddZddZdS) zModuleCommand.ListSubCommandlistz,list all module streams, profiles and statescCs|jj}d|_d|_dS)NT)rdemandsavailable_repossack_activation)rr2rrr configureRsz&ModuleCommand.ListSubCommand.configurecCs|j}|jjr&|j|jjtjjj}nV|jj rF|j|jjtjjj }n6|jj rf|j|jjtjjj }n|j|jjtjjj }|rt|dS|jjrtd}tjj|dS)NzNo matching Modules to list)rrenabledZ_get_brief_descriptionrlibdnfr ModulePackageContainerZModuleState_ENABLEDdisabledZModuleState_DISABLED installedZModuleState_INSTALLEDZModuleState_UNKNOWNprintrr exceptionsError)rZmodsoutputmsgrrr run_on_moduleWs(z*ModuleCommand.ListSubCommand.run_on_moduleN)r1)r-r.r/aliasesrsummaryr5r@rrrrListSubCommandMsrCc@s(eZdZdZedZddZddZdS) zModuleCommand.InfoSubCommandr z)print detailed information about a modulecCs|jj}d|_d|_dS)NT)rr2r3r4)rr2rrrr5tsz&ModuleCommand.InfoSubCommand.configurecCsf|jjr|jj|jj}n*|jjr4|jj|jj}n|jj|jj}|rRt|nt j j t ddS)NzNo matching Modules to list) rverboserZ_get_full_inforprofileZ_get_info_profilesZ _get_infor;r r<r=r)rr>rrrr@ys z*ModuleCommand.InfoSubCommand.run_on_moduleN)r )r-r.r/rArrBr5r@rrrrInfoSubCommandosrFc@s(eZdZdZedZddZddZdS) zModuleCommand.EnableSubCommandenablezenable a module streamcCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4 resolving root_user)rr2rrrr5s z(ModuleCommand.EnableSubCommand.configurecCsy|jj|jjWnltjjk r}zL|jjj rb|j s@|j rD||j rb|j dt jjjkrb|tjt|WYdd}~XnXdS)Nr)rrGrrr r< MarkingErrorsrconfstrictno_match_group_specserror_group_specsmodule_depsolv_errorsr7r r8!ModuleErrorType_ERROR_IN_DEFAULTSrerrorstr)rerrrr@s   z,ModuleCommand.EnableSubCommand.run_on_moduleN)rG)r-r.r/rArrBr5r@rrrrEnableSubCommandsrTc@s(eZdZdZedZddZddZdS) zModuleCommand.DisableSubCommanddisablez%disable a module with all its streamscCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z)ModuleCommand.DisableSubCommand.configurecCsy|jj|jjWnltjjk r}zL|jjj rb|j s@|j rD||j rb|j dt jjjkrb|tjt|WYdd}~XnXdS)Nr)rrUrrr r<rJrrKrLrMrNrOr7r r8rPrrQrR)rrSrrrr@s   z-ModuleCommand.DisableSubCommand.run_on_moduleN)rU)r-r.r/rArrBr5r@rrrrDisableSubCommandsrVc@s(eZdZdZedZddZddZdS) zModuleCommand.ResetSubCommandresetzreset a modulecCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z'ModuleCommand.ResetSubCommand.configurecCsby|jj|jjWnHtjjk r\}z(|jjj r>|j r>|t j t |WYdd}~XnXdS)N)rrWrrr r<rJrrKrLrMrrQrR)rrSrrrr@s z+ModuleCommand.ResetSubCommand.run_on_moduleN)rW)r-r.r/rArrBr5r@rrrrResetSubCommandsrXc@s(eZdZdZedZddZddZdS) zModuleCommand.InstallSubCommandinstallz/install a module profile including its packagescCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z)ModuleCommand.InstallSubCommand.configurecCspy|jj|jj|jjjWnNtjj k rj}z.|jjjrL|j sH|j rL|t j t|WYdd}~XnXdS)N)rrYrrrrKrLr r<rJrMrNrrQrR)rrSrrrr@s  z-ModuleCommand.InstallSubCommand.run_on_moduleN)rY)r-r.r/rArrBr5r@rrrrInstallSubCommandsrZc@s(eZdZdZedZddZddZdS) zModuleCommand.UpdateSubCommandr%z0update packages associated with an active streamcCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z(ModuleCommand.UpdateSubCommand.configurecCs&|jj|jj}|r"tdj|dS)Nz, )rZupgraderrrjoin)rZ module_specsrrrr@sz,ModuleCommand.UpdateSubCommand.run_on_moduleN)r%)r-r.r/rArrBr5r@rrrrUpdateSubCommandsr\c@s(eZdZd ZedZddZddZdS) zModuleCommand.RemoveSubCommandremoveerasez3remove installed module profiles and their packagescCs0|jj}d|_d|_d|_d|_d|_d|_dS)NTF)rr2Z allow_erasingr3Zfresh_metadatarHrIr4)rr2rrrr5sz(ModuleCommand.RemoveSubCommand.configurec Cs|jj|jj}|jjr|j}|j|t\}}|j|jj j |\}}|jj j j j|d}|jj j j j|d}xF|D]>}||krtdj|} tj| q|jjj||jjjdqW|sdStjtjj|ddS)N)rz0Package {} belongs to multiple modules, skipping)Z clean_deps)rM)rr]rrallr)r,rrr#ZgetModulePackagessackr$r:filtermrr!rr Zgoalr^rKZclean_requirements_on_removerQr r<rJ) rZskipped_groupsr&Zremove_names_from_specr'Z keep_namesZ remove_queryZ keep_querypkgr?rrrr@s&  z,ModuleCommand.RemoveSubCommand.run_on_moduleN)r]r^)r-r.r/rArrBr5r@rrrrRemoveSubCommands rcc@s(eZdZdZedZddZddZdS) z ModuleCommand.SwitchToSubCommand switch-toz7switch a module to a stream and distrosync rpm packagescCs.|jj}d|_d|_d|_d|_d|jj_dS)NT) rr2r3r4rHrIrrKZmodule_stream_switch)rr2rrrr5s z*ModuleCommand.SwitchToSubCommand.configurecCsry|jj|jj|jjjdWnNtjj k rl}z.|jjjrN|j sJ|j rN|t j t|WYdd}~XnXdS)N)rL)rZ switch_torrrrKrLr r<rJrMrNrrQrR)rrSrrrr@"s  z.ModuleCommand.SwitchToSubCommand.run_on_moduleN)rd)r-r.r/rArrBr5r@rrrrSwitchToSubCommandsrec@s(eZdZdZedZddZddZdS) z ModuleCommand.ProvidesSubCommandprovideszlist modular packagescCs|jj}d|_d|_dS)NT)rr2r3r4)rr2rrrr50sz*ModuleCommand.ProvidesSubCommand.configurecCs |jj|jj}|rt|dS)N)rZ_what_providesrrr;)rr>rrrr@5sz.ModuleCommand.ProvidesSubCommand.run_on_moduleN)rf)r-r.r/rArrBr5r@rrrrProvidesSubCommand+srgc@s(eZdZdZedZddZddZdS) z!ModuleCommand.RepoquerySubCommand repoqueryz#list packages belonging to a modulecCs|jj}d|_d|_dS)NT)rr2r3r4)rr2rrrr5?sz+ModuleCommand.RepoquerySubCommand.configurec Cst}x*|jjD]}|jj|\}}|j|qW|j|t\}}t}|jjs\|jj r|j j j jj |d}x|D]} |j t| qzW|jjr|j j j jj |d}x|D]} |j t| qWdjt|} t| dS)N)Z nevra_strict)r )rrrrrr%r, availabler:rr`r$rar+rRr[sortedr;) rr&rr(r'Znames_from_specZspec_artifactsZpackage_stringsr$rbr>rrrr@Ds"  z/ModuleCommand.RepoquerySubCommand.run_on_moduleN)rh)r-r.r/rArrBr5r@rrrrRepoquerySubCommand:srlr zInteract with Modules.cs>tt|jfdd|jD}d|_dd|D|_dS)Nc3s|]}|VqdS)Nr).0subcmd)rrr dsz)ModuleCommand.__init__..cSsi|]}|jD] }||qqSr)rA)rmrnaliasrrr fsz*ModuleCommand.__init__..)r rr SUBCMDSrn_subcmd_name2obj)rrZ subcmd_objs)r)rrr bs zModuleCommand.__init__cCs|j}|jdddtdd|jdddtdd|jd d dtd d|jd d dtdd|jdddtdd|jdddtddg}g}xHt|jdddD]2}|j|jd|jdj|jd|jpdqW|jdd|ddj |d|jd d!d"td#d$dS)%Nz --enabledr6 store_truezshow only enabled modules)destactionhelpz --disabledr9zshow only disabled modulesz --installedr:z'show only installed modules or packagesz --profilerEzshow profile contentz --availablerjzshow only available packagesz--allr_zremove all modular packagescSs |jdS)Nr)rA)xrrr~sz-ModuleCommand.set_argparser..)keyrz{}: {}rrnrzri)nargschoicesmetavarrwrz module-spec*zModule specification)r}r{rw) Zadd_mutually_exclusive_group add_argumentrrkrrappendrAr!rBr[)rparserZnarrowsZsubcommand_choicesZsubcommand_helprnrrr set_argparseris8       "  zModuleCommand.set_argparserc CsZy|j|jjd|_Wn(ttfk r@|jjjtYnX|j|j_|jjdS)Nr) rsrrnrKeyErrorrZ optparserZ print_usager5)rrrrr5s   zModuleCommand.configurecCs|j|jjdS)N)check_required_argumentrnr@)rrrrrunszModuleCommand.runcCsRdd|jD}|jjd|krN|jjsNttdjtjj |jj |jjddS)NcSsg|]}|jD]}|qqSr)rA)rmrnrprrr sz9ModuleCommand.check_required_argument..rz{} {} {}: too few arguments) SUBCMDS_NOT_REQUIRED_ARGrrnrrrr!r utilZ MAIN_PROGZcommand)rZnot_required_argumentrrrrs z%ModuleCommand.check_required_argument)r )r-r.r/rCommandr rCrFrTrVrXrZr\rcrergrlrrrrArrBr rr5rrr0rr)rrr%s.'"%   r)Z __future__rZdnf.clirrZdnf.i18nrZdnf.module.exceptionsrZdnf.utilrr sysosr*r7Zdnf.module.module_baseZdnf.exceptionsrrrrrrs    commands/__pycache__/updateinfo.cpython-36.pyc000064400000033121151030066770015346 0ustar003 ft`2J@sdZddlmZddlmZddlmZddlZddlZddlZddlm Z ddl m Z ddl m Z mZdd lmZd d ZGd d d e jZdS)zUpdateInfo CLI command.)absolute_import)print_function)unicode_literalsN)commands) OptionParser)_ exact_width)unicodecCstdd|DS)z7Return maximum length of items in a non-empty iterable.css|]}t|VqdS)N)r).0itemr /usr/lib/python3.6/updateinfo.py &sz_maxlen..)max)iterabler r r _maxlen$src s.eZdZdZejedejedejedej edej ediZ ededed ed d Z d d d d d d ddZ dgee jZedZdZdddegZfddZeddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Z d.d/Z!d0d1Z"d2d3Z#d4d5Z$Z%S)6UpdateInfoCommandz)Implementation of the UpdateInfo command.bugfix enhancementsecurityunknown newpackagez Critical/Sec.zImportant/Sec.z Moderate/Sec.zLow/Sec.)Critical ImportantModerateLowlistinfosummary)zlist-updateinfoz list-securityzlist-seczinfo-updateinfoz info-securityzinfo-seczsummary-updateinfoZ updateinfoz!display advisories about packages available installedupdatesallcstt|j|d|_dS)zInitialize the command.N)superr__init___installed_query)selfcli) __class__r r r$CszUpdateInfoCommand.__init__c Cs|j}|jddddtdd|jddddtd d|jd dd dtd d|jd dddtdddddg}|j}|jddddtdd|jddddtdd|jddddtdd|jddddtdd|jd d!ddtd"d|jd#d$d%||d&tjtd'd(dS))Nz --available _availabilityr store_constz?advisories about newer versions of installed packages (default))destconstactionhelpz --installedr z?advisories about equal and older versions of installed packagesz --updatesr!zbadvisories about newer versions of those installed packages for which a newer version is availablez--allr"z3advisories about any versions of installed packagesrrrz --summary _spec_actionz$show summary of advisories (default)z--listzshow list of advisoriesz--infozshow info of advisoriesz --with-cvewith_cveF store_truez'show only advisories with CVE reference)r+defaultr-r.z --with-bzwith_bzz,show only advisories with bugzilla referencespec*ZSPECrzPackage specification)nargsmetavarchoicesr2r-r.)Zadd_mutually_exclusive_group add_argumentrrZPkgNarrowCallback)parser availabilityZcmdsZ output_formatr r r set_argparserHsD                zUpdateInfoCommand.set_argparsercCsd|jj_d|jj_|jj|jkr6|j|jj|j_n|jjrJ|jj|j_|jj r`|jj |j_ n:|jj s||jj d|j kr|j |j_ n|jj jd|j_ t|j_|jjr|jjjtj|jjr|jjjtj|jjr|jjjtj|jjr|jjjtj|jj r|jj jd}|dkr:|jjjtjn|dkrV|jjjtjnp|d krr|jjjtjnT|dkr|jjjtjn8|d krd|j_n$|d krd|j_n|jj jd||jjr|jj j|jjd S)zADo any command-specific configuration based on command arguments.Trrrrsecr bugzillasbzscvesN)rr=)r>r?) r'ZdemandsZavailable_reposZsack_activationoptsZcommanddirect_commands spec_actionr/r)r;r4availabilitiesavailability_defaultpopset_advisory_typesraddhawkeyADVISORY_BUGFIXrADVISORY_ENHANCEMENTrADVISORY_NEWPACKAGErADVISORY_SECURITYr3r0insertadvisoryextend)r&r4r r r configurensJ                zUpdateInfoCommand.configurecCs|jjdkr$|j|jj}td}n^|jjdkrH|j|jj}td}n:|jjdkrl|j|jj}td}n|j|jj}td}|jjdkr|j |n$|jjdkr|j |n |j ||dS)z#Execute the command with arguments.r r!r"rrrN) rAr;installed_apkg_adv_instsr4rupdating_apkg_adv_instsall_apkg_adv_instsavailable_apkg_adv_instsrC display_list display_infodisplay_summary)r&apkg_adv_insts descriptionr r r runs           zUpdateInfoCommand.runcCs@|jdkr |jjjjj|_|jj|j|jd}t |dkS)N)nameZevr__gter) r%basesackqueryr Zapplyfilterr]evrlen)r&apackageqr r r _newer_equal_installeds z(UpdateInfoCommand._newer_equal_installedcs,|jj rJ|jj rJ|jj rJ|jj rJ|jj rJ|jj rJ|jj rJdSj|jjkr\dSt fdd|jjDrzdS|jjrj|jjkrdS|jjrt fdd|jjDrdS|jjrt fdd|jjDrdS|jjrt ddj DrdS|jjr(t ddj Dr(dSd S) NTc3s|]}tjj|VqdS)N)fnmatch fnmatchcaseid)r pat)rPr r rsz6UpdateInfoCommand._advisory_matcher..csg|]}j|qSr )Z match_bug)r Zbug)rPr r sz7UpdateInfoCommand._advisory_matcher..csg|]}j|qSr )Z match_cve)r Zcve)rPr r rkscSsg|]}|jtjkqSr )typerJ REFERENCE_CVE)r refr r r rkscSsg|]}|jtjkqSr )rlrJREFERENCE_BUGZILLA)r rnr r r rksF) rArHr4severityZbugzillar@r0r3rlany references)r&rPr )rPr _advisory_matchers2       ""  z#UpdateInfoCommand._advisory_matcherc#shxb|j|D]Tj|jj}|j|}tfdd|jjD}|sJ|r |j}||fVq WdS)z4Return (adv. package, advisory, installed) triplets.c3s|]}tjj|VqdS)N)rgrhr])r rj)rdr r rszAUpdateInfoCommand._apackage_advisory_installed..N) Zget_advisory_pkgsZ get_advisoryr^r_rsrqrAr4rf)r&Z pkgs_queryZcmptypespecsrPZadvisory_matchZapackage_matchr r )rdr _apackage_advisory_installeds   z.UpdateInfoCommand._apackage_advisory_installedcCs@|jj}|jjdd}|j}|r<|j|jj|jd}|S)z.z %*s %s)rprintrrJrMrNrKrLADVISORY_UNKNOWNrr r^confZautocheck_running_kernelr'Z_check_running_kernel) r&rZr[Ztyp2cntZ label_countswidthindentlabelcountr r r rYs2 $ z!UpdateInfoCommand.display_summaryc sfdd}fdd}t}x|D]\}}}d|j|j|jf}jjsRjjrx|jD]Z} | jt j krxjj rxqZn| jt j krjj rqZ|j|j f|j |||jft| j<qZWq$|j|j f|j |||jft|j<q$Wg} d} } } xt|jddd D]r\\}}}}t| t|} xR|jD]F\}}t| t|} ||}t| t|} | j||||||fq.WqWxZ| D]R\}}}}}jjjrtd || || || ||fntd || || ||fqWd S) zDisplay the list of advisories.cs jjdksdS|rdSdSdS)Nr"zi z )rAr;)inst)r&r r inst2mark2s  z1UpdateInfoCommand.display_list..inst2markcs2|tjkrjj|tdSjj|tdSdS)Nz Unknown/Sec.r)rJrNSECURITY2LABELgetr TYPE2LABEL)typZsev)r&r r type2label:s z2UpdateInfoCommand.display_list..type2labelz%s-%s.%srcSs|dS)Nrr )xr r r Rsz0UpdateInfoCommand.display_list..)keyz%s%-*s %-*s %-*s %sz%s%-*s %-*s %sN)dictr]rbarchrAr0r3rrrlrJrormrp setdefaultupdatedrisorteditemsrrcappendr^rverboser)r&rZrrZnevra_inst_dictrrPr ZnevrarnZadvlistZidwZtlwZnwrZaupdatedrZaidZatypesevrr )r&r rW0s4   *( $$ zUpdateInfoCommand.display_listc sjjjjjjtdtdtdtdtdtdtdtdtd td f fd d }t}x"|D]\}}}|j|||qtWtd j t |ddddS)z/Display the details about available advisories.z Update IDZTypeZUpdatedZBugsZCVEsZ DescriptionZSeverityZRightsZFilesZ Installedc s|jgjj|jtdgt|jggg|jp0dj|j g|j pBdjt t fdd|j Ddg }xV|jD]L}|jtjkr|djdj|j|jpdqn|jtjkrn|dj|jqnW|dj|djsd|d<d|d <jjd kr|rtd ntd g|d <t}g}|jdd|jd|j|jddxxt|D]j\}}|ddgfkrtqXxJt|D]>\}} |dkr|nd} |t| } |jd| d| | fq~WqXWdj|S)Nrrc3s|]}|jkr|jVqdS)N)rfilename)r Zpkg)archesr r rsszHUpdateInfoCommand.display_info..advisory2info..z{} - {}rr"trueZfalse =Oz rz %*s%s: %s )rirrrlrr rr[ splitlinesrpZrightsrrGZpackagesrrrJrorformattitlermsortrAr;rzip enumeraterjoin) rPr Z attributesrnrlinesrZ atr_linesilinerZ key_padding)rlabelsr&rr r advisory2infoisF          "z5UpdateInfoCommand.display_info..advisory2infoz cSs|jS)N)lower)rr r r rsz0UpdateInfoCommand.display_info..)rN) r^r_Z list_archesrrrrGrIrrr)r&rZrZ advisoriesrrPr r )rrr&rr rXas  (zUpdateInfoCommand.display_info)&__name__ __module__ __qualname____doc__rJrKrrLrNrrMrrrBrkeysaliasesrrErDr$ staticmethodr<rRr\rfrsrurzrVrSrTrUrrYrWrX __classcell__r r )r(r r)sJ        &6   1r)rZ __future__rrrrrgrJZdnf.clirZdnf.cli.option_parserrZdnf.i18nrrZ dnf.pycompr rZCommandrr r r r s      commands/__pycache__/check.cpython-36.opt-1.pyc000064400000007213151030066770015227 0ustar003 ft`?@sVddlmZddlmZddlmZddlmZddlZddlZ Gdddej Z dS))absolute_import)unicode_literals)_)commandsNc@s8eZdZdZd ZedZeddZddZ dd Z d S) CheckCommandzSA class containing methods needed by the cli to execute the check command. checkz#check for problems in the packagedbc Cs|jddddtdd|jddddtd d|jd ddd td d|jd dddtdd|jddddtdd|jddddd ddggtjddS)Nz--all check_typesZ append_constallzshow all problems; default)destactionconsthelpz--dependencies dependencieszshow dependency problemsz --duplicates duplicateszshow duplicate problemsz --obsoleted obsoletedzshow obsoleted packagesz --providesprovideszshow problems with providescheck_yum_types*)nargschoicesr ) add_argumentrargparseZSUPPRESS)parserr/usr/lib/python3.6/check.py set_argparser$s$     zCheckCommand.set_argparsercCsxd|jj_|jjr<|jjr0|jj|jj|j_n |jj|j_|jjsPdh|j_nt|jj|j_|jjj dg7_ dS)NTr ) ZcliZdemandsZsack_activationoptsrrsetbaseconfZdisable_excludes)selfrrr configure;s   zCheckCommand.configurec Cst}|jjjj}|jjjddhrd}x||D]r}xt|jtt|j t|j BD]}t |j drtq`t |j|gds`t |j dr|dkrtjj|j}tjj|}|jt |dtjj|}|jjj|_|j|dd|j}|rq`td} |j| j|jjjj||jjjj|q`Wxx|jD]n} |j| gt | j d d } xJ| D]B} d } |j| j|jjjj||jjjj| |jjjj| q^Wq8Wq6W|jjjdd hrN|jj!|} |j"j#| j$}xl|j%D]`\}}|j&xL|d dD]<}tdj|jjjj|d |jjjj|} |j| qWqW|jjjddhrx||D]t}xl|j'D]b}|j|gt |j d d }t |rttdj|jjjj|d |jjjj|} |j| qtWqhW|jjjddhr\xf|D]^}xV|j(D]L}||j|gdkrtd} |j| j|jjjj||jjjj|qWqWxt)|D]} t*| qfW|rtj+j,djt |dS)Nr rZrpmlib)r(F)ZselectZoptionalz{} has missing requires of {}r)rnamez"{} has installed conflict "{}": {}rz{} is a duplicate with {}rz{} is obsoleted by {}rz%{} provides {} but it cannot be foundzCheck discovered {} problem(s))-rrsackZqueryZ installedrr intersectionZregular_requiresZ requires_preZprereq_ignoreinststr startswithlenfilterdnfZ rpmdb_sackselectorZSelectorgoalZGoalrZprotect_running_kernelZinstallrunraddformatoutputZtermZboldZ conflictssplitZ_get_installonly_queryZ duplicated differenceZ _name_dictitemssortZ obsoletesrsortedprint exceptionsError)r Z output_setqr%ZpkgZrequirer,r-ZsolvedmsgZconflictZ conflictedZ conflict_pkgZ installonlyZdupsr#ZpkgsdupZobsoleterZproviderrrr.Is(     $       zCheckCommand.runN)r) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrr!r.rrrrrs  r) Z __future__rrZdnf.i18nrZdnf.clirrZdnf.exceptionsr+ZCommandrrrrrs    commands/__pycache__/alias.cpython-36.opt-1.pyc000064400000012322151030066770015240 0ustar003 ft`@sddlmZddlmZddlmZddlZddlZddlZddl Zddlm Z ddl Zddl Zddl mZejdZGdd d e jZdS) )absolute_import)print_function)unicode_literalsN)commands)_dnfc@sleZdZdZedZeddZddZddZ d d Z d d Z d dZ ddZ ddZddZddZdS) AliasCommandaliaszList or create command aliasescCsl|j}|jdddtdd|jdddtdd|jdd d d d d gtd d|jdddtdddS)Nz--enable-resolvingF store_truezenable aliases resolving)defaultactionhelpz--disable-resolvingzdisable aliases resolving subcommand?listadddeletezaction to do with aliases)nargsr choicesr r *zcommand[=result]zalias definition)rmetavarr )Zadd_mutually_exclusive_group add_argumentr)parserZ enable_groupr/usr/lib/python3.6/alias.py set_argparser*s     zAliasCommand.set_argparsercCsH|jj}|jjdkrd|_tjjj|_|jj |jj |_ |j dS)NrrT)rr) clidemandsoptsrZ root_userraliasesZAliases aliases_baseZ _load_aliasesenabledZresolving_enabled_update_config_from_options)selfrrrr configure9s   zAliasCommand.configurecCsd}|jjrd}tjtd|jjr8d}tjtd|dk rtjjt j j j sft t j j j djt jjjt j j j ddd|i|jjs||j_dS)NTzAliases are now enabledFzAliases are now disabledwmainr!)rZenable_resolvingloggerinforZdisable_resolvingospathexistsrrrZALIASES_CONF_PATHopencloseconfZ BaseConfigZwrite_raw_configfiler Z_disabled_by_environr!)r#r!rrrr"Bs z(AliasCommand._update_config_from_optionscCsi}x|jjD]}|jdd}|dj}t|jdkrLtjtd|q|jdrhtjtd|qt|dkrtjtd|q|dj||<qW|S)N=rzInvalid alias key: %s-zAlias argument has no value: %s) rr splitstriplenr'warningr startswith)r#Z new_aliasesr cmdrrr_parse_option_aliasTs    z AliasCommand._parse_option_aliascCsxtjjtjjjs&ttjjjdjytjjj tjjj}Wn4tj j k rr}zt j td|dSd}~XnX|S)Nr%zConfig error: %s)r)r*r+rrrALIASES_USER_PATHr,r-Z AliasesConfig exceptionsZ ConfigErrorr'r5r)r#r.errr_load_user_aliaseseszAliasCommand._load_user_aliasescCsdttjjjd}d}|dj|7}|d7}x*|jD]\}}|dj|dj|7}q4W|j|dS)Nr%z[main] zenabled = {} z [aliases] z{} = {}  ) r,rrrr9formatitemsjoinwrite)r# user_aliasesr!Zfileobjoutputkeyvaluerrr_store_user_aliasespsz AliasCommand._store_user_aliasescCsP|j}|j}|dkrdS|j||j||jtjtddj|j dS)NzAliases added: %sz, ) r<rupdaterFr!r'r(rr@keys)r#rr.rBrrr add_aliasesys zAliasCommand.add_aliasesc Cs|j}|j}|dkrdSg}xF|D]>}y||=|j|Wq$tk r`tjtd|Yq$Xq$W|j||jtjtddj |dS)NzAlias not found: %szAliases deleted: %sz, ) r<rappendKeyErrorr'r(rrFr!r@)r#cmdsr.rBZ valid_cmdsr7rrrremove_aliasess zAliasCommand.remove_aliasescCs~|g}y|jj|}WnHtjjk r^}z(tjtd||dj|jj |WYdd}~XnXt td|dj|fdS)Nz%s, alias %s="%s"r=z Alias %s='%s') r Z_resolverr:Errorr'errorrr@rprint)r#r7argsr;rrr list_aliass0zAliasCommand.list_aliascCs|jjstjtd|jjdkrL|j}|s>tj j td|j |dS|jjdkr|jj }|gkrxtj j td|j |dS|jj s|jjstjtddSxX|jjD]}|j|qWns      commands/__pycache__/upgrade.cpython-36.pyc000064400000007141151030066770014642 0ustar003 ft`~@stddlmZddlmZddlZddlZddlZddlmZddl m Z ddl m Z ej dZGdd d ejZdS) )absolute_import)unicode_literalsN)commands) OptionParser)_dnfc@sXeZdZdZdZedZed d Zd d Z d dZ ddZ ddZ ddZ ddZdS)UpgradeCommandzTA class containing methods needed by the cli to execute the update command. upgradeupdate upgrade-to update-to localupdateupz,upgrade a package or packages on your systemcCs"|jddtdtjtdddS)NZpackages*zPackage to upgradeZPACKAGE)nargshelpactionmetavar) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/upgrade.py set_argparser*szUpgradeCommand.set_argparsercCsZ|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jd|_ d|_ d|_dS)zVerify that conditions are met so that this command can run. These include that there are enabled repositories with gpg keys, and that this command is being run by the root user. TN)clidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepoupgrade_minimal all_securityskipped_grp_specs)selfrrrr configure0s zUpgradeCommand.configurecCs|jr dnd}|jj|j||jd|jjs<|jjs<|jjrzd}||jO}||j O}||j O}||j O}|rdSn|j j dStjjtddS)NeqZgte)cmp_typeallFzNo packages marked for upgrade.)rrZ _populate_update_security_filterrrr pkg_specs grp_specs_update_modules _update_files_update_packages_update_groupsrZ upgrade_allr exceptionsErrorr)r!r$resultrrrrunBs       zUpgradeCommand.runcCsNt|jj}tjjr6tjjj|j}|j |jj|_ n |jj|_ t|j |kS)N) lenrr'rrZ WITH_MODULESmodule module_baseZ ModuleBaser r )r!Zgroup_specs_numr2rrrr(Vs   zUpgradeCommand._update_modulescCsd}|jjrx~|jj|jjd|jjjdD]^}y|jj|d}Wq*tjj k r}z$t j t d|jjj j|jWYdd}~Xq*Xq*W|S)NF)strictprogressTzNo match for argument: %s)rrrZadd_remote_rpmsoutputr4Zpackage_upgraderr, MarkingErrorloggerinfortermboldlocation)r!successZpkgerrrr)`s  *zUpgradeCommand._update_filescCsrd}xh|jjD]\}y|jj|d}Wqtjjk rh}z"tjt d|jj j j |WYdd}~XqXqW|S)NFTzNo match for argument: %s) rr&rr rr,r6r7r8rr5r9r:)r!r<Zpkg_specr=rrrr*ms  (zUpgradeCommand._update_packagescCs|jr|jj|jdSdS)NTF)r rZenv_group_upgrade)r!rrrr+xszUpgradeCommand._update_groupsN)r r r r r r)__name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrr"r/r(r)r*r+rrrrr#s    r)Z __future__rrZloggingZdnf.exceptionsrZdnf.baseZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZ getLoggerr7ZCommandrrrrrs      commands/__pycache__/search.cpython-36.opt-1.pyc000064400000010452151030066770015416 0ustar003 ft`@sddlmZddlmZddlmZddlZddlmZddlmZddl m Z m Z m Z ddl Z ddlZ ddlZ ddlZddlZejdZGd d d ejZdS) )absolute_import)print_function)unicode_literalsN)commands) OptionParser)ucd_C_dnfc@sPeZdZdZdZedZeddZddZ d d Z d d Z d dZ ddZ dS) SearchCommandzTA class containing methods needed by the cli to execute the search command. searchsez+search package details for the given stringc Cs<|jddtdd|jddtddgdtjtd d dS) Nz--all store_truez'search also package description and URL)actionhelp query_string+ZKEYWORDallzKeyword to search for)nargsmetavarchoicesdefaultrr) add_argumentrrZPkgNarrowCallback)parserr/usr/lib/python3.6/search.py set_argparser0s  zSearchCommand.set_argparsercs4tjdtddfdtddfdtddfdtd fffd d fd d }tjj}x(|D] }j|d|j|d|qbWjj rxd|D] }j|d|j|d|qWn:t |}t |j }x$|D]}t |j ||kr||=qWd}d} d} d} d} jjjs0jjjj|j dj} t} x|jd| dD]}jjjs~|j|j| krlqF| j|j|j||j|kr|j|}d} | |j |kr|j |} d} | |j|| kkr|j|| k} d} | r|| || d} jjj||j||qFWt |dkr0tjtddS)z0Search for simple text tags in a package object.nameZlongNamesummaryZSummary descriptionZ DescriptionZurlZURLc sy|S|SdS)Nr)attr) TRANS_TBLrr_translate_attrCsz.SearchCommand._search.._translate_attrcs^t|}tdj|}|r*td|}n td|}jjj|dj|}tt|dS)Nz & z%s Exactly Matched: %%sz%s Matched: %%sz, )maprjoinbaseoutputZ fmtSectionprintr) exact_matchZattrskeysZ trans_attrsZtrans_attrs_strZ section_textZ formatted)r#selfrr_print_section_headerIs  z4SearchCommand._search.._print_section_headerNF)pkgT)reverseZlimit_torzNo matches found.) collections OrderedDictr rr Z match_counterZ MatchCounter_search_countedoptsrlenlistr*matched_needlesr&ZconfZshowdupesfromrepossackqueryfiltermZlatestsetsortedrZarchaddZ matched_keysZmatched_haystacksr'Z matchcallbackloggerinfo)r+argsr,counterargZneedlesZpkgsr-Z used_attrsr5r)Zprint_section_headerlimitseenr)r"r#r+r_search9s`               zSearchCommand._searchcCs`d||i}tjj|r$d||i}|jjjjtjf|}x|j D]}|j |||qFW|S)Nz %s__substrz%s__glob) r utilZis_glob_patternr&r6r7r8hawkeyZICASErunr;)r+r?r!ZneedleZfdictqr-rrrr1s   zSearchCommand._search_countedcCs |jjs|jjtjtjddS)N)stdoutstderr)r2quietcliZredirect_loggerloggingZWARNINGINFO)r+rrr pre_configureszSearchCommand.pre_configurecCsD|jjs|jj|jj}d|_d|_d|_|jjp:|jj |j_dS)NTF) r2rJrKZredirect_repo_progressdemandsZavailable_reposZfresh_metadataZsack_activationrZquery_string_action)r+rOrrr configures zSearchCommand.configurecCstjtd|j|jjS)NzSearching Packages: )r<debugrrCr2r)r+rrrrFszSearchCommand.runN)r r )__name__ __module__ __qualname____doc__aliasesrr staticmethodrrCr1rNrPrFrrrrr (s O  r )Z __future__rrrr/Zdnf.clirZdnf.cli.option_parserrZdnf.i18nrrr r Zdnf.match_counterZdnf.utilrErLZ getLoggerr<ZCommandr rrrrs      commands/__pycache__/group.cpython-36.opt-1.pyc000064400000024215151030066770015307 0ustar003 g:@sddlmZddlmZddlmZddlmZddlmZm Z ddl Z ddlZ ddl Z ddlZ ddlZejdZGdd d ejZdS) )absolute_import)unicode_literals) CompsQuery)commands)_ucdNdnfcseZdZdZdddddddZd-eejZed Z d dd Z d.Z d/Z ddZ fddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zed%d&Zd'd(Zd)d*Zd+d,ZZS)0 GroupCommandz; Single sub-command interface for most groups interaction. listinstallremoveinfo)Z grouplistZ groupinstallZ groupupdateZ groupremoveZ grouperaseZ groupinfogroupgroupsgrpz'display, or use, the groups informationupgrade)updateZerasesummarymarkcCsn|jj|jj}|r<|jjdk r4|jjjd|jj||j_|jjdkrPd|j_|jj|jj|jj|j_dS)Nrr)direct_commandsgetoptsZcommandsubcmdargsinsert _CMD_ALIASES)selfZdirectr/usr/lib/python3.6/group.py _canonical6s   zGroupCommand._canonicalcstt|j|d|_dS)NF)superr __init___remark)rcli) __class__rrr!CszGroupCommand.__init__cCs$td}t|jjs tjj|dS)Nz4No group data available for configured repositories.)rlenbasecompsr exceptionsZ CompsError)rmsgrrr _assert_compsGs zGroupCommand._assert_compscsTfdd}j|dkr(jjj}njjjdj|}tjjt tjj ||S)Ncsjjjj|j}| S)N)r&historyenvrid)r,Z env_found)rrravailable_predMsz7GroupCommand._environment_lists..available_pred,) r*r&r' environmentsenvironments_by_patternjoinrutilZmapallr partition)rpatternsr.envsr)rr_environment_listsLs   zGroupCommand._environment_listsc sfdd}g}g}j|dkr0jjj}njjjdj|}x2|D]*}|}||r^|}| sj|jrJ|j|qJW||fS)Ncsjjjj|j}|rdSdS)NTF)r&r+rrr-)rZ group_found)rrrinstalled_predZsz1GroupCommand._group_lists..installed_predr/)r*r&r'rgroups_by_patternr2 uservisibleappend) rr:r5r8 installed availableZgrpsrZtgt_listr)rr _group_listsYs    zGroupCommand._group_listscCs~xt|D]l}d}x&|jjj|D]}|jj|d}qWx&|jjj|D]}|jj|d}qFW|stjt d|qWdgfS)NFTz!Warning: Group %s does not exist.r) r&r'r1outputZdisplay_groups_in_environmentr9Zdisplay_pkgs_in_groupsloggererrorr)ruserlistZstrngZ group_matchedr,rrrr_infoqs   zGroupCommand._infocsd}d}d}|jjjp|jjxz|r|ddkr@d}|jdq |ddkr\d}|jdq |ddkrxd}|jdq |ddkrd|jdq Pq W|jjrd}|jjrd}|jjrd}|sd}d}|dk r@x\|D]T}|jj }t |j |dk}t |j |dk} | r| rt jtd d |d}qW|r@dgfS|j|\} } |j||\} } fd d }fd d}|s|td| |s|td| |s dx,| D]$}|jrq|td|dqWdx,| D]$}|jsq|td|dqW|rdgfSdx,| D]$}|jr2q"|td|dq"Wdx,| D]$}|jsdqT|td|dqTWdgfS)Nrhiddenr<r=idsTFzWarning: No groups match:z %scs`s t|d|jdk r|jntd}r:|d|j7}|jrN|d|j7}tdj|dS)Nz %sz z (%s)z [%s]z{})printui_namerr- lang_onlyformat)sectrr))done print_idsrr_out_grpsz$GroupCommand._list.._out_grpcsT|r t|xB|D]:}d|jdk r(|jntd}rD|d|j7}t|qWdS)Nz %sz z (%s))rGrHrr-)rKr6er))rMrr_out_envs z$GroupCommand._list.._out_envzAvailable Environment Groups:zInstalled Environment Groups:zInstalled Groups:zInstalled Language Groups:zAvailable Groups:zAvailable Language Groups:)r&confverboserrFpoprEr<r=r'r%r9r1r@rArr7r>rI)rrBr:Z showinstalledZ showavailableZerrsrr'Zin_groupZin_environmentZenv_instZ env_availr<r=rNrPr)rLrMr_lists                    zGroupCommand._listc Cst|jj|jjtjtjBtjtjB}|jj}|j |}|j j rXt |jj jdg}nt |jj j}tjj|}x|jD]}|j||qzWx|jD]}|j||qWdS)Noptional)rr&r'r+GROUPS ENVIRONMENTSZ AVAILABLE INSTALLED_build_comps_solverrr with_optionaltuplerQgroup_package_typeslibdnfZ transactionZlistToCompsPackageTyper0Z_environment_installrZ_group_install) rr5qsolverrestypesZ pkg_typesenv_idZgroup_idrrr _mark_installs      zGroupCommand._mark_installcCslt|jj|jjtjtjBtj}|jj}|j|}x|j D]}|j |qd}|j||\}}dd}d}x|D]}|jrlq`|d7}q`W|td|d}x|D]}|jsq|d7}qW|td|d}x|D]}|jrq|d7}qW|td |d}x|D]}|jsq|d7}qW|td |dgfS) NrDrrEcSs|sdStjd||dS)Nz%s %u)r@r )rKZnumrrrrNsz'GroupCommand._summary.._out_grpzInstalled Groups:zInstalled Language Groups:FzAvailable Groups:zAvailable Language Groups:)r%rSrrEr>rIr)rrBr:r<r=rNrLrrrr_summary sH           zGroupCommand._summaryc Cs|jddtdd|j}|jddtdd|jddtdd|jd dtd d|jd dtd d|jd ddtdjtjddjtjddd|jdddtdddS)Nz--with-optional store_truez$include optional packages from group)actionhelpz--hiddenzshow also hidden groupsz --installedzshow only installed groupsz --availablezshow only available groupsz--idszshow also ID of groupsr?ZCOMMANDz'available subcommands: {} (default), {}rz, rD)nargsmetavarrkr*Z COMMAND_ARGzargument for group subcommand) add_argumentrZadd_mutually_exclusive_grouprJr _GROUP_SUBCOMMANDSr2)parserZ grpparserrrr set_argparser<s"       zGroupCommand.set_argparsercCs|j|jj}|jj}||jkrBtjtddj|jt j j |d krf| rf|j j j |t j j |j j}d|_|d krd|_d|_|dkrd|_d |_nd|_|dkrtj|j|d krtj|j|j dS) Nz$Invalid groups sub-command, use: %s.z, r r rr TrF)r r rr )r rr r)r r)rrrrrqr@Zcriticalrr2rr#ZCliErrorZ optparserZ print_helpdemandsZsack_activationZ root_userZ resolvingZ allow_erasingZavailable_reposrZ_checkEnabledRepor&Z _checkGPGKey)rcmdrrtrrr configurePs.   zGroupCommand.configurecCs|jj}|jj}|dkr"|j|S|dkr4|j|S|dkrF|j|S|dkrx|j|\}}|dkrn|j|S|j|S|dkr$|jj rt |j j j dg}nt |j j j }d|_y|j j|||j j jStjjk r"}z6td }tj||j jjj|tjjtd WYdd}~XnX|d kr:|j j|S|dkrx<|D]4}y|j j|gWntjjk rzYnXqJWdS) Nrr r rr r rUTzNo package %s available.z)Unable to find a mandatory group package.r)rrrrhrTrCrgrdrcrZr[r&rQr\r"Zenv_group_installstrictrr(Z MarkingErrorrr@r r?ZtermZboldZPackagesNotAvailableErrorZenv_group_upgradeZenv_group_removeError)rrurfrrarOr)argrrrrunosD            zGroupCommand.runcCsf|js dS|jj}|jj}|j}x@|jjjjj|dD]$}|j j |}|j ||j ||q:WdS)N)name) r"r&Z_goalr+Z group_membersZsackZqueryr<ZfiltermZrpmZ get_reasonZ set_reasonZ group_reason)rZgoalr+namesZpkgreasonrrrrun_transactions zGroupCommand.run_transaction)rrr)r r )rr r r r rr)__name__ __module__ __qualname____doc__rr[keysaliasesrrrrerqrr!r*r7r>rCrTrcrdrgrh staticmethodrsrvrzr~ __classcell__rr)r$rr $s8  h / *r )Z __future__rrZ dnf.compsrZdnf.clirZdnf.i18nrrZlibdnf.transactionr]rZdnf.exceptionsZdnf.utilZloggingZ getLoggerr@ZCommandr rrrrs     commands/__pycache__/updateinfo.cpython-36.opt-1.pyc000064400000033121151030066770016305 0ustar003 ft`2J@sdZddlmZddlmZddlmZddlZddlZddlZddlm Z ddl m Z ddl m Z mZdd lmZd d ZGd d d e jZdS)zUpdateInfo CLI command.)absolute_import)print_function)unicode_literalsN)commands) OptionParser)_ exact_width)unicodecCstdd|DS)z7Return maximum length of items in a non-empty iterable.css|]}t|VqdS)N)r).0itemr /usr/lib/python3.6/updateinfo.py &sz_maxlen..)max)iterabler r r _maxlen$src s.eZdZdZejedejedejedej edej ediZ ededed ed d Z d d d d d d ddZ dgee jZedZdZdddegZfddZeddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Z d.d/Z!d0d1Z"d2d3Z#d4d5Z$Z%S)6UpdateInfoCommandz)Implementation of the UpdateInfo command.bugfix enhancementsecurityunknown newpackagez Critical/Sec.zImportant/Sec.z Moderate/Sec.zLow/Sec.)Critical ImportantModerateLowlistinfosummary)zlist-updateinfoz list-securityzlist-seczinfo-updateinfoz info-securityzinfo-seczsummary-updateinfoZ updateinfoz!display advisories about packages available installedupdatesallcstt|j|d|_dS)zInitialize the command.N)superr__init___installed_query)selfcli) __class__r r r$CszUpdateInfoCommand.__init__c Cs|j}|jddddtdd|jddddtd d|jd dd dtd d|jd dddtdddddg}|j}|jddddtdd|jddddtdd|jddddtdd|jddddtdd|jd d!ddtd"d|jd#d$d%||d&tjtd'd(dS))Nz --available _availabilityr store_constz?advisories about newer versions of installed packages (default))destconstactionhelpz --installedr z?advisories about equal and older versions of installed packagesz --updatesr!zbadvisories about newer versions of those installed packages for which a newer version is availablez--allr"z3advisories about any versions of installed packagesrrrz --summary _spec_actionz$show summary of advisories (default)z--listzshow list of advisoriesz--infozshow info of advisoriesz --with-cvewith_cveF store_truez'show only advisories with CVE reference)r+defaultr-r.z --with-bzwith_bzz,show only advisories with bugzilla referencespec*ZSPECrzPackage specification)nargsmetavarchoicesr2r-r.)Zadd_mutually_exclusive_group add_argumentrrZPkgNarrowCallback)parser availabilityZcmdsZ output_formatr r r set_argparserHsD                zUpdateInfoCommand.set_argparsercCsd|jj_d|jj_|jj|jkr6|j|jj|j_n|jjrJ|jj|j_|jj r`|jj |j_ n:|jj s||jj d|j kr|j |j_ n|jj jd|j_ t|j_|jjr|jjjtj|jjr|jjjtj|jjr|jjjtj|jjr|jjjtj|jj r|jj jd}|dkr:|jjjtjn|dkrV|jjjtjnp|d krr|jjjtjnT|dkr|jjjtjn8|d krd|j_n$|d krd|j_n|jj jd||jjr|jj j|jjd S)zADo any command-specific configuration based on command arguments.Trrrrsecr bugzillasbzscvesN)rr=)r>r?) r'ZdemandsZavailable_reposZsack_activationoptsZcommanddirect_commands spec_actionr/r)r;r4availabilitiesavailability_defaultpopset_advisory_typesraddhawkeyADVISORY_BUGFIXrADVISORY_ENHANCEMENTrADVISORY_NEWPACKAGErADVISORY_SECURITYr3r0insertadvisoryextend)r&r4r r r configurensJ                zUpdateInfoCommand.configurecCs|jjdkr$|j|jj}td}n^|jjdkrH|j|jj}td}n:|jjdkrl|j|jj}td}n|j|jj}td}|jjdkr|j |n$|jjdkr|j |n |j ||dS)z#Execute the command with arguments.r r!r"rrrN) rAr;installed_apkg_adv_instsr4rupdating_apkg_adv_instsall_apkg_adv_instsavailable_apkg_adv_instsrC display_list display_infodisplay_summary)r&apkg_adv_insts descriptionr r r runs           zUpdateInfoCommand.runcCs@|jdkr |jjjjj|_|jj|j|jd}t |dkS)N)nameZevr__gter) r%basesackqueryr Zapplyfilterr]evrlen)r&apackageqr r r _newer_equal_installeds z(UpdateInfoCommand._newer_equal_installedcs,|jj rJ|jj rJ|jj rJ|jj rJ|jj rJ|jj rJ|jj rJdSj|jjkr\dSt fdd|jjDrzdS|jjrj|jjkrdS|jjrt fdd|jjDrdS|jjrt fdd|jjDrdS|jjrt ddj DrdS|jjr(t ddj Dr(dSd S) NTc3s|]}tjj|VqdS)N)fnmatch fnmatchcaseid)r pat)rPr r rsz6UpdateInfoCommand._advisory_matcher..csg|]}j|qSr )Z match_bug)r Zbug)rPr r sz7UpdateInfoCommand._advisory_matcher..csg|]}j|qSr )Z match_cve)r Zcve)rPr r rkscSsg|]}|jtjkqSr )typerJ REFERENCE_CVE)r refr r r rkscSsg|]}|jtjkqSr )rlrJREFERENCE_BUGZILLA)r rnr r r rksF) rArHr4severityZbugzillar@r0r3rlany references)r&rPr )rPr _advisory_matchers2       ""  z#UpdateInfoCommand._advisory_matcherc#shxb|j|D]Tj|jj}|j|}tfdd|jjD}|sJ|r |j}||fVq WdS)z4Return (adv. package, advisory, installed) triplets.c3s|]}tjj|VqdS)N)rgrhr])r rj)rdr r rszAUpdateInfoCommand._apackage_advisory_installed..N) Zget_advisory_pkgsZ get_advisoryr^r_rsrqrAr4rf)r&Z pkgs_queryZcmptypespecsrPZadvisory_matchZapackage_matchr r )rdr _apackage_advisory_installeds   z.UpdateInfoCommand._apackage_advisory_installedcCs@|jj}|jjdd}|j}|r<|j|jj|jd}|S)z.z %*s %s)rprintrrJrMrNrKrLADVISORY_UNKNOWNrr r^confZautocheck_running_kernelr'Z_check_running_kernel) r&rZr[Ztyp2cntZ label_countswidthindentlabelcountr r r rYs2 $ z!UpdateInfoCommand.display_summaryc sfdd}fdd}t}x|D]\}}}d|j|j|jf}jjsRjjrx|jD]Z} | jt j krxjj rxqZn| jt j krjj rqZ|j|j f|j |||jft| j<qZWq$|j|j f|j |||jft|j<q$Wg} d} } } xt|jddd D]r\\}}}}t| t|} xR|jD]F\}}t| t|} ||}t| t|} | j||||||fq.WqWxZ| D]R\}}}}}jjjrtd || || || ||fntd || || ||fqWd S) zDisplay the list of advisories.cs jjdksdS|rdSdSdS)Nr"zi z )rAr;)inst)r&r r inst2mark2s  z1UpdateInfoCommand.display_list..inst2markcs2|tjkrjj|tdSjj|tdSdS)Nz Unknown/Sec.r)rJrNSECURITY2LABELgetr TYPE2LABEL)typZsev)r&r r type2label:s z2UpdateInfoCommand.display_list..type2labelz%s-%s.%srcSs|dS)Nrr )xr r r Rsz0UpdateInfoCommand.display_list..)keyz%s%-*s %-*s %-*s %sz%s%-*s %-*s %sN)dictr]rbarchrAr0r3rrrlrJrormrp setdefaultupdatedrisorteditemsrrcappendr^rverboser)r&rZrrZnevra_inst_dictrrPr ZnevrarnZadvlistZidwZtlwZnwrZaupdatedrZaidZatypesevrr )r&r rW0s4   *( $$ zUpdateInfoCommand.display_listc sjjjjjjtdtdtdtdtdtdtdtdtd td f fd d }t}x"|D]\}}}|j|||qtWtd j t |ddddS)z/Display the details about available advisories.z Update IDZTypeZUpdatedZBugsZCVEsZ DescriptionZSeverityZRightsZFilesZ Installedc s|jgjj|jtdgt|jggg|jp0dj|j g|j pBdjt t fdd|j Ddg }xV|jD]L}|jtjkr|djdj|j|jpdqn|jtjkrn|dj|jqnW|dj|djsd|d<d|d <jjd kr|rtd ntd g|d <t}g}|jdd|jd|j|jddxxt|D]j\}}|ddgfkrtqXxJt|D]>\}} |dkr|nd} |t| } |jd| d| | fq~WqXWdj|S)Nrrc3s|]}|jkr|jVqdS)N)rfilename)r Zpkg)archesr r rsszHUpdateInfoCommand.display_info..advisory2info..z{} - {}rr"trueZfalse =Oz rz %*s%s: %s )rirrrlrr rr[ splitlinesrpZrightsrrGZpackagesrrrJrorformattitlermsortrAr;rzip enumeraterjoin) rPr Z attributesrnrlinesrZ atr_linesilinerZ key_padding)rlabelsr&rr r advisory2infoisF          "z5UpdateInfoCommand.display_info..advisory2infoz cSs|jS)N)lower)rr r r rsz0UpdateInfoCommand.display_info..)rN) r^r_Z list_archesrrrrGrIrrr)r&rZrZ advisoriesrrPr r )rrr&rr rXas  (zUpdateInfoCommand.display_info)&__name__ __module__ __qualname____doc__rJrKrrLrNrrMrrrBrkeysaliasesrrErDr$ staticmethodr<rRr\rfrsrurzrVrSrTrUrrYrWrX __classcell__r r )r(r r)sJ        &6   1r)rZ __future__rrrrrgrJZdnf.clirZdnf.cli.option_parserrZdnf.i18nrrZ dnf.pycompr rZCommandrr r r r s      commands/__pycache__/upgrade.cpython-36.opt-1.pyc000064400000007141151030066770015601 0ustar003 ft`~@stddlmZddlmZddlZddlZddlZddlmZddl m Z ddl m Z ej dZGdd d ejZdS) )absolute_import)unicode_literalsN)commands) OptionParser)_dnfc@sXeZdZdZdZedZed d Zd d Z d dZ ddZ ddZ ddZ ddZdS)UpgradeCommandzTA class containing methods needed by the cli to execute the update command. upgradeupdate upgrade-to update-to localupdateupz,upgrade a package or packages on your systemcCs"|jddtdtjtdddS)NZpackages*zPackage to upgradeZPACKAGE)nargshelpactionmetavar) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/upgrade.py set_argparser*szUpgradeCommand.set_argparsercCsZ|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jd|_ d|_ d|_dS)zVerify that conditions are met so that this command can run. These include that there are enabled repositories with gpg keys, and that this command is being run by the root user. TN)clidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepoupgrade_minimal all_securityskipped_grp_specs)selfrrrr configure0s zUpgradeCommand.configurecCs|jr dnd}|jj|j||jd|jjs<|jjs<|jjrzd}||jO}||j O}||j O}||j O}|rdSn|j j dStjjtddS)NeqZgte)cmp_typeallFzNo packages marked for upgrade.)rrZ _populate_update_security_filterrrr pkg_specs grp_specs_update_modules _update_files_update_packages_update_groupsrZ upgrade_allr exceptionsErrorr)r!r$resultrrrrunBs       zUpgradeCommand.runcCsNt|jj}tjjr6tjjj|j}|j |jj|_ n |jj|_ t|j |kS)N) lenrr'rrZ WITH_MODULESmodule module_baseZ ModuleBaser r )r!Zgroup_specs_numr2rrrr(Vs   zUpgradeCommand._update_modulescCsd}|jjrx~|jj|jjd|jjjdD]^}y|jj|d}Wq*tjj k r}z$t j t d|jjj j|jWYdd}~Xq*Xq*W|S)NF)strictprogressTzNo match for argument: %s)rrrZadd_remote_rpmsoutputr4Zpackage_upgraderr, MarkingErrorloggerinfortermboldlocation)r!successZpkgerrrr)`s  *zUpgradeCommand._update_filescCsrd}xh|jjD]\}y|jj|d}Wqtjjk rh}z"tjt d|jj j j |WYdd}~XqXqW|S)NFTzNo match for argument: %s) rr&rr rr,r6r7r8rr5r9r:)r!r<Zpkg_specr=rrrr*ms  (zUpgradeCommand._update_packagescCs|jr|jj|jdSdS)NTF)r rZenv_group_upgrade)r!rrrr+xszUpgradeCommand._update_groupsN)r r r r r r)__name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrr"r/r(r)r*r+rrrrr#s    r)Z __future__rrZloggingZdnf.exceptionsrZdnf.baseZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZ getLoggerr7ZCommandrrrrrs      commands/__pycache__/module.cpython-36.opt-1.pyc000064400000035164151030066770015445 0ustar003 ft`A@sddlmZddlmZmZddlmZddlmZddl m Z ddl Z ddl Z ddl Z ddlZddlZddlZ ddlZ GdddejZdS) )print_function)commandsCliError)_)NoModuleException)loggerNc s*eZdZGdddejZGdddeZGdddeZGdddeZGd d d eZ Gd d d eZ Gd ddeZ GdddeZ GdddeZ GdddeZGdddeZGdddeZeeee e e e e eeeh ZehZd%ZedZfddZddZdd Zd!d"Zd#d$ZZS)& ModuleCommandcs,eZdZfddZddZddZZS)zModuleCommand.SubCommandcs(ttj|j|tjjj|j|_dS)N) superr SubCommand__init__dnfmodule module_baseZ ModuleBasebase)selfcli) __class__/usr/lib/python3.6/module.pyr (sz!ModuleCommand.SubCommand.__init__c Cst}x|jjD]}|jj|\}}|dkr.q|jr:|jnd}|jrJ|jnd}|jr^|jdksd|jrxt j t dj ||j r|j nd}|jjj||dd|}|j|qW|S)NzjOnly module name, stream, architecture or profile is used. Ignoring unneeded information in argument: '{}')setopts module_specr _get_modulesnamestreamversioncontextrinforformatarchr_moduleContainerqueryupdate) rmodules_from_specsr__Znsvcaprrr"modulesrrr#_get_modules_from_name_stream_specs,s zs   z3ModuleCommand.SubCommand._get_module_artifact_names)__name__ __module__ __qualname__r r)r, __classcell__rr)rrr &s r c@s(eZdZdZedZddZddZdS) zModuleCommand.ListSubCommandlistz,list all module streams, profiles and statescCs|jj}d|_d|_dS)NT)rdemandsavailable_repossack_activation)rr2rrr configureRsz&ModuleCommand.ListSubCommand.configurecCs|j}|jjr&|j|jjtjjj}nV|jj rF|j|jjtjjj }n6|jj rf|j|jjtjjj }n|j|jjtjjj }|rt|dS|jjrtd}tjj|dS)NzNo matching Modules to list)rrenabledZ_get_brief_descriptionrlibdnfr ModulePackageContainerZModuleState_ENABLEDdisabledZModuleState_DISABLED installedZModuleState_INSTALLEDZModuleState_UNKNOWNprintrr exceptionsError)rZmodsoutputmsgrrr run_on_moduleWs(z*ModuleCommand.ListSubCommand.run_on_moduleN)r1)r-r.r/aliasesrsummaryr5r@rrrrListSubCommandMsrCc@s(eZdZdZedZddZddZdS) zModuleCommand.InfoSubCommandr z)print detailed information about a modulecCs|jj}d|_d|_dS)NT)rr2r3r4)rr2rrrr5tsz&ModuleCommand.InfoSubCommand.configurecCsf|jjr|jj|jj}n*|jjr4|jj|jj}n|jj|jj}|rRt|nt j j t ddS)NzNo matching Modules to list) rverboserZ_get_full_inforprofileZ_get_info_profilesZ _get_infor;r r<r=r)rr>rrrr@ys z*ModuleCommand.InfoSubCommand.run_on_moduleN)r )r-r.r/rArrBr5r@rrrrInfoSubCommandosrFc@s(eZdZdZedZddZddZdS) zModuleCommand.EnableSubCommandenablezenable a module streamcCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4 resolving root_user)rr2rrrr5s z(ModuleCommand.EnableSubCommand.configurecCsy|jj|jjWnltjjk r}zL|jjj rb|j s@|j rD||j rb|j dt jjjkrb|tjt|WYdd}~XnXdS)Nr)rrGrrr r< MarkingErrorsrconfstrictno_match_group_specserror_group_specsmodule_depsolv_errorsr7r r8!ModuleErrorType_ERROR_IN_DEFAULTSrerrorstr)rerrrr@s   z,ModuleCommand.EnableSubCommand.run_on_moduleN)rG)r-r.r/rArrBr5r@rrrrEnableSubCommandsrTc@s(eZdZdZedZddZddZdS) zModuleCommand.DisableSubCommanddisablez%disable a module with all its streamscCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z)ModuleCommand.DisableSubCommand.configurecCsy|jj|jjWnltjjk r}zL|jjj rb|j s@|j rD||j rb|j dt jjjkrb|tjt|WYdd}~XnXdS)Nr)rrUrrr r<rJrrKrLrMrNrOr7r r8rPrrQrR)rrSrrrr@s   z-ModuleCommand.DisableSubCommand.run_on_moduleN)rU)r-r.r/rArrBr5r@rrrrDisableSubCommandsrVc@s(eZdZdZedZddZddZdS) zModuleCommand.ResetSubCommandresetzreset a modulecCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z'ModuleCommand.ResetSubCommand.configurecCsby|jj|jjWnHtjjk r\}z(|jjj r>|j r>|t j t |WYdd}~XnXdS)N)rrWrrr r<rJrrKrLrMrrQrR)rrSrrrr@s z+ModuleCommand.ResetSubCommand.run_on_moduleN)rW)r-r.r/rArrBr5r@rrrrResetSubCommandsrXc@s(eZdZdZedZddZddZdS) zModuleCommand.InstallSubCommandinstallz/install a module profile including its packagescCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z)ModuleCommand.InstallSubCommand.configurecCspy|jj|jj|jjjWnNtjj k rj}z.|jjjrL|j sH|j rL|t j t|WYdd}~XnXdS)N)rrYrrrrKrLr r<rJrMrNrrQrR)rrSrrrr@s  z-ModuleCommand.InstallSubCommand.run_on_moduleN)rY)r-r.r/rArrBr5r@rrrrInstallSubCommandsrZc@s(eZdZdZedZddZddZdS) zModuleCommand.UpdateSubCommandr%z0update packages associated with an active streamcCs$|jj}d|_d|_d|_d|_dS)NT)rr2r3r4rHrI)rr2rrrr5s z(ModuleCommand.UpdateSubCommand.configurecCs&|jj|jj}|r"tdj|dS)Nz, )rZupgraderrrjoin)rZ module_specsrrrr@sz,ModuleCommand.UpdateSubCommand.run_on_moduleN)r%)r-r.r/rArrBr5r@rrrrUpdateSubCommandsr\c@s(eZdZd ZedZddZddZdS) zModuleCommand.RemoveSubCommandremoveerasez3remove installed module profiles and their packagescCs0|jj}d|_d|_d|_d|_d|_d|_dS)NTF)rr2Z allow_erasingr3Zfresh_metadatarHrIr4)rr2rrrr5sz(ModuleCommand.RemoveSubCommand.configurec Cs|jj|jj}|jjr|j}|j|t\}}|j|jj j |\}}|jj j j j|d}|jj j j j|d}xF|D]>}||krtdj|} tj| q|jjj||jjjdqW|sdStjtjj|ddS)N)rz0Package {} belongs to multiple modules, skipping)Z clean_deps)rM)rr]rrallr)r,rrr#ZgetModulePackagessackr$r:filtermrr!rr Zgoalr^rKZclean_requirements_on_removerQr r<rJ) rZskipped_groupsr&Zremove_names_from_specr'Z keep_namesZ remove_queryZ keep_querypkgr?rrrr@s&  z,ModuleCommand.RemoveSubCommand.run_on_moduleN)r]r^)r-r.r/rArrBr5r@rrrrRemoveSubCommands rcc@s(eZdZdZedZddZddZdS) z ModuleCommand.SwitchToSubCommand switch-toz7switch a module to a stream and distrosync rpm packagescCs.|jj}d|_d|_d|_d|_d|jj_dS)NT) rr2r3r4rHrIrrKZmodule_stream_switch)rr2rrrr5s z*ModuleCommand.SwitchToSubCommand.configurecCsry|jj|jj|jjjdWnNtjj k rl}z.|jjjrN|j sJ|j rN|t j t|WYdd}~XnXdS)N)rL)rZ switch_torrrrKrLr r<rJrMrNrrQrR)rrSrrrr@"s  z.ModuleCommand.SwitchToSubCommand.run_on_moduleN)rd)r-r.r/rArrBr5r@rrrrSwitchToSubCommandsrec@s(eZdZdZedZddZddZdS) z ModuleCommand.ProvidesSubCommandprovideszlist modular packagescCs|jj}d|_d|_dS)NT)rr2r3r4)rr2rrrr50sz*ModuleCommand.ProvidesSubCommand.configurecCs |jj|jj}|rt|dS)N)rZ_what_providesrrr;)rr>rrrr@5sz.ModuleCommand.ProvidesSubCommand.run_on_moduleN)rf)r-r.r/rArrBr5r@rrrrProvidesSubCommand+srgc@s(eZdZdZedZddZddZdS) z!ModuleCommand.RepoquerySubCommand repoqueryz#list packages belonging to a modulecCs|jj}d|_d|_dS)NT)rr2r3r4)rr2rrrr5?sz+ModuleCommand.RepoquerySubCommand.configurec Cst}x*|jjD]}|jj|\}}|j|qW|j|t\}}t}|jjs\|jj r|j j j jj |d}x|D]} |j t| qzW|jjr|j j j jj |d}x|D]} |j t| qWdjt|} t| dS)N)Z nevra_strict)r )rrrrrr%r, availabler:rr`r$rar+rRr[sortedr;) rr&rr(r'Znames_from_specZspec_artifactsZpackage_stringsr$rbr>rrrr@Ds"  z/ModuleCommand.RepoquerySubCommand.run_on_moduleN)rh)r-r.r/rArrBr5r@rrrrRepoquerySubCommand:srlr zInteract with Modules.cs>tt|jfdd|jD}d|_dd|D|_dS)Nc3s|]}|VqdS)Nr).0subcmd)rrr dsz)ModuleCommand.__init__..cSsi|]}|jD] }||qqSr)rA)rmrnaliasrrr fsz*ModuleCommand.__init__..)r rr SUBCMDSrn_subcmd_name2obj)rrZ subcmd_objs)r)rrr bs zModuleCommand.__init__cCs|j}|jdddtdd|jdddtdd|jd d dtd d|jd d dtdd|jdddtdd|jdddtddg}g}xHt|jdddD]2}|j|jd|jdj|jd|jpdqW|jdd|ddj |d|jd d!d"td#d$dS)%Nz --enabledr6 store_truezshow only enabled modules)destactionhelpz --disabledr9zshow only disabled modulesz --installedr:z'show only installed modules or packagesz --profilerEzshow profile contentz --availablerjzshow only available packagesz--allr_zremove all modular packagescSs |jdS)Nr)rA)xrrr~sz-ModuleCommand.set_argparser..)keyrz{}: {}rrnrzri)nargschoicesmetavarrwrz module-spec*zModule specification)r}r{rw) Zadd_mutually_exclusive_group add_argumentrrkrrappendrAr!rBr[)rparserZnarrowsZsubcommand_choicesZsubcommand_helprnrrr set_argparseris8       "  zModuleCommand.set_argparserc CsZy|j|jjd|_Wn(ttfk r@|jjjtYnX|j|j_|jjdS)Nr) rsrrnrKeyErrorrZ optparserZ print_usager5)rrrrr5s   zModuleCommand.configurecCs|j|jjdS)N)check_required_argumentrnr@)rrrrrunszModuleCommand.runcCsRdd|jD}|jjd|krN|jjsNttdjtjj |jj |jjddS)NcSsg|]}|jD]}|qqSr)rA)rmrnrprrr sz9ModuleCommand.check_required_argument..rz{} {} {}: too few arguments) SUBCMDS_NOT_REQUIRED_ARGrrnrrrr!r utilZ MAIN_PROGZcommand)rZnot_required_argumentrrrrs z%ModuleCommand.check_required_argument)r )r-r.r/rCommandr rCrFrTrVrXrZr\rcrergrlrrrrArrBr rr5rrr0rr)rrr%s.'"%   r)Z __future__rZdnf.clirrZdnf.i18nrZdnf.module.exceptionsrZdnf.utilrr sysosr*r7Zdnf.module.module_baseZdnf.exceptionsrrrrrrs    commands/__pycache__/repolist.cpython-36.opt-1.pyc000064400000016402151030066770016013 0ustar003 ft`z2@sddlmZddlmZddlmZddlmZmZmZm Z ddl m Z ddl Z ddlZ ddlZ ddlZddlZddlZddlZejdZdd Zd d Zd d ZddZGdddejZdS))absolute_import)unicode_literals)commands)_ucdfill_exact_width exact_width) OptionParserNdnfcCsd|rtjj|jjntd}|jdkr4td|S|jsFtd|St|j}td||fSdS)NunknownzNever (last: %s)zInstant (last: %s)z%s second(s) (last: %s))r utilnormalize_time_repo getTimestamprZmetadata_expire _num2ui_num)repomdZlastnumr/usr/lib/python3.6/repolist.py _expire_str%s    rcCsttjjd|dS)Nz%dT)rr Zpycompformat)rrrrr0srcCsF|jj}|jj}x,|D]$}tj||r.dStj||rdSqWdS)NTF)idlowernamefnmatch)rZpatternsridZrnmZpatrrr _repo_match4s     rcCs>d}x*|jtjdj|jdD]}||j7}qWtjjj |S)Nr)flags) reponame__eq) queryhawkeyIGNORE_EXCLUDESfiltermrZ_sizer clirZ format_number)sackrretZpkgrrr _repo_size?sr)c@s@eZdZdZdZedZeddZddZ d d Z d d Z d S)RepoListCommandzVA class containing methods needed by the cli to execute the repolist command. repolistrepoinfoz,display the configured software repositoriesc Csz|j}|jdddddtdd|jddddtd d |jd ddd td d |jddddddd gtjtdddS)Nz--all _repos_action store_constallzshow all repos)destactionconstdefaulthelpz --enabledenabledzshow enabled repos (default))r0r1r2r4z --disableddisabledzshow disabled reposrepos*zenabled-defaultZ REPOSITORYzRepository specification)nargsr3metavarchoicesr1r4)Zadd_mutually_exclusive_group add_argumentrr ZPkgNarrowCallback)parserZ repolimitrrr set_argparserNs    zRepoListCommand.set_argparsercCs |jjs|jjtjtjddS)N)stdoutstderr)optsquietr&Zredirect_loggerloggingZWARNINGINFO)selfrrr pre_configure_szRepoListCommand.pre_configurecCsT|jjs|jj|jj}|jjjs0|jjdkrpsz'RepoListCommand.run..r)keyZgreenZboldZredZnormalrzNo repositories availabler/zenabled-defaultTr6r,r5FzRepo-id : zRepo-name : zRepo-status : zRepo-revision : zRepo-tags : z, cSsi|]\}}||qSrr)rNkvrrr sz'RepoListCommand.run..zRepo-distro-tags : z[%s]: %s)r )r!zRepo-updated : zRepo-pkgs : zRepo-available-pkgs: zRepo-size : zRepo-metalink : z Updated : zRepo-mirrors : zRepo-baseurl : z %s (%d more)r zRepo-expire : zRepo-exclude : zRepo-include : zRepo-excluded : zRepo-filename :  z zrepo idZstatusz repo namez%s %sz%s %s %szTotal packages: {})rRrRrR)=rArLr7rHrIrJlistvaluessortoperator attrgetteroutputtermZFG_COLORZMODEloggerZwarningrlenrr5rKrr)r'rrappendrZmetadataZ fmtKeyValFillrZ getRevisionZgetContentTagsjoinsortedZ getDistroTagsitemsr"r#r$r%rr rrZgetMaxTimestampZmetalinkrZ mirrorlistZbaseurlZ getMirrorsrZ excludepkgsZ includepkgsZrepofilemapprintcolumnsrr)-rEargZextcmdsrJr7r^Z on_ehibegZ on_dhibegZon_hiendZtot_numZcolsZinclude_statusZrepoinfo_outputrZehibegZdhibegZhiendZ ui_enabledZ ui_endis_widZui_excludes_numr5Zui_sizerroutZtagsZdistroTagsDictZdistrorZ num_availableZui_numZui_num_availableZtsZbaseurlsZmirrorsZurlZexpireZid_lenZnm_lenZst_lenZrnameleftZtxt_ridZtxt_rnammsgrrrrunns.          "               zRepoListCommand.runN)r+r,) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodr>rFrMrlrrrrr*Fs  r*)Z __future__rrZdnf.clirZdnf.i18nrrrrZdnf.cli.option_parserr Zdnf.cli.formatr Z dnf.pycompZdnf.utilrr#rCr[Z getLoggerr_rrrr)ZCommandr*rrrrs"       commands/__pycache__/clean.cpython-36.opt-1.pyc000064400000010011151030066770015222 0ustar003 ft`t@sddlmZddlmZddlmZddlmZmZddlm Z ddlZ ddl Z ddl Z ddl Z ddlZ ddlZddlZddlZddlZejdZdd d gd gd gd gdd d gd Zd dZddZddZddZGdddejZdS))absolute_import)unicode_literals)commands)_P_)miscNdnfmetadatadbcachez expire-cachepackages)r r r z expire-cacheallccsVxPtj|D]B\}}}tjj||}x(|D] }tjj||}tjj|Vq*Wq WdS)z:Traverse dirpath recursively and yield relative filenames.N)oswalkpathrelpathjoinnormpath)dirpathrootdirsfilesbasefrr/usr/lib/python3.6/clean.py_tree1s  rcsfdd|DS)z5Yield those filenames that match any of the patterns.c3s(|] }D]}tj||r |Vq qdS)N)rematch).0rp)patternsrr <sz_filter..r)rr r)r r_filter:sr"cCsLd}xB|D]:}tjj||}tjtjjtd|t j ||d7}q W|S)z(Remove the given filenames from dirpath.rzRemoving file %s) r rrloggerlogrloggingZDDEBUGrrZunlink_f)rrcountrrrrr_clean?s   r(cs0tjjdfdd|D}tdd|DS)z:Return the repo IDs that have some cached metadata around.r c3s|]}tj|VqdS)N)rr)rr)metapatrrr!Msz _cached_repos..css|]}|r|jdVqdS)ZrepoidN)group)rmrrrr!Ns)rrepo CACHE_FILESset)rZmatchesr)r)r _cached_reposJs r/c@s0eZdZdZd ZedZeddZddZ dS) CleanCommandzSA class containing methods needed by the cli to execute the clean command. cleanzremove cached datacCs|jddtjtdddS)Ntype+zMetadata type to clean)nargschoiceshelp) add_argument _CACHE_TYPESkeysr)parserrrr set_argparserYszCleanCommand.set_argparserc Csf|jjj}tjj|d}tjj|d}tjj|jjjd}x$y|oJ|oJ|t dd|j j D}t t |}tjtddj|d|krt|}|jjjj||jdtjtddd |D}t|t||} tjtd d | | dSQRXWq>tjjk r\} z:|jjjsHtd | j} tj| tj d n| WYdd} ~ Xq>Xq>WdS)NTcss |]}t|D] }|VqqdS)N)r8)rctrrrr!gsz#CleanCommand.run..zCleaning data:  z expire-cachezCache was expiredcSsg|]}tjj|qSr)rr,r-)rr=rrr qsz$CleanCommand.run..z%d file removedz%d files removedz*Waiting for process with pid %d to finish.)!rZconfcachedirrlockZbuild_metadata_lockZbuild_download_lockZbuild_rpmdb_lockZ persistdirr.Zoptsr2listrr$debugrrr/Z_repo_persistorZexpired_to_addupdateremoveinfor(r"r exceptionsZ LockErrorZ exit_on_lockpidtimeZsleep) selfrAZmd_lockZ download_lockZ rpmdb_locktypesrZexpiredr r'emsgrrrrun_s2      zCleanCommand.runN)r1) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodr;rOrrrrr0Qs  r0)Z __future__rrZdnf.clirZdnf.i18nrrZdnf.yumrrZdnf.exceptionsZdnf.lockZ dnf.loggingZdnf.repor&r rrJZ getLoggerr$r8rr"r(r/ZCommandr0rrrrs0       commands/__pycache__/install.cpython-36.pyc000064400000013703151030066770014662 0ustar003 ft`S@sddlmZddlmZddlZddlmZddlZddlZddl m Z ddl m Z ddl mZejdZGd d d e jZdS) )absolute_import)unicode_literalsN)chain)commands) OptionParser)_dnfc@seZdZdZejejejdZdZ de ej Z e dZedd Zd d Zd d ZddZddZddZddZddZddZddZdS)InstallCommandzUA class containing methods needed by the cli to execute the install command. )z install-nz install-naz install-nevrazalternative-for({})install localinstallinz,install a package or packages on your systemcCs"|jddtdtjtdddS)Npackage+ZPACKAGEzPackage to install)nargsmetavaractionhelp) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/install.py set_argparser1szInstallCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jdS)zVerify that conditions are met so that this command can run. That there are enabled repositories with gpg keys, and that this command is called with appropriate arguments. TN) clidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepo)selfrrrr configure7szInstallCommand.configurec CsPg}g}g}|j}|jj|j|jjdkrf|jjs>|jjrf|j|jj|jj j rft j j tdg}|jjo||jjdkrTt jjrLy,t jjj|j}|j|jj|jj j dWnt j jk rH}zp|jrx|jD]}|j|qW|jrx|jD]}|jd|qW|j} | r8tjt jjj| dWYdd}~XnXn|jj}|jjr|r|j|jj|jj j rt j j tdn|j}|r|r|j||jj j rt j j tdn|r|jjdkr|j||jjdkr|j |}t!|dks$t!|dks$|rL|jj j rLt j j"tddj#||ddS) Nr zNothing to do.)strict@rzUnable to find a match )pkg_specZpackages)$_get_nevra_forms_from_commandrZ _populate_update_security_filterrcommand grp_specs pkg_specs_log_not_valid_rpm_file_pathsrconfrr exceptionsErrorrZ WITH_MODULESmodule module_baseZ ModuleBaser Z MarkingErrorsZno_match_group_specsappendZerror_group_specsmodule_depsolv_errorsloggererrorZformat_modular_solver_errorsr_inform_not_a_valid_combination_install_files_install_groups_install_packageslenZPackagesNotAvailableErrorjoin) rerr_pkgserrsZerror_module_specs nevra_formsZskipped_grp_specsr,eZe_specr.rrrrunEsX            . zInstallCommand.runcCs&|jj|jkr|j|jjgSgSdS)N)rr$r9)rrrrr#zsz,InstallCommand._get_nevra_forms_from_commandcCsJtdd|}x6t|jj|D]$}td}tj||jjj j |qWdS)NcSsd|S)Nr r)grrrsz>InstallCommand._log_not_valid_rpm_file_paths..zNot a valid rpm file path: %s) maprrr&rr/inforoutputtermbold)rr%Z group_namespkgmsgrrrr'sz,InstallCommand._log_not_valid_rpm_file_pathscCs2x,|D]$}td}tj||jjjj|qWdS)NzNot a valid form: %s)rr/Zwarningrr@rArB)rformsZformrDrrrr1s z.InstallCommand._inform_not_a_valid_combinationc Csg}|jjj}x~|jj|jj||jjjdD]^}y|jj||dWq,t j j k rt d}t j||jjjj|j|j|Yq,Xq,W|S)N)rprogress)rzNo match for argument: %s)rr(rZadd_remote_rpmsrrr@rFZpackage_installrr) MarkingErrorrr/r?rArBlocationr-)rr7rrCrDrrrr2s zInstallCommand._install_filesc CsPy&|jj|t|jjj|jjjdWn$tjjk rJ|jjjrFYnXdS)N)r) rZenv_group_installtupler(Zgroup_package_typesrrr)r*)rr%rrrr3s  zInstallCommand._install_groupscCsV|jjjj|jj|d}|rRtd}tj|j|dj t t dd|DdS)N)Zprovidesz/There are following alternatives for "{0}": {1}z, cSsg|] }|jqSr)name).0Zaltrrr sz7InstallCommand._report_alternatives..) rZsackqueryZfiltermalternatives_provideformatrr/r?r6sortedset)rr"rMrDrrr_report_alternativess z#InstallCommand._report_alternativescCsg}|jjj}x|jjD]}y|jj|||dWqtjjk r}zJdj |j |jj j j |}tj||jj||j||j|WYdd}~XqXqW|S)N)rrEz{}: {})rr(rrr&r rr)rGrOvaluer@rArBr/r?Z_report_icase_hintrRr-)rr9r8rr"r:rDrrrr4s     z InstallCommand._install_packagesN)r r r )__name__ __module__ __qualname____doc__hawkeyZ FORM_NAMEZFORM_NAZ FORM_NEVRAr9rNrIkeysaliasesrZsummary staticmethodrrr;r#r'r1r2r3rRr4rrrrr %s"  5  r )Z __future__rrZlogging itertoolsrrXZdnf.exceptionsrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZ getLoggerr/ZCommandr rrrrs       commands/__pycache__/makecache.cpython-36.opt-1.pyc000064400000002357151030066770016057 0ustar003 ft`m@sxddlmZddlmZddlmZddlmZddlZddlZddl Zddl Zddl Z e j dZ GdddejZdS) )absolute_import)unicode_literals)commands)_Ndnfc@s,eZdZd ZedZeddZddZdS) MakeCacheCommand makecachemczgenerate the metadata cachecCs,|jdddd|jdddgdtjddS)Nz--timer store_true timer_opt)actiondesttimer?)nargschoicesmetavarhelp) add_argumentargparseZSUPPRESS)parserr/usr/lib/python3.6/makecache.py set_argparser's zMakeCacheCommand.set_argparsercCs2|jjdk p|jj}td}tj||jj|S)Nz*Making cache files for all metadata files.)Zoptsrr rloggerdebugbaseZ update_cache)selfrmsgrrrrun.s zMakeCacheCommand.runN)rr ) __name__ __module__ __qualname__aliasesrZsummary staticmethodrrrrrrr#s r)Z __future__rrZdnf.clirZdnf.i18nrrrZdnf.exceptionsZdnf.utilZloggingZ getLoggerrZCommandrrrrrs     commands/__pycache__/autoremove.cpython-36.pyc000064400000003572151030066770015405 0ustar003 ft` @stddlmZddlmZddlmZddlmZddlmZddl Z ddl Z ddl Z e j dZGdd d ejZdS) )absolute_import)unicode_literals)commands) OptionParser)_Ndnfc@sReZdZejejejdZd eej Z e dZ e ddZddZdd Zd S) AutoremoveCommand)z autoremove-nz autoremove-nazautoremove-nevra autoremovezKremove all unneeded packages that were originally installed as dependenciescCs"|jddtdtjtdddS)NZpackages*zPackage to removeZPACKAGE)nargshelpactionmetavar) add_argumentrrZParseSpecGroupFileCallback)parserr /usr/lib/python3.6/autoremove.py set_argparser,szAutoremoveCommand.set_argparsercCs\|jj}d|_d|_d|_t|jj|jj|jj grLd|j j _ d|_ d|_n d|_d|_dS)NTF)ZclidemandsZ resolvingZ root_userZsack_activationanyopts grp_specs pkg_specs filenamesbaseZconfZclean_requirements_on_removeZ allow_erasingZavailable_reposZfresh_metadata)selfrrrr configure2s zAutoremoveCommand.configurecCsjt|jj|jj|jjgr\g}|jj|jkr<|j|jjg}|jj||jj|jj|jjn |jjdS)N) rrrrrZcommand nevra_formsrr )rZformsrrrrunBs zAutoremoveCommand.runN)r )__name__ __module__ __qualname__hawkeyZ FORM_NAMEZFORM_NAZ FORM_NEVRArtuplekeysaliasesrZsummary staticmethodrrrrrrrr"s  r)Z __future__rrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZdnf.exceptionsrr"ZloggingZ getLoggerZloggerZCommandrrrrrs      commands/__pycache__/swap.cpython-36.pyc000064400000003537151030066770014172 0ustar003 ft`s @s`ddlmZddlmZddlmZddlmZddlZddl Z e j dZ Gdddej Z dS) )absolute_import)unicode_literals)_)commandsNdnfc@sLeZdZdZdZedjejj dZ e ddZ ddZ d d Zd d Zd S) SwapCommandzNA class containing methods needed by the cli to execute the swap command. swapz=run an interactive {prog} mod for remove and install one spec)progcCs,|jddtdd|jddtdddS)N remove_specZstorezThe specs that will be removed)actionhelp install_specz The specs that will be installed) add_argumentr)parserr/usr/lib/python3.6/swap.py set_argparser&s zSwapCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|jtj |j|j j gdS)NT) clidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseZ_checkEnabledRepooptsr )selfrrrr configure,szSwapCommand.configurecCs@|jjj|}|dk r<||j}|jjj|||g|jdS)N)rZ cli_commandsgetZ optparserZparse_command_argsrun)rZcmd_strspecZcmd_clscmdrrr_perform5s  zSwapCommand._performcCs$|jd|jj|jd|jjdS)NremoveZinstall)rrr r )rrrrr<szSwapCommand.runN)r)__name__ __module__ __qualname____doc__aliasesrformatrutilZMAIN_PROG_UPPERZsummary staticmethodrrrrrrrrrs   r)Z __future__rrZdnf.i18nrZdnf.clirZdnf.utilrZloggingZ getLoggerZloggerZCommandrrrrrs     commands/__pycache__/downgrade.cpython-36.pyc000064400000003413151030066770015163 0ustar003 ft` @sRddlmZddlmZddlmZddlmZddlmZGdddej Z dS) )absolute_import)unicode_literals)commands) OptionParser)_c@s8eZdZdZd ZedZeddZddZ d d Z d S) DowngradeCommandzWA class containing methods needed by the cli to execute the downgrade command. downgradedgzDowngrade a packagecCs|jddtdtjddS)Npackage*zPackage to downgrade)nargshelpaction) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/downgrade.py set_argparser$szDowngradeCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jdS)NT) ZclidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepo)selfrrrr configure)szDowngradeCommand.configurecCsJ|jj|jjd|jjjd}|jj|jjdd|jjD||jj j dS)NF)strictprogresscSsg|] }d|qS)@r).0xrrr 8sz(DowngradeCommand.run..)Zspecs file_pkgsr) rZadd_remote_rpmsrroutputrZ downgradePkgsZ pkg_specsZ grp_specsZconfr)rr rrrrun4s zDowngradeCommand.runN)rr ) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrrr"rrrrrs   rN) Z __future__rrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZCommandrrrrrs     commands/__pycache__/check.cpython-36.pyc000064400000007213151030066770014270 0ustar003 ft`?@sVddlmZddlmZddlmZddlmZddlZddlZ Gdddej Z dS))absolute_import)unicode_literals)_)commandsNc@s8eZdZdZd ZedZeddZddZ dd Z d S) CheckCommandzSA class containing methods needed by the cli to execute the check command. checkz#check for problems in the packagedbc Cs|jddddtdd|jddddtd d|jd ddd td d|jd dddtdd|jddddtdd|jddddd ddggtjddS)Nz--all check_typesZ append_constallzshow all problems; default)destactionconsthelpz--dependencies dependencieszshow dependency problemsz --duplicates duplicateszshow duplicate problemsz --obsoleted obsoletedzshow obsoleted packagesz --providesprovideszshow problems with providescheck_yum_types*)nargschoicesr ) add_argumentrargparseZSUPPRESS)parserr/usr/lib/python3.6/check.py set_argparser$s$     zCheckCommand.set_argparsercCsxd|jj_|jjr<|jjr0|jj|jj|j_n |jj|j_|jjsPdh|j_nt|jj|j_|jjj dg7_ dS)NTr ) ZcliZdemandsZsack_activationoptsrrsetbaseconfZdisable_excludes)selfrrr configure;s   zCheckCommand.configurec Cst}|jjjj}|jjjddhrd}x||D]r}xt|jtt|j t|j BD]}t |j drtq`t |j|gds`t |j dr|dkrtjj|j}tjj|}|jt |dtjj|}|jjj|_|j|dd|j}|rq`td} |j| j|jjjj||jjjj|q`Wxx|jD]n} |j| gt | j d d } xJ| D]B} d } |j| j|jjjj||jjjj| |jjjj| q^Wq8Wq6W|jjjdd hrN|jj!|} |j"j#| j$}xl|j%D]`\}}|j&xL|d dD]<}tdj|jjjj|d |jjjj|} |j| qWqW|jjjddhrx||D]t}xl|j'D]b}|j|gt |j d d }t |rttdj|jjjj|d |jjjj|} |j| qtWqhW|jjjddhr\xf|D]^}xV|j(D]L}||j|gdkrtd} |j| j|jjjj||jjjj|qWqWxt)|D]} t*| qfW|rtj+j,djt |dS)Nr rZrpmlib)r(F)ZselectZoptionalz{} has missing requires of {}r)rnamez"{} has installed conflict "{}": {}rz{} is a duplicate with {}rz{} is obsoleted by {}rz%{} provides {} but it cannot be foundzCheck discovered {} problem(s))-rrsackZqueryZ installedrr intersectionZregular_requiresZ requires_preZprereq_ignoreinststr startswithlenfilterdnfZ rpmdb_sackselectorZSelectorgoalZGoalrZprotect_running_kernelZinstallrunraddformatoutputZtermZboldZ conflictssplitZ_get_installonly_queryZ duplicated differenceZ _name_dictitemssortZ obsoletesrsortedprint exceptionsError)r Z output_setqr%ZpkgZrequirer,r-ZsolvedmsgZconflictZ conflictedZ conflict_pkgZ installonlyZdupsr#ZpkgsdupZobsoleterZproviderrrr.Is(     $       zCheckCommand.runN)r) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrr!r.rrrrrs  r) Z __future__rrZdnf.i18nrZdnf.clirrZdnf.exceptionsr+ZCommandrrrrrs    commands/__pycache__/reinstall.cpython-36.pyc000064400000005740151030066770015213 0ustar003 ft`]@slddlmZddlmZddlmZddlmZddlmZddl Z ddl Z e j dZ Gdd d ejZdS) )absolute_import)unicode_literals)commands) OptionParser)_Ndnfc@s8eZdZdZd ZedZeddZddZ d d Z d S) ReinstallCommandzSA class containing methods needed by the cli to execute the reinstall command. reinstallreizreinstall a packagecCs"|jddtdtjtdddS)Npackages+zPackage to reinstallZPACKAGE)nargshelpactionmetavar) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/reinstall.py set_argparser(szReinstallCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jdS)a Verify that conditions are met so that this command can run. These include that the program is being run by the root user, that there are enabled repositories with gpg keys, and that this command is called with appropriate arguments. TN) ZclidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepo)selfrrrr configure.szReinstallCommand.configurecCsd}xp|jj|jjd|jjjdD]P}y|jj|Wn6tjj k rlt j t d|jjj j|jYq"Xd}q"WxR|jjdd|jjDD]2}y|jj|Wntjjk r}zPx,|jD]"}t j t d|jj j|jPqWt j t d|jjj j|WYdd}~Xqtjjk r}z^xV|jD]L}d}|jjj|}|rdt d |}t d }t j ||jjj j||qLsz(ReinstallCommand.run..z(Package %s available, but not installed.z (from %s)z%Installed package %s%s not available.z+Only the above marking errors are expected.z!No packages marked for reinstall.)rZadd_remote_rpmsrroutputrZpackage_reinstallr exceptionsZ MarkingErrorloggerinforZtermZboldlocationZ pkg_specsZ grp_specsr ZPackagesNotInstalledErrorr nameZPackagesNotAvailableErrorhistoryZrepoAssertionErrorError)rdoneZpkgZpkg_specerrZxmsgZpkgrepomsgrrrrun=sB $   "  zReinstallCommand.runN)r r ) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrrr/rrrrr!s  r)Z __future__rrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZdnf.exceptionsrZloggingZ getLoggerr%ZCommandrrrrrs      commands/__pycache__/mark.cpython-36.pyc000064400000005545151030066770014153 0ustar003 ft` @spddlmZddlmZddlZddlmZddlmZddl Z ddl Z ddl Z e j dZ GdddejZdS) )print_function)unicode_literalsN)_)commandsdnfc@sLeZdZdZedZeddZddZddZ d d Z d d Z d dZ dS) MarkCommandmarkz7mark or unmark installed packages as installed by user.cCs6|jdddddgtdd|jdd d td d dS) NrZinstallremovegroupzhinstall: mark as installed by user remove: unmark as installed by user group: mark as installed by group)nargschoiceshelppackage+ZPACKAGEzPackage specification)r metavarr) add_argumentr)parserr/usr/lib/python3.6/mark.py set_argparser)s  zMarkCommand.set_argparsercCs,|jjj|tjjtjtdt |dS)Nz%s marked as user installed.) basehistory set_reasonlibdnf transactionZTransactionItemReason_USERloggerinforstr)selfpkgrrr _mark_install2szMarkCommand._mark_installcCs,|jjj|tjjtjtdt |dS)Nz%s unmarked as user installed.) rrrrrZ TransactionItemReason_DEPENDENCYrrrr)rr rrr _mark_remove6szMarkCommand._mark_removecCs,|jjj|tjjtjtdt |dS)Nz%s marked as group installed.) rrrrrZTransactionItemReason_GROUPrrrr)rr rrr _mark_group:szMarkCommand._mark_groupcCs$|jj}d|_d|_d|_d|_dS)NTF)clidemandsZsack_activationZ root_userZavailable_reposZ resolving)rr%rrr configure>s zMarkCommand.configurec Cs|jjd}|jj}tjt|d|}g}xR|D]J}tjj|}|j |j j }x|D] }||qVWt |dkr2|j |q2W|rtjtdx|D]}tjtd|qWtjj|j jj}|dkr|j j} n|j} |j jj| gg|j jj| dS)NrZ_mark_zError:zPackage %s is not installed.)Zoptsrr functoolspartialgetattrrZsubjectZSubjectZget_best_queryrZsacklenappendrerrorrr$ZCliErrorrZlastZ_rpmdb_versionZend_rpmdb_versionZbegend) rcmdZpkgsZ mark_funcZnotfoundr ZsubjqoldZ rpmdb_versionrrrrunEs,         zMarkCommand.runN)r) __name__ __module__ __qualname__aliasesrZsummary staticmethodrr!r"r#r&r1rrrrr$s r)Z __future__rrZlibdnf.transactionrZdnf.i18nrZdnf.clirrr'ZloggingZ getLoggerrZCommandrrrrrs     commands/__pycache__/downgrade.cpython-36.opt-1.pyc000064400000003413151030066770016122 0ustar003 ft` @sRddlmZddlmZddlmZddlmZddlmZGdddej Z dS) )absolute_import)unicode_literals)commands) OptionParser)_c@s8eZdZdZd ZedZeddZddZ d d Z d S) DowngradeCommandzWA class containing methods needed by the cli to execute the downgrade command. downgradedgzDowngrade a packagecCs|jddtdtjddS)Npackage*zPackage to downgrade)nargshelpaction) add_argumentrrZParseSpecGroupFileCallback)parserr/usr/lib/python3.6/downgrade.py set_argparser$szDowngradeCommand.set_argparsercCsH|jj}d|_d|_d|_d|_tj|j|j|j j sDtj |jdS)NT) ZclidemandsZsack_activationZavailable_reposZ resolvingZ root_userrZ _checkGPGKeybaseopts filenamesZ_checkEnabledRepo)selfrrrr configure)szDowngradeCommand.configurecCsJ|jj|jjd|jjjd}|jj|jjdd|jjD||jj j dS)NF)strictprogresscSsg|] }d|qS)@r).0xrrr 8sz(DowngradeCommand.run..)Zspecs file_pkgsr) rZadd_remote_rpmsrroutputrZ downgradePkgsZ pkg_specsZ grp_specsZconfr)rr rrrrun4s zDowngradeCommand.runN)rr ) __name__ __module__ __qualname____doc__aliasesrZsummary staticmethodrrr"rrrrrs   rN) Z __future__rrZdnf.clirZdnf.cli.option_parserrZdnf.i18nrZCommandrrrrrs     commands/__pycache__/search.cpython-36.pyc000064400000010452151030066770014457 0ustar003 ft`@sddlmZddlmZddlmZddlZddlmZddlmZddl m Z m Z m Z ddl Z ddlZ ddlZ ddlZddlZejdZGd d d ejZdS) )absolute_import)print_function)unicode_literalsN)commands) OptionParser)ucd_C_dnfc@sPeZdZdZdZedZeddZddZ d d Z d d Z d dZ ddZ dS) SearchCommandzTA class containing methods needed by the cli to execute the search command. searchsez+search package details for the given stringc Cs<|jddtdd|jddtddgdtjtd d dS) Nz--all store_truez'search also package description and URL)actionhelp query_string+ZKEYWORDallzKeyword to search for)nargsmetavarchoicesdefaultrr) add_argumentrrZPkgNarrowCallback)parserr/usr/lib/python3.6/search.py set_argparser0s  zSearchCommand.set_argparsercs4tjdtddfdtddfdtddfdtd fffd d fd d }tjj}x(|D] }j|d|j|d|qbWjj rxd|D] }j|d|j|d|qWn:t |}t |j }x$|D]}t |j ||kr||=qWd}d} d} d} d} jjjs0jjjj|j dj} t} x|jd| dD]}jjjs~|j|j| krlqF| j|j|j||j|kr|j|}d} | |j |kr|j |} d} | |j|| kkr|j|| k} d} | r|| || d} jjj||j||qFWt |dkr0tjtddS)z0Search for simple text tags in a package object.nameZlongNamesummaryZSummary descriptionZ DescriptionZurlZURLc sy|S|SdS)Nr)attr) TRANS_TBLrr_translate_attrCsz.SearchCommand._search.._translate_attrcs^t|}tdj|}|r*td|}n td|}jjj|dj|}tt|dS)Nz & z%s Exactly Matched: %%sz%s Matched: %%sz, )maprjoinbaseoutputZ fmtSectionprintr) exact_matchZattrskeysZ trans_attrsZtrans_attrs_strZ section_textZ formatted)r#selfrr_print_section_headerIs  z4SearchCommand._search.._print_section_headerNF)pkgT)reverseZlimit_torzNo matches found.) collections OrderedDictr rr Z match_counterZ MatchCounter_search_countedoptsrlenlistr*matched_needlesr&ZconfZshowdupesfromrepossackqueryfiltermZlatestsetsortedrZarchaddZ matched_keysZmatched_haystacksr'Z matchcallbackloggerinfo)r+argsr,counterargZneedlesZpkgsr-Z used_attrsr5r)Zprint_section_headerlimitseenr)r"r#r+r_search9s`               zSearchCommand._searchcCs`d||i}tjj|r$d||i}|jjjjtjf|}x|j D]}|j |||qFW|S)Nz %s__substrz%s__glob) r utilZis_glob_patternr&r6r7r8hawkeyZICASErunr;)r+r?r!ZneedleZfdictqr-rrrr1s   zSearchCommand._search_countedcCs |jjs|jjtjtjddS)N)stdoutstderr)r2quietcliZredirect_loggerloggingZWARNINGINFO)r+rrr pre_configureszSearchCommand.pre_configurecCsD|jjs|jj|jj}d|_d|_d|_|jjp:|jj |j_dS)NTF) r2rJrKZredirect_repo_progressdemandsZavailable_reposZfresh_metadataZsack_activationrZquery_string_action)r+rOrrr configures zSearchCommand.configurecCstjtd|j|jjS)NzSearching Packages: )r<debugrrCr2r)r+rrrrFszSearchCommand.runN)r r )__name__ __module__ __qualname____doc__aliasesrr staticmethodrrCr1rNrPrFrrrrr (s O  r )Z __future__rrrr/Zdnf.clirZdnf.cli.option_parserrZdnf.i18nrrr r Zdnf.match_counterZdnf.utilrErLZ getLoggerr<ZCommandr rrrrs      commands/__pycache__/mark.cpython-36.opt-1.pyc000064400000005545151030066770015112 0ustar003 ft` @spddlmZddlmZddlZddlmZddlmZddl Z ddl Z ddl Z e j dZ GdddejZdS) )print_function)unicode_literalsN)_)commandsdnfc@sLeZdZdZedZeddZddZddZ d d Z d d Z d dZ dS) MarkCommandmarkz7mark or unmark installed packages as installed by user.cCs6|jdddddgtdd|jdd d td d dS) NrZinstallremovegroupzhinstall: mark as installed by user remove: unmark as installed by user group: mark as installed by group)nargschoiceshelppackage+ZPACKAGEzPackage specification)r metavarr) add_argumentr)parserr/usr/lib/python3.6/mark.py set_argparser)s  zMarkCommand.set_argparsercCs,|jjj|tjjtjtdt |dS)Nz%s marked as user installed.) basehistory set_reasonlibdnf transactionZTransactionItemReason_USERloggerinforstr)selfpkgrrr _mark_install2szMarkCommand._mark_installcCs,|jjj|tjjtjtdt |dS)Nz%s unmarked as user installed.) rrrrrZ TransactionItemReason_DEPENDENCYrrrr)rr rrr _mark_remove6szMarkCommand._mark_removecCs,|jjj|tjjtjtdt |dS)Nz%s marked as group installed.) rrrrrZTransactionItemReason_GROUPrrrr)rr rrr _mark_group:szMarkCommand._mark_groupcCs$|jj}d|_d|_d|_d|_dS)NTF)clidemandsZsack_activationZ root_userZavailable_reposZ resolving)rr%rrr configure>s zMarkCommand.configurec Cs|jjd}|jj}tjt|d|}g}xR|D]J}tjj|}|j |j j }x|D] }||qVWt |dkr2|j |q2W|rtjtdx|D]}tjtd|qWtjj|j jj}|dkr|j j} n|j} |j jj| gg|j jj| dS)NrZ_mark_zError:zPackage %s is not installed.)Zoptsrr functoolspartialgetattrrZsubjectZSubjectZget_best_queryrZsacklenappendrerrorrr$ZCliErrorrZlastZ_rpmdb_versionZend_rpmdb_versionZbegend) rcmdZpkgsZ mark_funcZnotfoundr ZsubjqoldZ rpmdb_versionrrrrunEs,         zMarkCommand.runN)r) __name__ __module__ __qualname__aliasesrZsummary staticmethodrr!r"r#r&r1rrrrr$s r)Z __future__rrZlibdnf.transactionrZdnf.i18nrZdnf.clirrr'ZloggingZ getLoggerrZCommandrrrrrs     commands/swap.py000064400000004563151030066770007706 0ustar00# # Copyright (C) 2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.i18n import _ from dnf.cli import commands import dnf.util import logging logger = logging.getLogger("dnf") class SwapCommand(commands.Command): """A class containing methods needed by the cli to execute the swap command. """ aliases = ('swap',) summary = _('run an interactive {prog} mod for remove and install one spec').format( prog=dnf.util.MAIN_PROG_UPPER) @staticmethod def set_argparser(parser): parser.add_argument('remove_spec', action="store", help=_('The specs that will be removed')) parser.add_argument('install_spec', action="store", help=_( 'The specs that will be installed')) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True commands._checkGPGKey(self.base, self.cli) commands._checkEnabledRepo(self.base, [self.opts.install_spec]) def _perform(self, cmd_str, spec): cmd_cls = self.cli.cli_commands.get(cmd_str) if cmd_cls is not None: cmd = cmd_cls(self.cli) self.cli.optparser.parse_command_args(cmd, [cmd_str, spec]) cmd.run() def run(self): self._perform('remove', self.opts.remove_spec) self._perform('install', self.opts.install_spec) commands/upgrademinimal.py000064400000003407151030066770011726 0ustar00# # Copyright (C) 2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import from __future__ import unicode_literals from dnf.i18n import _ from dnf.cli.commands.upgrade import UpgradeCommand class UpgradeMinimalCommand(UpgradeCommand): """A class containing methods needed by the cli to execute the check command. """ aliases = ('upgrade-minimal', 'update-minimal', 'up-min') summary = _("upgrade, but only 'newest' package match which fixes a problem" " that affects your system") def configure(self): UpgradeCommand.configure(self) self.upgrade_minimal = True if not any([self.opts.bugfix, self.opts.enhancement, self.opts.newpackage, self.opts.security, self.opts.advisory, self.opts.bugzilla, self.opts.cves, self.opts.severity]): self.all_security = True commands/deplist.py000064400000002746151030066770010401 0ustar00# # Copyright (C) 2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from dnf.i18n import _ from dnf.cli.commands.repoquery import RepoQueryCommand class DeplistCommand(RepoQueryCommand): """ The command is alias for 'dnf repoquery --deplist' """ aliases = ('deplist',) summary = _("[deprecated, use repoquery --deplist] List package's dependencies and what packages provide them") def configure(self): RepoQueryCommand.configure(self) self.opts.deplist = True commands/__init__.py000064400000076573151030066770010505 0ustar00# Copyright 2006 Duke University # Copyright (C) 2012-2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Written by Seth Vidal """ Classes for subcommands of the yum command line interface. """ from __future__ import print_function from __future__ import unicode_literals from dnf.cli.option_parser import OptionParser from dnf.i18n import _ import dnf.cli import dnf.exceptions import dnf.pycomp import dnf.util import logging import os logger = logging.getLogger('dnf') _RPM_VERIFY = _("To diagnose the problem, try running: '%s'.") % \ 'rpm -Va --nofiles --nodigest' _RPM_REBUILDDB = _("You probably have corrupted RPMDB, running '%s'" " might fix the issue.") % 'rpm --rebuilddb' gpg_msg = \ _("""You have enabled checking of packages via GPG keys. This is a good thing. However, you do not have any GPG public keys installed. You need to download the keys for packages you wish to install and install them. You can do that by running the command: rpm --import public.gpg.key Alternatively you can specify the url to the key you would like to use for a repository in the 'gpgkey' option in a repository section and {prog} will install it for you. For more information contact your distribution or package provider.""") def _checkGPGKey(base, cli): """Verify that there are gpg keys for the enabled repositories in the rpm database. :param base: a :class:`dnf.Base` object. :raises: :class:`cli.CliError` """ if not base.conf.gpgcheck: return if not base._gpg_key_check(): for repo in base.repos.iter_enabled(): if (repo.gpgcheck or repo.repo_gpgcheck) and not repo.gpgkey: logger.critical("\n%s\n", gpg_msg.format(prog=dnf.util.MAIN_PROG_UPPER)) logger.critical(_("Problem repository: %s"), repo) raise dnf.cli.CliError def _checkEnabledRepo(base, possible_local_files=()): """Verify that there is at least one enabled repo. :param base: a :class:`dnf.Base` object. :param possible_local_files: the list of strings that could be a local rpms :raises: :class:`cli.CliError`: """ if base.repos._any_enabled(): return for lfile in possible_local_files: if lfile.endswith(".rpm") and os.path.exists(lfile): return scheme = dnf.pycomp.urlparse.urlparse(lfile)[0] if scheme in ('http', 'ftp', 'file', 'https'): return msg = _('There are no enabled repositories in "{}".').format('", "'.join(base.conf.reposdir)) raise dnf.cli.CliError(msg) class Command(object): """Abstract base class for CLI commands.""" aliases = [] # :api summary = "" # :api opts = None def __init__(self, cli): # :api self.cli = cli @property def base(self): # :api return self.cli.base @property def _basecmd(self): return self.aliases[0] @property def output(self): return self.cli.base.output def set_argparser(self, parser): """Define command specific options and arguments. #:api""" pass def pre_configure(self): # :api """Do any command-specific pre-configuration.""" pass def configure(self): # :api """Do any command-specific configuration.""" pass def get_error_output(self, error): """Get suggestions for resolving the given error.""" if isinstance(error, dnf.exceptions.TransactionCheckError): return (_RPM_VERIFY, _RPM_REBUILDDB) raise NotImplementedError('error not supported yet: %s' % error) def run(self): # :api """Execute the command.""" pass def run_resolved(self): """Finalize operation after resolvement""" pass def run_transaction(self): """Finalize operations post-transaction.""" pass class InfoCommand(Command): """A class containing methods needed by the cli to execute the info command. """ aliases = ('info',) summary = _('display details about a package or group of packages') DEFAULT_PKGNARROW = 'all' pkgnarrows = {'available', 'installed', 'extras', 'updates', 'upgrades', 'autoremove', 'recent', 'obsoletes', DEFAULT_PKGNARROW} @classmethod def set_argparser(cls, parser): narrows = parser.add_mutually_exclusive_group() narrows.add_argument('--all', dest='_packages_action', action='store_const', const='all', default=None, help=_("show all packages (default)")) narrows.add_argument('--available', dest='_packages_action', action='store_const', const='available', help=_("show only available packages")) narrows.add_argument('--installed', dest='_packages_action', action='store_const', const='installed', help=_("show only installed packages")) narrows.add_argument('--extras', dest='_packages_action', action='store_const', const='extras', help=_("show only extras packages")) narrows.add_argument('--updates', dest='_packages_action', action='store_const', const='upgrades', help=_("show only upgrades packages")) narrows.add_argument('--upgrades', dest='_packages_action', action='store_const', const='upgrades', help=_("show only upgrades packages")) narrows.add_argument('--autoremove', dest='_packages_action', action='store_const', const='autoremove', help=_("show only autoremove packages")) narrows.add_argument('--recent', dest='_packages_action', action='store_const', const='recent', help=_("show only recently changed packages")) parser.add_argument('packages', nargs='*', metavar=_('PACKAGE'), choices=cls.pkgnarrows, default=cls.DEFAULT_PKGNARROW, action=OptionParser.PkgNarrowCallback, help=_("Package name specification")) def configure(self): demands = self.cli.demands demands.sack_activation = True if self.opts._packages_action: self.opts.packages_action = self.opts._packages_action if self.opts.packages_action != 'installed': demands.available_repos = True if self.opts.obsoletes: if self.opts._packages_action: self.cli._option_conflict("--obsoletes", "--" + self.opts._packages_action) else: self.opts.packages_action = 'obsoletes' if self.opts.packages_action == 'updates': self.opts.packages_action = 'upgrades' def run(self): self.cli._populate_update_security_filter(self.opts) return self.base.output_packages('info', self.opts.packages_action, self.opts.packages) class ListCommand(InfoCommand): """A class containing methods needed by the cli to execute the list command. """ aliases = ('list', 'ls') summary = _('list a package or groups of packages') def run(self): self.cli._populate_update_security_filter(self.opts) return self.base.output_packages('list', self.opts.packages_action, self.opts.packages) class ProvidesCommand(Command): """A class containing methods needed by the cli to execute the provides command. """ aliases = ('provides', 'whatprovides', 'prov') summary = _('find what package provides the given value') @staticmethod def set_argparser(parser): parser.add_argument('dependency', nargs='+', metavar=_('PROVIDE'), help=_("Provide specification to search for")) def configure(self): demands = self.cli.demands demands.available_repos = True demands.fresh_metadata = False demands.sack_activation = True def run(self): logger.debug(_("Searching Packages: ")) return self.base.provides(self.opts.dependency) class CheckUpdateCommand(Command): """A class containing methods needed by the cli to execute the check-update command. """ aliases = ('check-update', 'check-upgrade') summary = _('check for available package upgrades') @staticmethod def set_argparser(parser): parser.add_argument('--changelogs', dest='changelogs', default=False, action='store_true', help=_('show changelogs before update')) parser.add_argument('packages', nargs='*', metavar=_('PACKAGE')) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.plugin_filtering_enabled = True if self.opts.changelogs: demands.changelogs = True _checkEnabledRepo(self.base) def run(self): self.cli._populate_update_security_filter(self.opts, cmp_type="gte") found = self.base.check_updates(self.opts.packages, print_=True, changelogs=self.opts.changelogs) if found: self.cli.demands.success_exit_status = 100 if self.base.conf.autocheck_running_kernel: self.cli._check_running_kernel() class RepoPkgsCommand(Command): """Implementation of the repository-packages command.""" class CheckUpdateSubCommand(Command): """Implementation of the info sub-command.""" aliases = ('check-update',) def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" found = self.base.check_updates(self.opts.pkg_specs, self.reponame, print_=True) if found: self.cli.demands.success_exit_status = 100 class InfoSubCommand(Command): """Implementation of the info sub-command.""" aliases = ('info',) def configure(self): demands = self.cli.demands demands.sack_activation = True if self.opts._pkg_specs_action: self.opts.pkg_specs_action = self.opts._pkg_specs_action if self.opts.pkg_specs_action != 'installed': demands.available_repos = True if self.opts.obsoletes: if self.opts._pkg_specs_action: self.cli._option_conflict("--obsoletes", "--" + self.opts._pkg_specs_action) else: self.opts.pkg_specs_action = 'obsoletes' def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" self.cli._populate_update_security_filter(self.opts) self.base.output_packages('info', self.opts.pkg_specs_action, self.opts.pkg_specs, self.reponame) class InstallSubCommand(Command): """Implementation of the install sub-command.""" aliases = ('install',) def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def run_on_repo(self): self.cli._populate_update_security_filter(self.opts) """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) done = False if not self.opts.pkg_specs: # Install all packages. try: self.base.install('*', self.reponame) except dnf.exceptions.MarkingError: logger.info(_('No package available.')) else: done = True else: # Install packages. for pkg_spec in self.opts.pkg_specs: try: self.base.install(pkg_spec, self.reponame) except dnf.exceptions.MarkingError as e: msg = '{}: {}'.format(e.value, self.base.output.term.bold(pkg_spec)) logger.info(msg) else: done = True if not done: raise dnf.exceptions.Error(_('No packages marked for install.')) class ListSubCommand(InfoSubCommand): """Implementation of the list sub-command.""" aliases = ('list',) def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" self.cli._populate_update_security_filter(self.opts) self.base.output_packages('list', self.opts.pkg_specs_action, self.opts.pkg_specs, self.reponame) class MoveToSubCommand(Command): """Implementation of the move-to sub-command.""" aliases = ('move-to',) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) done = False if not self.opts.pkg_specs: # Reinstall all packages. try: self.base.reinstall('*', new_reponame=self.reponame) except dnf.exceptions.PackagesNotInstalledError: logger.info(_('No package installed.')) except dnf.exceptions.PackagesNotAvailableError: logger.info(_('No package available.')) except dnf.exceptions.MarkingError: assert False, 'Only the above marking errors are expected.' else: done = True else: # Reinstall packages. for pkg_spec in self.opts.pkg_specs: try: self.base.reinstall(pkg_spec, new_reponame=self.reponame) except dnf.exceptions.PackagesNotInstalledError: msg = _('No match for argument: %s') logger.info(msg, pkg_spec) except dnf.exceptions.PackagesNotAvailableError as err: for pkg in err.packages: xmsg = '' pkgrepo = self.base.history.repo(pkg) if pkgrepo: xmsg = _(' (from %s)') % pkgrepo msg = _('Installed package %s%s not available.') logger.info(msg, self.output.term.bold(pkg), xmsg) except dnf.exceptions.MarkingError: assert False, \ 'Only the above marking errors are expected.' else: done = True if not done: raise dnf.exceptions.Error(_('Nothing to do.')) class ReinstallOldSubCommand(Command): """Implementation of the reinstall-old sub-command.""" aliases = ('reinstall-old',) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) done = False if not self.opts.pkg_specs: # Reinstall all packages. try: self.base.reinstall('*', self.reponame, self.reponame) except dnf.exceptions.PackagesNotInstalledError: msg = _('No package installed from the repository.') logger.info(msg) except dnf.exceptions.PackagesNotAvailableError: logger.info(_('No package available.')) except dnf.exceptions.MarkingError: assert False, 'Only the above marking errors are expected.' else: done = True else: # Reinstall packages. for pkg_spec in self.opts.pkg_specs: try: self.base.reinstall(pkg_spec, self.reponame, self.reponame) except dnf.exceptions.PackagesNotInstalledError: msg = _('No match for argument: %s') logger.info(msg, pkg_spec) except dnf.exceptions.PackagesNotAvailableError as err: for pkg in err.packages: xmsg = '' pkgrepo = self.base.history.repo(pkg) if pkgrepo: xmsg = _(' (from %s)') % pkgrepo msg = _('Installed package %s%s not available.') logger.info(msg, self.output.term.bold(pkg), xmsg) except dnf.exceptions.MarkingError: assert False, \ 'Only the above marking errors are expected.' else: done = True if not done: raise dnf.exceptions.Error(_('Nothing to do.')) class ReinstallSubCommand(Command): """Implementation of the reinstall sub-command.""" aliases = ('reinstall',) def __init__(self, cli): """Initialize the command.""" super(RepoPkgsCommand.ReinstallSubCommand, self).__init__(cli) self.wrapped_commands = (RepoPkgsCommand.ReinstallOldSubCommand(cli), RepoPkgsCommand.MoveToSubCommand(cli)) def configure(self): self.cli.demands.available_repos = True for command in self.wrapped_commands: command.opts = self.opts command.reponame = self.reponame command.configure() def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) for command in self.wrapped_commands: try: command.run_on_repo() except dnf.exceptions.Error: continue else: break else: raise dnf.exceptions.Error(_('No packages marked for reinstall.')) class RemoveOrDistroSyncSubCommand(Command): """Implementation of the remove-or-distro-sync sub-command.""" aliases = ('remove-or-distro-sync',) def configure(self): demands = self.cli.demands demands.available_repos = True demands.sack_activation = True demands.resolving = True demands.root_user = True def _replace(self, pkg_spec, reponame): """Synchronize a package with another repository or remove it.""" self.cli.base.sack.disable_repo(reponame) subject = dnf.subject.Subject(pkg_spec) matches = subject.get_best_query(self.cli.base.sack) history = self.cli.base.history installed = [ pkg for pkg in matches.installed() if history.repo(pkg) == reponame] if not installed: raise dnf.exceptions.PackagesNotInstalledError( 'no package matched', pkg_spec) available = matches.available() clean_deps = self.cli.base.conf.clean_requirements_on_remove for package in installed: if available.filter(name=package.name, arch=package.arch): self.cli.base._goal.distupgrade(package) else: self.cli.base._goal.erase(package, clean_deps=clean_deps) def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) done = False if not self.opts.pkg_specs: # Sync all packages. try: self._replace('*', self.reponame) except dnf.exceptions.PackagesNotInstalledError: msg = _('No package installed from the repository.') logger.info(msg) else: done = True else: # Reinstall packages. for pkg_spec in self.opts.pkg_specs: try: self._replace(pkg_spec, self.reponame) except dnf.exceptions.PackagesNotInstalledError: msg = _('No match for argument: %s') logger.info(msg, pkg_spec) else: done = True if not done: raise dnf.exceptions.Error(_('Nothing to do.')) class RemoveOrReinstallSubCommand(Command): """Implementation of the remove-or-reinstall sub-command.""" aliases = ('remove-or-reinstall',) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) done = False if not self.opts.pkg_specs: # Reinstall all packages. try: self.base.reinstall('*', old_reponame=self.reponame, new_reponame_neq=self.reponame, remove_na=True) except dnf.exceptions.PackagesNotInstalledError: msg = _('No package installed from the repository.') logger.info(msg) except dnf.exceptions.MarkingError: assert False, 'Only the above marking error is expected.' else: done = True else: # Reinstall packages. for pkg_spec in self.opts.pkg_specs: try: self.base.reinstall( pkg_spec, old_reponame=self.reponame, new_reponame_neq=self.reponame, remove_na=True) except dnf.exceptions.PackagesNotInstalledError: msg = _('No match for argument: %s') logger.info(msg, pkg_spec) except dnf.exceptions.MarkingError: assert False, 'Only the above marking error is expected.' else: done = True if not done: raise dnf.exceptions.Error(_('Nothing to do.')) class RemoveSubCommand(Command): """Implementation of the remove sub-command.""" aliases = ('remove',) def configure(self): demands = self.cli.demands demands.sack_activation = True demands.allow_erasing = True demands.available_repos = False demands.resolving = True demands.root_user = True def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" done = False if not self.opts.pkg_specs: # Remove all packages. try: self.base.remove('*', self.reponame) except dnf.exceptions.MarkingError: msg = _('No package installed from the repository.') logger.info(msg) else: done = True else: # Remove packages. for pkg_spec in self.opts.pkg_specs: try: self.base.remove(pkg_spec, self.reponame) except dnf.exceptions.MarkingError as e: logger.info(str(e)) else: done = True if not done: logger.warning(_('No packages marked for removal.')) class UpgradeSubCommand(Command): """Implementation of the upgrade sub-command.""" aliases = ('upgrade', 'upgrade-to') def configure(self): demands = self.cli.demands demands.sack_activation = True demands.available_repos = True demands.resolving = True demands.root_user = True def run_on_repo(self): """Execute the command with respect to given arguments *cli_args*.""" _checkGPGKey(self.base, self.cli) done = False if not self.opts.pkg_specs: # Update all packages. self.base.upgrade_all(self.reponame) done = True else: # Update packages. for pkg_spec in self.opts.pkg_specs: try: self.base.upgrade(pkg_spec, self.reponame) except dnf.exceptions.MarkingError: logger.info(_('No match for argument: %s'), pkg_spec) else: done = True if not done: raise dnf.exceptions.Error(_('No packages marked for upgrade.')) SUBCMDS = {CheckUpdateSubCommand, InfoSubCommand, InstallSubCommand, ListSubCommand, MoveToSubCommand, ReinstallOldSubCommand, ReinstallSubCommand, RemoveOrDistroSyncSubCommand, RemoveOrReinstallSubCommand, RemoveSubCommand, UpgradeSubCommand} aliases = ('repository-packages', 'repo-pkgs', 'repo-packages', 'repository-pkgs') summary = _('run commands on top of all packages in given repository') def __init__(self, cli): """Initialize the command.""" super(RepoPkgsCommand, self).__init__(cli) subcmd_objs = (subcmd(cli) for subcmd in self.SUBCMDS) self.subcmd = None self._subcmd_name2obj = { alias: subcmd for subcmd in subcmd_objs for alias in subcmd.aliases} def set_argparser(self, parser): narrows = parser.add_mutually_exclusive_group() narrows.add_argument('--all', dest='_pkg_specs_action', action='store_const', const='all', default=None, help=_("show all packages (default)")) narrows.add_argument('--available', dest='_pkg_specs_action', action='store_const', const='available', help=_("show only available packages")) narrows.add_argument('--installed', dest='_pkg_specs_action', action='store_const', const='installed', help=_("show only installed packages")) narrows.add_argument('--extras', dest='_pkg_specs_action', action='store_const', const='extras', help=_("show only extras packages")) narrows.add_argument('--updates', dest='_pkg_specs_action', action='store_const', const='upgrades', help=_("show only upgrades packages")) narrows.add_argument('--upgrades', dest='_pkg_specs_action', action='store_const', const='upgrades', help=_("show only upgrades packages")) narrows.add_argument('--autoremove', dest='_pkg_specs_action', action='store_const', const='autoremove', help=_("show only autoremove packages")) narrows.add_argument('--recent', dest='_pkg_specs_action', action='store_const', const='recent', help=_("show only recently changed packages")) parser.add_argument( 'reponame', nargs=1, action=OptionParser._RepoCallbackEnable, metavar=_('REPOID'), help=_("Repository ID")) subcommand_choices = [subcmd.aliases[0] for subcmd in self.SUBCMDS] subcommand_choices_all = [alias for subcmd in self.SUBCMDS for alias in subcmd.aliases] parser.add_argument('subcmd', nargs=1, metavar="SUBCOMMAND", choices=subcommand_choices_all, help=", ".join(subcommand_choices)) DEFAULT_PKGNARROW = 'all' pkgnarrows = {DEFAULT_PKGNARROW, 'installed', 'available', 'autoremove', 'extras', 'obsoletes', 'recent', 'upgrades'} parser.add_argument('pkg_specs', nargs='*', metavar=_('PACKAGE'), choices=pkgnarrows, default=DEFAULT_PKGNARROW, action=OptionParser.PkgNarrowCallback, help=_("Package specification")) def configure(self): """Verify whether the command can run with given arguments.""" # Check sub-command. try: self.subcmd = self._subcmd_name2obj[self.opts.subcmd[0]] except (dnf.cli.CliError, KeyError) as e: self.cli.optparser.print_usage() raise dnf.cli.CliError self.subcmd.opts = self.opts self.subcmd.reponame = self.opts.reponame[0] self.subcmd.configure() def run(self): """Execute the command with respect to given arguments *extcmds*.""" self.subcmd.run_on_repo() class HelpCommand(Command): """A class containing methods needed by the cli to execute the help command. """ aliases = ('help',) summary = _('display a helpful usage message') @staticmethod def set_argparser(parser): parser.add_argument('cmd', nargs='?', metavar=_('COMMAND'), help=_("{prog} command to get help for").format( prog=dnf.util.MAIN_PROG_UPPER)) def run(self): if (not self.opts.cmd or self.opts.cmd not in self.cli.cli_commands): self.cli.optparser.print_help() else: command = self.cli.cli_commands[self.opts.cmd] self.cli.optparser.print_help(command(self)) main.py000064400000014546151030066770006061 0ustar00# Copyright 2005 Duke University # Copyright (C) 2012-2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """ Entrance point for the yum command line interface. """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from dnf.conf import Conf from dnf.cli.cli import Cli from dnf.cli.option_parser import OptionParser from dnf.i18n import ucd from dnf.cli.utils import show_lock_owner from dnf.i18n import _ import dnf.cli import dnf.cli.cli import dnf.cli.option_parser import dnf.exceptions import dnf.i18n import dnf.logging import dnf.util import errno import hawkey import libdnf.error import logging import os import os.path import sys logger = logging.getLogger("dnf") def ex_IOError(e): logger.log(dnf.logging.SUBDEBUG, '', exc_info=True) logger.critical(ucd(e)) return 1 def ex_Error(e): logger.log(dnf.logging.SUBDEBUG, '', exc_info=True) if e.value is not None: logger.critical(_('Error: %s'), ucd(e)) return 1 def main(args, conf_class=Conf, cli_class=Cli, option_parser_class=OptionParser): try: dnf.i18n.setup_stdout() with dnf.cli.cli.BaseCli(conf_class()) as base: return _main(base, args, cli_class, option_parser_class) except dnf.exceptions.ProcessLockError as e: logger.critical(e.value) show_lock_owner(e.pid) return 200 except dnf.exceptions.LockError as e: logger.critical(e.value) return 200 except dnf.exceptions.DepsolveError as e: return 1 except dnf.exceptions.Error as e: return ex_Error(e) except hawkey.Exception as e: logger.critical(_('Error: %s'), ucd(e)) return 1 except libdnf.error.Error as e: logger.critical(_('Error: %s'), ucd(e)) return 1 except IOError as e: return ex_IOError(e) except KeyboardInterrupt as e: logger.critical('{}: {}'.format(type(e).__name__, _("Terminated."))) return 1 def _main(base, args, cli_class, option_parser): """Run the dnf program from a command line interface.""" # our core object for the cli base._logging._presetup() cli = cli_class(base) # do our cli parsing and config file setup # also sanity check the things being passed on the cli try: cli.configure(list(map(ucd, args)), option_parser()) except (IOError, OSError) as e: return ex_IOError(e) return cli_run(cli, base) def cli_run(cli, base): # Try to open the current directory to see if we have # read and execute access. If not, chdir to / try: f = open(".") except IOError as e: if e.errno == errno.EACCES: logger.critical(_('No read/execute access in current directory, moving to /')) os.chdir("/") else: f.close() try: cli.run() except dnf.exceptions.LockError: raise except (IOError, OSError) as e: return ex_IOError(e) if cli.demands.resolving: try: ret = resolving(cli, base) except dnf.exceptions.DepsolveError as e: ex_Error(e) msg = "" if not cli.demands.allow_erasing and base._goal.problem_conflicts(available=True): msg += _("try to add '{}' to command line to replace conflicting " "packages").format("--allowerasing") if cli.base.conf.strict: if not msg: msg += _("try to add '{}' to skip uninstallable packages").format( "--skip-broken") else: msg += _(" or '{}' to skip uninstallable packages").format("--skip-broken") if cli.base.conf.best: prio = cli.base.conf._get_priority("best") if prio <= dnf.conf.PRIO_MAINCONFIG: if not msg: msg += _("try to add '{}' to use not only best candidate packages").format( "--nobest") else: msg += _(" or '{}' to use not only best candidate packages").format( "--nobest") if msg: logger.info("({})".format(msg)) raise if ret: return ret cli.command.run_transaction() return cli.demands.success_exit_status def resolving(cli, base): """Perform the depsolve, download and RPM transaction stage.""" if base.transaction is None: base.resolve(cli.demands.allow_erasing) logger.info(_('Dependencies resolved.')) cli.command.run_resolved() # Run the transaction displays = [] if cli.demands.transaction_display is not None: displays.append(cli.demands.transaction_display) try: base.do_transaction(display=displays) except dnf.cli.CliError as exc: logger.error(ucd(exc)) return 1 except dnf.exceptions.TransactionCheckError as err: for msg in cli.command.get_error_output(err): logger.critical(msg) return 1 except IOError as e: return ex_IOError(e) else: logger.info(_('Complete!')) return 0 def user_main(args, exit_code=False): """Call one of the multiple main() functions based on environment variables. :param args: command line arguments passed into yum :param exit_code: if *exit_code* is True, this function will exit python with its exit code when it has finished executing. Otherwise, it will return its exit code. :return: the exit code from dnf.yum execution """ errcode = main(args) if exit_code: sys.exit(errcode) return errcode if __name__ == "__main__": user_main(sys.argv[1:], exit_code=True) __init__.py000064400000002305151030066770006662 0ustar00# __init__.py # DNF cli subpackage. # # Copyright (C) 2012-2016 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # from __future__ import absolute_import import dnf.exceptions class CliError(dnf.exceptions.Error): """CLI Exception. :api""" pass from dnf.cli.cli import Cli # :api from dnf.cli.commands import Command # :api