Lint: Fix str-format-in-logging, len-as-condition, etc. (1)

This fixes violations found in the following locations:

- salt/auth/
- salt/beacons/
- salt/cli/
- salt/utils/
This commit is contained in:
Erik Johnson 2019-01-16 15:57:50 -06:00 committed by Daniel Wozniak
parent 3ac465e59f
commit 8a23ec902d
35 changed files with 74 additions and 85 deletions

View file

@ -139,7 +139,7 @@ class _LDAPConnection(object):
self.ldap.set_option(ldap.OPT_REFERRALS, 0) # Needed for AD
if not anonymous:
if self.bindpw is None or len(self.bindpw) < 1:
if not self.bindpw:
raise CommandExecutionError(
"LDAP bind password is not set: password cannot be empty if auth.ldap.anonymous is False"
)
@ -289,7 +289,7 @@ def _bind(username, password, anonymous=False, opts=None):
scope,
)
result = _ldap.search_s(basedn, int(scope), paramvalues["filter"])
if len(result) < 1:
if not result:
log.warning("Unable to find user %s", username)
return False
elif len(result) > 1:

View file

@ -88,10 +88,10 @@ def auth(username, password, **kwargs):
cert = X509.load_cert_string(pem, X509.FORMAT_PEM)
cacert = X509.load_cert(cacert_file, X509.FORMAT_PEM)
if cert.verify(cacert.get_pubkey()):
log.info("Successfully authenticated certificate: {0}".format(pem))
log.info("Successfully authenticated certificate: %s", pem)
return True
else:
log.info("Failed to authenticate certificate: {0}".format(pem))
log.info("Failed to authenticate certificate: %s", pem)
return False
c = OpenSSL.crypto

View file

