[PY3] Add unicode_literals to pkg/pkgrepo states/modules

This commit is contained in:
Erik Johnson 2018-01-18 10:55:07 -06:00
parent ab63da4f35
commit 9df3dab883
No known key found for this signature in database
GPG Key ID: 5E5583C437808F3F
34 changed files with 364 additions and 380 deletions

View File

@ -2,7 +2,7 @@
'''
Support for DEB packages
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
@ -15,6 +15,7 @@ import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
log = logging.getLogger(__name__)
@ -327,7 +328,7 @@ def _get_pkg_license(pkg):
cpr = "/usr/share/doc/{0}/copyright".format(pkg)
if os.path.exists(cpr):
with salt.utils.files.fopen(cpr) as fp_:
for line in fp_.read().split(os.linesep):
for line in salt.utils.stringutils.to_unicode(fp_.read()).split(os.linesep):
if line.startswith("License:"):
licenses.add(line.split(":", 1)[1].strip())
@ -365,7 +366,7 @@ def _get_pkg_ds_avail():
pkg_mrk = "Package:"
pkg_name = "package"
with salt.utils.files.fopen(avail) as fp_:
for pkg_info in fp_.read().split(pkg_mrk):
for pkg_info in salt.utils.stringutils.to_unicode(fp_.read()).split(pkg_mrk):
nfo = dict()
for line in (pkg_mrk + pkg_info).split(os.linesep):
line = line.split(": ", 1)

View File

@ -72,7 +72,7 @@ variables, if set, but these values can also be overridden in several ways:
pkg.installed:
- fromrepo: ftp://ftp2.freebsd.org/
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy

View File

@ -8,7 +8,7 @@ Homebrew for macOS
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
@ -64,7 +64,7 @@ def _tap(tap, runas=None):
try:
_call_brew(cmd)
except CommandExecutionError:
log.error('Failed to tap "{0}"'.format(tap))
log.error('Failed to tap "%s"', tap)
return False
return True
@ -289,7 +289,7 @@ def _info(*pkgs):
cmd = 'brew info --json=v1 {0}'.format(' '.join(pkgs))
brew_result = _call_brew(cmd)
if brew_result['retcode']:
log.error('Failed to get info about packages: {0}'.format(' '.join(pkgs)))
log.error('Failed to get info about packages: %s', ' '.join(pkgs))
return {}
output = salt.utils.json.loads(brew_result['stdout'])
return dict(zip(pkgs, output))

View File

@ -6,7 +6,7 @@ Installer is the native .pkg/.mpkg package manager for macOS.
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import os.path
# Import 3rd-party libs

View File

@ -31,7 +31,7 @@ In other words `salt mac-machine pkg.refresh_db` is more like
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import re

View File

@ -22,7 +22,7 @@ Package support for OpenBSD
- ruby%2.3
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy

View File

@ -17,7 +17,7 @@ Support for Opkg
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
@ -30,6 +30,7 @@ import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
@ -193,9 +194,7 @@ def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(
'{0}'.format(out)
)
raise CommandExecutionError(out)
return ret
@ -741,9 +740,7 @@ def _set_state(pkg, state):
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError(
'Invalid state: {0}'.format(state)
)
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
@ -828,9 +825,7 @@ def list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(
'{0}'.format(comment)
)
raise CommandExecutionError(comment)
else:
out = call['stdout']
@ -951,9 +946,7 @@ def info_installed(*names, **kwargs):
else:
comment += call['stdout']
raise CommandExecutionError(
'{0}'.format(comment)
)
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
@ -968,9 +961,7 @@ def info_installed(*names, **kwargs):
else:
comment += call['stdout']
raise CommandExecutionError(
'{0}'.format(comment)
)
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
@ -1006,7 +997,7 @@ def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=un
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: str(x).split(':', 1)[-1] if ignore_epoch else str(x)
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
@ -1054,6 +1045,7 @@ def list_repos(**kwargs): # pylint: disable=unused-argument
if filename.endswith(".conf"):
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
repo = {}
if line.startswith('#'):
@ -1103,12 +1095,13 @@ def _del_repo_from_file(alias, filepath):
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if alias != cols[1]:
output.append(line)
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
@ -1127,7 +1120,7 @@ def _add_new_repo(alias, uri, compressed, enabled=True):
conffile = os.path.join(OPKG_CONFDIR, alias + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(repostr)
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(alias, repostr, filepath):
@ -1137,11 +1130,13 @@ def _mod_repo_in_file(alias, repostr, filepath):
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(line.strip())
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if alias not in cols:
output.append(line)
else:
output.append(repostr + '\n')
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)

View File

@ -11,7 +11,7 @@ A module to wrap pacman calls, since Arch is the best
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import copy
import fnmatch
import logging
@ -229,7 +229,7 @@ def list_pkgs(versions_as_list=False, **kwargs):
name, version_num = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Q: Unexpected formatting in '
'line: \'{0}\''.format(line))
'line: \'%s\'', line)
else:
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
@ -271,7 +271,7 @@ def group_list():
group, pkg = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Sgg: Unexpected formatting in '
'line: \'{0}\''.format(line))
'line: \'%s\'', line)
else:
available.setdefault(group, []).append(pkg)
@ -287,7 +287,7 @@ def group_list():
group, pkg = line.split()[0:2]
except ValueError:
log.error('Problem parsing pacman -Qg: Unexpected formatting in '
'line: \'{0}\''.format(line))
'line: \'%s\'', line)
else:
installed.setdefault(group, []).append(pkg)
@ -295,7 +295,10 @@ def group_list():
for group in installed:
if group not in available:
log.error('Pacman reports group {0} installed, but it is not in the available list ({1})!'.format(group, available))
log.error(
'Pacman reports group %s installed, but it is not in the '
'available list (%s)!', group, available
)
continue
if len(installed[group]) == len(available[group]):
ret['installed'].append(group)
@ -342,7 +345,7 @@ def group_info(name):
pkg = line.split()[1]
except ValueError:
log.error('Problem parsing pacman -Sgg: Unexpected formatting in '
'line: \'{0}\''.format(line))
'line: \'%s\'', line)
else:
ret['default'].add(pkg)
@ -1004,7 +1007,7 @@ def list_repo_pkgs(*args, **kwargs):
try:
repos = [x.strip() for x in fromrepo.split(',')]
except AttributeError:
repos = [x.strip() for x in str(fromrepo).split(',')]
repos = [x.strip() for x in six.text_type(fromrepo).split(',')]
else:
repos = []

View File

@ -4,7 +4,7 @@ Resources needed by pkg providers
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import copy
import fnmatch
import logging
@ -35,7 +35,7 @@ def _repack_pkgs(pkgs, normalize=True):
_normalize_name = lambda pkgname: pkgname
return dict(
[
(_normalize_name(str(x)), str(y) if y is not None else y)
(_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y)
for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs))
]
)
@ -79,7 +79,7 @@ def pack_sources(sources, normalize=True):
ret = {}
for source in sources:
if (not isinstance(source, dict)) or len(source) != 1:
log.error('Invalid input: {0}'.format(pprint.pformat(sources)))
log.error('Invalid input: %s', pprint.pformat(sources))
log.error('Input must be a list of 1-element dicts')
return {}
else:

View File

@ -10,7 +10,7 @@ Package support for pkgin based systems, inspired from freebsdpkg module
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import os
@ -61,10 +61,9 @@ def _get_version():
'''
Get the pkgin version
'''
ppath = _check_pkgin()
version_string = __salt__['cmd.run'](
'{0} -v'.format(ppath), output_loglevel='trace'
)
[_check_pkgin(), '-v'],
output_loglevel='trace')
if version_string is None:
# Dunno why it would, but...
return False
@ -133,7 +132,7 @@ def search(pkg_name):
pkg_name = '^{0}$'.format(pkg_name)
out = __salt__['cmd.run'](
'{0} se {1}'.format(pkgin, pkg_name),
[pkgin, 'se', pkg_name],
output_loglevel='trace'
)
for line in out.splitlines():
@ -173,22 +172,16 @@ def latest_version(*names, **kwargs):
if refresh:
refresh_db()
cmd_prefix = [pkgin, 'se']
if _supports_parsing():
cmd_prefix.insert(1, '-p')
for name in names:
if _supports_regex():
name = '^{0}$'.format(name)
out = __salt__['cmd.run'](
'{0}{1} se {2}'.format(
pkgin,
' -p' if _supports_parsing() else '',
name,
),
output_loglevel='trace'
)
cmd = copy.deepcopy(cmd_prefix)
cmd.append('^{0}$'.format(name) if _supports_regex() else name)
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if _supports_parsing(): # split on ;
p = line.split(';')
else:
p = line.split() # pkgname-version status
p = line.split(',' if _supports_parsing() else None)
if p and p[0] in ('=:', '<:', '>:', ''):
# These are explanation comments
@ -250,21 +243,17 @@ def refresh_db(force=False):
pkgin = _check_pkgin()
if pkgin:
call = __salt__['cmd.run_all'](
'{0}{1} up'.format(
pkgin,
' -f' if force else '',
),
output_loglevel='trace')
cmd = [pkgin, 'up']
if force:
cmd.insert(1, '-f')
call = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(
'{0}'.format(comment)
)
raise CommandExecutionError(comment)
return True
@ -297,14 +286,12 @@ def list_pkgs(versions_as_list=False, **kwargs):
return ret
pkgin = _check_pkgin()
if pkgin:
pkg_command = '{0} ls'.format(pkgin)
else:
pkg_command = 'pkg_info'
ret = {}
out = __salt__['cmd.run'](pkg_command, output_loglevel='trace')
out = __salt__['cmd.run'](
[pkgin, 'ls'] if pkgin else ['pkg_info'],
output_loglevel='trace')
for line in out.splitlines():
try:
# Some versions of pkgin check isatty unfortunately
@ -415,12 +402,12 @@ def install(name=None, refresh=False, fromrepo=None,
if pkgin:
cmd = pkgin
if fromrepo:
log.info('Setting PKG_REPOS={0}'.format(fromrepo))
log.info('Setting PKG_REPOS=%s', fromrepo)
env.append(('PKG_REPOS', fromrepo))
else:
cmd = 'pkg_add'
if fromrepo:
log.info('Setting PKG_PATH={0}'.format(fromrepo))
log.info('Setting PKG_PATH=%s', fromrepo)
env.append(('PKG_PATH', fromrepo))
if pkg_type == 'file':
@ -431,15 +418,12 @@ def install(name=None, refresh=False, fromrepo=None,
args.append('-f') # update repo db
args.extend(('-y', 'in')) # Assume yes when asked
args.insert(0, cmd)
args.extend(pkg_params)
old = list_pkgs()
out = __salt__['cmd.run_all'](
'{0} {1}'.format(cmd, ' '.join(args)),
env=env,
output_loglevel='trace'
)
out = __salt__['cmd.run_all'](args, env=env, output_loglevel='trace')
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
@ -583,18 +567,11 @@ def remove(name=None, pkgs=None, **kwargs):
if not args:
return {}
for_remove = ' '.join(args)
pkgin = _check_pkgin()
if pkgin:
cmd = '{0} -y remove {1}'.format(pkgin, for_remove)
else:
cmd = 'pkg_remove {0}'.format(for_remove)
cmd = [pkgin, '-y', 'remove'] if pkgin else ['pkg_remove']
cmd.extend(args)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace'
)
out = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
@ -690,7 +667,7 @@ def file_dict(*packages):
files = {}
for package in packages:
cmd = 'pkg_info -qL {0}'.format(package)
cmd = ['pkg_info', '-qL', package]
ret = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
files[package] = []

View File

@ -36,7 +36,7 @@ file, in order to use this module to manage packages, like so:
pkg: pkgng
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
@ -49,6 +49,7 @@ import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import CommandExecutionError, MinionError
from salt.ext import six
@ -74,7 +75,7 @@ def __virtual__():
providers = {}
if 'providers' in __opts__:
providers = __opts__['providers']
log.debug('__opts__.providers: {0}'.format(providers))
log.debug('__opts__.providers: %s', providers)
if providers and 'pkg' in providers and providers['pkg'] == 'pkgng':
log.debug('Configuration option \'providers:pkg\' is set to '
'\'pkgng\', using \'pkgng\' in favor of \'freebsdpkg\'.')
@ -131,11 +132,11 @@ def _contextkey(jail=None, chroot=None, root=None, prefix='pkg.list_pkgs'):
unique to that jail/chroot is used.
'''
if jail:
return str(prefix) + '.jail_{0}'.format(jail)
return six.text_type(prefix) + '.jail_{0}'.format(jail)
elif chroot:
return str(prefix) + '.chroot_{0}'.format(chroot)
return six.text_type(prefix) + '.chroot_{0}'.format(chroot)
elif root:
return str(prefix) + '.root_{0}'.format(root)
return six.text_type(prefix) + '.root_{0}'.format(root)
return prefix
@ -157,6 +158,7 @@ def parse_config(file_name='/usr/local/etc/pkg.conf'):
with salt.utils.files.fopen(file_name) as ifile:
for line in ifile:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('#') or line.startswith('\n'):
pass
else:

