Skip to content

Commit 9196f45

Browse files
keetonianjlhood
authored andcommitted
chore: turn on flake 8 (aws#720)
1 parent 5a4947b commit 9196f45

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+228
-189
lines changed

.flake8

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[flake8]
22
max-line-length = 120
3-
ignore = E126
3+
ignore = E126 F821 W504 W605

Makefile

+6-2
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ init:
3939
$(info [*] Install requirements...)
4040
@pip install -r requirements/dev.txt -r requirements/base.txt
4141

42+
flake:
43+
$(info [*] Running flake8...)
44+
@flake8 samtranslator
45+
4246
test:
4347
$(info [*] Run the unit test with minimum code coverage of $(CODE_COVERAGE)%...)
4448
@pytest --cov samtranslator --cov-report term-missing --cov-fail-under $(CODE_COVERAGE) tests
@@ -49,7 +53,7 @@ build-docs:
4953
@$(MAKE) -C docs/website html
5054

5155
# Command to run everytime you make changes to verify everything works
52-
dev: test
56+
dev: flake test
5357

5458
# Verifications to run before sending a pull request
5559
pr: init dev
@@ -68,4 +72,4 @@ TARGETS
6872
build-docs Generate the documentation.
6973
pr Perform all checks before submitting a Pull Request.
7074

71-
endef
75+
endef

samtranslator/intrinsics/actions.py

+16-19
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from six import string_types
44

5+
56
class Action(object):
67
"""
78
Base class for intrinsic function actions. Each intrinsic function must subclass this,
@@ -45,14 +46,15 @@ def can_handle(self, input_dict):
4546
"""
4647

4748
return input_dict is not None \
48-
and isinstance(input_dict, dict) \
49-
and len(input_dict) == 1 \
50-
and self.intrinsic_name in input_dict
49+
and isinstance(input_dict, dict) \
50+
and len(input_dict) == 1 \
51+
and self.intrinsic_name in input_dict
5152

5253
@classmethod
5354
def _parse_resource_reference(cls, ref_value):
5455
"""
55-
Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property" separately.
56+
Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property"
57+
separately.
5658
5759
:param string ref_value: Input reference value which *may* contain the structure "LogicalId.Property"
5860
:return string, string: Returns two values - logical_id, property. If the input does not contain the structure,
@@ -162,6 +164,7 @@ def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
162164
self.intrinsic_name: resolved_value
163165
}
164166

167+
165168
class SubAction(Action):
166169
intrinsic_name = "Fn::Sub"
167170

@@ -189,7 +192,6 @@ def do_replacement(full_ref, prop_name):
189192

190193
return self._handle_sub_action(input_dict, do_replacement)
191194

192-
193195
def resolve_resource_refs(self, input_dict, supported_resource_refs):
194196
"""
195197
Resolves reference to some property of a resource. Inside string to be substituted, there could be either a
@@ -249,7 +251,6 @@ def do_replacement(full_ref, ref_value):
249251

250252
return self._handle_sub_action(input_dict, do_replacement)
251253

252-
253254
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
254255
"""
255256
Resolves reference to some property of a resource. Inside string to be substituted, there could be either a
@@ -306,14 +307,13 @@ def do_replacement(full_ref, ref_value):
306307

307308
return self._handle_sub_action(input_dict, do_replacement)
308309

309-
310310
def _handle_sub_action(self, input_dict, handler):
311311
"""
312312
Handles resolving replacements in the Sub action based on the handler that is passed as an input.
313313
314314
:param input_dict: Dictionary to be resolved
315-
:param supported_values: One of several different objects that contain the supported values that need to be changed.
316-
See each method above for specifics on these objects.
315+
:param supported_values: One of several different objects that contain the supported values that
316+
need to be changed. See each method above for specifics on these objects.
317317
:param handler: handler that is specific to each implementation.
318318
:return: Resolved value of the Sub dictionary
319319
"""
@@ -327,7 +327,6 @@ def _handle_sub_action(self, input_dict, handler):
327327

328328
return input_dict
329329

330-
331330
def _handle_sub_value(self, sub_value, handler_method):
332331
"""
333332
Generic method to handle value to Fn::Sub key. We are interested in parsing the ${} syntaxes inside
@@ -365,15 +364,15 @@ def handler_method(full_ref, ref_value):
365364
366365
:param string text: Input text
367366
:param handler_method: Method to be called to handle each occurrence of ${blah} reference structure.
368-
First parameter to this method is the full reference structure Ex: ${LogicalId.Property}. Second parameter is just the
369-
value of the reference such as "LogicalId.Property"
367+
First parameter to this method is the full reference structure Ex: ${LogicalId.Property}.
368+
Second parameter is just the value of the reference such as "LogicalId.Property"
370369
371370
:return string: Text with all reference structures replaced as necessary
372371
"""
373372

374373
# RegExp to find pattern "${logicalId.property}" and return the word inside bracket
375374
logical_id_regex = '[A-Za-z0-9\.]+'
376-
ref_pattern = re.compile(r'\$\{('+logical_id_regex+')\}')
375+
ref_pattern = re.compile(r'\$\{(' + logical_id_regex + ')\}')
377376

378377
# Find all the pattern, and call the handler to decide how to substitute them.
379378
# Do the substitution and return the final text
@@ -383,14 +382,14 @@ def handler_method(full_ref, ref_value):
383382
lambda match: handler_method(match.group(0), match.group(1)),
384383
text)
385384

385+
386386
class GetAttAction(Action):
387387
intrinsic_name = "Fn::GetAtt"
388388

389389
def resolve_parameter_refs(self, input_dict, parameters):
390390
# Parameters can never be referenced within GetAtt value
391391
return input_dict
392392

393-
394393
def resolve_resource_refs(self, input_dict, supported_resource_refs):
395394
"""
396395
Resolve resource references within a GetAtt dict.
@@ -441,12 +440,11 @@ def resolve_resource_refs(self, input_dict, supported_resource_refs):
441440
splits = value_str.split(self._resource_ref_separator)
442441
logical_id = splits[0]
443442
property = splits[1]
444-
remaining = splits[2:] # if any
443+
remaining = splits[2:] # if any
445444

446445
resolved_value = supported_resource_refs.get(logical_id, property)
447446
return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
448447

449-
450448
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
451449
"""
452450
Resolve resource references within a GetAtt dict.
@@ -485,12 +483,11 @@ def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
485483
value_str = self._resource_ref_separator.join(value)
486484
splits = value_str.split(self._resource_ref_separator)
487485
logical_id = splits[0]
488-
remaining = splits[1:] # if any
486+
remaining = splits[1:] # if any
489487

490488
resolved_value = supported_resource_id_refs.get(logical_id)
491489
return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
492490

493-
494491
def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining):
495492
"""
496493
Resolves the function and returns the updated dictionary
@@ -505,4 +502,4 @@ def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining):
505502
# This is the new value of Fn::GetAtt
506503
input_dict[key] = [resolved_value] + remaining
507504

