Skip to content

Commit

Permalink
Upgrade pylint => 1.7.1 (Azure#3448)
Browse files Browse the repository at this point in the history
  • Loading branch information
troydai authored May 24, 2017
1 parent 074d07f commit 2e4010d
Show file tree
Hide file tree
Showing 114 changed files with 581 additions and 752 deletions.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mock==1.3.0
paramiko==2.0.2
pip==9.0.1
pygments==2.1.3
pylint==1.5.4
pylint==1.7.1
pyOpenSSL==16.2.0
pyyaml==3.11
requests==2.9.1
Expand Down
9 changes: 1 addition & 8 deletions scripts/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,7 @@ python -m azure.cli -h --debug
# Ensure tokens are erased from VCR recordings
python -m automation.tests.check_vcr_recordings

# PyLint does not yet support Python 3.6 https://github.com/PyCQA/pylint/issues/1241

LOCAL_PYTHON_VERSION=$(python -c 'import sys; print("{0}.{1}".format(sys.version_info[0], sys.version_info[1]))')
if [[ "$TRAVIS_PYTHON_VERSION" == "3.6" || "$LOCAL_PYTHON_VERSION" == "3.6" ]]; then
echo 'Skipping check_style since it is not supported in python 3.6'
else
check_style --ci;
fi
check_style --ci;

if [ "$CODE_COVERAGE" == "True" ]; then
echo "Run tests with code coverage."
Expand Down
5 changes: 1 addition & 4 deletions src/azure-cli-core/azure/cli/core/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ def get_config_parser():
import sys

python_version = sys.version_info.major
if python_version == 3:
return configparser.ConfigParser()
else:
return configparser.SafeConfigParser()
return configparser.ConfigParser() if python_version == 3 else configparser.SafeConfigParser()


class AzConfig(object):
Expand Down
8 changes: 2 additions & 6 deletions src/azure-cli-core/azure/cli/core/_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import os


def get_config_dir():
if os.getenv('AZURE_CONFIG_DIR'):
return os.getenv('AZURE_CONFIG_DIR')
else:
return os.path.expanduser(os.path.join('~', '.azure'))
import os
return os.getenv('AZURE_CONFIG_DIR', None) or os.path.expanduser(os.path.join('~', '.azure'))
10 changes: 5 additions & 5 deletions src/azure-cli-core/azure/cli/core/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def show_help(nouns, parser, is_group):

help_file.load(parser)

if len(nouns) == 0:
if not nouns:
print("\nFor version info, use 'az --version'")
help_file.command = ''

Expand Down Expand Up @@ -80,7 +80,7 @@ def print_detailed_help(help_file):
elif help_file.type == 'group':
_print_groups(help_file)

if len(help_file.examples) > 0:
if help_file.examples:
_print_examples(help_file)


Expand All @@ -104,7 +104,7 @@ def print_arguments(help_file):
_print_indent('')
return

if len(help_file.parameters) == 0:
if not help_file.parameters:
_print_indent('none', indent)
required_tag = ' [Required]'
max_name_length = max(len(p.name) + (len(required_tag) if p.required else 0)
Expand Down Expand Up @@ -207,7 +207,7 @@ def _print_items(items):

indent = 1
max_name_length = max(len(c.name) for c in help_file.children) \
if len(help_file.children) > 0 \
if help_file.children \
else 0
subgroups = [c for c in help_file.children if isinstance(c, GroupHelpFile)]
subcommands = [c for c in help_file.children if c not in subgroups]
Expand Down Expand Up @@ -275,7 +275,7 @@ class HelpFile(HelpObject): # pylint: disable=too-few-public-methods,too-many-i
def __init__(self, delimiters):
super(HelpFile, self).__init__()
self.delimiters = delimiters
self.name = delimiters.split()[-1] if len(delimiters) > 0 else delimiters
self.name = delimiters.split()[-1] if delimiters else delimiters
self.command = delimiters
self.type = ''
self.short_summary = ''
Expand Down
15 changes: 7 additions & 8 deletions src/azure-cli-core/azure/cli/core/_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ def _decode_str(output):

class ComplexEncoder(json.JSONEncoder):

def default(self, obj): # pylint: disable=method-hidden
if isinstance(obj, bytes) and not isinstance(obj, str):
return obj.decode()
return json.JSONEncoder.default(self, obj)
def default(self, o): # pylint: disable=method-hidden
if isinstance(o, bytes) and not isinstance(o, str):
return o.decode()
return json.JSONEncoder.default(self, o)


def format_json(obj):
Expand Down Expand Up @@ -134,7 +134,7 @@ def __init__(self, should_sort_keys=False):

@staticmethod
def _capitalize_first_char(x):
return x[0].upper() + x[1:] if x and len(x) > 0 else x
return x[0].upper() + x[1:] if x else x

def _auto_table_item(self, item):
new_entry = OrderedDict()
Expand All @@ -160,8 +160,7 @@ def _auto_table(self, result):
for item in result:
new_result.append(self._auto_table_item(item))
return new_result
else:
return self._auto_table_item(result)
return self._auto_table_item(result)

def dump(self, data):
table_data = self._auto_table(data)
Expand Down Expand Up @@ -218,7 +217,7 @@ def _dump_obj(data, stream):
@staticmethod
def _dump_row(data, stream):
separator = ''
if isinstance(data, dict) or isinstance(data, list):
if isinstance(data, (dict, list)):
if isinstance(data, OrderedDict):
values = data.values()
elif isinstance(data, dict):
Expand Down
18 changes: 6 additions & 12 deletions src/azure-cli-core/azure/cli/core/_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,8 @@ def _retrieve_token():
if user_type == _USER:
return self._creds_cache.retrieve_token_for_user(username_or_sp_id,
account[_TENANT_ID], resource)
else:
return self._creds_cache.retrieve_token_for_service_principal(username_or_sp_id,
resource)
return self._creds_cache.retrieve_token_for_service_principal(username_or_sp_id, resource)

from azure.cli.core.adal_authentication import AdalAuthentication
auth_object = AdalAuthentication(_retrieve_token)

Expand Down Expand Up @@ -395,9 +394,7 @@ def __init__(self, auth_context_factory, adal_token_cache, arm_client_factory=No
def create_arm_client_factory(config):
if arm_client_factory:
return arm_client_factory(config)
else:
return change_ssl_cert_verification(SubscriptionClient(
config, base_url=CLOUD.endpoints.resource_manager))
return change_ssl_cert_verification(SubscriptionClient(config, base_url=CLOUD.endpoints.resource_manager))

self._arm_client_factory = create_arm_client_factory
self.tenants = []
Expand Down Expand Up @@ -635,12 +632,9 @@ def __init__(self, password_arg_value):

def acquire_token(self, authentication_context, resource, client_id):
if hasattr(self, 'secret'):
return authentication_context.acquire_token_with_client_credentials(resource,
client_id,
self.secret)
else:
return authentication_context.acquire_token_with_client_certificate(
resource, client_id, self.cert_file_string, self.thumbprint)
return authentication_context.acquire_token_with_client_credentials(resource, client_id, self.secret)
return authentication_context.acquire_token_with_client_certificate(resource, client_id, self.cert_file_string,
self.thumbprint)

def get_entry_to_persist(self, sp_id, tenant):
entry = {
Expand Down
1 change: 1 addition & 0 deletions src/azure-cli-core/azure/cli/core/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Session(collections.MutableMapping):
'''

def __init__(self, encoding=None):
super(Session, self).__init__()
self.filename = None
self.data = {}
self._encoding = encoding if encoding else 'utf-8-sig'
Expand Down
7 changes: 4 additions & 3 deletions src/azure-cli-core/azure/cli/core/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def execute(self, unexpanded_argv): # pylint: disable=too-many-statements
self.parser.load_command_table(command_table)
self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser)

if len(argv) == 0:
if not argv:
enable_autocomplete(self.parser)
az_subparser = self.parser.subparsers[tuple()]
_help.show_welcome(az_subparser)
Expand Down Expand Up @@ -273,8 +273,9 @@ def _maybe_load_file(arg):
return arg
elif ix == 0:
return Application._load_file(poss_file)
else: # if @ not at the start it can't be a file
return arg

# if @ not at the start it can't be a file
return arg

@staticmethod
def _expand_file_prefix(arg):
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/azlogging.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def configure_logging(argv):
az_logger.setLevel(logging.DEBUG)
az_logger.propagate = False

if len(root_logger.handlers) and len(az_logger.handlers):
if root_logger.handlers and az_logger.handlers:
# loggers already configured
return
_init_console_handlers(root_logger, az_logger, log_level_config)
Expand Down
12 changes: 5 additions & 7 deletions src/azure-cli-core/azure/cli/core/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def __call__(self, poller):
try:
message = '{} {}'.format(
str(message),
json.loads(client_exception.response.text)['error']['details'][0]['message'])
json.loads(client_exception.response.text)['error']['details'][0]['message']) # pylint: disable=no-member
except: # pylint: disable=bare-except
pass

Expand Down Expand Up @@ -195,9 +195,9 @@ def __call__(self, result):
elif isinstance(result, ClientRawResponse):
# --no-wait returns a ClientRawResponse
return None
else:
# --validate returns a 'normal' response
return result

# --validate returns a 'normal' response
return result


class CommandTable(dict):
Expand Down Expand Up @@ -392,8 +392,7 @@ def get_op_handler(operation):
op = getattr(op, part)
if isinstance(op, types.FunctionType):
return op
else:
return six.get_method_function(op)
return six.get_method_function(op)
except (ValueError, AttributeError):
raise ValueError("The operation '{}' is invalid.".format(operation))

Expand Down Expand Up @@ -443,7 +442,6 @@ def create_command(module_name, name, operation,
raise ValueError("Operation must be a string. Got '{}'".format(operation))

def _execute_command(kwargs):
from msrestazure.azure_exceptions import CloudError
if confirmation \
and not kwargs.get(CONFIRM_PARAM_NAME) \
and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def _option_descriptions(operation):
option_descs = {}
lines = inspect.getdoc(operation)
param_breaks = ["'''", '"""', ':param', ':type', ':return', ':rtype']
if lines:
if lines: # pylint: disable=too-many-nested-blocks
lines = lines.splitlines()
index = 0
while index < len(lines):
Expand Down
20 changes: 6 additions & 14 deletions src/azure-cli-core/azure/cli/core/commands/arm.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,7 @@ def __new__(cls, val):


def resource_exists(resource_group, name, namespace, type, **_): # pylint: disable=redefined-builtin
'''Checks if the given resource exists.
'''
from azure.mgmt.resource import ResourceManagementClient

''' Checks if the given resource exists. '''
odata_filter = "resourceGroup eq '{}' and name eq '{}'" \
" and resourceType eq '{}/{}'".format(resource_group, name, namespace, type)
client = get_mgmt_service_client(ResourceType.MGMT_RESOURCE_RESOURCES).resources
Expand All @@ -109,18 +106,16 @@ def resource_exists(resource_group, name, namespace, type, **_): # pylint: disa


def add_id_parameters(command_table):

def split_action(arguments):
class SplitAction(argparse.Action): # pylint: disable=too-few-public-methods

def __call__(self, parser, namespace, values, option_string=None):
''' The SplitAction will take the given ID parameter and spread the parsed
parts of the id into the individual backing fields.
Since the id value is expected to be of type `IterateValue`, all the backing
(dest) fields will also be of type `IterateValue`
'''
try:
try: # pylint: disable=too-many-nested-blocks
for value in [values] if isinstance(values, str) else values:
parts = parse_resource_id(value)
for arg in [arg for arg in arguments.values() if arg.id_part]:
Expand All @@ -132,7 +127,7 @@ def __call__(self, parser, namespace, values, option_string=None):
if isinstance(existing_values, str):
if not getattr(arg.type, 'configured_default_applied', None):
logger.warning(
"Property '%s=%s' being overriden by value '%s' from IDs parameter.", # pylint: disable=line-too-long
"Property '%s=%s' being overriden by value '%s' from IDs parameter.",
arg.name, existing_values, parts[arg.id_part]
)
existing_values = IterateValue()
Expand Down Expand Up @@ -503,7 +498,7 @@ def _find_split():
value = []
brackets = False
chars = list(expression)
while len(chars) > 0:
while chars:
c = chars.pop(0)
if c == '=' and not brackets:
# keys done the rest is value
Expand All @@ -519,15 +514,12 @@ def _find_split():
# normal character
key += c

key = ''.join(key) # pylint: disable=redefined-variable-type
value = ''.join(value) # pylint: disable=redefined-variable-type
return key, value
return ''.join(key), ''.join(value)

equals_count = expression.count('=')
if equals_count == 1:
return expression.split('=', 1)
else:
return _find_split()
return _find_split()


def set_properties(instance, expression):
Expand Down
6 changes: 2 additions & 4 deletions src/azure-cli-core/azure/cli/core/commands/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ def get_resources_in_resource_group(resource_group_name, resource_type=None):
filter_str = "resourceType eq '{}'".format(resource_type) if resource_type else None
if supported_api_version(ResourceType.MGMT_RESOURCE_RESOURCES, max_api='2016-09-01'):
return list(rcf.resource_groups.list_resources(resource_group_name, filter=filter_str))
else:
return list(rcf.resources.list_by_resource_group(resource_group_name, filter=filter_str))
return list(rcf.resources.list_by_resource_group(resource_group_name, filter=filter_str))


def get_resources_in_subscription(resource_type=None):
Expand All @@ -84,8 +83,7 @@ def completer(prefix, action, parsed_args, **kwargs): # pylint: disable=unused-
if getattr(parsed_args, 'resource_group_name', None):
rg = parsed_args.resource_group_name
return [r.name for r in get_resources_in_resource_group(rg, resource_type=resource_type)]
else:
return [r.name for r in get_resources_in_subscription(resource_type=resource_type)]
return [r.name for r in get_resources_in_subscription(resource_type=resource_type)]
return completer


Expand Down
6 changes: 3 additions & 3 deletions src/azure-cli-core/azure/cli/core/commands/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ def validate_file_or_dict(string):
if os.path.exists(string):
from azure.cli.core.util import get_file_json
return get_file_json(string)
else:
from azure.cli.core.util import shell_safe_json_parse
return shell_safe_json_parse(string)

from azure.cli.core.util import shell_safe_json_parse
return shell_safe_json_parse(string)


SPECIFIED_SENTINEL = '__SET__'
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/extensions/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def handle_query_parameter(**kwargs):
del args._jmespath_query
if query_expression:
def filter_output(**kwargs):
from jmespath import search, Options
from jmespath import Options
kwargs['event_data']['result'] = query_expression.search(
kwargs['event_data']['result'], Options(collections.OrderedDict))
application.remove(application.FILTER_RESULT, filter_output)
Expand Down
3 changes: 1 addition & 2 deletions src/azure-cli-core/azure/cli/core/help_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,4 @@ def _load_help_file(delimiters):
import yaml
if delimiters in helps:
return yaml.load(helps[delimiters])
else:
return None
return None
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/prompting.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def prompt_choice_list(msg, a_list, default=1, help_string=None):
if val == '?' and help_string is not None:
print(help_string)
continue
if len(val) == 0:
if not val:
val = '{}'.format(default)
try:
ans = int(val)
Expand Down
Loading

0 comments on commit 2e4010d

Please sign in to comment.