View File

@ -8,7 +8,7 @@ Pkgutil support for Solaris
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy

View File

@ -2,7 +2,7 @@
'''
Package support for the REST example
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging
@ -11,6 +11,9 @@ import logging
import salt.utils.data
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
@ -67,7 +70,7 @@ def version(*names, **kwargs):
salt '*' pkg.version <package1> <package2> <package3> ...
'''
if len(names) == 1:
return str(__proxy__['rest_sample.package_status'](names[0]))
return six.text_type(__proxy__['rest_sample.package_status'](names[0]))
def upgrade(refresh=True, skip_verify=True, **kwargs):
@ -90,9 +93,9 @@ def installed(
p = __proxy__['rest_sample.package_status'](name)
if version is None:
if 'ret' in p:
return str(p['ret'])
return six.text_type(p['ret'])
else:
return True
else:
if p is not None:
return version == str(p)
return version == six.text_type(p)

View File

@ -4,7 +4,7 @@ Support for rpm
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import re
@ -184,7 +184,7 @@ def verify(*packages, **kwargs):
try:
ignore_types = [x.strip() for x in ignore_types.split(',')]
except AttributeError:
ignore_types = [x.strip() for x in str(ignore_types).split(',')]
ignore_types = [x.strip() for x in six.text_type(ignore_types).split(',')]
verify_options = kwargs.get('verify_options', [])
if not isinstance(verify_options, (list, six.string_types)):
@ -195,7 +195,7 @@ def verify(*packages, **kwargs):
try:
verify_options = [x.strip() for x in verify_options.split(',')]
except AttributeError:
verify_options = [x.strip() for x in str(verify_options).split(',')]
verify_options = [x.strip() for x in six.text_type(verify_options).split(',')]
cmd = ['rpm']
cmd.extend(['--' + x for x in verify_options])
@ -544,7 +544,7 @@ def info(*packages, **attr):
comment = ''
if 'stderr' in call:
comment += (call['stderr'] or call['stdout'])
raise CommandExecutionError('{0}'.format(comment))
raise CommandExecutionError(comment)
elif 'error' in call['stderr']:
raise CommandExecutionError(call['stderr'])
else:
@ -582,7 +582,7 @@ def info(*packages, **attr):
try:
pkg_data[key] = datetime.datetime.utcfromtimestamp(int(value)).isoformat() + "Z"
except ValueError:
log.warning('Could not convert "{0}" into Unix time'.format(value))
log.warning('Could not convert "%s" into Unix time', value)
continue
# Convert Unix ticks into an Integer
@ -590,7 +590,7 @@ def info(*packages, **attr):
try:
pkg_data[key] = int(value)
except ValueError:
log.warning('Could not convert "{0}" into Unix time'.format(value))
log.warning('Could not convert "%s" into Unix time', value)
continue
if key not in ['description', 'name'] and value:
pkg_data[key] = value
@ -635,7 +635,9 @@ def version_cmp(ver1, ver2, ignore_epoch=False):
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
'''
normalize = lambda x: str(x).split(':', 1)[-1] if ignore_epoch else str(x)
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch \
else six.text_type(x)
ver1 = normalize(ver1)
ver2 = normalize(ver2)

View File

@ -36,8 +36,7 @@ Or you can override it globally by setting the :conf_minion:`providers` paramete
'''
# Import python libs
from __future__ import print_function
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
@ -141,7 +140,7 @@ def upgrade_available(name):
salt '*' pkg.upgrade_available apache-22
'''
version = None
cmd = 'pkg list -Huv {0}'.format(name)
cmd = ['pkg', 'list', '-Huv', name]
lines = __salt__['cmd.run_stdout'](cmd).splitlines()
if not lines:
return {}
@ -299,16 +298,15 @@ def version(*names, **kwargs):
salt '*' pkg_resource.version pkg://solaris/entire
'''
namelist = ''
for pkgname in names:
namelist += '{0} '.format(pkgname)
cmd = '/bin/pkg list -Hv {0}'.format(namelist)
lines = __salt__['cmd.run_stdout'](cmd).splitlines()
ret = {}
for line in lines:
ret[_ips_get_pkgname(line)] = _ips_get_pkgversion(line)
if ret:
return ret
if names:
cmd = ['/bin/pkg', 'list', '-Hv']
cmd.extend(names)
lines = __salt__['cmd.run_stdout'](cmd).splitlines()
ret = {}
for line in lines:
ret[_ips_get_pkgname(line)] = _ips_get_pkgversion(line)
if ret:
return ret
return ''
@ -325,7 +323,7 @@ def latest_version(name, **kwargs):
salt '*' pkg.latest_version pkg://solaris/entire
'''
cmd = '/bin/pkg list -Hnv {0}'.format(name)
cmd = ['/bin/pkg', 'list', '-Hnv', name]
lines = __salt__['cmd.run_stdout'](cmd).splitlines()
ret = {}
for line in lines:
@ -352,7 +350,7 @@ def get_fmri(name, **kwargs):
if name.startswith('pkg://'):
# already full fmri
return name
cmd = '/bin/pkg list -aHv {0}'.format(name)
cmd = ['/bin/pkg', 'list', '-aHv', name]
# there can be more packages matching the name
lines = __salt__['cmd.run_stdout'](cmd).splitlines()
if not lines:
@ -380,7 +378,7 @@ def normalize_name(name, **kwargs):
if name.startswith('pkg://'):
# already full fmri
return name
cmd = '/bin/pkg list -aHv {0}'.format(name)
cmd = ['/bin/pkg', 'list', '-aHv', name]
# there can be more packages matching the name
lines = __salt__['cmd.run_stdout'](cmd).splitlines()
# if we get more lines, it's multiple match (name not unique)
@ -405,7 +403,7 @@ def is_installed(name, **kwargs):
salt '*' pkg.is_installed bash
'''
cmd = '/bin/pkg list -Hv {0}'.format(name)
cmd = ['/bin/pkg', 'list', '-Hv', name]
return __salt__['cmd.retcode'](cmd) == 0
@ -423,8 +421,8 @@ def search(name, versions_as_list=False, **kwargs):
'''
ret = {}
cmd = '/bin/pkg list -aHv {0}'.format(name)
out = __salt__['cmd.run_all'](cmd)
cmd = ['/bin/pkg', 'list', '-aHv', name]
out = __salt__['cmd.run_all'](cmd, ignore_retcode=True)
if out['retcode'] != 0:
# error = nothing found
return {}
@ -481,11 +479,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa
list(pkg.items())[0][1])
else:
pkg2inst += '{0} '.format(list(pkg.items())[0][0])
log.debug(
'Installing these packages instead of {0}: {1}'.format(
name, pkg2inst
)
)
log.debug('Installing these packages instead of %s: %s', name, pkg2inst)
else: # install single package
if version:
@ -493,9 +487,9 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa
else:
pkg2inst = "{0}".format(name)
cmd = 'pkg install -v --accept '
cmd = ['pkg', 'install', '-v', '--accept']
if test:
cmd += '-n '
cmd.append('-n')
# Get a list of the packages before install so we can diff after to see
# what got installed.
@ -503,7 +497,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa
# Install or upgrade the package
# If package is already installed
cmd += '{0}'.format(pkg2inst)
cmd.append(pkg2inst)
out = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
@ -556,23 +550,18 @@ def remove(name=None, pkgs=None, **kwargs):
salt '*' pkg.remove pkg://solaris/shell/tcsh
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
pkg2rm = ''
if pkgs: # multiple packages specified
for pkg in pkgs:
pkg2rm += '{0} '.format(pkg)
log.debug(
'Installing these packages instead of {0}: {1}'.format(
name, pkg2rm
)
)
else: # remove single package
pkg2rm = '{0}'.format(name)
targets = salt.utils.args.split_input(pkgs) if pkgs else [name]
if not targets:
return {}
if pkgs:
log.debug('Removing these packages instead of %s: %s', name, targets)
# Get a list of the currently installed pkgs.
old = list_pkgs()
# Remove the package(s)
cmd = '/bin/pkg uninstall -v {0}'.format(pkg2rm)
cmd = ['/bin/pkg', 'uninstall', '-v'] + targets
out = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
# Get a list of the packages after the uninstall

View File

@ -8,7 +8,7 @@ Package support for Solaris
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
@ -19,6 +19,7 @@ import logging
import salt.utils.data
import salt.utils.functools
import salt.utils.files
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, MinionError
log = logging.getLogger(__name__)
@ -57,21 +58,23 @@ def _write_adminfile(kwargs):
basedir = kwargs.get('basedir', 'default')
# Make tempfile to hold the adminfile contents.
fd_, adminfile = salt.utils.files.mkstemp(prefix="salt-", close_fd=False)
adminfile = salt.utils.files.mkstemp(prefix="salt-")
# Write to file then close it.
os.write(fd_, 'email={0}\n'.format(email))
os.write(fd_, 'instance={0}\n'.format(instance))
os.write(fd_, 'partial={0}\n'.format(partial))
os.write(fd_, 'runlevel={0}\n'.format(runlevel))
os.write(fd_, 'idepend={0}\n'.format(idepend))
os.write(fd_, 'rdepend={0}\n'.format(rdepend))
os.write(fd_, 'space={0}\n'.format(space))
os.write(fd_, 'setuid={0}\n'.format(setuid))
os.write(fd_, 'conflict={0}\n'.format(conflict))
os.write(fd_, 'action={0}\n'.format(action))
os.write(fd_, 'basedir={0}\n'.format(basedir))
os.close(fd_)
def _write_line(fp_, line):
fp_.write(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(adminfile, 'w') as fp_:
_write_line(fp_, 'email={0}\n'.format(email))
_write_line(fp_, 'instance={0}\n'.format(instance))
_write_line(fp_, 'partial={0}\n'.format(partial))
_write_line(fp_, 'runlevel={0}\n'.format(runlevel))
_write_line(fp_, 'idepend={0}\n'.format(idepend))
_write_line(fp_, 'rdepend={0}\n'.format(rdepend))
_write_line(fp_, 'space={0}\n'.format(space))
_write_line(fp_, 'setuid={0}\n'.format(setuid))
_write_line(fp_, 'conflict={0}\n'.format(conflict))
_write_line(fp_, 'action={0}\n'.format(action))
_write_line(fp_, 'basedir={0}\n'.format(basedir))
return adminfile
@ -337,42 +340,46 @@ def install(name=None, sources=None, saltenv='base', **kwargs):
log.error('"sources" param required for solaris pkg_add installs')
return {}
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
adminfile = _write_adminfile(kwargs)
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
adminfile = _write_adminfile(kwargs)
old = list_pkgs()
cmd_prefix = '/usr/sbin/pkgadd -n -a {0} '.format(adminfile)
old = list_pkgs()
cmd_prefix = ['/usr/sbin/pkgadd', '-n', '-a', adminfile]
# Only makes sense in a global zone but works fine in non-globals.
if kwargs.get('current_zone_only') == 'True':
cmd_prefix += '-G '
# Only makes sense in a global zone but works fine in non-globals.
if kwargs.get('current_zone_only') == 'True':
cmd_prefix += '-G '
errors = []
for pkg in pkg_params:
cmd = cmd_prefix + '-d {0} "all"'.format(pkg)
# Install the package{s}
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
errors = []
for pkg in pkg_params:
cmd = cmd_prefix + ['-d', pkg, 'all']
# Install the package{s}
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
# Remove the temp adminfile
if 'admin_source' not in kwargs:
os.unlink(adminfile)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret
@ -442,63 +449,40 @@ def remove(name=None, pkgs=None, saltenv='base', **kwargs):
if not targets:
return {}
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
# Set the adminfile default variables
email = kwargs.get('email', '')
instance = kwargs.get('instance', 'quit')
partial = kwargs.get('partial', 'nocheck')
runlevel = kwargs.get('runlevel', 'nocheck')
idepend = kwargs.get('idepend', 'nocheck')
rdepend = kwargs.get('rdepend', 'nocheck')
space = kwargs.get('space', 'nocheck')
setuid = kwargs.get('setuid', 'nocheck')
conflict = kwargs.get('conflict', 'nocheck')
action = kwargs.get('action', 'nocheck')
basedir = kwargs.get('basedir', 'default')
try:
if 'admin_source' in kwargs:
adminfile = __salt__['cp.cache_file'](kwargs['admin_source'], saltenv)
else:
# Make tempfile to hold the adminfile contents.
adminfile = _write_adminfile(kwargs)
# Make tempfile to hold the adminfile contents.
fd_, adminfile = salt.utils.files.mkstemp(prefix="salt-", close_fd=False)
# Remove the package
cmd = ['/usr/sbin/pkgrm', '-n', '-a', adminfile] + targets
out = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
# Write to file then close it.
os.write(fd_, 'email={0}\n'.format(email))
os.write(fd_, 'instance={0}\n'.format(instance))
os.write(fd_, 'partial={0}\n'.format(partial))
os.write(fd_, 'runlevel={0}\n'.format(runlevel))
os.write(fd_, 'idepend={0}\n'.format(idepend))
os.write(fd_, 'rdepend={0}\n'.format(rdepend))
os.write(fd_, 'space={0}\n'.format(space))
os.write(fd_, 'setuid={0}\n'.format(setuid))
os.write(fd_, 'conflict={0}\n'.format(conflict))
os.write(fd_, 'action={0}\n'.format(action))
os.write(fd_, 'basedir={0}\n'.format(basedir))
os.close(fd_)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
# Remove the package
cmd = ['/usr/sbin/pkgrm', '-n', '-a', adminfile] + targets
out = __salt__['cmd.run_all'](cmd,
python_shell=False,
output_loglevel='trace')
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
# Remove the temp adminfile
if 'admin_source' not in kwargs:
os.unlink(adminfile)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
finally:
# Remove the temp adminfile
if 'admin_source' not in kwargs:
try:
os.remove(adminfile)
except (NameError, OSError):
pass
return ret

View File

@ -2,7 +2,7 @@
'''
Service support for the REST example
'''
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import Python libs
import logging

View File

@ -11,7 +11,7 @@ Provides the service module for systemd
<module-provider-override>`.
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import errno
import glob
import logging
@ -24,6 +24,7 @@ import shlex
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.stringutils
import salt.utils.systemd
from salt.exceptions import CommandExecutionError
@ -70,7 +71,7 @@ def _canonical_unit_name(name):
of the valid suffixes as a service.
'''
if not isinstance(name, six.string_types):
name = str(name)
name = six.text_type(name)
if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES):
return name
return '%s.service' % name
@ -158,6 +159,7 @@ def _default_runlevel():
try:
with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('env DEFAULT_RUNLEVEL'):
runlevel = line.split('=')[-1].strip()
except Exception:
@ -167,6 +169,7 @@ def _default_runlevel():
try:
with salt.utils.files.fopen('/etc/inittab') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if not line.startswith('#') and 'initdefault' in line:
runlevel = line.split(':')[1]
except Exception:
@ -179,6 +182,7 @@ def _default_runlevel():
('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single'))
with salt.utils.files.fopen('/proc/cmdline') as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
for arg in line.strip().split():
if arg in valid_strings:
runlevel = arg

