Skip to content
Prev Previous commit
Next Next commit
Update
  • Loading branch information
bebound committed Jun 26, 2023
commit 517cf5785cd8365ba0b1c10553d5dc2164b74468
10 changes: 9 additions & 1 deletion pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,15 @@ disable=
redundant-u-string-prefix,
raising-bad-type,
unused-private-member,
used-before-assignment
used-before-assignment,
# These rules were added in Pylint >= 2.12 and are disabled to avoid making retroactively required
broad-exception-raised,
deprecated-module,
missing-timeout,
superfluous-parens,
implicit-str-concat,
modified-iterating-list,
unnecessary-dunder-call,

[FORMAT]
max-line-length=120
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/aaz/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def show(self):
key = self.keys[idx]
if isinstance(schema, AAZObjectArg):
try:
schema = schema[key]
schema = schema[key] # pylint: disable=unsubscriptable-object
except AAZUndefinedValueError:
# show the help of current schema
break
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,11 +309,11 @@ def ensure_aks_acr_role_assignment(cmd, assignee, registry_id, detach=False, is_
if not delete_role_assignments(
cmd.cli_ctx, "acrpull", assignee, scope=registry_id, is_service_principal=is_service_principal
):
raise AzCLIError("Could not delete role assignments for ACR. " "Are you an Owner on this subscription?")
raise AzCLIError("Could not delete role assignments for ACR. Are you an Owner on this subscription?")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

W1404: Implicit string concatenation found in call (implicit-str-concat)

return

if not add_role_assignment(cmd, "acrpull", assignee, scope=registry_id, is_service_principal=is_service_principal):
raise AzCLIError("Could not create a role assignment for ACR. " "Are you an Owner on this subscription?")
raise AzCLIError("Could not create a role assignment for ACR. Are you an Owner on this subscription?")
return


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def items(self):
return self.__store.items()

def __format_count(self):
untouched_keys = [x for x in self.__store.keys() if x not in self.__count.keys()]
untouched_keys = [x for x in self.__store if x not in self.__count]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C0201: Consider iterating the dictionary directly instead of calling .keys() (consider-iterating-dictionary)

for k in untouched_keys:
self.__count[k] = 0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ def __print_features_preview(old_json, new_json, strict=False, yes=False):

diff_output = __find_ff_diff(old_json=old_json, new_json=new_json, strict=strict)

if diff_output == {}:
if not diff_output:
logger.warning('\nThe target configuration already contains all feature flags in source. No changes will be made.')
return False

Expand All @@ -675,7 +675,7 @@ def __print_kv_preview(old_json, new_json, strict=False, yes=False):

diff_output = __find_kv_diff(old_json=old_json, new_json=new_json, strict=strict)

if diff_output == {}:
if not diff_output:
logger.warning('\nTarget configuration already contains all key-values in source. No changes will be made.')
return False

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def _validate_ip_address_existence(cmd, namespace):
scm_site = namespace.scm_site
configs = _generic_site_operation(cmd.cli_ctx, resource_group_name, name, 'get_configuration', slot)
access_rules = configs.scm_ip_security_restrictions if scm_site else configs.ip_security_restrictions
ip_exists = [(lambda x: x.ip_address == namespace.ip_address)(x) for x in access_rules]
ip_exists = [x.ip_address == namespace.ip_address for x in access_rules]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C3002: Lambda expression called directly. Execute the expression inline instead. (unnecessary-direct-lambda-call)

if True in ip_exists:
raise ArgumentUsageError('IP address: ' + namespace.ip_address + ' already exists. '
'Cannot add duplicate IP address values.')
Expand Down Expand Up @@ -521,11 +521,11 @@ def validate_registry_user(namespace):
if namespace.environment and namespace.registry_username:
if not namespace.registry_server or (not namespace.registry_password and ACR_IMAGE_SUFFIX not in namespace.registry_server): # pylint: disable=line-too-long
raise RequiredArgumentMissingError("Usage error: --registry-server, --registry-password and"
" --registry-username are required together if not using Azure Container Registry")
" --registry-username are required together if not using Azure Container Registry") # pylint: disable=line-too-long


def validate_registry_pass(namespace):
if namespace.environment and namespace.registry_password:
if not namespace.registry_server or (not namespace.registry_username and ACR_IMAGE_SUFFIX not in namespace.registry_server): # pylint: disable=line-too-long
raise RequiredArgumentMissingError("Usage error: --registry-server, --registry-password and"
" --registry-username are required together if not using Azure Container Registry")
" --registry-username are required together if not using Azure Container Registry") # pylint: disable=line-too-long
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ def delete_staticsite(cmd, name, resource_group_name=None, no_wait=False):

def _parse_pair(pair, delimiter):
if delimiter not in pair:
InvalidArgumentValueError("invalid format of pair {0}".format(pair))
raise InvalidArgumentValueError("invalid format of pair {0}".format(pair))
Copy link
Contributor Author

@bebound bebound Jun 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line makes no sense without raise.

W0133: Exception statement has no effect (pointless-exception-statement)