508-
return input_dict
505+
return input_dict

samtranslator/intrinsics/resolver.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,17 @@
33
from samtranslator.intrinsics.actions import Action, SubAction, RefAction, GetAttAction
44

55
# All intrinsics are supported by default
6-
DEFAULT_SUPPORTED_INTRINSICS = {action.intrinsic_name:action() for action in [RefAction, SubAction, GetAttAction]}
6+
DEFAULT_SUPPORTED_INTRINSICS = {action.intrinsic_name: action() for action in [RefAction, SubAction, GetAttAction]}
7+
78

89
class IntrinsicsResolver(object):
910

1011
def __init__(self, parameters, supported_intrinsics=DEFAULT_SUPPORTED_INTRINSICS):
1112
"""
1213
Instantiate the resolver
1314
:param dict parameters: Map of parameter names to their values
14-
:param dict supported_intrinsics: Dictionary of intrinsic functions this class supports along with the Action class that
15-
can process this intrinsic
15+
:param dict supported_intrinsics: Dictionary of intrinsic functions this class supports along with the
16+
Action class that can process this intrinsic
1617
:raises TypeError: If parameters or the supported_intrinsics arguments are invalid
1718
"""
1819

@@ -26,7 +27,6 @@ def __init__(self, parameters, supported_intrinsics=DEFAULT_SUPPORTED_INTRINSICS
2627
self.supported_intrinsics = supported_intrinsics
2728
self.parameters = parameters
2829

29-
3030
def resolve_parameter_refs(self, input):
3131
"""
3232
Resolves references to parameters within the given dictionary recursively. Other intrinsic functions such as
@@ -218,5 +218,5 @@ def _is_intrinsic_dict(self, input):
218218
"""
219219
# All intrinsic functions are dictionaries with just one key
220220
return isinstance(input, dict) \
221-
and len(input) == 1 \
222-
and list(input.keys())[0] in self.supported_intrinsics
221+
and len(input) == 1 \
222+
and list(input.keys())[0] in self.supported_intrinsics

samtranslator/model/__init__.py

+19-15
Original file line numberDiff line numberDiff line change
@@ -307,16 +307,17 @@ def get_runtime_attr(self, attr_name):
307307

308308
def get_passthrough_resource_attributes(self):
309309
"""
310-
Returns a dictionary of resource attributes of the ResourceMacro that should be passed through from the main
310+
Returns a dictionary of resource attributes of the ResourceMacro that should be passed through from the main
311311
vanilla CloudFormation resource to its children. Currently only Condition is copied.
312312
313313
:return: Dictionary of resource attributes.
314-
"""
314+
"""
315315
attributes = None
316316
if 'Condition' in self.resource_attributes:
317-
attributes = { 'Condition': self.resource_attributes['Condition'] }
317+
attributes = {'Condition': self.resource_attributes['Condition']}
318318
return attributes
319-
319+
320+
320321
class ResourceMacro(Resource):
321322
"""A ResourceMacro object represents a CloudFormation macro. A macro appears in the CloudFormation template in the
322323
"Resources" mapping, but must be expanded into one or more vanilla CloudFormation resources before a stack can be
@@ -346,6 +347,7 @@ def to_cloudformation(self, **kwargs):
346347
"""
347348
raise NotImplementedError("Method to_cloudformation() must be implemented in a subclass of ResourceMacro")
348349

350+
349351
class SamResourceMacro(ResourceMacro):
350352
"""ResourceMacro that specifically refers to SAM (AWS::Serverless::*) resources.
351353
"""
@@ -384,17 +386,18 @@ def get_resource_references(self, generated_cfn_resources, supported_resource_re
384386
by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it
385387
supports and the type of CFN resource this property resolves to.
386388
387-
:param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this SAM resource
388-
:param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object holding
389-
the mapping between property names and LogicalId of the generated CFN resource it maps to
389+
:param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this
390+
SAM resource
391+
:param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object
392+
holding the mapping between property names and LogicalId of the generated CFN resource it maps to
390393
:return: Updated supported_resource_refs
391394
"""
392395

393396
if supported_resource_refs is None:
394397
raise ValueError("`supported_resource_refs` object is required")
395398

396399
# Create a map of {ResourceType: LogicalId} for quick access
397-
resource_id_by_type = {resource.resource_type:resource.logical_id for resource in generated_cfn_resources}
400+
resource_id_by_type = {resource.resource_type: resource.logical_id for resource in generated_cfn_resources}
398401

399402
for property, cfn_type in self.referable_properties.items():
400403
if cfn_type in resource_id_by_type:
@@ -406,7 +409,7 @@ def _construct_tag_list(self, tags, additional_tags=None):
406409
if not bool(tags):
407410
tags = {}
408411

409-
if additional_tags == None:
412+
if additional_tags is None:
410413
additional_tags = {}
411414

412415
for tag in self._RESERVED_TAGS:
@@ -424,7 +427,8 @@ def _check_tag(self, reserved_tag_name, tags):
424427
if reserved_tag_name in tags:
425428
raise InvalidResourceException(self.logical_id, reserved_tag_name + " is a reserved Tag key name and "
426429
"cannot be set on your resource. "
427-
"Please change the tag key in the input.")
430+
"Please change the tag key in the "
431+
"input.")
428432