View File

@ -30,8 +30,7 @@ old.
'''
# Import python future libs
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import absolute_import, print_function, unicode_literals
import collections
import datetime
import errno
@ -120,7 +119,7 @@ def latest_version(*names, **kwargs):
# no need to call _refresh_db_conditional as list_pkgs will do it
installed_pkgs = list_pkgs(
versions_as_list=True, saltenv=saltenv, refresh=refresh)
log.trace('List of installed packages: {0}'.format(installed_pkgs))
log.trace('List of installed packages: %s', installed_pkgs)
# iterate over all requested package names
for name in names:
@ -147,27 +146,31 @@ def latest_version(*names, **kwargs):
# get latest available (from winrepo_dir) version of package
pkg_info = _get_package_info(name, saltenv=saltenv)
log.trace('Raw winrepo pkg_info for {0} is {1}'.format(name, pkg_info))
log.trace('Raw winrepo pkg_info for %s is %s', name, pkg_info)
# latest_available can be version number or 'latest' or even 'Not Found'
latest_available = _get_latest_pkg_version(pkg_info)
if latest_available:
log.debug('Latest available version '
'of package {0} is {1}'.format(name, latest_available))
log.debug(
'Latest available version of package %s is %s',
name, latest_available
)
# check, whether latest available version
# is newer than latest installed version
if compare_versions(ver1=six.text_type(latest_available),
oper='>',
ver2=six.text_type(latest_installed)):
log.debug('Upgrade of {0} from {1} to {2} '
'is available'.format(name,
latest_installed,
latest_available))
log.debug(
'Upgrade of %s from %s to %s is available',
name, latest_installed, latest_available
)
ret[name] = latest_available
else:
log.debug('No newer version than {0} of {1} '
'is available'.format(latest_installed, name))
log.debug(
'No newer version than %s of %s is available',
latest_installed, name
)
if len(names) == 1:
return ret[names[0]]
return ret
@ -836,26 +839,28 @@ def _repo_process_pkg_sls(filename, short_path_name, ret, successful_verbose):
for version_str, repodata in six.iteritems(versions):
# Ensure version is a string/unicode
if not isinstance(version_str, six.string_types):
msg = (
'package \'{0}\'{{0}}, version number {1} '
log.error(
"package '%s' within '%s', version number %s' "
"is not a string",
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', version number {1} '
'is not a string'.format(pkgname, version_str)
)
log.error(
msg.format(' within \'{0}\''.format(short_path_name))
)
errors.append(msg.format(''))
continue
# Ensure version contains a dict
if not isinstance(repodata, dict):
msg = (
'package \'{0}\'{{0}}, repo data for '
'version number {1} is not defined as a dictionary '
log.error(
"package '%s' within '%s', repo data for "
'version number %s is not defined as a dictionary',
pkgname, short_path_name, version_str
)
errors.append(
'package \'{0}\', repo data for '
'version number {1} is not defined as a dictionary'
.format(pkgname, version_str)
)
log.error(
msg.format(' within \'{0}\''.format(short_path_name))
)
errors.append(msg.format(''))
continue
revmap[repodata['full_name']] = pkgname
if errors:
@ -917,8 +922,10 @@ def _get_msiexec(use_msiexec):
if os.path.isfile(use_msiexec):
return True, use_msiexec
else:
log.warning(("msiexec path '{0}' not found. Using system registered"
" msiexec instead").format(use_msiexec))
log.warning(
"msiexec path '%s' not found. Using system registered "
"msiexec instead", use_msiexec
)
use_msiexec = True
if use_msiexec is True:
return True, 'msiexec'
@ -1119,7 +1126,7 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
# Make sure pkginfo was found
if not pkginfo:
log.error('Unable to locate package {0}'.format(pkg_name))
log.error('Unable to locate package %s', pkg_name)
ret[pkg_name] = 'Unable to locate package {0}'.format(pkg_name)
continue
@ -1145,8 +1152,8 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
continue
# If version number not installed, is the version available?
elif version_num != 'latest' and version_num not in pkginfo:
log.error('Version {0} not found for package '
'{1}'.format(version_num, pkg_name))
log.error('Version %s not found for package %s',
version_num, pkg_name)
ret[pkg_name] = {'not found': version_num}
continue
@ -1160,8 +1167,8 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
# Is there an installer configured?
if not installer:
log.error('No installer configured for version {0} of package '
'{1}'.format(version_num, pkg_name))
log.error('No installer configured for version %s of package %s',
version_num, pkg_name)
ret[pkg_name] = {'no installer': version_num}
continue
@ -1195,7 +1202,7 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
# Check if the cache_file was cached successfully
if not cached_file:
log.error('Unable to cache {0}'.format(cache_file))
log.error('Unable to cache %s', cache_file)
ret[pkg_name] = {
'failed to cache cache_file': cache_file
}
@ -1209,8 +1216,10 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache file {0} '
'from saltenv: {1}'.format(installer, saltenv))
log.error(
'Unable to cache file %s from saltenv: %s',
installer, saltenv
)
ret[pkg_name] = {'unable to cache': installer}
continue
@ -1226,7 +1235,7 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache {0}'.format(installer))
log.error('Unable to cache %s', installer)
ret[pkg_name] = {'unable to cache': installer}
continue
else:
@ -1241,13 +1250,13 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
source_hash = pkginfo[version_num].get('source_hash', False)
if source_hash:
source_sum = _get_source_sum(source_hash, cached_pkg, saltenv)
log.debug('Source {0} hash: {1}'.format(source_sum['hash_type'],
source_sum['hsum']))
log.debug('Source %s hash: %s',
source_sum['hash_type'], source_sum['hsum'])
cached_pkg_sum = salt.utils.hashutils.get_hash(cached_pkg,
source_sum['hash_type'])
log.debug('Package {0} hash: {1}'.format(source_sum['hash_type'],
cached_pkg_sum))
log.debug('Package %s hash: %s',
source_sum['hash_type'], cached_pkg_sum)
if source_sum['hsum'] != cached_pkg_sum:
raise SaltInvocationError(
@ -1305,7 +1314,7 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
flags=re.IGNORECASE + re.UNICODE) is not None:
ret[pkg_name] = {'install status': 'task started'}
if not __salt__['task.run'](name='update-salt-software'):
log.error('Failed to install {0}'.format(pkg_name))
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
@ -1320,15 +1329,14 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
break
if not task_running:
log.error(
'Failed to install {0}'.format(pkg_name))
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
# All other packages run with task scheduler
else:
if not __salt__['task.run_wait'](name='update-salt-software'):
log.error('Failed to install {0}'.format(pkg_name))
log.error('Failed to install %s', pkg_name)
log.error('Scheduled Task failed to run')
ret[pkg_name] = {'install status': 'failed'}
else:
@ -1354,9 +1362,9 @@ def install(name=None, refresh=False, pkgs=None, **kwargs):
ret[pkg_name] = {'install status': 'success, reboot initiated'}
changed.append(pkg_name)
else:
log.error('Failed to install {0}'.format(pkg_name))
log.error('retcode {0}'.format(result['retcode']))
log.error('installer output: {0}'.format(result['stdout']))
log.error('Failed to install %s', pkg_name)
log.error('retcode %s', result['retcode'])
log.error('installer output: %s', result['stdout'])
ret[pkg_name] = {'install status': 'failed'}
# Get a new list of installed software
@ -1577,7 +1585,7 @@ def remove(name=None, pkgs=None, version=None, **kwargs):
# Check if the installer was cached successfully
if not cached_pkg:
log.error('Unable to cache {0}'.format(uninstaller))
log.error('Unable to cache %s', uninstaller)
ret[pkgname] = {'unable to cache': uninstaller}
continue
else:
@ -1765,7 +1773,7 @@ def get_repo_data(saltenv='base'):
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(repo_details.winrepo_file, 'rb') as repofile:
try:
repodata = serial.loads(repofile.read()) or {}
repodata = salt.utils.data.decode(serial.loads(repofile.read()) or {})
__context__['winrepo.data'] = repodata
return repodata
except Exception as exc:

View File

@ -9,7 +9,7 @@ Package support for XBPS package manager (used by VoidLinux)
# new repo?
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
import logging
@ -20,6 +20,7 @@ import salt.utils.data
import salt.utils.files
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.decorators as decorators
from salt.exceptions import CommandExecutionError, MinionError
@ -51,10 +52,9 @@ def _get_version():
'''
Get the xbps version
'''
xpath = _check_xbps()
version_string = __salt__['cmd.run'](
'{0} --version'.format(xpath), output_loglevel='trace'
)
[_check_xbps(), '--version'],
output_loglevel='trace')
if version_string is None:
# Dunno why it would, but...
return False
@ -108,8 +108,10 @@ def list_pkgs(versions_as_list=False, **kwargs):
# XXX handle package status (like 'ii') ?
pkg, ver = line.split(None)[1].rsplit('-', 1)
except ValueError:
log.error('xbps-query: Unexpected formatting in '
'line: "{0}"'.format(line))
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
__salt__['pkg_resource.add_pkg'](ret, pkg, ver)
@ -153,11 +155,13 @@ def list_upgrades(refresh=True):
try:
pkg, ver = line.split()[0].rsplit('-', 1)
except (ValueError, IndexError):
log.error('xbps-query: Unexpected formatting in '
'line: "{0}"'.format(line))
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
continue
log.trace('pkg={0} version={1}'.format(pkg, ver))
log.trace('pkg=%s version=%s', pkg, ver)
ret[pkg] = ver
return ret
@ -211,9 +215,9 @@ def latest_version(*names, **kwargs):
# retrieve list of updatable packages
# ignore return code since 'is up to date' case produces retcode==17 (xbps 0.51)
cmd = '{0} {1}'.format('xbps-install -un', ' '.join(names))
out = __salt__['cmd.run'](cmd, ignore_retcode=True,
output_loglevel='trace')
cmd = ['xbps-install', '-un']
cmd.extend(names)
out = __salt__['cmd.run'](cmd, ignore_retcode=True, output_loglevel='trace')
for line in out.splitlines():
if not line:
continue
@ -223,11 +227,13 @@ def latest_version(*names, **kwargs):
try:
pkg, ver = line.split()[0].rsplit('-', 1)
except (ValueError, IndexError):
log.error('xbps-query: Unexpected formatting in '
'line: "{0}"'.format(line))
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
continue
log.trace('pkg={0} version={1}'.format(pkg, ver))
log.trace('pkg=%s version=%s', pkg, ver)
if pkg in names:
ret[pkg] = ver
@ -273,7 +279,7 @@ def refresh_db():
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError('{0}'.format(comment))
raise CommandExecutionError(comment)
return True
@ -403,23 +409,20 @@ def install(name=None, refresh=False, fromrepo=None,
return {}
if pkg_type != 'repository':
log.error('xbps: pkg_type "{0}" not supported.'.format(pkg_type))
log.error('xbps: pkg_type "%s" not supported.', pkg_type)
return {}
args = []
cmd = ['xbps-install']
if refresh:
args.append('-S') # update repo db
cmd.append('-S') # update repo db
if fromrepo:
args.append('--repository={0}'.format(fromrepo))
args.append('-y') # assume yes when asked
args.extend(pkg_params)
cmd.append('--repository={0}'.format(fromrepo))
cmd.append('-y') # assume yes when asked
cmd.extend(pkg_params)
old = list_pkgs()
__salt__['cmd.run'](
'{0} {1}'.format('xbps-install', ' '.join(args)),
output_loglevel='trace'
)
__salt__['cmd.run'](cmd, output_loglevel='trace')
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
@ -500,8 +503,10 @@ def list_repos():
try:
nb, url, rsa = line.strip().split(' ', 2)
except ValueError:
log.error('Problem parsing xbps-query: Unexpected formatting in '
'line: "{0}"'.format(line))
log.error(
'Problem parsing xbps-query: '
'Unexpected formatting in line: "%s"', line
)
repo['nbpkg'] = int(nb) if nb.isdigit() else 0
repo['url'] = url
repo['rsasigned'] = True if rsa == '(RSA signed)' else False
@ -556,14 +561,14 @@ def _locate_repo_files(repo, rewrite=False):
write_buff = []
with salt.utils.files.fopen(filename, 'r') as cur_file:
for line in cur_file:
if regex.match(line):
if regex.match(salt.utils.stringutils.to_unicode(line)):
ret_val.append(filename)
else:
write_buff.append(line)
if rewrite and filename in ret_val:
if len(write_buff) > 0:
with salt.utils.files.fopen(filename, 'w') as rewrite_file:
rewrite_file.write("".join(write_buff))
rewrite_file.writelines(write_buff)
else: # Prune empty files
os.remove(filename)
@ -591,7 +596,11 @@ def add_repo(repo, conffile='/usr/share/xbps.d/15-saltstack.conf'):
if len(_locate_repo_files(repo)) == 0:
try:
with salt.utils.files.fopen(conffile, 'a+') as conf_file:
conf_file.write('repository='+repo+'\n')
conf_file.write(
salt.utils.stringutils.to_str(
'repository={0}\n'.format(repo)
)
)
except IOError:
return False

View File

@ -15,7 +15,7 @@ Support for YUM/DNF
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import contextlib
import datetime
import fnmatch
@ -824,14 +824,14 @@ def list_repo_pkgs(*args, **kwargs):
try:
fromrepo = [x.strip() for x in fromrepo.split(',')]
except AttributeError:
fromrepo = [x.strip() for x in str(fromrepo).split(',')]
fromrepo = [x.strip() for x in six.text_type(fromrepo).split(',')]
if disablerepo and not isinstance(disablerepo, list):
try:
disablerepo = [x.strip() for x in disablerepo.split(',')
if x != '*']
except AttributeError:
disablerepo = [x.strip() for x in str(disablerepo).split(',')
disablerepo = [x.strip() for x in six.text_type(disablerepo).split(',')
if x != '*']
if enablerepo and not isinstance(enablerepo, list):
@ -839,7 +839,7 @@ def list_repo_pkgs(*args, **kwargs):
enablerepo = [x.strip() for x in enablerepo.split(',')
if x != '*']
except AttributeError:
enablerepo = [x.strip() for x in str(enablerepo).split(',')
enablerepo = [x.strip() for x in six.text_type(enablerepo).split(',')
if x != '*']
if fromrepo:
@ -849,7 +849,7 @@ def list_repo_pkgs(*args, **kwargs):
repo_name for repo_name, repo_info in six.iteritems(list_repos())
if repo_name in enablerepo
or (repo_name not in disablerepo
and str(repo_info.get('enabled', '1')) == '1')
and six.text_type(repo_info.get('enabled', '1')) == '1')
]
ret = {}
@ -1618,7 +1618,7 @@ def install(name=None,
if not to_unhold:
yield
else:
log.debug('Unholding packages: {0}'.format(', '.join(to_unhold)))
log.debug('Unholding packages: %s', ', '.join(to_unhold))
try:
# Using list() here for python3 compatibility, dict.keys() no
# longer returns a list in python3.
@ -2705,7 +2705,7 @@ def del_repo(repo, basedir=None, **kwargs): # pylint: disable=W0613
content += '\n{0}\n'.format(comments)
with salt.utils.files.fopen(repofile, 'w') as fileout:
fileout.write(content)
fileout.write(salt.utils.stringutils.to_str(content))
return 'Repo {0} has been removed from {1}'.format(repo, repofile)
@ -2846,7 +2846,7 @@ def mod_repo(repo, basedir=None, **kwargs):
content += '\n{0}\n'.format(comments)
with salt.utils.files.fopen(repofile, 'w') as fileout:
fileout.write(content)
fileout.write(salt.utils.stringutils.to_str(content))
return {repofile: filerepos}
@ -2862,7 +2862,8 @@ def _parse_repo_file(filename):
parsed.read(filename)
except configparser.MissingSectionHeaderError as err:
log.error(
'Failed to parse file {0}, error: {1}'.format(filename, err.message)
'Failed to parse file %s, error: %s',
filename, err.message
)
return ('', {})
@ -2875,12 +2876,13 @@ def _parse_repo_file(filename):
headers = ''
with salt.utils.files.fopen(filename, 'r') as rawfile:
for line in rawfile:
line = salt.utils.stringutils.to_unicode(line)
if line.strip().startswith('#'):
headers += '{0}\n'.format(line.strip())
else:
break
return (headers, config)
return (headers, salt.utils.data.decode(config))
def file_list(*packages):

View File

@ -13,7 +13,7 @@ Package support for openSUSE via the zypper package manager
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import re
@ -38,6 +38,7 @@ import salt.utils.files
import salt.utils.functools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.systemd
from salt.utils.versions import LooseVersion
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
@ -295,7 +296,7 @@ class _Zypper(object):
log.debug("Collected data about blocking process.")
__salt__['event.fire_master'](data, self.TAG_BLOCKED)
log.debug("Fired a Zypper blocked event to the master with the data: {0}".format(str(data)))
log.debug("Fired a Zypper blocked event to the master with the data: %s", data)
log.debug("Waiting 5 seconds for Zypper gets released...")
time.sleep(5)
if not was_blocked:
@ -430,7 +431,7 @@ def list_upgrades(refresh=True, **kwargs):
if 'fromrepo' in kwargs:
repo_name = kwargs['fromrepo']
if not isinstance(repo_name, six.string_types):
repo_name = str(repo_name)
repo_name = six.text_type(repo_name)
cmd.extend(['--repo', repo_name])
for update_node in __zypper__.nolock.xml.call(*cmd).getElementsByTagName('update'):
if update_node.getAttribute('kind') == 'package':
@ -480,7 +481,7 @@ def info_installed(*names, **kwargs):
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, **kwargs).items():
t_nfo = dict()
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
for key, value in six.iteritems(pkg_nfo):
if isinstance(value, six.string_types):
# Check, if string is encoded in a proper UTF-8
if six.PY3:
@ -489,7 +490,7 @@ def info_installed(*names, **kwargs):
value_ = value.decode('UTF-8', 'ignore').encode('UTF-8', 'ignore')
if value != value_:
value = kwargs.get('errors', 'ignore') == 'ignore' and value_ or 'N/A (invalid UTF-8)'
log.error('Package {0} has bad UTF-8 code in {1}: {2}'.format(pkg_name, key, value))
log.error('Package %s has bad UTF-8 code in %s: %s', pkg_name, key, value)
if key == 'source_rpm':
t_nfo['source'] = value
else:
@ -1180,7 +1181,7 @@ def install(name=None,
downgrades = []
if fromrepo:
fromrepoopt = ['--force', '--force-resolution', '--from', fromrepo]
log.info('Targeting repo \'{0}\''.format(fromrepo))
log.info('Targeting repo \'%s\'', fromrepo)
else:
fromrepoopt = ''
cmd_install = ['install', '--auto-agree-with-licenses']
@ -1315,7 +1316,7 @@ def upgrade(refresh=True,
if fromrepo:
for repo in fromrepo:
cmd_update.extend(['--from', repo])
log.info('Targeting repos: {0}'.format(fromrepo))
log.info('Targeting repos: %s', fromrepo)
if novendorchange:
# TODO: Grains validation should be moved to Zypper class
@ -1502,7 +1503,8 @@ def list_locks():
locks = {}
if os.path.exists(LOCKS):
with salt.utils.files.fopen(LOCKS) as fhr:
for meta in [item.split('\n') for item in fhr.read().split('\n\n')]:
items = salt.utils.stringutils.to_unicode(fhr.read()).split('\n\n')
for meta in [item.split('\n') for item in items]:
lock = {}
for element in [el for el in meta if el]:
if ':' in element:
@ -1946,7 +1948,7 @@ def list_products(all=False, refresh=False):
oem_file = os.path.join(OEM_PATH, p_nfo['productline'])
if os.path.isfile(oem_file):
with salt.utils.files.fopen(oem_file, 'r') as rfile:
oem_release = rfile.readline().strip()
oem_release = salt.utils.stringutils.to_unicode(rfile.readline()).strip()
if oem_release:
p_nfo['release'] = oem_release
ret.append(p_nfo)
@ -2207,10 +2209,10 @@ def resolve_capabilities(pkgs, refresh, **kwargs):
if len(result) == 1:
name = result.keys()[0]
elif len(result) > 1:
log.warn("Found ambiguous match for capability '{0}'.".format(pkg))
log.warn("Found ambiguous match for capability '%s'.", pkg)
except CommandExecutionError as exc:
# when search throws an exception stay with original name and version
log.debug("Search failed with: {0}".format(exc))
log.debug("Search failed with: %s", exc)
if version:
ret.append({name: version})

View File

@ -74,7 +74,7 @@ state module
'''
# Import python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import fnmatch
import logging
import os
@ -424,9 +424,8 @@ def _find_remove_targets(name=None,
if not _fulfills_version_spec(cver, oper, verstr,
ignore_epoch=ignore_epoch):
log.debug(
'Current version ({0}) did not match desired version '
'specification ({1}), will not remove'
.format(cver, verstr)
'Current version (%s) did not match desired version '
'specification (%s), will not remove', cver, verstr
)
else:
targets.append(pkgname)
@ -439,9 +438,8 @@ def _find_remove_targets(name=None,
if not targets:
# All specified packages are already absent
msg = (
'All specified packages{0} are already absent'
.format(' (matching specified versions)' if version_spec else '')
msg = 'All specified packages{0} are already absent'.format(
' (matching specified versions)' if version_spec else ''
)
return {'name': name,
'changes': {},
@ -757,9 +755,9 @@ def _find_install_targets(name=None,
altered_files[key] = verify_result
else:
log.debug(
'Current version ({0}) did not match desired version '
'specification ({1}), adding to installation targets'
.format(cver, val)
'Current version (%s) did not match desired version '
'specification (%s), adding to installation targets',
cver, val
)
targets[key] = val
@ -1498,7 +1496,7 @@ def installed(
'comment': 'pkg.verify not implemented'}
if not isinstance(version, six.string_types) and version is not None:
version = str(version)
version = six.text_type(version)
kwargs['allow_updates'] = allow_updates
@ -1536,7 +1534,7 @@ def installed(
return {'name': name,
'changes': {},
'result': False,
'comment': str(exc)}
'comment': six.text_type(exc)}
if 'result' in hold_ret and not hold_ret['result']:
return {'name': name,
@ -1705,7 +1703,7 @@ def installed(
name=name, pkgs=pkgs, sources=sources
)
except (CommandExecutionError, SaltInvocationError) as exc:
comment.append(str(exc))
comment.append(six.text_type(exc))
ret = {'name': name,
'changes': changes,
'result': False,
@ -2925,7 +2923,7 @@ def uptodate(name, refresh=False, pkgs=None, **kwargs):
packages = [pkg for pkg in packages if pkg in pkgs]
expected = {pkgname: pkgver for pkgname, pkgver in six.iteritems(expected) if pkgname in pkgs}
except Exception as exc:
ret['comment'] = str(exc)
ret['comment'] = six.text_type(exc)
return ret
else:
ret['comment'] = 'refresh must be either True or False'
@ -3031,7 +3029,7 @@ def group_installed(name, skip=None, include=None, **kwargs):
return ret
for idx, item in enumerate(skip):
if not isinstance(item, six.string_types):
skip[idx] = str(item)
skip[idx] = six.text_type(item)
if include is None:
include = []
@ -3041,7 +3039,7 @@ def group_installed(name, skip=None, include=None, **kwargs):
return ret
for idx, item in enumerate(include):
if not isinstance(item, six.string_types):
include[idx] = str(item)
include[idx] = six.text_type(item)
try:
diff = __salt__['pkg.group_diff'](name)

View File

@ -13,6 +13,7 @@ typically rather simple:
pkgng.update_packaging_site:
- name: "http://192.168.0.2"
'''
from __future__ import absolute_import, print_function, unicode_literals
def update_packaging_site(name):

View File

@ -86,7 +86,7 @@ these states. Here is some example SLS:
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import sys
# Import salt libs
@ -98,6 +98,9 @@ import salt.utils.pkg.deb
import salt.utils.pkg.rpm
import salt.utils.versions
# Import 3rd-party libs
from salt.ext import six
def __virtual__():
'''
@ -358,7 +361,7 @@ def managed(name, ppa=None, **kwargs):
try:
repo = ':'.join(('ppa', ppa))
except TypeError:
repo = ':'.join(('ppa', str(ppa)))
repo = ':'.join(('ppa', six.text_type(ppa)))
kwargs['disabled'] = not salt.utils.data.is_true(enabled) \
if enabled is not None \
@ -455,7 +458,7 @@ def managed(name, ppa=None, **kwargs):
salt.utils.data.is_true(pre[kwarg]):
break
else:
if str(sanitizedkwargs[kwarg]) != str(pre[kwarg]):
if six.text_type(sanitizedkwargs[kwarg]) != six.text_type(pre[kwarg]):
break
else:
ret['result'] = True

View File

@ -4,7 +4,7 @@ integration tests for mac_pkgutil
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt Testing libs

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import os
# Import Salt Testing libs

View File

@ -4,7 +4,7 @@
tests for pkg state
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import time
@ -26,6 +26,7 @@ import salt.utils.pkg.rpm
import salt.utils.platform
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import range # pylint: disable=import-error,redefined-builtin
log = logging.getLogger(__name__)
@ -511,7 +512,7 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin):
pkgquery = 'version'
ret = self.run_function('pkg.info_installed', [package])
self.assertTrue(pkgquery in str(ret))
self.assertTrue(pkgquery in six.text_type(ret))
@skipIf(salt.utils.platform.is_windows(), 'minion is windows')
@requires_system_grains

View File

@ -4,7 +4,7 @@ tests for pkgrepo states
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing libs
from tests.support.case import ModuleCase

View File

@ -4,7 +4,7 @@
'''
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import salt module
import salt.modules.mac_pkgutil as mac_pkgutil

View File

@ -4,7 +4,7 @@
'''
# Import Python Libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin

View File

@ -4,7 +4,7 @@
'''
# Import Python Libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
import yaml
# Import Salt Testing Libs

View File

@ -4,7 +4,7 @@
'''
# Import Python Libs
from __future__ import absolute_import
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin