Skip to content

Commit

Permalink
Merge pull request #51202 from terminalmage/lint-3
Browse files Browse the repository at this point in the history
Lint: Fix str-format-in-logging, len-as-condition, etc. (3)
  • Loading branch information
Erik Johnson authored Jan 30, 2019
2 parents 8dec102 + d31ec21 commit af96b6e
Show file tree
Hide file tree
Showing 73 changed files with 265 additions and 347 deletions.
6 changes: 2 additions & 4 deletions salt/modules/aixpkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa
return {}

if pkgs:
log.debug('Removing these fileset(s)/rpm package(s) {0}: {1}'
.format(name, targets))
log.debug('Removing these fileset(s)/rpm package(s) %s: %s', name, targets)

# Get a list of the currently installed pkgs.
old = list_pkgs()
Expand Down Expand Up @@ -320,8 +319,7 @@ def remove(name=None, pkgs=None, **kwargs):
return {}

if pkgs:
log.debug('Removing these fileset(s)/rpm package(s) {0}: {1}'
.format(name, targets))
log.debug('Removing these fileset(s)/rpm package(s) %s: %s', name, targets)

errors = []

Expand Down
2 changes: 1 addition & 1 deletion salt/modules/apk.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def latest_version(*names, **kwargs):
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))

if len(names) == 0:
if not names:
return ''

ret = {}
Expand Down
8 changes: 4 additions & 4 deletions salt/modules/aptpkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def latest_version(*names, **kwargs):
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)