429433
def _resolve_string_parameter(self, intrinsics_resolver, parameter_value, parameter_name):
430434
if not parameter_value:
@@ -450,9 +454,9 @@ def __init__(self, *modules):
450454
for module in modules:
451455
# Get all classes in the specified module which have a class variable resource_type.
452456
for _, resource_class in inspect.getmembers(module,
453-
lambda cls: inspect.isclass(cls)
454-
and cls.__module__ == module.__name__
455-
and hasattr(cls, 'resource_type')):
457+
lambda cls: inspect.isclass(cls) and
458+
cls.__module__ == module.__name__ and
459+
hasattr(cls, 'resource_type')):
456460
self.resource_types[resource_class.resource_type] = resource_class
457461

458462
def can_resolve(self, resource_dict):
@@ -469,8 +473,8 @@ def resolve_resource_type(self, resource_dict):
469473
:rtype: class
470474
"""
471475
if not self.can_resolve(resource_dict):
472-
raise TypeError("Resource dict has missing or invalid value for key Type. Resource Dict is: "
473-
+ str(resource_dict))
476+
raise TypeError("Resource dict has missing or invalid value for key Type. Resource Dict is: " +
477+
str(resource_dict))
474478
if resource_dict['Type'] not in self.resource_types:
475479
raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type']))
476480
return self.resource_types[resource_dict['Type']]

samtranslator/model/api/api_generator.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
from samtranslator.translator.arn_generator import ArnGenerator
1414

1515
_CORS_WILDCARD = "'*'"
16-
CorsProperties = namedtuple("_CorsProperties", ["AllowMethods", "AllowHeaders", "AllowOrigin", "MaxAge", "AllowCredentials"])
16+
CorsProperties = namedtuple("_CorsProperties", ["AllowMethods", "AllowHeaders", "AllowOrigin", "MaxAge",
17+
"AllowCredentials"])
1718
# Default the Cors Properties to '*' wildcard and False AllowCredentials. Other properties are actually Optional
1819
CorsProperties.__new__.__defaults__ = (None, None, _CORS_WILDCARD, None, False)
1920

@@ -23,7 +24,10 @@
2324

2425
class ApiGenerator(object):
2526

26-
def __init__(self, logical_id, cache_cluster_enabled, cache_cluster_size, variables, depends_on, definition_body, definition_uri, name, stage_name, endpoint_configuration=None, method_settings=None, binary_media=None, cors=None, auth=None, access_log_setting=None, canary_setting=None, tracing_enabled=None):
27+
def __init__(self, logical_id, cache_cluster_enabled, cache_cluster_size, variables, depends_on,
28+
definition_body, definition_uri, name, stage_name, endpoint_configuration=None,
29+
method_settings=None, binary_media=None, cors=None, auth=None, access_log_setting=None,
30+
canary_setting=None, tracing_enabled=None):
2731
"""Constructs an API Generator class that generates API Gateway resources
2832
2933
:param logical_id: Logical id of the SAM API Resource
@@ -224,7 +228,7 @@ def _add_cors(self):
224228