@ -192,7 +192,7 @@ class Beacon(object):
"""
indexes = [index for index, item in enumerate(beacon_config) if label in item]
if len(indexes) < 1:
if not indexes:
return -1
else:
return indexes[0]

View file

@ -163,11 +163,10 @@ def beacon(config):
# Maybe send an event if we don't have any devices
if "no_devices_event" in _config and _config["no_devices_event"] is True:
if len(found_devices) == 0 and not last_state_extra["no_devices"]:
if not found_devices and not last_state_extra["no_devices"]:
ret.append({"tag": "no_devices"})
# Did we have no devices listed this time around?
last_state_extra["no_devices"] = len(found_devices) == 0
last_state_extra["no_devices"] = not found_devices
return ret

View file

@ -116,7 +116,7 @@ def beacon(config):
for tag in _config.get("tags", {}):
if "regex" not in _config["tags"][tag]:
continue
if len(_config["tags"][tag]["regex"]) < 1:
if not _config["tags"][tag]["regex"]:
continue
try:
d[tag] = re.compile(r"{0}".format(_config["tags"][tag]["regex"]))

View file

@ -272,7 +272,7 @@ def _compare(cur_cmp, cur_struct):
elif isinstance(cur_struct, (six.integer_types, float)) and isinstance(
cur_cmp, (six.string_types, six.text_type)
):
# Comapring the numerical value against a presumably mathematical value
# Comparing the numerical value against a presumably mathematical value
log.debug(
"Comparing a numeric value (%d) with a string (%s)", cur_struct, cur_cmp
)
@ -324,16 +324,12 @@ def beacon(config):
fun_cfg = mod.values()[0]
args = fun_cfg.pop("_args", [])
kwargs = fun_cfg.pop("_kwargs", {})
log.debug(
"Executing {fun} with {args} and {kwargs}".format(
fun=fun, args=args, kwargs=kwargs
)
)
log.debug("Executing %s with %s and %s", fun, args, kwargs)
fun_ret = __salt__[fun](*args, **kwargs)
log.debug("Got the reply from the minion:")
log.debug(fun_ret)
if not fun_ret.get("result", False):
log.error("Error whilst executing {}".format(fun))
log.error("Error whilst executing %s", fun)
log.error(fun_ret)
continue
fun_ret_out = fun_ret["out"]
@ -346,9 +342,9 @@ def beacon(config):
# catch any exception and continue
# to not jeopardise the execution of the next function in the list
continue
log.debug("Result of comparison: {res}".format(res=fun_cmp_result))
log.debug("Result of comparison: %s", fun_cmp_result)
if fun_cmp_result:
log.info("Matched {fun} with {cfg}".format(fun=fun, cfg=fun_cfg))
log.info("Matched %s with %s", fun, fun_cfg)
event["tag"] = "{os}/{fun}".format(os=__grains__["os"], fun=fun)
event["fun"] = fun
event["args"] = args

View file

@ -125,7 +125,7 @@ def beacon(config):
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if len(config) < 1:
if not config:
config = [
{
"loadavg": ["all"],

View file

@ -92,7 +92,7 @@ def beacon(config):
client = TwilioRestClient(_config["account_sid"], _config["auth_token"])
messages = client.messages.list(to=_config["twilio_number"])
log.trace("Num messages: %d", len(messages))
if len(messages) < 1:
if not messages:
log.trace("Twilio beacon has no texts")
return ret

View file

@ -1026,8 +1026,10 @@ def wait_for_psexecsvc(host, port, username, password, timeout=900):
if time.time() - start > timeout:
return False
log.debug(
"Retrying psexec connection to host {0} on port {1} "
"(try {2})".format(host, port, try_count)
"Retrying psexec connection to host %s on port %s (try %s)",
host,
port,
try_count,
)
time.sleep(1)
@ -1535,7 +1537,7 @@ def deploy_script(
)
if sudo:
comps = tmp_dir.lstrip("/").rstrip("/").split("/")
if len(comps) > 0:
if comps:
if len(comps) > 1 or comps[0] != "tmp":
ret = root_cmd(
'chown {0} "{1}"'.format(username, tmp_dir),

View file

@ -61,7 +61,7 @@ def deep_diff(old, new, ignore=None):
new = copy.deepcopy(new)
stack = [(old, new, False)]
while len(stack) > 0:
while stack:
tmps = []
tmp_old, tmp_new, reentrant = stack.pop()
for key in set(list(tmp_old) + list(tmp_new)):

View file

@ -130,9 +130,7 @@ def _tree(domain, tld=False):
domain,
).group()
log.info(
"Without tldextract, dns.util resolves the TLD of {0} to {1}".format(
domain, tld
)
"Without tldextract, dns.util resolves the TLD of %s to %s", domain, tld
)
res = [domain]

View file

@ -238,7 +238,7 @@ class EtcdClient(object):
except etcd.EtcdException as err:
# EtcdValueError inherits from ValueError, so we don't want to accidentally
# catch this below on ValueError and give a bogus error message
log.error("etcd: {0}".format(err))
log.error("etcd: %s", err)
raise
except ValueError:
# python-etcd doesn't fully support python 2.6 and ends up throwing this for *any* exception because
@ -253,7 +253,7 @@ class EtcdClient(object):
return result
def _flatten(self, data, path=""):
if len(data.keys()) == 0:
if not data:
return {path: {}}
path = path.strip("/")
flat = {}

View file

@ -1248,7 +1248,7 @@ class EventReturn(salt.utils.process.SignalHandlingProcess):
else:
# Only a single event returner
log.debug(
"Calling event returner %s, only one " "configured.",
"Calling event returner %s, only one configured.",
self.opts["event_return"],
)
event_return = "{0}.event_return".format(self.opts["event_return"])

View file

@ -87,7 +87,7 @@ def sync(opts, form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None)
for sub_env in saltenv:
log.info("Syncing %s for environment '%s'", form, sub_env)
cache = []
log.info("Loading cache from {0}, for {1})".format(source, sub_env))
log.info("Loading cache from %s, for %s", source, sub_env)
# Grab only the desired files (.py, .pyx, .so)
cache.extend(
fileclient.cache_dir(

View file

@ -199,7 +199,7 @@ def _parse_size(value):
else:
style = "="
if len(scalar) > 0:
if scalar:
multiplier = {
"b": 2 ** 0,
"k": 2 ** 10,
@ -498,7 +498,7 @@ class PrintOption(Option):
self.fmt.append(arg)
if arg not in ["name", "path"]:
self.need_stat = True
if len(self.fmt) == 0:
if not self.fmt:
self.fmt.append("path")
def requires(self):
@ -629,7 +629,7 @@ class Finder(object):
if key.startswith("_"):
# this is a passthrough object, continue
continue
if value is None or len(str(value)) == 0:
if not value:
raise ValueError('missing value for "{0}" option'.format(key))
try:
obj = globals()[key.title() + "Option"](key, value)
@ -645,7 +645,7 @@ class Finder(object):
criteria[_REQUIRES_PATH].append(obj)
if hasattr(obj, "execute"):
self.actions.append(obj)
if len(self.actions) == 0:
if not self.actions:
self.actions.append(PrintOption("print", ""))
# order criteria so that least expensive checks are done first
self.criteria = (

View file

@ -59,7 +59,7 @@ def get_user_pubkeys(users):
ret[user] = {}
for key in keys:
if len(key_ids) > 0:
if key_ids:
if six.text_type(key["id"]) in key_ids:
ret[user][key["id"]] = key["key"]
else:

View file

@ -437,9 +437,10 @@ def query(
try:
match_hostname(sockwrap.getpeercert(), hostname)
except CertificateError as exc:
ret["error"] = (
"The certificate was invalid. Error returned was: %s",
pprint.pformat(exc),
ret[
"error"
] = "The certificate was invalid. Error returned was: {0}".format(
pprint.pformat(exc)
)
return ret
@ -634,9 +635,7 @@ def query(
if status is True:
ret["status"] = 0
ret["error"] = six.text_type(exc)
log.debug(
"Cannot perform 'http.query': {0} - {1}".format(url_full, ret["error"])
)
log.debug("Cannot perform 'http.query': %s - %s", url_full, ret["error"])
return ret
if stream is True or handle is True:
@ -1048,7 +1047,7 @@ def _sanitize_url_components(comp_list, field):
"""
Recursive function to sanitize each component of the url.
"""
if len(comp_list) == 0:
if not comp_list:
return ""
elif comp_list[0].startswith("{0}=".format(field)):
ret = "{0}=XXXXXXXXXX&".format(field)

View file

@ -770,10 +770,7 @@ def parse_updates(rule):
"""
rules = shlex.split(rule)
rules.pop(0)
if len(rules) > 0:
return {"url": rules[0]}
else:
return True
return {"url": rules[0]} if rules else True
def parse_upgrade(rule):

