Skip to content

Commit

Permalink
Lint: Fix str-format-in-logging, len-as-condition, etc. (1)
Browse files Browse the repository at this point in the history
This fixes violations found in the following locations:

- salt/auth/
- salt/beacons/
- salt/cli/
- salt/utils/
  • Loading branch information
terminalmage authored and dwoz committed May 19, 2020
1 parent 3ac465e commit 8a23ec9
Show file tree
Hide file tree
Showing 35 changed files with 74 additions and 85 deletions.
4 changes: 2 additions & 2 deletions salt/auth/ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def __init__(
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"
)
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions salt/auth/pki.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion salt/beacons/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def _get_index(self, beacon_config, label):
"""

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]
Expand Down
5 changes: 2 additions & 3 deletions salt/beacons/adb.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion salt/beacons/log_beacon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]))
Expand Down
14 changes: 5 additions & 9 deletions salt/beacons/napalm_beacon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down Expand Up @@ -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"]
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion salt/beacons/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
2 changes: 1 addition & 1 deletion salt/beacons/twilio_txt_msg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 5 additions & 3 deletions salt/utils/cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion salt/utils/dictdiffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)):
Expand Down
4 changes: 1 addition & 3 deletions salt/utils/dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions salt/utils/etcd_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def read(self, key, recursive=False, wait=False, timeout=None, waitIndex=None):
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
Expand All @@ -253,7 +253,7 @@ def read(self, key, recursive=False, wait=False, timeout=None, waitIndex=None):
return result

def _flatten(self, data, path=""):
if len(data.keys()) == 0:
if not data:
return {path: {}}
path = path.strip("/")
flat = {}
Expand Down
2 changes: 1 addition & 1 deletion salt/utils/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,7 +1248,7 @@ def flush_events(self):
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"])
Expand Down
2 changes: 1 addition & 1 deletion salt/utils/extmods.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 4 additions & 4 deletions salt/utils/find.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def _parse_size(value):
else:
style = "="

if len(scalar) > 0:
if scalar:
multiplier = {
"b": 2 ** 0,
"k": 2 ** 10,
Expand Down Expand Up @@ -498,7 +498,7 @@ def __init__(self, key, value):
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):
Expand Down Expand Up @@ -629,7 +629,7 @@ def __init__(self, options):
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)
Expand All @@ -645,7 +645,7 @@ def __init__(self, options):
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 = (
Expand Down
2 changes: 1 addition & 1 deletion salt/utils/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 6 additions & 7 deletions salt/utils/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 1 addition & 4 deletions salt/utils/kickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions salt/utils/master.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ def _tgt_to_list(self):
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,
Expand Down Expand Up @@ -826,7 +826,7 @@ def run(self):

try:

if len(new_c_data) == 0:
if not new_c_data:
log.debug("ConCache Got empty update from worker")
continue

Expand Down
2 changes: 1 addition & 1 deletion salt/utils/minions.py
Original file line number Diff line number Diff line change
Expand Up @@ -899,7 +899,7 @@ def auth_check_expanded(
# 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:
Expand Down
16 changes: 8 additions & 8 deletions salt/utils/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ def first(self):
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 (
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
Loading

0 comments on commit 8a23ec9

Please sign in to comment.