index = pair.index(delimiter)
return pair[:index], pair[1 + index:]
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/backup/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -929,7 +929,7 @@ def move_recovery_points(cmd, resource_group_name, vault_name, item_name, rp_nam
container_uri = cust_help.get_protection_container_uri_from_id(item_name.id)
item_uri = cust_help.get_protected_item_uri_from_id(item_name.id)

if source_tier not in common.tier_type_map.keys():
if source_tier not in common.tier_type_map:
raise InvalidArgumentValueError('This source tier-type is not accepted by move command at present.')

parameters = MoveRPAcrossTiersRequest(source_tier_type=common.tier_type_map[source_tier],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def move_wl_recovery_points(cmd, resource_group_name, vault_name, item_name, rp_
container_uri = cust_help.get_protection_container_uri_from_id(item_name.id)
item_uri = cust_help.get_protected_item_uri_from_id(item_name.id)

if source_tier not in common.tier_type_map.keys():
if source_tier not in common.tier_type_map:
raise InvalidArgumentValueError('This source tier-type is not accepted by move command at present.')

parameters = MoveRPAcrossTiersRequest(source_tier_type=common.tier_type_map[source_tier],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,9 +294,8 @@ def deserialize_json(self, kwargs, json_obj):
except DeserializationError as error:
message += f": {error}"
raise ValueError(message.format(self._request_param['model']))
else:
if kwargs[self._request_param['name']] is None:
raise ValueError(message.format(self._request_param['model']))
if kwargs[self._request_param['name']] is None:
raise ValueError(message.format(self._request_param['model']))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R1720: Unnecessary "else" after "raise", remove the "else" and de-indent the code inside it (no-else-raise)


def queue_argument(self, name=None, path=None, root=None,
options=None, type=None, # pylint: disable=redefined-builtin
Expand Down
46 changes: 22 additions & 24 deletions src/azure-cli/azure/cli/command_modules/batch/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,13 @@ def validate_options(namespace):
end = namespace.end_range
except AttributeError:
return
else:
namespace.ocp_range = None
del namespace.start_range
del namespace.end_range
if start or end:
start = start if start else 0
end = end if end else ""
namespace.ocp_range = f"bytes={start}-{end}"
namespace.ocp_range = None
del namespace.start_range
del namespace.end_range
if start or end:
start = start if start else 0
end = end if end else ""
namespace.ocp_range = f"bytes={start}-{end}"


def validate_file_destination(namespace):
Expand All @@ -225,22 +224,21 @@ def validate_file_destination(namespace):
path = namespace.destination
except AttributeError:
return
else:
# TODO: Need to confirm this logic...
file_path = path
file_dir = os.path.dirname(path)
if os.path.isdir(path):
file_name = os.path.basename(namespace.file_name)
file_path = os.path.join(path, file_name)
elif not os.path.isdir(file_dir):
try:
os.mkdir(file_dir)
except EnvironmentError as exp:
message = "Directory {} does not exist, and cannot be created: {}"
raise ValueError(message.format(file_dir, exp))
if os.path.isfile(file_path):
raise ValueError(f"File {file_path} already exists.")
namespace.destination = file_path
# TODO: Need to confirm this logic...
file_path = path
file_dir = os.path.dirname(path)
if os.path.isdir(path):
file_name = os.path.basename(namespace.file_name)
file_path = os.path.join(path, file_name)
elif not os.path.isdir(file_dir):
try:
os.mkdir(file_dir)
except EnvironmentError as exp:
message = "Directory {} does not exist, and cannot be created: {}"
raise ValueError(message.format(file_dir, exp))
if os.path.isfile(file_path):
raise ValueError(f"File {file_path} already exists.")
namespace.destination = file_path

# CUSTOM REQUEST VALIDATORS

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def _get_scale_settings(initial_count, min_count, max_count):
if not initial_count and not min_count and not max_count:
# Get from the config file
return None
if sum([1 if v is not None else 0 for v in (min_count, max_count)]) == 1:
if sum(1 if v is not None else 0 for v in (min_count, max_count)) == 1:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R1728: Consider using a generator instead 'sum(1 if v is not None else 0 for v in (min_count, max_count))' (consider-using-generator)

raise CLIError('You need to either provide both min and max node counts or not provide any of them')
if min_count is not None and max_count is not None and min_count > max_count:
raise CLIError('Maximum nodes count must be greater or equal to minimum nodes count')
Expand Down
3 changes: 1 addition & 2 deletions src/azure-cli/azure/cli/command_modules/dms/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,8 +318,7 @@ def get_file_or_parse_json(value, value_type):
except Exception as e:
raise CLIError("The supplied input for '{type}' is not a valid file path or a valid json object. {ex}'"
.format(type=value_type, ex=e))
else:
return json_parse
return json_parse


def create_connection(connection_info_json, prompt_prefix, typeOfInfo):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1416,7 +1416,7 @@ def download_key(client, file_path, hsm_name=None, identifier=None, # pylint: d
'PEM': _export_public_key_to_pem
}

if encoding not in methods.keys():
if encoding not in methods:
raise CLIError('Unsupported encoding: {}. (Supported encodings: DER, PEM)'.format(encoding))

try:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ def create_log_analytics_workspace_table(cmd, resource_group_name, workspace_nam
description=None, no_wait=False):
if retention_in_days and total_retention_in_days:
if total_retention_in_days < retention_in_days:
InvalidArgumentValueError('InvalidArgumentValueError: The specified value of --retention-time'
' should be less than --total-retention-time')
raise InvalidArgumentValueError('InvalidArgumentValueError: The specified value of --retention-time'
' should be less than --total-retention-time')
columns_list = None
if columns:
columns_list = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def _gen_metrics_alert_rules_clone_list(monitor_client, source_resource, target_

def _add_into_existing_scopes(monitor_client, alert_rule, target_resource):
alert_rule.scopes.append(target_resource)
resource_group_name, name = _parse_id(alert_rule.id).values()
resource_group_name, name = _parse_id(alert_rule.id).values() # pylint: disable=unbalanced-dict-unpacking
return monitor_client.metric_alerts.create_or_update(resource_group_name=resource_group_name,
rule_name=name,
parameters=alert_rule)
Expand All @@ -40,10 +40,10 @@ def _clone_and_replace_action_group(source_monitor_client, target_monitor_client
if action.action_group_id in action_group_mapping:
alert_rule.actions[index] = action_group_mapping[action.action_group_id][1]
else:
resource_group_name, name = _parse_id(action.action_group_id).values()
resource_group_name, name = _parse_id(action.action_group_id).values() # pylint: disable=unbalanced-dict-unpacking
action_group = source_monitor_client.action_groups.get(resource_group_name, name)
name = CLONED_NAME.format(name, gen_guid())
resource_group_name, _ = _parse_id(target_resource).values()
resource_group_name, _ = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking
new_action_group = target_monitor_client.action_groups.create_or_update(resource_group_name,
name,
action_group)
Expand All @@ -57,7 +57,7 @@ def _clone_and_replace_action_group(source_monitor_client, target_monitor_client

def _clone_alert_rule(monitor_client, alert_rule, target_resource):
alert_rule.scopes = [target_resource]
resource_group_name, name = _parse_id(target_resource).values()
resource_group_name, name = _parse_id(target_resource).values() # pylint: disable=unbalanced-dict-unpacking
name = CLONED_NAME.format(name, gen_guid())
return monitor_client.metric_alerts.create_or_update(resource_group_name=resource_group_name,
rule_name=name,
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/mysql/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ def replace_memory_optimized_tier(result):
for capability_idx, capability in enumerate(result):
for edition_idx, edition in enumerate(capability.supported_flexible_server_editions):
if edition.name == 'MemoryOptimized':
result[capability_idx].supported_flexible_server_editions[edition_idx].name = 'BusinessCritical'
capability.supported_flexible_server_editions[edition_idx].name = 'BusinessCritical'

return result

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ def replace_memory_optimized_tier(result):
for capability_idx, capability in enumerate(result):
for edition_idx, edition in enumerate(capability.supported_flexible_server_editions):
if edition.name == 'MemoryOptimized':
result[capability_idx].supported_flexible_server_editions[edition_idx].name = 'BusinessCritical'
capability.supported_flexible_server_editions[edition_idx].name = 'BusinessCritical'
Copy link
Contributor Author

@bebound bebound Jun 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R1736: Unnecessary list index lookup, use 'capability' instead (unnecessary-list-index-lookup)


return result

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def add_client_cert(cmd,
issuer_thumbprint = ','.join(issuer_thumbprint)
cluster.clients.append(ClientCertificate(is_admin=is_admin, common_name=common_name, issuer_thumbprint=issuer_thumbprint))
else:
CLIError("Thumbprint and Common name are empty")
raise CLIError("Thumbprint and Common name are empty")

poller = client.managed_clusters.begin_create_or_update(resource_group_name, cluster_name, cluster)
return LongRunningOperation(cmd.cli_ctx)(poller)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -496,7 +496,7 @@ def _find_role_id(cli_ctx):
# This in fact shoud not happen.
if len(app_role_id_map) < 3:
requird_role_defs = [USER_READ_ALL, APPLICATION_READ_ALL, GROUP_MEMBER_READ_ALL]
missing_role_defs = [role for role in requird_role_defs if role not in app_role_id_map.keys()]
missing_role_defs = [role for role in requird_role_defs if role not in app_role_id_map]
error_message = "Querying Microsoft Graph API failed to find the following roles: %s.", ", ".join(missing_role_defs)
logger.warning(error_message)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def list_tables(client, num_results=None, marker=None, show_next_marker=None):

def exists(client, table_name):
generator = client.query_tables("TableName eq '{}'".format(table_name))
return list(next(generator.by_page())) != []
return bool(list(next(generator.by_page())))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C1803: 'list(...) != []' can be simplified to 'list(...)' as an empty list is falsey (use-implicit-booleaness-not-comparison)



# pylint: disable=redefined-builtin
Expand Down