View file

@ -398,7 +398,7 @@ class MasterPillarUtil(object):
ckminions = salt.utils.minions.CkMinions(self.opts)
_res = ckminions.check_minions(self.tgt, self.tgt_type)
minion_ids = _res["minions"]
if len(minion_ids) == 0:
if not minion_ids:
log.debug(
'No minions matched for tgt="%s" and tgt_type="%s"',
self.tgt,
@ -826,7 +826,7 @@ class ConnectedCache(Process):
try:
if len(new_c_data) == 0:
if not new_c_data:
log.debug("ConCache Got empty update from worker")
continue

View file

@ -899,7 +899,7 @@ class CkMinions(object):
# if we take out all the allowed minions, and there are any left, then
# the target includes minions that are not allowed by eauth
# so we can give up here.
if len(minions - allowed_minions_from_auth_list) > 0:
if minions - allowed_minions_from_auth_list:
return False
try:

View file

@ -182,9 +182,9 @@ def _generate_minion_id():
hosts.append(a_nfo[3])
except socket.gaierror:
log.warning(
"Cannot resolve address {addr} info via socket: {message}".format(
addr=hosts.first() or "localhost (N/A)", message=socket.gaierror
)
"Cannot resolve address %s info via socket: %s",
hosts.first() or "localhost (N/A)",
socket.gaierror,
)
# Universal method for everywhere (Linux, Slowlaris, Windows etc)
for f_name in (
@ -1227,7 +1227,7 @@ def _subnets(proto="inet", interfaces_=None):
subnet = "prefixlen"
dflt_cidr = 128
else:
log.error("Invalid proto {0} calling subnets()".format(proto))
log.error("Invalid proto %s calling subnets()", proto)
return
for ip_info in ifaces.values():
@ -1450,7 +1450,7 @@ def hex2ip(hex_ip, invert=False):
else:
return address.compressed
except ipaddress.AddressValueError as ex:
log.error("hex2ip - ipv6 address error: {0}".format(ex))
log.error("hex2ip - ipv6 address error: %s", ex)
return hex_ip
try:
@ -1700,7 +1700,7 @@ def _freebsd_remotes_on(port, which_end):
cmd = salt.utils.args.shlex_split("sockstat -4 -c -p {0}".format(port))
data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError as ex:
log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
log.error('Failed "sockstat" with returncode = %s', ex.returncode)
raise
lines = salt.utils.stringutils.to_str(data).split("\n")
@ -1762,7 +1762,7 @@ def _netbsd_remotes_on(port, which_end):
cmd = salt.utils.args.shlex_split("sockstat -4 -c -n -p {0}".format(port))
data = subprocess.check_output(cmd) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError as ex:
log.error('Failed "sockstat" with returncode = {0}'.format(ex.returncode))
log.error('Failed "sockstat" with returncode = %s', ex.returncode)
raise
lines = salt.utils.stringutils.to_str(data).split("\n")
@ -1909,7 +1909,7 @@ def _linux_remotes_on(port, which_end):
# to locate Internet addresses, and it is not an error in this case.
log.warning('"lsof" returncode = 1, likely no active TCP sessions.')
return remotes
log.error('Failed "lsof" with returncode = {0}'.format(ex.returncode))
log.error('Failed "lsof" with returncode = %s', ex.returncode)
raise
lines = salt.utils.stringutils.to_str(data).split("\n")

View file

@ -89,13 +89,13 @@ class NxapiClient(object):
)
# Create UHTTPConnection object for NX-API communication over UDS.
log.info("Nxapi connection arguments: {0}".format(self.nxargs))
log.info("Nxapi connection arguments: %s", self.nxargs)
log.info("Connecting over unix domain socket")
self.connection = UHTTPConnection(self.NXAPI_UDS)
else:
# Remote connection - Proxy Minion, connect over http(s)
log.info("Nxapi connection arguments: {0}".format(self.nxargs))
log.info("Connecting over {}".format(self.nxargs["transport"]))
log.info("Nxapi connection arguments: %s", self.nxargs)
log.info("Connecting over %s", self.nxargs["transport"])
self.connection = salt.utils.http.query
def _use_remote_connection(self, kwargs):
@ -172,7 +172,7 @@ class NxapiClient(object):
request["headers"] = headers
request["payload"] = json.dumps(payload)
request["opts"] = {"http_request_timeout": self.nxargs["timeout"]}
log.info("request: {0}".format(request))
log.info("request: %s", request)
return request
def request(self, type, command_list):
@ -246,8 +246,8 @@ class NxapiClient(object):
for cmd_result, cmd in zip(output, command_list):
code = cmd_result.get("code")
msg = cmd_result.get("msg")
log.info("command {}:".format(cmd))
log.info("PARSE_RESPONSE: {0} {1}".format(code, msg))
log.info("command %s:", cmd)
log.info("PARSE_RESPONSE: %s %s", code, msg)
if code == "400":
raise CommandExecutionError(
{

View file

@ -209,7 +209,7 @@ class SaltNeutron(NeutronShell):
return resource
if resource.get("name") == name_or_id:
ret.append(resource)
if len(ret) == 0:
if not ret:
raise exceptions.MinionError("Resource not found.")
elif len(ret) >= 2:
raise exceptions.MinionError("Multiple resource matches found.")

View file

@ -95,7 +95,7 @@ class OrderedSet(MutableSet):
return OrderedSet(self)
def __getstate__(self):
if len(self) == 0:
if not self.items:
# The state can't be an empty list.
# We need to return a truthy value, or else __setstate__ won't be run.
#

View file

@ -3091,7 +3091,7 @@ class SaltRunOptionParser(
if self.options.doc and len(self.args) > 1:
self.error("You can only get documentation for one method at one time")
if len(self.args) > 0:
if self.args:
self.config["fun"] = self.args[0]
else:
self.config["fun"] = ""

View file

@ -547,7 +547,7 @@ class ProcessManager(object):
yield gen.sleep(10)
else:
time.sleep(10)
if len(self._process_map) == 0:
if not self._process_map:
break
# OSError is raised if a signal handler is called (SIGTERM) during os.wait
except OSError:

View file

@ -108,7 +108,7 @@ class Registry(object):
attr[id_] = OrderedDict()
# if we have requisites in our stack then add them to the state
if len(cls.requisites) > 0:
if cls.requisites:
for req in cls.requisites:
if req.requisite not in state.kwargs:
state.kwargs[req.requisite] = []
@ -183,7 +183,7 @@ class StateFactory(object):
self.valid_funcs = valid_funcs
def __getattr__(self, func):
if len(self.valid_funcs) > 0 and func not in self.valid_funcs:
if self.valid_funcs and func not in self.valid_funcs:
raise InvalidFunction(
"The function '{0}' does not exist in the "
"StateFactory for '{1}'".format(func, self.module)

View file

@ -29,5 +29,5 @@ def set_inventory_base_uri_default(config, opts):
return
base_roots = config.get("file_roots", {}).get("base", [])
if len(base_roots) > 0:
if base_roots:
opts["inventory_base_uri"] = base_roots[0]

View file

@ -254,7 +254,7 @@ def match_class_glob(_class, saltclass_path):
matches.extend(glob.glob(straight))
matches.extend(glob.glob(sub_straight))
matches.extend(glob.glob(sub_init))
if len(matches) == 0:
if not matches:
log.warning("%s: Class globbing did not yield any results", _class)
for match in matches:
classes.append(get_class_from_file(match, saltclass_path))

View file

@ -30,7 +30,7 @@ def sdb_get(uri, opts, utils=None):
sdlen = len("sdb://")
indx = uri.find("/", sdlen)
if (indx == -1) or len(uri[(indx + 1) :]) == 0:
if (indx == -1) or not uri[(indx + 1) :]:
return uri
profile = opts.get(uri[sdlen:indx], {})
@ -61,7 +61,7 @@ def sdb_set(uri, value, opts, utils=None):
sdlen = len("sdb://")
indx = uri.find("/", sdlen)
if (indx == -1) or len(uri[(indx + 1) :]) == 0:
if (indx == -1) or not uri[(indx + 1) :]:
return False
profile = opts.get(uri[sdlen:indx], {})
@ -92,7 +92,7 @@ def sdb_delete(uri, opts, utils=None):
sdlen = len("sdb://")
indx = uri.find("/", sdlen)
if (indx == -1) or len(uri[(indx + 1) :]) == 0:
if (indx == -1) or not uri[(indx + 1) :]:
return False
profile = opts.get(uri[sdlen:indx], {})

View file

@ -460,9 +460,7 @@ def _pack_alternative(extended_cfg, digest_collector, tfp):
)
if not os.path.exists(top):
log.error(
"File path {} does not exist. Unable to add to salt-ssh thin".format(
top
)
"File path %s does not exist. Unable to add to salt-ssh thin", top
)
continue
if not os.path.isdir(top):

View file

@ -40,7 +40,7 @@ def get_timestamp_at(time_in=None, time_at=None):
time_at = time_now + dt
return time.mktime(time_at.timetuple())
elif time_at:
log.debug("Predicted at specified as {}".format(time_at))
log.debug("Predicted at specified as %s", time_at)
if isinstance(time_at, (six.integer_types, float)):
# then it's a timestamp
return time_at

View file

@ -2368,7 +2368,7 @@ def check_perms(
else:
try:
set_owner(obj_name=obj_name, principal=owner, obj_type=obj_type)
log.debug("Owner set to {0}".format(owner))
log.debug("Owner set to %s", owner)
ret["changes"]["owner"] = owner
except CommandExecutionError:
ret["result"] = False
@ -2398,7 +2398,7 @@ def check_perms(
)
# Check permissions
log.debug("Getting current permissions for {0}".format(obj_name))
log.debug("Getting current permissions for %s", obj_name)
cur_perms = get_permissions(obj_name=obj_name, obj_type=obj_type)
# Verify Deny Permissions
@ -2426,7 +2426,7 @@ def check_perms(
# Check reset
# If reset=True, which users will be removed as a result
if reset:
log.debug("Resetting permissions for {0}".format(obj_name))
log.debug("Resetting permissions for %s", obj_name)
cur_perms = get_permissions(obj_name=obj_name, obj_type=obj_type)
for user_name in cur_perms["Not Inherited"]:
# case insensitive dictionary search
@ -2487,7 +2487,7 @@ def check_perms(
ret["comment"] = "\n".join(ret["comment"])
# Set result for test = True
if __opts__["test"] and (ret["changes"]):
if __opts__["test"] and ret["changes"]:
ret["result"] = None
return ret

View file

@ -120,7 +120,7 @@ def _netsh_file(content):
) as fp:
fp.write(content)
try:
log.debug("{0}:\n{1}".format(fp.name, content))
log.debug("%s:\n%s", fp.name, content)
return salt.modules.cmdmod.run(
"netsh -f {0}".format(fp.name), python_shell=True
)

View file

@ -60,7 +60,7 @@ def _to_full_dict(xmltree):
xmldict[attrName] = attrValue
if not xmltree:
if len(xmldict) == 0:
if not xmldict:
# If we don't have attributes, we should return the value as a string
# ex: <entry>test</entry>
return xmltree.text