if len(names) == 0:
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
Expand Down Expand Up @@ -572,7 +572,7 @@ def install(name=None,
if not fromrepo and repo:
fromrepo = repo

if pkg_params is None or len(pkg_params) == 0:
if not pkg_params:
return {}

cmd_prefix = []
Expand Down Expand Up @@ -1282,7 +1282,7 @@ def list_pkgs(versions_as_list=False,
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if len(cols):
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
Expand Down Expand Up @@ -1586,7 +1586,7 @@ def _skip_source(source):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if len(options) > 0:
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/augeas_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def _check_load_paths(load_path):
else:
log.info('Invalid augeas_cfg load_path entry: %s removed', _path)

if len(_paths) == 0:
if not _paths:
return None

return ':'.join(_paths)
Expand Down
3 changes: 1 addition & 2 deletions salt/modules/aws_sqs.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,7 @@ def delete_queue(name, region, opts=None, user=None):
queues = list_queues(region, opts, user)
url_map = _parse_queue_list(queues)

logger = logging.getLogger(__name__)
logger.debug('map ' + six.text_type(url_map))
log.debug('map %s', url_map)
if name in url_map:
delete = {'queue-url': url_map[name]}

Expand Down
11 changes: 4 additions & 7 deletions salt/modules/azurearm_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,7 @@ def default_security_rule_get(name, security_group, resource_group, **kwargs):
'error': 'Unable to find {0} in {1}!'.format(name, security_group)
}
except KeyError as exc:
log.error(
'Unable to find {0} in {1}!'.format(name, security_group)
)
log.error('Unable to find %s in %s!', name, security_group)
result = {'error': str(exc)}

return result
Expand Down Expand Up @@ -233,9 +231,7 @@ def default_security_rules_list(security_group, resource_group, **kwargs):
try:
result = secgroup['default_security_rules']
except KeyError as exc:
log.error(
'No default security rules found for {0}!'.format(security_group)
)
log.error('No default security rules found for %s!', security_group)
result = {'error': str(exc)}

return result
Expand Down Expand Up @@ -357,7 +353,8 @@ def security_rule_create_or_update(name, access, direction, priority, protocol,
# pylint: disable=eval-used
if not eval(params[0]) and not eval(params[1]):
log.error(
'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1])
'Either the %s or %s parameter must be provided!',
params[0], params[1]
)
return False
# pylint: disable=eval-used
Expand Down
16 changes: 5 additions & 11 deletions salt/modules/bcache.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,7 @@ def attach_(dev=None):
if 'cache' in data:
res[dev] = attach_(dev)

if len(res):
return res
else:
return None
return res if res else None

bcache = uuid(dev)
if bcache:
Expand Down Expand Up @@ -150,10 +147,7 @@ def detach(dev=None):
if 'cache' in data:
res[dev] = detach(dev)

if len(res):
return res
else:
return None
return res if res else None

log.debug('Detaching %s', dev)
if not _bcsys(dev, 'detach', 'goaway', 'error', 'Error detaching {0}'.format(dev)):
Expand Down Expand Up @@ -536,7 +530,7 @@ def device(dev, stats=False, config=False, internals=False, superblock=False):
if internals:
interres = result.pop('inter_ro', {})
interres.update(result.pop('inter_rw', {}))
if len(interres):
if interres:
for key in interres:
if key.startswith('internal'):
nkey = re.sub(r'internal[s/]*', '', key)
Expand Down Expand Up @@ -668,7 +662,7 @@ def _bdev(dev=None):
if not dev:
return False
else:
return _devbase(os.path.realpath(os.path.join(dev, '../')))
return _devbase(os.path.dirname(dev))


def _bcpath(dev):
Expand Down Expand Up @@ -826,7 +820,7 @@ def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=Fals
for intf in intflist:
if intf in result:
ifres[intf] = result.pop(intf)
if len(ifres):
if ifres:
bresult[iftype] = ifres

return bresult
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/boto3_elasticache.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None
orig_wait = wait
while wait > 0:
r = s(name=name, conn=conn)
if not r or not len(r) or r[0].get(status_param) == status_gone:
if not r or r[0].get(status_param) == status_gone:
log.info('%s %s deleted.', desc.title(), name)
return True
sleep = wait if wait % 60 == wait else 60
Expand Down Expand Up @@ -1018,7 +1018,7 @@ def modify_cache_parameter_group(name, region=None, key=None, keyid=None, profil
Params = args['ParameterNameValues']
except ValueError as e:
raise SaltInvocationError('Invalid `ParameterNameValues` structure passed.')
while len(Params) > 0:
while Params:
args.update({'ParameterNameValues': Params[:20]})
Params = Params[20:]
if not _modify_resource(name, name_param='CacheParameterGroupName',
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_asg.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def update(name, launch_config_name, availability_zones, min_size, max_size,
_asg.resume_processes()
# suspend any that are specified. Note that the boto default of empty
# list suspends all; don't do that.
if suspended_processes is not None and len(suspended_processes) > 0:
if suspended_processes:
_asg.suspend_processes(suspended_processes)
log.info('Updated ASG %s', name)
# ### scaling policies
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_cloudtrail.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def describe(Name,
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
trails = conn.describe_trails(trailNameList=[Name])
if trails and len(trails.get('trailList', [])) > 0:
if trails and trails.get('trailList'):
keys = ('Name', 'S3BucketName', 'S3KeyPrefix',
'SnsTopicName', 'IncludeGlobalServiceEvents',
'IsMultiRegionTrail',
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_cloudwatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def get_alarm(name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

alarms = conn.describe_alarms(alarm_names=[name])
if len(alarms) == 0:
if not alarms:
return None
if len(alarms) > 1:
log.error("multiple alarms matched name '%s'", name)
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_cloudwatch_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def exists(Name, region=None, key=None, keyid=None, profile=None):

try:
events = conn.list_rules(NamePrefix=Name)
if len(events) == 0:
if not events:
return {'exists': False}
for rule in events.get('Rules', []):
if rule.get('Name', None) == Name:
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_dynamodb.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ def extract_index(index_data, global_index=False):
'read': parsed_data['read_capacity_units'],
'write': parsed_data['write_capacity_units']
}
if parsed_data['name'] and len(keys) > 0:
if parsed_data['name'] and keys:
if global_index:
if parsed_data.get('keys_only') and parsed_data.get('includes'):
raise SaltInvocationError('Only one type of GSI projection can be used.')
Expand Down
10 changes: 5 additions & 5 deletions salt/modules/boto_ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -765,7 +765,7 @@ def get_tags(instance_id=None, keyid=None, key=None, profile=None,
tags = []
client = _get_conn(key=key, keyid=keyid, profile=profile, region=region)
result = client.get_all_tags(filters={"resource-id": instance_id})
if len(result) > 0:
if result:
for tag in result:
tags.append({tag.name: tag.value})
else:
Expand Down Expand Up @@ -1255,7 +1255,7 @@ def get_attribute(attribute, instance_name=None, instance_id=None, region=None,
if len(instances) > 1:
log.error('Found more than one EC2 instance matching the criteria.')
return False
elif len(instances) < 1:
elif not instances:
log.error('Found no EC2 instance matching the criteria.')
return False
instance_id = instances[0]
Expand Down Expand Up @@ -1854,10 +1854,10 @@ def set_volumes_tags(tag_maps, authoritative=False, dry_run=False,
changes['new'][vol.id] = tags
else:
log.debug('No changes needed for vol.id %s', vol.id)
if len(add):
if add:
d = dict((k, tags[k]) for k in add)
log.debug('New tags for vol.id %s: %s', vol.id, d)
if len(update):
if update:
d = dict((k, tags[k]) for k in update)
log.debug('Updated tags for vol.id %s: %s', vol.id, d)
if not dry_run:
Expand All @@ -1866,7 +1866,7 @@ def set_volumes_tags(tag_maps, authoritative=False, dry_run=False,
ret['comment'] = "Failed to set tags on vol.id {0}: {1}".format(vol.id, tags)
return ret
if authoritative:
if len(remove):
if remove:
log.debug('Removed tags for vol.id %s: %s', vol.id, remove)
if not delete_tags(vol.id, remove, region=region, key=key, keyid=keyid, profile=profile):
ret['success'] = False
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/boto_elb.py
Original file line number Diff line number Diff line change
Expand Up @@ -807,10 +807,10 @@ def set_instances(name, instances, test=False, region=None, key=None, keyid=None
remove = current - desired
if test:
return bool(add or remove)
if len(remove):
if remove:
if deregister_instances(name, list(remove), region, key, keyid, profile) is False:
ret = False
if len(add):
if add:
if register_instances(name, list(add), region, key, keyid, profile) is False:
ret = False
return ret
Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -971,7 +971,7 @@ def describe_event_source_mapping(UUID=None, EventSourceArn=None,

ids = _get_ids(UUID, EventSourceArn=EventSourceArn,
FunctionName=FunctionName)
if len(ids) < 1:
if not ids:
return {'event_source_mapping': None}

UUID = ids[0]
Expand Down
4 changes: 2 additions & 2 deletions salt/modules/boto_rds.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ def create(name, allocated_storage, db_instance_class, engine,
status = describe_db_instances(name=name, jmespath=jmespath,
region=region, key=key, keyid=keyid,
profile=profile)
if len(status):
if status:
stat = status[0]
else:
# Whoops, something is horribly wrong...
Expand Down Expand Up @@ -507,7 +507,7 @@ def update_parameter_group(name, parameters, apply_method="pending-reboot",
item.update({'ParameterValue': str(value)}) # future lint: disable=blacklisted-function
param_list.append(item)

if not len(param_list):
if not param_list:
return {'results': False}

try:
Expand Down
6 changes: 3 additions & 3 deletions salt/modules/boto_s3_bucket.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def delete_objects(Bucket, Delete, MFA=None, RequestPayer=None,
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}

if len(failed):
if failed:
return {'deleted': False, 'failed': failed}
else:
return {'deleted': True}
Expand Down Expand Up @@ -336,11 +336,11 @@ def empty(Bucket, MFA=None, RequestPayer=None, region=None, key=None,
Delete = {}
Delete['Objects'] = [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('Versions', [])]
Delete['Objects'] += [{'Key': v['Key'], 'VersionId': v['VersionId']} for v in stuff.get('DeleteMarkers', [])]
if len(Delete['Objects']):
if Delete['Objects']:
ret = delete_objects(Bucket, Delete, MFA=MFA, RequestPayer=RequestPayer,
region=region, key=key, keyid=keyid, profile=profile)
failed = ret.get('failed', [])
if len(failed):
if failed:
return {'deleted': False, 'failed': ret[failed]}
return {'deleted': True}

Expand Down
2 changes: 1 addition & 1 deletion salt/modules/boto_vpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2171,7 +2171,7 @@ def route_exists(destination_cidr_block, route_table_name=None, route_table_id=N
'vpc_peering_connection_id': vpc_peering_connection_id
}
route_comp = set(route_dict.items()) ^ set(route_check.items())
if len(route_comp) == 0:
if not route_comp:
log.info('Route %s exists.', destination_cidr_block)
return {'exists': True}

Expand Down
18 changes: 6 additions & 12 deletions salt/modules/capirca_acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,16 +185,14 @@ def _import_platform_generator(platform):
The generator class is identified looking under the <platform> module
for a class inheriting the `ACLGenerator` class.
'''
log.debug('Using platform: {plat}'.format(plat=platform))
log.debug('Using platform: %s', platform)
for mod_name, mod_obj in inspect.getmembers(aclgen):
if mod_name == platform and inspect.ismodule(mod_obj):
for plat_obj_name, plat_obj in inspect.getmembers(mod_obj): # pylint: disable=unused-variable
if inspect.isclass(plat_obj) and issubclass(plat_obj, aclgen.aclgenerator.ACLGenerator):
log.debug('Identified Capirca class {cls} for {plat}'.format(
cls=plat_obj,
plat=platform))
log.debug('Identified Capirca class %s for %s', plat_obj, platform)
return plat_obj
log.error('Unable to identify any Capirca plaform class for {plat}'.format(plat=platform))
log.error('Unable to identify any Capirca plaform class for %s', platform)


def _get_services_mapping():
Expand Down Expand Up @@ -239,7 +237,7 @@ def _get_services_mapping():
log.error(verr)
log.error('Did not read that properly:')
log.error(line)
log.error('Please report the above error: {port} does not seem a valid port value!'.format(port=port))
log.error('Please report the above error: %s does not seem a valid port value!', port)
_SERVICES[srv_name]['protocol'].append(protocol)
return _SERVICES

Expand Down Expand Up @@ -462,10 +460,7 @@ def _get_term_object(filter_name,
'''
Return an instance of the ``_Term`` class given the term options.
'''
log.debug('Generating config for term {tname} under filter {fname}'.format(
tname=term_name,
fname=filter_name
))
log.debug('Generating config for term %s under filter %s', term_name, filter_name)
term = _Term()
term.name = term_name
term_opts = {}
Expand Down Expand Up @@ -547,8 +542,7 @@ def _get_policy_object(platform,
log.debug(six.text_type(policy))
platform_generator = _import_platform_generator(platform)
policy_config = platform_generator(policy, 2)
log.debug('Generating policy config for {platform}:'.format(
platform=platform))
log.debug('Generating policy config for %s:', platform)
log.debug(six.text_type(policy_config))
return policy_config

Expand Down
Loading

0 comments on commit af96b6e

Please sign in to comment.