225229
editor = SwaggerEditor(self.definition_body)
226230
for path in editor.iter_on_path():
227-
editor.add_cors(path, properties.AllowOrigin, properties.AllowHeaders, properties.AllowMethods,
231+
editor.add_cors(path, properties.AllowOrigin, properties.AllowHeaders, properties.AllowMethods,
228232
max_age=properties.MaxAge, allow_credentials=properties.AllowCredentials)
229233

230234
# Assign the Swagger back to template

samtranslator/model/apigateway.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -187,15 +187,18 @@ def _get_identity_source(self):
187187
identity_source_headers = list(map(lambda h: 'method.request.header.' + h, self.identity.get('Headers')))
188188

189189
if self.identity.get('QueryStrings'):
190-
identity_source_query_strings = list(map(lambda qs: 'method.request.querystring.' + qs, self.identity.get('QueryStrings')))
190+
identity_source_query_strings = list(map(lambda qs: 'method.request.querystring.' + qs,
191+
self.identity.get('QueryStrings')))
191192

192193
if self.identity.get('StageVariables'):
193-
identity_source_stage_variables = list(map(lambda sv: 'stageVariables.' + sv, self.identity.get('StageVariables')))
194+
identity_source_stage_variables = list(map(lambda sv: 'stageVariables.' + sv,
195+
self.identity.get('StageVariables')))
194196

195197
if self.identity.get('Context'):
196198
identity_source_context = list(map(lambda c: 'context.' + c, self.identity.get('Context')))
197199

198-
identity_source_array = identity_source_headers + identity_source_query_strings + identity_source_stage_variables + identity_source_context
200+
identity_source_array = (identity_source_headers + identity_source_query_strings +
201+
identity_source_stage_variables + identity_source_context)
199202
identity_source = ', '.join(identity_source_array)
200203

201204
return identity_source

samtranslator/model/cloudformation.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from samtranslator.model import PropertyType, Resource
2-
from samtranslator.model.types import is_type, one_of, is_str, list_of, any_type
3-
from samtranslator.model.intrinsics import fnGetAtt, ref
2+
from samtranslator.model.types import is_type, is_str, list_of
3+
from samtranslator.model.intrinsics import ref
44

55

66
class NestedStack(Resource):
@@ -16,4 +16,4 @@ class NestedStack(Resource):
1616

1717
runtime_attrs = {
1818
"stack_id": lambda self: ref(self.logical_id)
19-
}
19+
}

0 commit comments

Comments
 (0)