diff --git a/salt/modules/aixpkg.py b/salt/modules/aixpkg.py index 4f9852b504df..19c52ba67305 100644 --- a/salt/modules/aixpkg.py +++ b/salt/modules/aixpkg.py @@ -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() @@ -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 = [] diff --git a/salt/modules/apk.py b/salt/modules/apk.py index 2e9a2a952e79..0d7ae9616999 100644 --- a/salt/modules/apk.py +++ b/salt/modules/apk.py @@ -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 = {} diff --git a/salt/modules/aptpkg.py b/salt/modules/aptpkg.py index 2d25023a0172..7cf658f3cf2b 100644 --- a/salt/modules/aptpkg.py +++ b/salt/modules/aptpkg.py @@ -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 @@ -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 = [] @@ -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'], @@ -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 diff --git a/salt/modules/augeas_cfg.py b/salt/modules/augeas_cfg.py index dae81c8ca07c..71e8f9932163 100644 --- a/salt/modules/augeas_cfg.py +++ b/salt/modules/augeas_cfg.py @@ -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) diff --git a/salt/modules/aws_sqs.py b/salt/modules/aws_sqs.py index 4dfff1d7c620..4fe8b2e55aea 100644 --- a/salt/modules/aws_sqs.py +++ b/salt/modules/aws_sqs.py @@ -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]} diff --git a/salt/modules/azurearm_network.py b/salt/modules/azurearm_network.py index 9f68b721bbf1..0270e8b40926 100644 --- a/salt/modules/azurearm_network.py +++ b/salt/modules/azurearm_network.py @@ -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 @@ -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 @@ -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 diff --git a/salt/modules/bcache.py b/salt/modules/bcache.py index 71e1784098d0..8bc7253c53ba 100644 --- a/salt/modules/bcache.py +++ b/salt/modules/bcache.py @@ -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: @@ -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)): @@ -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) @@ -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): @@ -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 diff --git a/salt/modules/boto3_elasticache.py b/salt/modules/boto3_elasticache.py index fc86b0e7f0e0..e3b3c14382d6 100644 --- a/salt/modules/boto3_elasticache.py +++ b/salt/modules/boto3_elasticache.py @@ -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 @@ -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', diff --git a/salt/modules/boto_asg.py b/salt/modules/boto_asg.py index 0df3b0806667..a37db1930702 100644 --- a/salt/modules/boto_asg.py +++ b/salt/modules/boto_asg.py @@ -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 diff --git a/salt/modules/boto_cloudtrail.py b/salt/modules/boto_cloudtrail.py index c7ac67d08d5c..ab54018a1e74 100644 --- a/salt/modules/boto_cloudtrail.py +++ b/salt/modules/boto_cloudtrail.py @@ -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', diff --git a/salt/modules/boto_cloudwatch.py b/salt/modules/boto_cloudwatch.py index e32e606b8ace..b8d2b0218d4b 100644 --- a/salt/modules/boto_cloudwatch.py +++ b/salt/modules/boto_cloudwatch.py @@ -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) diff --git a/salt/modules/boto_cloudwatch_event.py b/salt/modules/boto_cloudwatch_event.py index 529401df0293..930602a5034d 100644 --- a/salt/modules/boto_cloudwatch_event.py +++ b/salt/modules/boto_cloudwatch_event.py @@ -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: diff --git a/salt/modules/boto_dynamodb.py b/salt/modules/boto_dynamodb.py index ad1c0256e461..81f8ab3a37c9 100644 --- a/salt/modules/boto_dynamodb.py +++ b/salt/modules/boto_dynamodb.py @@ -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.') diff --git a/salt/modules/boto_ec2.py b/salt/modules/boto_ec2.py index 4245850f6fad..2d6ea76c100d 100644 --- a/salt/modules/boto_ec2.py +++ b/salt/modules/boto_ec2.py @@ -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: @@ -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] @@ -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: @@ -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 diff --git a/salt/modules/boto_elb.py b/salt/modules/boto_elb.py index 72999cd298b7..66455a3c0b6a 100644 --- a/salt/modules/boto_elb.py +++ b/salt/modules/boto_elb.py @@ -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 diff --git a/salt/modules/boto_lambda.py b/salt/modules/boto_lambda.py index 50db64a64507..136d2eeae63a 100644 --- a/salt/modules/boto_lambda.py +++ b/salt/modules/boto_lambda.py @@ -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] diff --git a/salt/modules/boto_rds.py b/salt/modules/boto_rds.py index 512db58e65cc..5cc978bfa24c 100644 --- a/salt/modules/boto_rds.py +++ b/salt/modules/boto_rds.py @@ -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... @@ -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: diff --git a/salt/modules/boto_s3_bucket.py b/salt/modules/boto_s3_bucket.py index e308832d9490..93311525fc70 100644 --- a/salt/modules/boto_s3_bucket.py +++ b/salt/modules/boto_s3_bucket.py @@ -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} @@ -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} diff --git a/salt/modules/boto_vpc.py b/salt/modules/boto_vpc.py index 2c9800503bc2..424de900b471 100644 --- a/salt/modules/boto_vpc.py +++ b/salt/modules/boto_vpc.py @@ -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} diff --git a/salt/modules/capirca_acl.py b/salt/modules/capirca_acl.py index bd3e25654b5a..7e7e080141ac 100644 --- a/salt/modules/capirca_acl.py +++ b/salt/modules/capirca_acl.py @@ -185,16 +185,14 @@ def _import_platform_generator(platform): The generator class is identified looking under the 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(): @@ -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 @@ -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 = {} @@ -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 diff --git a/salt/modules/chef.py b/salt/modules/chef.py index 786508b0d4a0..79dcb1f9765d 100644 --- a/salt/modules/chef.py +++ b/salt/modules/chef.py @@ -215,6 +215,6 @@ def _exec_cmd(*args, **kwargs): for k, v in six.iteritems(kwargs) if not k.startswith('__') ]) cmd_exec = '{0}{1}'.format(cmd_args, cmd_kwargs) - log.debug('Chef command: {0}'.format(cmd_exec)) + log.debug('Chef command: %s', cmd_exec) return __salt__['cmd.run_all'](cmd_exec, python_shell=False) diff --git a/salt/modules/cmdmod.py b/salt/modules/cmdmod.py index 34f893f8994a..9151a81fca9c 100644 --- a/salt/modules/cmdmod.py +++ b/salt/modules/cmdmod.py @@ -849,11 +849,11 @@ def _get_stripped(cmd): ) log.error(log_callback(msg)) if ret['stdout']: - log.log(output_loglevel, 'stdout: {0}'.format(log_callback(ret['stdout']))) + log.log(output_loglevel, 'stdout: %s', log_callback(ret['stdout'])) if ret['stderr']: - log.log(output_loglevel, 'stderr: {0}'.format(log_callback(ret['stderr']))) + log.log(output_loglevel, 'stderr: %s', log_callback(ret['stderr'])) if ret['retcode']: - log.log(output_loglevel, 'retcode: {0}'.format(ret['retcode'])) + log.log(output_loglevel, 'retcode: %s', ret['retcode']) return ret @@ -3425,7 +3425,7 @@ def shell_info(shell, list_modules=False): hive='HKEY_LOCAL_MACHINE', key='Software\\Microsoft\\PowerShell') pw_keys.sort(key=int) - if len(pw_keys) == 0: + if not pw_keys: return { 'error': 'Unable to locate \'powershell\' Reason: Cannot be ' 'found in registry.', diff --git a/salt/modules/config.py b/salt/modules/config.py index dd2442c0bf13..e1f1256d98da 100644 --- a/salt/modules/config.py +++ b/salt/modules/config.py @@ -400,8 +400,8 @@ def get(key, default='', delimiter=':', merge=None, omit_opts=False, return sdb.sdb_get(ret, __opts__) else: if merge not in ('recurse', 'overwrite'): - log.warning('Unsupported merge strategy \'{0}\'. Falling back ' - 'to \'recurse\'.'.format(merge)) + log.warning('Unsupported merge strategy \'%s\'. Falling back ' + 'to \'recurse\'.', merge) merge = 'recurse' merge_lists = salt.config.master_config('/etc/salt/master').get('pillar_merge_lists') @@ -459,7 +459,7 @@ def gather_bootstrap_script(bootstrap=None): if not HAS_CLOUD: return False, 'config.gather_bootstrap_script is unavailable' ret = salt.utils.cloud.update_bootstrap(__opts__, url=bootstrap) - if 'Success' in ret and len(ret['Success']['Files updated']) > 0: + if 'Success' in ret and ret['Success']['Files updated']: return ret['Success']['Files updated'][0] diff --git a/salt/modules/container_resource.py b/salt/modules/container_resource.py index aec04e301c5b..45349e70d6f6 100644 --- a/salt/modules/container_resource.py +++ b/salt/modules/container_resource.py @@ -372,12 +372,11 @@ def _state(name): # Before we try to replace the file, compare checksums. source_md5 = __salt__['file.get_sum'](local_file, 'md5') if source_md5 == _get_md5(name, dest, run_all): - log.debug('{0} and {1}:{2} are the same file, skipping copy' - .format(source, name, dest)) + log.debug('%s and %s:%s are the same file, skipping copy', source, name, dest) return True - log.debug('Copying {0} to {1} container \'{2}\' as {3}' - .format(source, container_type, name, dest)) + log.debug('Copying %s to %s container \'%s\' as %s', + source, container_type, name, dest) # Using cat here instead of opening the file, reading it into memory, # and passing it as stdin to run(). This will keep down memory diff --git a/salt/modules/cpan.py b/salt/modules/cpan.py index ab765f2bd016..e9d3ca660e16 100644 --- a/salt/modules/cpan.py +++ b/salt/modules/cpan.py @@ -118,7 +118,7 @@ def remove(module, details=False): for file_ in files: if file_ in rm_details: continue - log.trace('Removing {0}'.format(file_)) + log.trace('Removing %s', file_) if __salt__['file.remove'](file_): rm_details[file_] = 'removed' else: diff --git a/salt/modules/cron.py b/salt/modules/cron.py index 7b3cfef4e4e0..c833c807a174 100644 --- a/salt/modules/cron.py +++ b/salt/modules/cron.py @@ -304,7 +304,7 @@ def raw_cron(user): python_shell=False) ).splitlines(True) - if len(lines) != 0 and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'): + if lines and lines[0].startswith('# DO NOT EDIT THIS FILE - edit the master and reinstall.'): del lines[0:3] return ''.join(lines) diff --git a/salt/modules/csf.py b/salt/modules/csf.py index 64d86e3a3c18..c5706b432b0d 100644 --- a/salt/modules/csf.py +++ b/salt/modules/csf.py @@ -215,8 +215,7 @@ def _csf_to_list(option): def split_option(option): - l = re.split("(?: +)?\=(?: +)?", option) # pylint: disable=W1401 - return l + return re.split(r'(?: +)?\=(?: +)?', option) def get_option(option): diff --git a/salt/modules/cyg.py b/salt/modules/cyg.py index fcbdbbd85abf..100e7788dacf 100644 --- a/salt/modules/cyg.py +++ b/salt/modules/cyg.py @@ -71,7 +71,7 @@ def _check_cygwin_installed(cyg_arch='x86_64'): path_to_cygcheck = os.sep.join(['C:', _get_cyg_dir(cyg_arch), 'bin', 'cygcheck.exe']) - LOG.debug('Path to cygcheck.exe: {0}'.format(path_to_cygcheck)) + LOG.debug('Path to cygcheck.exe: %s', path_to_cygcheck) if not os.path.exists(path_to_cygcheck): LOG.debug('Could not find cygcheck.exe') return False @@ -87,7 +87,7 @@ def _get_all_packages(mirror=DEFAULT_MIRROR, __context__['cyg.all_packages'] = {} if mirror not in __context__['cyg.all_packages']: __context__['cyg.all_packages'][mirror] = [] - if not len(__context__['cyg.all_packages'][mirror]): + if not __context__['cyg.all_packages'][mirror]: pkg_source = '/'.join([mirror, cyg_arch, 'setup.bz2']) file_data = _urlopen(pkg_source).read() @@ -125,7 +125,7 @@ def check_valid_package(package, if mirrors is None: mirrors = [{DEFAULT_MIRROR: DEFAULT_MIRROR_KEY}] - LOG.debug('Checking Valid Mirrors: {0}'.format(mirrors)) + LOG.debug('Checking Valid Mirrors: %s', mirrors) for mirror in mirrors: for mirror_url, key in mirror.items(): @@ -262,7 +262,7 @@ def uninstall(packages, args = [] if packages is not None: args.append('--remove-packages {pkgs}'.format(pkgs=packages)) - LOG.debug('args: {0}'.format(args)) + LOG.debug('args: %s', args) if not _check_cygwin_installed(cyg_arch): LOG.debug('We\'re convinced cygwin isn\'t installed') return True @@ -290,8 +290,7 @@ def update(cyg_arch='x86_64', mirrors=None): # Can't update something that isn't installed if not _check_cygwin_installed(cyg_arch): - LOG.debug('Cygwin ({0}) not installed,\ - could not update'.format(cyg_arch)) + LOG.debug('Cygwin (%s) not installed, could not update', cyg_arch) return False return _run_silent_cygwin(cyg_arch=cyg_arch, args=args, mirrors=mirrors) diff --git a/salt/modules/daemontools.py b/salt/modules/daemontools.py index 719816c48b8b..267bdf2d6641 100644 --- a/salt/modules/daemontools.py +++ b/salt/modules/daemontools.py @@ -237,7 +237,7 @@ def enabled(name, **kwargs): salt '*' daemontools.enabled ''' if not available(name): - log.error('Service {0} not found'.format(name)) + log.error('Service %s not found', name) return False run_file = os.path.join(SERVICE_DIR, name, 'run') diff --git a/salt/modules/deb_postgres.py b/salt/modules/deb_postgres.py index 9b5db2ac0dcc..10f91040ba69 100644 --- a/salt/modules/deb_postgres.py +++ b/salt/modules/deb_postgres.py @@ -66,8 +66,7 @@ def cluster_create(version, cmdstr = ' '.join([pipes.quote(c) for c in cmd]) ret = __salt__['cmd.run_all'](cmdstr, python_shell=False) if ret.get('retcode', 0) != 0: - log.error('Error creating a Postgresql' - ' cluster {0}/{1}'.format(version, name)) + log.error('Error creating a Postgresql cluster %s/%s', version, name) return False return ret @@ -136,8 +135,7 @@ def cluster_remove(version, ret = __salt__['cmd.run_all'](cmdstr, python_shell=False) # FIXME - return Boolean ? if ret.get('retcode', 0) != 0: - log.error('Error removing a Postgresql' - ' cluster {0}/{1}'.format(version, name)) + log.error('Error removing a Postgresql cluster %s/%s', version, name) else: ret['changes'] = ('Successfully removed' ' cluster {0}/{1}').format(version, name) diff --git a/salt/modules/debbuild.py b/salt/modules/debbuild.py index 97b484a4d40e..52ee2b60c5c1 100644 --- a/salt/modules/debbuild.py +++ b/salt/modules/debbuild.py @@ -515,7 +515,7 @@ def build(runas, dscs = make_src_pkg(dsc_dir, spec, sources, env, saltenv, runas) except Exception as exc: shutil.rmtree(dsc_dir) - log.error('Failed to make src package, exception \'{0}\''.format(exc)) + log.error('Failed to make src package, exception \'%s\'', exc) return ret root_user = 'root' @@ -575,8 +575,8 @@ def build(runas, shutil.copy(full, bdist) ret.setdefault('Packages', []).append(bdist) - except Exception as exc: - log.error('Error building from \'{0}\', execption \'{1}\''.format(dsc, exc)) + except Exception: + log.exception('Error building from %s', dsc) # remove any Packages file created for local dependency processing for pkgzfile in os.listdir(dest_dir): @@ -698,7 +698,7 @@ def make_repo(repodir, with salt.utils.files.fopen(repoconfopts, 'w') as fow: fow.write(salt.utils.stringutils.to_str(repocfg_opts)) - cmd = 'chown {0}:{1} -R {2}'.format(runas, runas, repoconf) + cmd = 'chown {0}:{0} -R {1}'.format(runas, repoconf) retrc = __salt__['cmd.retcode'](cmd, runas='root') if retrc != 0: raise SaltInvocationError( diff --git a/salt/modules/debian_ip.py b/salt/modules/debian_ip.py index 8fbe9fb06ddb..febfb53ba13b 100644 --- a/salt/modules/debian_ip.py +++ b/salt/modules/debian_ip.py @@ -171,8 +171,10 @@ def _error_msg_routes(iface, option, expected): def _log_default_iface(iface, opt, value): - msg = 'Using default option -- Interface: {0} Option: {1} Value: {2}' - log.info(msg.format(iface, opt, value)) + log.info( + 'Using default option -- Interface: %s Option: %s Value: %s', + iface, opt, value + ) def _error_msg_network(option, expected): @@ -185,8 +187,7 @@ def _error_msg_network(option, expected): def _log_default_network(opt, value): - msg = 'Using existing setting -- Setting: {0} Value: {1}' - log.info(msg.format(opt, value)) + log.info('Using existing setting -- Setting: %s Value: %s', opt, value) def _raise_error_iface(iface, option, expected): @@ -804,46 +805,26 @@ def _parse_settings_bond(opts, iface): } if opts['mode'] in ['balance-rr', '0']: - log.info( - 'Device: {0} Bonding Mode: load balancing (round-robin)'.format( - iface - ) - ) + log.info('Device: %s Bonding Mode: load balancing (round-robin)', iface) return _parse_settings_bond_0(opts, iface, bond_def) elif opts['mode'] in ['active-backup', '1']: - log.info( - 'Device: {0} Bonding Mode: fault-tolerance (active-backup)'.format( - iface - ) - ) + log.info('Device: %s Bonding Mode: fault-tolerance (active-backup)', iface) return _parse_settings_bond_1(opts, iface, bond_def) elif opts['mode'] in ['balance-xor', '2']: - log.info( - 'Device: {0} Bonding Mode: load balancing (xor)'.format(iface) - ) + log.info('Device: %s Bonding Mode: load balancing (xor)', iface) return _parse_settings_bond_2(opts, iface, bond_def) elif opts['mode'] in ['broadcast', '3']: - log.info( - 'Device: {0} Bonding Mode: fault-tolerance (broadcast)'.format( - iface - ) - ) + log.info('Device: %s Bonding Mode: fault-tolerance (broadcast)', iface) return _parse_settings_bond_3(opts, iface, bond_def) elif opts['mode'] in ['802.3ad', '4']: - log.info( - 'Device: {0} Bonding Mode: IEEE 802.3ad Dynamic link ' - 'aggregation'.format(iface) - ) + log.info('Device: %s Bonding Mode: IEEE 802.3ad Dynamic link ' + 'aggregation', iface) return _parse_settings_bond_4(opts, iface, bond_def) elif opts['mode'] in ['balance-tlb', '5']: - log.info( - 'Device: {0} Bonding Mode: transmit load balancing'.format(iface) - ) + log.info('Device: %s Bonding Mode: transmit load balancing', iface) return _parse_settings_bond_5(opts, iface, bond_def) elif opts['mode'] in ['balance-alb', '6']: - log.info( - 'Device: {0} Bonding Mode: adaptive load balancing'.format(iface) - ) + log.info('Device: %s Bonding Mode: adaptive load balancing', iface) return _parse_settings_bond_6(opts, iface, bond_def) else: valid = [ @@ -870,7 +851,7 @@ def _parse_settings_bond_0(opts, iface, bond_def): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 - if len(bond['arp_ip_target']) > 0: + if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip @@ -950,7 +931,7 @@ def _parse_settings_bond_2(opts, iface, bond_def): if 1 <= len(opts['arp_ip_target']) <= 16: bond.update({'arp_ip_target': ''}) for ip in opts['arp_ip_target']: # pylint: disable=C0103 - if len(bond['arp_ip_target']) > 0: + if bond['arp_ip_target']: bond['arp_ip_target'] = bond['arp_ip_target'] + ',' + ip else: bond['arp_ip_target'] = ip diff --git a/salt/modules/dig.py b/salt/modules/dig.py index 31af50ed38c3..ba1263f7a51e 100644 --- a/salt/modules/dig.py +++ b/salt/modules/dig.py @@ -93,10 +93,8 @@ def A(host, nameserver=None): # In this case, 0 is not the same as False if cmd['retcode'] != 0: log.warning( - 'dig returned exit code \'{0}\'. Returning empty list as ' - 'fallback.'.format( - cmd['retcode'] - ) + 'dig returned exit code \'%s\'. Returning empty list as fallback.', + cmd['retcode'] ) return [] @@ -125,10 +123,8 @@ def AAAA(host, nameserver=None): # In this case, 0 is not the same as False if cmd['retcode'] != 0: log.warning( - 'dig returned exit code \'{0}\'. Returning empty list as ' - 'fallback.'.format( - cmd['retcode'] - ) + 'dig returned exit code \'%s\'. Returning empty list as fallback.', + cmd['retcode'] ) return [] @@ -157,10 +153,8 @@ def NS(domain, resolve=True, nameserver=None): # In this case, 0 is not the same as False if cmd['retcode'] != 0: log.warning( - 'dig returned exit code \'{0}\'. Returning empty list as ' - 'fallback.'.format( - cmd['retcode'] - ) + 'dig returned exit code \'%s\'. Returning empty list as fallback.', + cmd['retcode'] ) return [] @@ -198,8 +192,8 @@ def SPF(domain, record='SPF', nameserver=None): # In this case, 0 is not the same as False if result['retcode'] != 0: log.warning( - 'dig returned exit code \'{0}\'. Returning empty list as fallback.' - .format(result['retcode']) + 'dig returned exit code \'%s\'. Returning empty list as fallback.', + result['retcode'] ) return [] @@ -209,7 +203,7 @@ def SPF(domain, record='SPF', nameserver=None): return SPF(domain, 'TXT', nameserver) sections = re.sub('"', '', result['stdout']).split() - if len(sections) == 0 or sections[0] != 'v=spf1': + if not sections or sections[0] != 'v=spf1': return [] if sections[1].startswith('redirect='): @@ -255,10 +249,8 @@ def MX(domain, resolve=False, nameserver=None): # In this case, 0 is not the same as False if cmd['retcode'] != 0: log.warning( - 'dig returned exit code \'{0}\'. Returning empty list as ' - 'fallback.'.format( - cmd['retcode'] - ) + 'dig returned exit code \'%s\'. Returning empty list as fallback.', + cmd['retcode'] ) return [] @@ -293,10 +285,8 @@ def TXT(host, nameserver=None): if cmd['retcode'] != 0: log.warning( - 'dig returned exit code \'{0}\'. Returning empty list as ' - 'fallback.'.format( - cmd['retcode'] - ) + 'dig returned exit code \'%s\'. Returning empty list as fallback.', + cmd['retcode'] ) return [] diff --git a/salt/modules/disk.py b/salt/modules/disk.py index 9b0c001e3515..687659a5ae8d 100644 --- a/salt/modules/disk.py +++ b/salt/modules/disk.py @@ -593,7 +593,7 @@ def hdparms(disks, args=None): disk_data = {} for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines(): line = line.strip() - if len(line) == 0 or line == disk + ':': + if not line or line == disk + ':': continue if ':' in line: @@ -623,13 +623,13 @@ def hdparms(disks, args=None): deep_key, val = val.split('=', 1) deep_key = deep_key.strip() val = val.strip() - if len(val): + if val: valdict[deep_key] = val - elif len(val): + elif val: rvals.append(val) - if len(valdict): + if valdict: rvals.append(valdict) - if len(rvals) == 0: + if not rvals: continue elif len(rvals) == 1: rvals = rvals[0] @@ -825,7 +825,7 @@ def _iostat_fbsd(interval, count, disks): for line in ret: if not line.startswith('device'): continue - elif not len(dev_header): + elif not dev_header: dev_header = line.split()[1:] while line is not False: line = next(ret, False) @@ -876,12 +876,12 @@ def _iostat_linux(interval, count, disks): ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if line.startswith('avg-cpu:'): - if not len(sys_header): + if not sys_header: sys_header = tuple(line.split()[1:]) line = [decimal.Decimal(x) for x in next(ret).split()] sys_stats.append(line) elif line.startswith('Device:'): - if not len(dev_header): + if not dev_header: dev_header = tuple(line.split()[1:]) while line is not False: line = next(ret, False) @@ -894,7 +894,7 @@ def _iostat_linux(interval, count, disks): iostats = {} - if len(sys_header): + if sys_header: iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): diff --git a/salt/modules/drac.py b/salt/modules/drac.py index 3cbf3ad17b5b..764eda3183ba 100644 --- a/salt/modules/drac.py +++ b/salt/modules/drac.py @@ -32,7 +32,7 @@ def __parse_drac(output): section = '' for i in output.splitlines(): - if len(i.rstrip()) > 0 and '=' in i: + if i.rstrip() and '=' in i: if section in drac: drac[section].update(dict( [[prop.strip() for prop in i.split('=')]] @@ -52,7 +52,7 @@ def __execute_cmd(command): cmd = __salt__['cmd.run_all']('racadm {0}'.format(command)) if cmd['retcode'] != 0: - log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode'])) + log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) return False return True @@ -71,7 +71,7 @@ def system_info(): cmd = __salt__['cmd.run_all']('racadm getsysinfo') if cmd['retcode'] != 0: - log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode'])) + log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) return __parse_drac(cmd['stdout']) @@ -90,7 +90,7 @@ def network_info(): cmd = __salt__['cmd.run_all']('racadm getniccfg') if cmd['retcode'] != 0: - log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode'])) + log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) return __parse_drac(cmd['stdout']) @@ -177,7 +177,7 @@ def list_users(): cfgUserAdmin -i {0}'.format(idx)) if cmd['retcode'] != 0: - log.warning('racadm return an exit code \'{0}\'.'.format(cmd['retcode'])) + log.warning('racadm return an exit code \'%s\'.', cmd['retcode']) for user in cmd['stdout'].splitlines(): if not user.startswith('cfg'): @@ -218,7 +218,7 @@ def delete_user(username, uid=None): cfgUserAdminUserName -i {0} ""'.format(uid)) else: - log.warning('\'{0}\' does not exist'.format(username)) + log.warning('\'%s\' does not exist', username) return False return True @@ -243,7 +243,7 @@ def change_password(username, password, uid=None): return __execute_cmd('config -g cfgUserAdmin -o \ cfgUserAdminPassword -i {0} {1}'.format(uid, password)) else: - log.warning('\'{0}\' does not exist'.format(username)) + log.warning('\'%s\' does not exist', username) return False return True @@ -277,7 +277,7 @@ def create_user(username, password, permissions, users=None): users = list_users() if username in users: - log.warning('\'{0}\' already exists'.format(username)) + log.warning('\'%s\' already exists', username) return False for idx in six.iterkeys(users): diff --git a/salt/modules/dracr.py b/salt/modules/dracr.py index 28f46a7fb11e..38c3ce85fa08 100644 --- a/salt/modules/dracr.py +++ b/salt/modules/dracr.py @@ -51,7 +51,7 @@ def __parse_drac(output): if i.strip().endswith(':') and '=' not in i: section = i[0:-1] drac[section] = {} - if len(i.rstrip()) > 0 and '=' in i: + if i.rstrip() and '=' in i: if section in drac: drac[section].update(dict( [[prop.strip() for prop in i.split('=')]] @@ -141,7 +141,7 @@ def __execute_ret(command, host=None, if l.startswith('Continuing execution'): continue - if len(l.strip()) == 0: + if not l.strip(): continue fmtlines.append(l) if '=' in l: @@ -511,7 +511,7 @@ def list_users(host=None, else: break else: - if len(_username) > 0: + if _username: users[_username].update({key: val}) return users @@ -1257,7 +1257,7 @@ def mapit(x, y): in_chassis = True continue - if len(l) < 1: + if not l: continue line = re.split(' +', l.strip()) diff --git a/salt/modules/ebuild.py b/salt/modules/ebuild.py index b5accab03383..aaaf5bc6353a 100644 --- a/salt/modules/ebuild.py +++ b/salt/modules/ebuild.py @@ -24,6 +24,7 @@ # Import salt libs import salt.utils.args +import salt.utils.compat import salt.utils.data import salt.utils.functools import salt.utils.path @@ -33,10 +34,6 @@ from salt.exceptions import CommandExecutionError, MinionError from salt.ext import six -# Workaround for 'reload' builtin of py2.7 -if six.PY3: - from importlib import reload # pylint: disable=no-name-in-module - # Import third party libs HAS_PORTAGE = False try: @@ -71,13 +68,13 @@ def __virtual__(): def _vartree(): import portage # pylint: disable=3rd-party-module-not-gated - portage = reload(portage) + portage = salt.utils.compat.reload(portage) return portage.db[portage.root]['vartree'] def _porttree(): import portage # pylint: disable=3rd-party-module-not-gated - portage = reload(portage) + portage = salt.utils.compat.reload(portage) return portage.db[portage.root]['porttree'] @@ -198,8 +195,10 @@ def check_db(*names, **kwargs): ret = {} for name in names: if name in ret: - log.warning('pkg.check_db: Duplicate package name \'{0}\' ' - 'submitted'.format(name)) + log.warning( + 'pkg.check_db: Duplicate package name \'%s\' submitted', + name + ) continue if '/' not in name: ret.setdefault(name, {})['found'] = False @@ -259,7 +258,7 @@ def latest_version(*names, **kwargs): ''' refresh = salt.utils.data.is_true(kwargs.pop('refresh', True)) - if len(names) == 0: + if not names: return '' # Refresh before looking for the latest version available @@ -480,7 +479,7 @@ def refresh_db(): timestamp = datetime.datetime.fromtimestamp(os.path.getmtime(main_repo_root)) if now - timestamp < day: log.info('Did not sync package tree since last sync was done at' - ' {0}, less than 1 day ago'.format(timestamp)) + ' %s, less than 1 day ago', timestamp) return False if has_emaint: @@ -631,7 +630,7 @@ def install(name=None, {'': {'old': '', 'new': ''}} ''' - log.debug('Called modules.pkg.install: {0}'.format( + log.debug('Called modules.pkg.install: %s', { 'name': name, 'refresh': refresh, @@ -640,7 +639,7 @@ def install(name=None, 'kwargs': kwargs, 'binhost': binhost, } - )) + ) if salt.utils.data.is_true(refresh): refresh_db() @@ -664,7 +663,7 @@ def install(name=None, version_num += '[{0}]'.format(','.join(uses)) pkg_params = {name: version_num} - if pkg_params is None or len(pkg_params) == 0: + if not pkg_params: return {} elif pkg_type == 'file': emerge_opts = ['tbz2file'] @@ -699,7 +698,7 @@ def install(name=None, prefix = gt_lt or '' prefix += eq or '' # If no prefix characters were supplied and verstr contains a version, use '=' - if len(verstr) > 0 and verstr[0] != ':' and verstr[0] != '[': + if verstr and verstr[0] != ':' and verstr[0] != '[': prefix = prefix or '=' target = '{0}{1}-{2}'.format(prefix, param, verstr) else: @@ -1229,7 +1228,7 @@ def check_extra_requirements(pkgname, pkgver): try: cpv = _porttree().dbapi.xmatch('bestmatch-visible', atom) except portage.exception.InvalidAtom as iae: - log.error('Unable to find a matching package for {0}: ({1})'.format(atom, iae)) + log.error('Unable to find a matching package for %s: (%s)', atom, iae) return False if cpv == '': @@ -1246,8 +1245,7 @@ def check_extra_requirements(pkgname, pkgver): des_uses = set(portage.dep.dep_getusedeps(atom)) cur_use = cur_use.split() - if len([x for x in des_uses.difference(cur_use) - if x[0] != '-' or x[1:] in cur_use]) > 0: + if [x for x in des_uses.difference(cur_use) if x[0] != '-' or x[1:] in cur_use]: return False if keyword: diff --git a/salt/modules/environ.py b/salt/modules/environ.py index c9a6a7d55b8c..8696ddaf8ec2 100644 --- a/salt/modules/environ.py +++ b/salt/modules/environ.py @@ -69,10 +69,7 @@ def setval(key, val, false_unsets=False, permanent=False): permanent_key = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' if not isinstance(key, six.string_types): - log.debug( - '{0}: \'key\' argument is not a string type: \'{1}\'' - .format(__name__, key) - ) + log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key) if val is False: if false_unsets is True: try: @@ -82,9 +79,8 @@ def setval(key, val, false_unsets=False, permanent=False): return None except Exception as exc: log.error( - '{0}: Exception occurred when unsetting ' - 'environ key \'{1}\': \'{2}\'' - .format(__name__, key, exc) + '%s: Exception occurred when unsetting ' + 'environ key \'%s\': \'%s\'', __name__, key, exc ) return False else: @@ -97,16 +93,14 @@ def setval(key, val, false_unsets=False, permanent=False): return os.environ[key] except Exception as exc: log.error( - '{0}: Exception occurred when setting' - 'environ key \'{1}\': \'{2}\'' - .format(__name__, key, exc) + '%s: Exception occurred when setting' + 'environ key \'%s\': \'%s\'', __name__, key, exc ) return False else: log.debug( - '{0}: \'val\' argument for key \'{1}\' is not a string ' - 'or False: \'{2}\'' - .format(__name__, key, val) + '%s: \'val\' argument for key \'%s\' is not a string ' + 'or False: \'%s\'', __name__, key, val ) return False @@ -161,8 +155,8 @@ def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, pe ret = {} if not isinstance(environ, dict): log.debug( - '{0}: \'environ\' argument is not a dict: \'{1}\'' - .format(__name__, environ) + '%s: \'environ\' argument is not a dict: \'%s\'', + __name__, environ ) return False if clear_all is True: @@ -177,9 +171,8 @@ def setenv(environ, false_unsets=False, clear_all=False, update_minion=False, pe ret[key] = setval(key, val, false_unsets, permanent=permanent) else: log.debug( - '{0}: \'val\' argument for key \'{1}\' is not a string ' - 'or False: \'{2}\'' - .format(__name__, key, val) + '%s: \'val\' argument for key \'%s\' is not a string ' + 'or False: \'%s\'', __name__, key, val ) return False @@ -213,10 +206,7 @@ def get(key, default=''): salt '*' environ.get baz default=False ''' if not isinstance(key, six.string_types): - log.debug( - '{0}: \'key\' argument is not a string type: \'{1}\'' - .format(__name__, key) - ) + log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key) return False return os.environ.get(key, default) @@ -241,10 +231,7 @@ def has_value(key, value=None): salt '*' environ.has_value foo ''' if not isinstance(key, six.string_types): - log.debug( - '{0}: \'key\' argument is not a string type: \'{1}\'' - .format(__name__, key) - ) + log.debug('%s: \'key\' argument is not a string type: \'%s\'', __name__, key) return False try: cur_val = os.environ[key] @@ -286,8 +273,8 @@ def item(keys, default=''): key_list = keys else: log.debug( - '{0}: \'keys\' argument is not a string or list type: \'{1}\'' - .format(__name__, keys) + '%s: \'keys\' argument is not a string or list type: \'%s\'', + __name__, keys ) for key in key_list: ret[key] = os.environ.get(key, default) diff --git a/salt/modules/eselect.py b/salt/modules/eselect.py index d350ec52d864..6320a44f5379 100644 --- a/salt/modules/eselect.py +++ b/salt/modules/eselect.py @@ -60,7 +60,7 @@ def exec_action(module, action, module_parameter=None, action_parameter=None, st if state_only: return True - if len(out) < 1: + if not out: return False if len(out) == 1 and not out[0].strip(): @@ -192,7 +192,7 @@ def set_target(module, target, module_parameter=None, action_parameter=None): # get list of available modules if module not in get_modules(): - log.error('Module {0} not available'.format(module)) + log.error('Module %s not available', module) return False exec_result = exec_action(module, 'set', module_parameter=module_parameter, action_parameter=action_parameter, state_only=True) diff --git a/salt/modules/file.py b/salt/modules/file.py index 67bff9b48943..adbf4adbd66b 100644 --- a/salt/modules/file.py +++ b/salt/modules/file.py @@ -533,11 +533,11 @@ def _cmp_attrs(path, attrs): return None old = [chr for chr in lattrs if chr not in attrs] - if len(old) > 0: + if old: diff[1] = ''.join(old) new = [chr for chr in attrs if chr not in lattrs] - if len(new) > 0: + if new: diff[0] = ''.join(new) return diff @@ -1942,7 +1942,7 @@ def line(path, content=None, match=None, mode=None, location=None, match = _regex_to_static(body, match) if os.stat(path).st_size == 0 and mode in ('delete', 'replace'): - log.warning('Cannot find text to {0}. File \'{1}\' is empty.'.format(mode, path)) + log.warning('Cannot find text to %s. File \'%s\' is empty.', mode, path) body = [] elif mode == 'delete' and match: body = [line for line in body if line != match[0]] @@ -2375,7 +2375,7 @@ def replace(path, else: # append_if_not_found # Make sure we have a newline at the end of the file - if 0 != len(new_file): + if new_file: if not new_file[-1].endswith(salt.utils.stringutils.to_bytes(os.linesep)): new_file[-1] += salt.utils.stringutils.to_bytes(os.linesep) new_file.append(not_found_content + salt.utils.stringutils.to_bytes(os.linesep)) @@ -4691,8 +4691,10 @@ def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, selinux_error = False try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') - log.debug('Current selinux context user:{0} role:{1} type:{2} range:{3}'.format( - current_seuser, current_serole, current_setype, current_serange)) + log.debug( + 'Current selinux context user:%s role:%s type:%s range:%s', + current_seuser, current_serole, current_setype, current_serange + ) except ValueError: log.error('Unable to get current selinux attributes') ret['result'] = False @@ -4745,7 +4747,7 @@ def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, requested_setype = current_setype result = set_selinux_context(name, user=requested_seuser, role=requested_serole, type=requested_setype, range=requested_serange, persist=True) - log.debug("selinux set result: {0}".format(result)) + log.debug('selinux set result: %s', result) current_seuser, current_serole, current_setype, current_serange = result.split(':') except ValueError: log.error('Unable to set current selinux attributes') @@ -5077,7 +5079,7 @@ def check_file_meta( try: differences = get_diff(name, tmp, show_filenames=False) except CommandExecutionError as exc: - log.error('Failed to diff files: {0}'.format(exc)) + log.error('Failed to diff files: %s', exc) differences = exc.strerror __clean_tmp(tmp) if differences: @@ -5117,10 +5119,10 @@ def check_file_meta( if seuser or serole or setype or serange: try: current_seuser, current_serole, current_setype, current_serange = get_selinux_context(name).split(':') - log.debug('Current selinux context user:{0} role:{1} type:{2} range:{3}'.format(current_seuser, - current_serole, - current_setype, - current_serange)) + log.debug( + 'Current selinux context user:%s role:%s type:%s range:%s', + current_seuser, current_serole, current_setype, current_serange + ) except ValueError as exc: log.error('Unable to get current selinux attributes') changes['selinux'] = exc.strerror @@ -5979,8 +5981,8 @@ def mknod_chrdev(name, 'changes': {}, 'comment': '', 'result': False} - log.debug('Creating character device name:{0} major:{1} minor:{2} mode:{3}' - .format(name, major, minor, mode)) + log.debug('Creating character device name:%s major:%s minor:%s mode:%s', + name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Character device {0} created.'.format(name)} @@ -6054,8 +6056,8 @@ def mknod_blkdev(name, 'changes': {}, 'comment': '', 'result': False} - log.debug('Creating block device name:{0} major:{1} minor:{2} mode:{3}' - .format(name, major, minor, mode)) + log.debug('Creating block device name:%s major:%s minor:%s mode:%s', + name, major, minor, mode) try: if __opts__['test']: ret['changes'] = {'new': 'Block device {0} created.'.format(name)} @@ -6127,7 +6129,7 @@ def mknod_fifo(name, 'changes': {}, 'comment': '', 'result': False} - log.debug('Creating FIFO name: {0}'.format(name)) + log.debug('Creating FIFO name: %s', name) try: if __opts__['test']: ret['changes'] = {'new': 'Fifo pipe {0} created.'.format(name)} diff --git a/salt/modules/firewalld.py b/salt/modules/firewalld.py index 8f48d9d7e907..ee3d5f75d610 100644 --- a/salt/modules/firewalld.py +++ b/salt/modules/firewalld.py @@ -551,7 +551,7 @@ def get_masquerade(zone=None, permanent=True): ''' zone_info = list_all(zone, permanent) - if 'no' in [zone_info[i]['masquerade'][0] for i in zone_info.keys()]: + if 'no' in [zone_info[i]['masquerade'][0] for i in zone_info]: return False return True diff --git a/salt/modules/freebsdports.py b/salt/modules/freebsdports.py index c5953b4a21f3..76231934d829 100644 --- a/salt/modules/freebsdports.py +++ b/salt/modules/freebsdports.py @@ -300,9 +300,7 @@ def showconfig(name, default=False, dict_return=False): try: pkg = output[0].split()[-1].rstrip(':') except (IndexError, AttributeError, TypeError) as exc: - log.error( - 'Unable to get pkg-version string: {0}'.format(exc) - ) + log.error('Unable to get pkg-version string: %s', exc) return {} ret = {pkg: {}} diff --git a/salt/modules/genesis.py b/salt/modules/genesis.py index 91daccb286d5..d74dd5515aae 100644 --- a/salt/modules/genesis.py +++ b/salt/modules/genesis.py @@ -167,10 +167,10 @@ def bootstrap( _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') - log.debug('First loop device is {0}'.format(loop1)) + log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') - log.debug('Second loop device is {0}'.format(loop2)) + log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) @@ -232,7 +232,7 @@ def _mkpart(root, fs_format, fs_opts, mount_dir): ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') - log.debug('First loop device is {0}'.format(loop1)) + log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' @@ -241,7 +241,7 @@ def _mkpart(root, fs_format, fs_opts, mount_dir): __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') - log.debug('Second loop device is {0}'.format(loop2)) + log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) @@ -406,8 +406,7 @@ def _bootstrap_deb( return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): - log.error('Required tool qemu not ' - 'present/readable at: {0}'.format(static_qemu)) + log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): diff --git a/salt/modules/gentoo_service.py b/salt/modules/gentoo_service.py index 199b7aea5ee3..de8ca15f3821 100644 --- a/salt/modules/gentoo_service.py +++ b/salt/modules/gentoo_service.py @@ -40,7 +40,7 @@ def __virtual__(): def _ret_code(cmd, ignore_retcode=False): - log.debug('executing [{0}]'.format(cmd)) + log.debug('executing [%s]', cmd) sts = __salt__['cmd.retcode'](cmd, python_shell=False, ignore_retcode=ignore_retcode) return sts diff --git a/salt/modules/gentoolkitmod.py b/salt/modules/gentoolkitmod.py index 3ed44d2008fc..fb606c6b6a9c 100644 --- a/salt/modules/gentoolkitmod.py +++ b/salt/modules/gentoolkitmod.py @@ -56,7 +56,7 @@ def _pretty_size(size): Print sizes in a similar fashion as eclean ''' units = [' G', ' M', ' K', ' B'] - while len(units) and size >= 1000: + while units and size >= 1000: size = size / 1024.0 units.pop() return '{0}{1}'.format(round(size, 1), units[-1]) diff --git a/salt/modules/glance.py b/salt/modules/glance.py index 16b90c907209..fb2edea57602 100644 --- a/salt/modules/glance.py +++ b/salt/modules/glance.py @@ -164,17 +164,16 @@ def get(key, default=None): raise SaltInvocationError('No credentials to authenticate with.') if HAS_KEYSTONE: - log.debug('Calling keystoneclient.v2_0.client.Client(' + - '{0}, **{1})'.format(ks_endpoint, kwargs)) + log.debug('Calling keystoneclient.v2_0.client.Client(%s, **%s)', + ks_endpoint, kwargs) keystone = kstone.Client(**kwargs) kwargs['token'] = keystone.get_token(keystone.session) # This doesn't realy prevent the password to show up # in the minion log as keystoneclient.session is # logging it anyway when in debug-mode kwargs.pop('password') - log.debug('Calling glanceclient.client.Client(' + - '{0}, {1}, **{2})'.format(api_version, - g_endpoint_url, kwargs)) + log.debug('Calling glanceclient.client.Client(%s, %s, **%s)', + api_version, g_endpoint_url, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return client.Client(api_version, g_endpoint_url, **kwargs) @@ -361,9 +360,10 @@ def image_show(id=None, name=None, profile=None): # pylint: disable=C0103 'result': False, 'comment': 'No image with ID {0}'.format(id) } - pformat = pprint.PrettyPrinter(indent=4).pformat - log.debug('Properties of image {0}:\n{1}'.format( - image.name, pformat(image))) + log.debug( + 'Properties of image %s:\n%s', + image.name, pprint.PrettyPrinter(indent=4).pformat(image) + ) schema = image_schema(profile=profile) if len(schema.keys()) == 1: @@ -403,7 +403,7 @@ def image_list(id=None, profile=None, name=None): # pylint: disable=C0103 'name "{0}"'.format(name) } _add_image(ret, image) - log.debug('Returning images: {0}'.format(ret)) + log.debug('Returning images: %s', ret) return ret @@ -446,7 +446,7 @@ def image_update(id=None, name=None, profile=None, **kwargs): # pylint: disable img_list = image_list(name=name, profile=profile) if img_list is dict and 'result' in img_list: return img_list - elif len(img_list) == 0: + elif not img_list: return { 'result': False, 'comment': @@ -460,13 +460,13 @@ def image_update(id=None, name=None, profile=None, **kwargs): # pylint: disable image = img_list[name] else: raise SaltInvocationError - log.debug('Found image:\n{0}'.format(image)) + log.debug('Found image:\n%s', image) to_update = {} for key, value in kwargs.items(): if key.startswith('_'): continue if key not in image or image[key] != value: - log.debug('add <{0}={1}> to to_update'.format(key, value)) + log.debug('add <%s=%s> to to_update', key, value) to_update[key] = value g_client = _auth(profile) updated = g_client.images.update(image['id'], **to_update) @@ -488,12 +488,13 @@ def schema_get(name, profile=None): salt '*' glance.schema_get name=f16-jeos ''' g_client = _auth(profile) - pformat = pprint.PrettyPrinter(indent=4).pformat schema_props = {} for prop in g_client.schemas.get(name).properties: schema_props[prop.name] = prop.description - log.debug('Properties of schema {0}:\n{1}'.format( - name, pformat(schema_props))) + log.debug( + 'Properties of schema %s:\n%s', + name, pprint.PrettyPrinter(indent=4).pformat(schema_props) + ) return {name: schema_props} diff --git a/salt/modules/glusterfs.py b/salt/modules/glusterfs.py index 3ca2301e0e9c..bd07dcd7312c 100644 --- a/salt/modules/glusterfs.py +++ b/salt/modules/glusterfs.py @@ -580,7 +580,7 @@ def add_volume_bricks(name, bricks): else: new_bricks.append(brick) - if len(new_bricks) > 0: + if new_bricks: for brick in new_bricks: cmd += ' {0}'.format(brick) return _gluster(cmd) diff --git a/salt/modules/heat.py b/salt/modules/heat.py index 170c56cb17aa..854699b5ff37 100644 --- a/salt/modules/heat.py +++ b/salt/modules/heat.py @@ -164,9 +164,8 @@ def get(key, default=None): except KeyError: heat_endpoint = __salt__['keystone.endpoint_get']('heat', profile)['publicurl'] heat_endpoint = heat_endpoint % token - log.debug('Calling heatclient.client.Client(' + - '{0}, {1}, **{2})'.format(api_version, heat_endpoint, - kwargs)) + log.debug('Calling heatclient.client.Client(%s, %s, **%s)', + api_version, heat_endpoint, kwargs) # may raise exc.HTTPUnauthorized, exc.HTTPNotFound # but we deal with those elsewhere return heatclient.client.Client(api_version, endpoint=heat_endpoint, **kwargs) @@ -250,7 +249,7 @@ def _poll_for_events(h_client, stack_name, action=None, poll_period=5, events = _get_stack_events(h_client, stack_id=stack_name, event_args={'sort_dir': 'asc', 'marker': marker}) - if len(events) == 0: + if not events: no_event_polls += 1 else: no_event_polls = 0 @@ -416,7 +415,7 @@ def delete_stack(name=None, poll=0, timeout=60, profile=None): ret['comment'] = 'Deleted stack {0}.'.format(name) return ret except Exception as ex: # pylint: disable=W0703 - log.exception('Delete failed {0}'.format(ex)) + log.exception('Delete failed %s', ex) ret['result'] = False ret['comment'] = '{0}'.format(ex) return ret @@ -543,10 +542,10 @@ def create_stack(name=None, template_file=None, environment=None, kwargs['template'] = template try: h_client.stacks.validate(**kwargs) - except Exception as ex: # pylint: disable=W0703 - log.exception('Template not valid {0}'.format(ex)) + except Exception as ex: + log.exception('Template not valid') ret['result'] = False - ret['comment'] = 'Template not valid {0}'.format(ex) + ret['comment'] = 'Template not valid: {0}'.format(ex) return ret env = {} if environment: @@ -609,9 +608,9 @@ def create_stack(name=None, template_file=None, environment=None, try: h_client.stacks.create(**fields) except Exception as ex: # pylint: disable=W0703 - log.exception('Create failed {0}'.format(ex)) + log.exception('Create failed') ret['result'] = False - ret['comment'] = '{0}'.format(ex) + ret['comment'] = six.text_type(ex) return ret if poll > 0: stack_status, msg = _poll_for_events(h_client, name, action='CREATE', @@ -743,7 +742,7 @@ def update_stack(name=None, template_file=None, environment=None, try: h_client.stacks.validate(**kwargs) except Exception as ex: # pylint: disable=W0703 - log.exception('Template not valid {0}'.format(ex)) + log.exception('Template not valid') ret['result'] = False ret['comment'] = 'Template not valid {0}'.format(ex) return ret @@ -806,7 +805,7 @@ def update_stack(name=None, template_file=None, environment=None, try: h_client.stacks.update(name, **fields) except Exception as ex: # pylint: disable=W0703 - log.exception('Update failed {0}'.format(ex)) + log.exception('Update failed') ret['result'] = False ret['comment'] = 'Update failed {0}'.format(ex) return ret diff --git a/salt/modules/highstate_doc.py b/salt/modules/highstate_doc.py index 77a1d378480f..88ccdd1f64bb 100644 --- a/salt/modules/highstate_doc.py +++ b/salt/modules/highstate_doc.py @@ -489,7 +489,7 @@ def proccess_lowstates(**kwargs): if not isinstance(ls, list): raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***') else: - if len(ls) > 0: + if ls: if not isinstance(ls[0], dict): raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***') @@ -516,7 +516,7 @@ def _state_data_to_yaml_string(data, whitelist=None, blacklist=None): kset &= set(whitelist) for k in kset: y[k] = data[k] - if len(y) == 0: + if not y: return None return salt.utils.yaml.safe_dump(y, default_flow_style=False) @@ -615,7 +615,7 @@ def proccesser_markdown(lowstate_item, config, **kwargs): for w in s.get('watch_in', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' - if s.get('require') and len(s.get('require')) > 0: + if s.get('require') and s.get('require'): requisites += 'require:\n' for w in s.get('require', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) @@ -671,7 +671,7 @@ def proccesser_markdown(lowstate_item, config, **kwargs): details += _format_markdown_system_file(s['name'], config) # if no state doc is created use default state as yaml - if len(details) == 0: + if not details: y = _state_data_to_yaml_string(s) if y: details += '```\n{0}```\n'.format(y) diff --git a/salt/modules/incron.py b/salt/modules/incron.py index b5a2dfeb6db6..7e24ee19f9e2 100644 --- a/salt/modules/incron.py +++ b/salt/modules/incron.py @@ -151,8 +151,9 @@ def raw_system_incron(): salt '*' incron.raw_system_incron ''' - log.debug("read_file {0}" . format(_read_file(_INCRON_SYSTEM_TAB, 'salt'))) - return ''.join(_read_file(_INCRON_SYSTEM_TAB, 'salt')) + _contents = _read_file(_INCRON_SYSTEM_TAB, 'salt') + log.debug('incron read_file contents: %s', _contents) + return ''.join(_contents) def raw_incron(user): @@ -186,7 +187,7 @@ def list_tab(user): data = raw_system_incron() else: data = raw_incron(user) - log.debug("user data {0}" . format(data)) + log.debug('incron user data %s', data) ret = {'crons': [], 'pre': [] } diff --git a/salt/modules/infoblox.py b/salt/modules/infoblox.py index 479446e827e4..31e3a7688b29 100644 --- a/salt/modules/infoblox.py +++ b/salt/modules/infoblox.py @@ -345,9 +345,7 @@ def get_host_domainname(name, domains=None, **api_opts): d = d.lower().rstrip('.') if name.endswith(d) and len(d) > len(match): match = d - if len(match) > 0: - return match - return None + return match if match else None def get_host_hostname(name, domains=None, **api_opts): @@ -649,8 +647,6 @@ def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): r = get_a(name, ipv4addr, allow_array=False, **api_opts) if not r: return True - if len(r) == 0: - return True if len(r) > 1 and not allow_array: raise Exception('More than one result, use allow_array to override') ret = [] diff --git a/salt/modules/ini_manage.py b/salt/modules/ini_manage.py index 1d3ca72993e1..a76ca3ca3ec4 100644 --- a/salt/modules/ini_manage.py +++ b/salt/modules/ini_manage.py @@ -453,7 +453,7 @@ def flush(self): next(ini_gen) ini_gen_list = list(ini_gen) # Avoid writing an initial line separator. - if len(ini_gen_list): + if ini_gen_list: ini_gen_list[0] = ini_gen_list[0].lstrip(os.linesep) outfile.writelines(salt.utils.data.encode(ini_gen_list)) except (OSError, IOError) as exc: diff --git a/salt/modules/inspectlib/fsdb.py b/salt/modules/inspectlib/fsdb.py index 5c74cd73849e..e5cdb4ebebd1 100644 --- a/salt/modules/inspectlib/fsdb.py +++ b/salt/modules/inspectlib/fsdb.py @@ -325,7 +325,7 @@ def _to_type(self, data, type): elif type == 'float': data = float(data) elif type == 'long': - data = sys.version_info[0] == 2 and long(data) or int(data) # pylint: disable=W1699 + data = sys.version_info[0] == 2 and long(data) or int(data) # pylint: disable=incompatible-py3-code,undefined-variable else: data = str(data) return data diff --git a/salt/modules/inspector.py b/salt/modules/inspector.py index 82ef1f41b107..e6583729c94c 100644 --- a/salt/modules/inspector.py +++ b/salt/modules/inspector.py @@ -56,7 +56,7 @@ def _(module): # importlib is in Python 2.7+ and 3+ import importlib mod = importlib.import_module("salt.modules.inspectlib.{0}".format(module)) - except ImportError as err: + except ImportError: # No importlib around (2.6) mod = getattr(__import__("salt.modules.inspectlib", globals(), locals(), fromlist=[six.text_type(module)]), module) # pylint: enable=E0598 diff --git a/salt/modules/ipset.py b/salt/modules/ipset.py index 8d3a33b6d56d..f1c9bf2b561c 100644 --- a/salt/modules/ipset.py +++ b/salt/modules/ipset.py @@ -286,7 +286,7 @@ def list_sets(family='ipv4'): sets = [] sets.append({}) for item in _tmp: - if len(item) == 0: + if not item: count = count + 1 sets.append({}) continue @@ -357,7 +357,7 @@ def add(setname=None, entry=None, family='ipv4', **kwargs): if 'comment' not in entry: cmd = '{0} comment "{1}"'.format(cmd, kwargs['comment']) - if len(set(['skbmark', 'skbprio', 'skbqueue']) & set(kwargs.keys())) > 0: + if set(['skbmark', 'skbprio', 'skbqueue']) & set(kwargs): if 'skbinfo' not in setinfo['Header']: return 'Error: Set {0} not created with skbinfo support'.format(setname) @@ -373,7 +373,7 @@ def add(setname=None, entry=None, family='ipv4', **kwargs): cmd = '{0} add -exist {1} {2}'.format(_ipset_cmd(), setname, cmd) out = __salt__['cmd.run'](cmd, python_shell=False) - if len(out) == 0: + if not out: return 'Success' return 'Error: {0}'.format(out) @@ -402,7 +402,7 @@ def delete(set=None, entry=None, family='ipv4', **kwargs): cmd = '{0} del {1} {2}'.format(_ipset_cmd(), set, entry) out = __salt__['cmd.run'](cmd, python_shell=False) - if len(out) == 0: + if not out: return 'Success' return 'Error: {0}'.format(out) @@ -445,7 +445,7 @@ def check(set=None, entry=None, family='ipv4'): current_members = _parse_members(settype, _find_set_members(set)) - if not len(current_members): + if not current_members: return False if isinstance(entry, list): @@ -523,10 +523,7 @@ def flush(set=None, family='ipv4'): cmd = '{0} flush'.format(_ipset_cmd()) out = __salt__['cmd.run'](cmd, python_shell=False) - if len(out) == 0: - return True - else: - return False + return not out def _find_set_members(set): diff --git a/salt/modules/iptables.py b/salt/modules/iptables.py index aff72560bf7a..9b8af2fd3366 100644 --- a/salt/modules/iptables.py +++ b/salt/modules/iptables.py @@ -163,7 +163,7 @@ def _regex_iptables_save(cmd_output, filters=None): pattern, e) continue - if len(__context__['iptables.save_filters']) > 0: + if __context__['iptables.save_filters']: # line by line get rid of any regex matches _filtered_cmd_output = \ [line for line in cmd_output.splitlines(True) @@ -679,7 +679,7 @@ def save(filename=None, family='ipv4'): ipt = __salt__['cmd.run'](cmd) # regex out the output if configured with filters - if len(_conf_save_filters()) > 0: + if _conf_save_filters(): ipt = _regex_iptables_save(ipt) out = __salt__['file.write'](filename, ipt) @@ -862,10 +862,7 @@ def append(table='filter', chain=None, rule=None, family='ipv4'): cmd = '{0} {1} -t {2} -A {3} {4}'.format( _iptables_cmd(family), wait, table, chain, rule) out = __salt__['cmd.run'](cmd) - if len(out) == 0: - return True - else: - return False + return not out def insert(table='filter', chain=None, position=None, rule=None, family='ipv4'): diff --git a/salt/modules/jboss7.py b/salt/modules/jboss7.py index da9e7b2452d4..5b1fb534e7b0 100644 --- a/salt/modules/jboss7.py +++ b/salt/modules/jboss7.py @@ -246,7 +246,7 @@ def update_datasource(jboss_config, name, new_properties, profile=None): 'success': True, 'comment': '' } - if len(changed_properties) > 0: + if changed_properties: ds_resource_description = __get_datasource_resource_description(jboss_config, name, profile) ds_attributes = ds_resource_description['attributes'] for key in changed_properties: @@ -474,7 +474,7 @@ def list_deployments(jboss_config): log.debug("======================== MODULE FUNCTION: jboss7.list_deployments") command_result = __salt__['jboss7_cli.run_command'](jboss_config, 'deploy') deployments = [] - if len(command_result['stdout']) > 0: + if command_result['stdout']: deployments = re.split('\\s*', command_result['stdout']) log.debug('deployments=%s', deployments) return deployments diff --git a/salt/modules/jboss7_cli.py b/salt/modules/jboss7_cli.py index a59c88029817..ab999868db20 100644 --- a/salt/modules/jboss7_cli.py +++ b/salt/modules/jboss7_cli.py @@ -231,7 +231,7 @@ def _parse(cli_output): tokens = __tokenize(cli_output) result = __process_tokens(tokens) - log.debug("=== RESULT: "+pprint.pformat(result)) + log.debug('=== RESULT: %s', pprint.pformat(result)) return result @@ -346,7 +346,7 @@ def __is_long(token): def __get_long(token): if six.PY2: - return long(token[0:-1]) # pylint: disable=incompatible-py3-code + return long(token[0:-1]) # pylint: disable=incompatible-py3-code,undefined-variable else: return int(token[0:-1]) diff --git a/salt/modules/k8s.py b/salt/modules/k8s.py index e0af204ba05e..11a2c7882e4e 100644 --- a/salt/modules/k8s.py +++ b/salt/modules/k8s.py @@ -756,7 +756,7 @@ def create_secret(namespace, name, sources, apiserver_url=None, force=False, upd return ret data[sname] = encoded - log.trace("secret data is: {0}".format(data)) + log.trace('secret data is: %s', data) if secret and update: if not data: diff --git a/salt/modules/layman.py b/salt/modules/layman.py index 4f2e8dac90aa..febe7418ed7a 100644 --- a/salt/modules/layman.py +++ b/salt/modules/layman.py @@ -55,7 +55,7 @@ def add(overlay): # If we did not have any overlays before and we successfully added # a new one. We need to ensure the make.conf is sourcing layman's # make.conf so emerge can see the overlays - if len(old_overlays) == 0 and len(new_overlays) > 0: + if not old_overlays and new_overlays: srcline = 'source /var/lib/layman/make.conf' makeconf = _get_makeconf() if not __salt__['file.contains'](makeconf, 'layman'): @@ -88,7 +88,7 @@ def delete(overlay): # If we now have no overlays added, We need to ensure that the make.conf # does not source layman's make.conf, as it will break emerge - if len(new_overlays) == 0: + if not new_overlays: srcline = 'source /var/lib/layman/make.conf' makeconf = _get_makeconf() if __salt__['file.contains'](makeconf, 'layman'): diff --git a/salt/modules/libcloud_compute.py b/salt/modules/libcloud_compute.py index f1191dea5908..c072813d4d8f 100644 --- a/salt/modules/libcloud_compute.py +++ b/salt/modules/libcloud_compute.py @@ -139,7 +139,7 @@ def list_sizes(profile, location_id=None, **libcloud_kwargs): libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: locations = [loc for loc in conn.list_locations() if loc.id == location_id] - if len(locations) == 0: + if not locations: raise ValueError("Location not found") else: sizes = conn.list_sizes(location=locations[0], **libcloud_kwargs) @@ -782,7 +782,7 @@ def _get_by_id(collection, id): Get item from a list by the id field ''' matches = [item for item in collection if item.id == id] - if len(matches) == 0: + if not matches: raise ValueError('Could not find a matching item') elif len(matches) > 1: raise ValueError('The id matched {0} items, not 1'.format(len(matches))) diff --git a/salt/modules/libcloud_loadbalancer.py b/salt/modules/libcloud_loadbalancer.py index 65849be4947d..729393ab980a 100644 --- a/salt/modules/libcloud_loadbalancer.py +++ b/salt/modules/libcloud_loadbalancer.py @@ -375,7 +375,7 @@ def balancer_detach_member(balancer_id, member_id, profile, **libcloud_kwargs): match = [member for member in members if member.id == member_id] if len(match) > 1: raise ValueError("Ambiguous argument, found mulitple records") - elif len(match) == 0: + elif not match: raise ValueError("Bad argument, found no records") else: member = match[0] diff --git a/salt/modules/linux_acl.py b/salt/modules/linux_acl.py index c0596b0eeb7c..0a787aaeafa5 100644 --- a/salt/modules/linux_acl.py +++ b/salt/modules/linux_acl.py @@ -41,7 +41,7 @@ def version(): def _raise_on_no_files(*args): - if len(args) == 0: + if not args: raise CommandExecutionError('You need to specify at least one file or directory to work with!') diff --git a/salt/modules/linux_sysctl.py b/salt/modules/linux_sysctl.py index 042e44d11b49..272f67dba866 100644 --- a/salt/modules/linux_sysctl.py +++ b/salt/modules/linux_sysctl.py @@ -132,7 +132,7 @@ def assign(name, value): if six.PY3: tran_tab = name.translate(''.maketrans('./', '/.')) else: - if isinstance(name, unicode): # pylint: disable=incompatible-py3-code + if isinstance(name, unicode): # pylint: disable=incompatible-py3-code,undefined-variable trans_args = {ord('/'): u'.', ord('.'): u'/'} else: trans_args = string.maketrans('./', '/.') diff --git a/salt/modules/logadm.py b/salt/modules/logadm.py index 2ccc7e7f79a9..3b34efd1f089 100644 --- a/salt/modules/logadm.py +++ b/salt/modules/logadm.py @@ -64,7 +64,7 @@ def _arg2opt(arg): ''' res = [o for o, a in option_toggles.items() if a == arg] res += [o for o, a in option_flags.items() if a == arg] - return res[0] if len(res) else None + return res[0] if res else None def _parse_conf(conf_file=default_conf): @@ -90,7 +90,7 @@ def _parse_options(entry, options, include_unset=True): ''' log_cfg = {} options = shlex.split(options) - if len(options) == 0: + if not options: return None ## identifier is entry or log? diff --git a/salt/modules/lxd.py b/salt/modules/lxd.py index d6c2d8d4b91e..2a7a0255d43c 100644 --- a/salt/modules/lxd.py +++ b/salt/modules/lxd.py @@ -336,9 +336,7 @@ def pylxd_client_get(remote_addr=None, cert=None, key=None, verify_cert=True): six.text_type(verify_cert),)) if pool_key in _connection_pool: - log.debug(( - 'Returning the client "{0}" from our connection pool' - ).format(remote_addr)) + log.debug('Returning the client "%s" from our connection pool', remote_addr) return _connection_pool[pool_key] try: @@ -374,12 +372,10 @@ def pylxd_client_get(remote_addr=None, cert=None, key=None, verify_cert=True): ) ) - log.debug(( - 'Trying to connecto to "{0}" ' - 'with cert "{1}", key "{2}" and ' - 'verify_cert "{3!s}"'.format( - remote_addr, cert, key, verify_cert) - )) + log.debug( + 'Trying to connect to "%s" with cert "%s", key "%s" and ' + 'verify_cert "%s"', remote_addr, cert, key, verify_cert + ) client = pylxd.Client( endpoint=remote_addr, cert=(cert, key,), @@ -3043,11 +3039,8 @@ def image_copy_lxd(source, if aliases is None: aliases = [] - log.debug( - 'Trying to copy the image "{0}" from "{1}" to "{2}"'.format( - source, src_remote_addr, remote_addr - ) - ) + log.debug('Trying to copy the image "%s" from "%s" to "%s"', + source, src_remote_addr, remote_addr) # This will fail with a SaltInvocationError if # the image doesn't exists on the source and with a CommandExecutionError diff --git a/salt/modules/mac_brew.py b/salt/modules/mac_brew.py index c4507d8267a5..8e851f67635a 100644 --- a/salt/modules/mac_brew.py +++ b/salt/modules/mac_brew.py @@ -390,7 +390,7 @@ def install(name=None, pkgs=None, taps=None, options=None, **kwargs): except MinionError as exc: raise CommandExecutionError(exc) - if pkg_params is None or len(pkg_params) == 0: + if not pkg_params: return {} formulas = ' '.join(pkg_params) diff --git a/salt/modules/mac_package.py b/salt/modules/mac_package.py index adda63ce737e..6e6bed357bdd 100644 --- a/salt/modules/mac_package.py +++ b/salt/modules/mac_package.py @@ -100,7 +100,7 @@ def install_app(app, target='/Applications/'): salt '*' macpackage.install_app /tmp/tmp.app /Applications/ ''' - if not target[-4:] == '.app': + if target[-4:] != '.app': if app[-1:] == '/': base_app = os.path.basename(app[:-1]) else: @@ -238,7 +238,7 @@ def get_pkg_id(pkg): # Find our identifiers for f in files: i = _get_pkg_id_from_pkginfo(os.path.join(temp_dir, f)) - if len(i): + if i: package_ids.extend(i) else: package_ids = _get_pkg_id_dir(pkg) diff --git a/salt/modules/mac_ports.py b/salt/modules/mac_ports.py index 78a38d54a943..f57c1916189b 100644 --- a/salt/modules/mac_ports.py +++ b/salt/modules/mac_ports.py @@ -319,7 +319,7 @@ def install(name=None, refresh=False, pkgs=None, **kwargs): pkg_params = {name: spec} - if pkg_params is None or len(pkg_params) == 0: + if not pkg_params: return {} formulas_array = [] diff --git a/salt/modules/mdata.py b/salt/modules/mdata.py index d271ea845c00..e4f7bc81f60e 100644 --- a/salt/modules/mdata.py +++ b/salt/modules/mdata.py @@ -116,7 +116,7 @@ def get_(*keyname): mdata = _check_mdata_get() ret = {} - if len(keyname) == 0: + if not keyname: keyname = list_() for k in keyname: diff --git a/salt/modules/mongodb.py b/salt/modules/mongodb.py index bf330eb75d0c..d508a652b311 100644 --- a/salt/modules/mongodb.py +++ b/salt/modules/mongodb.py @@ -513,7 +513,7 @@ def update_one(objects, collection, user=None, password=None, host=None, port=No authdb) if not isinstance(test_f, list): return 'The find result is not well formatted. An error appears; cannot update.' - elif len(test_f) < 1: + elif not test_f: return 'Did not find any result. You should try an insert before.' elif len(test_f) > 1: return 'Too many results. Please try to be more specific.' diff --git a/salt/modules/mysql.py b/salt/modules/mysql.py index fa01f6669503..c35db7c6dec7 100644 --- a/salt/modules/mysql.py +++ b/salt/modules/mysql.py @@ -1797,7 +1797,7 @@ def __grant_generate(grant, args = {} args['user'] = user args['host'] = host - if isinstance(ssl_option, list) and len(ssl_option): + if ssl_option and isinstance(ssl_option, list): qry += __ssl_option_sanitize(ssl_option) if salt.utils.data.is_true(grant_option): qry += ' WITH GRANT OPTION' @@ -2181,7 +2181,7 @@ def get_master_status(**connection_args): conn.close() # check for if this minion is not a master - if len(rtnv) == 0: + if not rtnv: rtnv.append([]) log.debug('%s-->%s', mod, len(rtnv[0])) @@ -2251,7 +2251,7 @@ def get_slave_status(**connection_args): conn.close() # check for if this minion is not a slave - if len(rtnv) == 0: + if not rtnv: rtnv.append([]) log.debug('%s-->%s', mod, len(rtnv[0])) @@ -2279,7 +2279,7 @@ def showvariables(**connection_args): return [] rtnv = __do_query_into_hash(conn, "SHOW VARIABLES") conn.close() - if len(rtnv) == 0: + if not rtnv: rtnv.append([]) log.debug('%s-->%s', mod, len(rtnv[0])) @@ -2307,7 +2307,7 @@ def showglobal(**connection_args): return [] rtnv = __do_query_into_hash(conn, "SHOW GLOBAL VARIABLES") conn.close() - if len(rtnv) == 0: + if not rtnv: rtnv.append([]) log.debug('%s-->%s', mod, len(rtnv[0])) diff --git a/tests/unit/modules/test_file.py b/tests/unit/modules/test_file.py index 693548295dc6..4a4875e5f46a 100644 --- a/tests/unit/modules/test_file.py +++ b/tests/unit/modules/test_file.py @@ -1249,8 +1249,10 @@ def test_delete_line_in_empty_file(self): patch('os.stat', self._anyattr), \ patch('salt.modules.file.log', _log): self.assertFalse(filemod.line('/dummy/path', content='foo', match='bar', mode=mode)) - self.assertIn('Cannot find text to {0}'.format(mode), - _log.warning.call_args_list[0][0][0]) + assert 'Cannot find text to ' in _log.warning.call_args_list[0][0][0], \ + _log.warning.call_args_list[0][0][0] + assert _log.warning.call_args_list[0][0][1] == mode, \ + _log.warning.call_args_list[0][0][1] @patch('os.path.realpath', MagicMock()) @patch('os.path.isfile', MagicMock(return_value=True))