Skip to content

Commit ba4ac42

Browse files
jfusskeetonian
authored andcommitted
chore: Adopt black formatting (#1322)
1 parent 34ac03e commit ba4ac42

File tree

113 files changed

+4860
-6826
lines changed

Some content is hidden

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

113 files changed

+4860
-6826
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
repos:
2+
- repo: https://github.com/python/black
3+
rev: 19.3b0
4+
hooks:
5+
- id: black
6+
language_version: python3.7
7+
exclude_types: ['markdown', 'ini', 'toml', 'rst']

.travis.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ matrix:
2121

2222
install:
2323
# Install the code requirements
24+
- mkdir $HOME/bin-black
25+
- wget -O $HOME/bin-black/black https://github.com/python/black/releases/download/19.3b0/black
26+
- chmod +x $HOME/bin-black/black
27+
- export PATH=$PATH:$HOME/bin-black
28+
- black --version
29+
2430
- make init
2531

2632
# Install Docs requirements

DEVELOPMENT_GUIDE.rst

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,23 @@ Setup Python locally using `pyenv`_
2626
#. ``pyenv install 2.7.14``
2727
#. Make the Python version available in the project: ``pyenv local 2.7.14``
2828

29+
2. Install Additional Tooling
30+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
31+
1. Black
32+
~~~~~~~~
33+
We format our code using [Black](https://github.com/python/black) and verify the source code is black compliant
34+
in Appveyor during PRs. You can find installation instructions on [Black's docs](https://black.readthedocs.io/en/stable/installation_and_usage.html).
2935

30-
2. Activate Virtualenv
36+
After installing, you can run our formatting through our Makefile by `make black-format` or integrating Black directly in your favorite IDE (instructions
37+
can be found [here](https://black.readthedocs.io/en/stable/editor_integration.html))
38+
39+
Pre-commit
40+
~~~~~~~~~~
41+
If you don't wish to manually run black on each pr or install black manually, we have integrated black into git hooks through [pre-commit](https://pre-commit.com/).
42+
After installing pre-commit, run `pre-commit install` in the root of the project. This will install black for you and run the black formatting on
43+
commit.
44+
45+
3. Activate Virtualenv
3146
~~~~~~~~~~~~~~~~~~~~~~
3247
Virtualenv allows you to install required libraries outside of the Python installation. A good practice is to setup
3348
a different virtualenv for each project. `pyenv`_ comes with a handy plugin that can create virtualenv.
@@ -37,7 +52,7 @@ a different virtualenv for each project. `pyenv`_ comes with a handy plugin that
3752
#. [Optional] Automatically activate the virtualenv in for this folder: ``pyenv local samtranslator27``
3853

3954

40-
3. Install dependencies
55+
4. Install dependencies
4156
~~~~~~~~~~~~~~~~~~~~~~~
4257
Install dependencies by running the following command. Make sure the Virtualenv you created above is active.
4358

Makefile

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,21 @@ 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-
4642
test:
4743
$(info [*] Run the unit test with minimum code coverage of $(CODE_COVERAGE)%...)
4844
@pytest --cov samtranslator --cov-report term-missing --cov-fail-under $(CODE_COVERAGE) tests
4945

46+
black:
47+
black setup.py samtranslator/* tests/* bin/*
48+
49+
black-check:
50+
black --check setup.py samtranslator/* tests/* bin/*
51+
5052
# Command to run everytime you make changes to verify everything works
51-
dev: flake test
53+
dev: test
5254

5355
# Verifications to run before sending a pull request
54-
pr: init dev
56+
pr: black-check init dev
5557

5658
define HELP_MESSAGE
5759

@@ -64,7 +66,6 @@ TARGETS
6466
init Initialize and install the requirements and dev-requirements for this project.
6567
test Run the Unit tests.
6668
dev Run all development tests after a change.
67-
build-docs Generate the documentation.
6869
pr Perform all checks before submitting a Pull Request.
6970

7071
endef

bin/sam-translate.py

Lines changed: 28 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from docopt import docopt
3030

3131
my_path = os.path.dirname(os.path.abspath(__file__))
32-
sys.path.insert(0, my_path + '/..')
32+
sys.path.insert(0, my_path + "/..")
3333

3434
from samtranslator.public.translator import ManagedPolicyLoader
3535
from samtranslator.translator.transform import transform
@@ -38,18 +38,19 @@
3838

3939
LOG = logging.getLogger(__name__)
4040
cli_options = docopt(__doc__)
41-
iam_client = boto3.client('iam')
41+
iam_client = boto3.client("iam")
4242
cwd = os.getcwd()
4343

44-
if cli_options.get('--verbose'):
44+
if cli_options.get("--verbose"):
4545
logging.basicConfig(level=logging.DEBUG)
4646
else:
4747
logging.basicConfig()
4848

49+
4950
def execute_command(command, args):
5051
try:
51-
aws_cmd = 'aws' if platform.system().lower() != 'windows' else 'aws.cmd'
52-
command_with_args = [aws_cmd, 'cloudformation', command] + list(args)
52+
aws_cmd = "aws" if platform.system().lower() != "windows" else "aws.cmd"
53+
command_with_args = [aws_cmd, "cloudformation", command] + list(args)
5354

5455
LOG.debug("Executing command: %s", command_with_args)
5556

@@ -63,8 +64,8 @@ def execute_command(command, args):
6364

6465

6566
def get_input_output_file_paths():
66-
input_file_option = cli_options.get('--template-file')
67-
output_file_option = cli_options.get('--output-template')
67+
input_file_option = cli_options.get("--template-file")
68+
output_file_option = cli_options.get("--output-template")
6869
input_file_path = os.path.join(cwd, input_file_option)
6970
output_file_path = os.path.join(cwd, output_file_option)
7071

@@ -73,67 +74,58 @@ def get_input_output_file_paths():
7374

7475
def package(input_file_path, output_file_path):
7576
template_file = input_file_path
76-
package_output_template_file = input_file_path + '._sam_packaged_.yaml'
77-
s3_bucket = cli_options.get('--s3-bucket')
77+
package_output_template_file = input_file_path + "._sam_packaged_.yaml"
78+
s3_bucket = cli_options.get("--s3-bucket")
7879
args = [
79-
'--template-file',
80+
"--template-file",
8081
template_file,
81-
'--output-template-file',
82+
"--output-template-file",
8283
package_output_template_file,
83-
'--s3-bucket',
84-
s3_bucket
84+
"--s3-bucket",
85+
s3_bucket,
8586
]
8687

87-
execute_command('package', args)
88+
execute_command("package", args)
8889

8990
return package_output_template_file
9091

9192

9293
def transform_template(input_file_path, output_file_path):
93-
with open(input_file_path, 'r') as f:
94+
with open(input_file_path, "r") as f:
9495
sam_template = yaml_parse(f)
9596

9697
try:
97-
cloud_formation_template = transform(
98-
sam_template, {}, ManagedPolicyLoader(iam_client))
99-
cloud_formation_template_prettified = json.dumps(
100-
cloud_formation_template, indent=2)
98+
cloud_formation_template = transform(sam_template, {}, ManagedPolicyLoader(iam_client))
99+
cloud_formation_template_prettified = json.dumps(cloud_formation_template, indent=2)
101100

102-
with open(output_file_path, 'w') as f:
101+
with open(output_file_path, "w") as f:
103102
f.write(cloud_formation_template_prettified)
104103

105-
print('Wrote transformed CloudFormation template to: ' + output_file_path)
104+
print ("Wrote transformed CloudFormation template to: " + output_file_path)
106105
except InvalidDocumentException as e:
107-
errorMessage = reduce(lambda message, error: message + ' ' + error.message, e.causes, e.message)
106+
errorMessage = reduce(lambda message, error: message + " " + error.message, e.causes, e.message)
108107
LOG.error(errorMessage)
109108
errors = map(lambda cause: cause.message, e.causes)
110109
LOG.error(errors)
111110

112111

113112
def deploy(template_file):
114-
capabilities = cli_options.get('--capabilities')
115-
stack_name = cli_options.get('--stack-name')
116-
args = [
117-
'--template-file',
118-
template_file,
119-
'--capabilities',
120-
capabilities,
121-
'--stack-name',
122-
stack_name
123-
]
113+
capabilities = cli_options.get("--capabilities")
114+
stack_name = cli_options.get("--stack-name")
115+
args = ["--template-file", template_file, "--capabilities", capabilities, "--stack-name", stack_name]
124116

125-
execute_command('deploy', args)
117+
execute_command("deploy", args)
126118

127119
return package_output_template_file
128120

129121

130-
if __name__ == '__main__':
122+
if __name__ == "__main__":
131123
input_file_path, output_file_path = get_input_output_file_paths()
132124

133-
if cli_options.get('package'):
125+
if cli_options.get("package"):
134126
package_output_template_file = package(input_file_path, output_file_path)
135127
transform_template(package_output_template_file, output_file_path)
136-
elif cli_options.get('deploy'):
128+
elif cli_options.get("deploy"):
137129
package_output_template_file = package(input_file_path, output_file_path)
138130
transform_template(package_output_template_file, output_file_path)
139131
deploy(output_file_path)

pyproject.toml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[tool.black]
2+
line-length = 120
3+
target_version = ['py27', 'py37', 'py36', 'py38']
4+
exclude = '''
5+
6+
(
7+
/(
8+
\.eggs # exclude a few common directories in the
9+
| \.git # root of the project
10+
| \.tox
11+
| \.venv
12+
| build
13+
| dist
14+
| pip-wheel-metadata
15+
| examples
16+
)/
17+
)
18+
'''

samtranslator/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '1.20.0'
1+
__version__ = "1.20.0"

samtranslator/intrinsics/actions.py

Lines changed: 40 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,12 @@ def can_handle(self, input_dict):
4646
:return: True if it matches expected structure, False otherwise
4747
"""
4848

49-
return input_dict is not None \
50-
and isinstance(input_dict, dict) \
51-
and len(input_dict) == 1 \
49+
return (
50+
input_dict is not None
51+
and isinstance(input_dict, dict)
52+
and len(input_dict) == 1
5253
and self.intrinsic_name in input_dict
54+
)
5355

5456
@classmethod
5557
def _parse_resource_reference(cls, ref_value):
@@ -132,9 +134,7 @@ def resolve_resource_refs(self, input_dict, supported_resource_refs):
132134
if not resolved_value:
133135
return input_dict
134136

135-
return {
136-
self.intrinsic_name: resolved_value
137-
}
137+
return {self.intrinsic_name: resolved_value}
138138

139139
def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
140140
"""
@@ -161,9 +161,7 @@ def resolve_resource_id_refs(self, input_dict, supported_resource_id_refs):
161161
if not resolved_value:
162162
return input_dict
163163

164-
return {
165-
self.intrinsic_name: resolved_value
166-
}
164+
return {self.intrinsic_name: resolved_value}
167165

168166

169167
class SubAction(Action):
@@ -372,16 +370,18 @@ def handler_method(full_ref, ref_value):
372370
"""
373371

374372
# RegExp to find pattern "${logicalId.property}" and return the word inside bracket
375-
logical_id_regex = '[A-Za-z0-9\.]+|AWS::[A-Z][A-Za-z]*'
376-
ref_pattern = re.compile(r'\$\{(' + logical_id_regex + ')\}')
373+
logical_id_regex = "[A-Za-z0-9\.]+|AWS::[A-Z][A-Za-z]*"
374+
ref_pattern = re.compile(r"\$\{(" + logical_id_regex + ")\}")
377375

378376
# Find all the pattern, and call the handler to decide how to substitute them.
379377
# Do the substitution and return the final text
380-
return re.sub(ref_pattern,
381-
# Pass the handler entire string ${logicalId.property} as first parameter and "logicalId.property"
382-
# as second parameter. Return value will be substituted
383-
lambda match: handler_method(match.group(0), match.group(1)),
384-
text)
378+
return re.sub(
379+
ref_pattern,
380+
# Pass the handler entire string ${logicalId.property} as first parameter and "logicalId.property"
381+
# as second parameter. Return value will be substituted
382+
lambda match: handler_method(match.group(0), match.group(1)),
383+
text,
384+
)
385385

386386

387387
class GetAttAction(Action):
@@ -427,10 +427,14 @@ def resolve_resource_refs(self, input_dict, supported_resource_refs):
427427
if not isinstance(value, list) or len(value) < 2:
428428
return input_dict
429429

430-
if (not all(isinstance(entry, string_types) for entry in value)):
430+
if not all(isinstance(entry, string_types) for entry in value):
431431
raise InvalidDocumentException(
432-
[InvalidTemplateException('Invalid GetAtt value {}. GetAtt expects an array with 2 strings.'
433-
.format(value))])
432+
[
433+
InvalidTemplateException(
434+
"Invalid GetAtt value {}. GetAtt expects an array with 2 strings.".format(value)
435+
)
436+
]
437+
)
434438

435439
# Value of GetAtt is an array. It can contain any number of elements, with first being the LogicalId of
436440
# resource and rest being the attributes. In a SAM template, a reference to a resource can be used in the
@@ -515,6 +519,7 @@ class FindInMapAction(Action):
515519
"""
516520
This action can't be used along with other actions.
517521
"""
522+
518523
intrinsic_name = "Fn::FindInMap"
519524

520525
def resolve_parameter_refs(self, input_dict, parameters):
@@ -535,21 +540,29 @@ def resolve_parameter_refs(self, input_dict, parameters):
535540
# FindInMap expects an array with 3 values
536541
if not isinstance(value, list) or len(value) != 3:
537542
raise InvalidDocumentException(
538-
[InvalidTemplateException('Invalid FindInMap value {}. FindInMap expects an array with 3 values.'
539-
.format(value))])
543+
[
544+
InvalidTemplateException(
545+
"Invalid FindInMap value {}. FindInMap expects an array with 3 values.".format(value)
546+
)
547+
]
548+
)
540549

541550
map_name = self.resolve_parameter_refs(value[0], parameters)
542551
top_level_key = self.resolve_parameter_refs(value[1], parameters)
543552
second_level_key = self.resolve_parameter_refs(value[2], parameters)
544553

545-
if not isinstance(map_name, string_types) or \
546-
not isinstance(top_level_key, string_types) or \
547-
not isinstance(second_level_key, string_types):
554+
if (
555+
not isinstance(map_name, string_types)
556+
or not isinstance(top_level_key, string_types)
557+
or not isinstance(second_level_key, string_types)
558+
):
548559
return input_dict
549560

550-
if map_name not in parameters or \
551-
top_level_key not in parameters[map_name] or \
552-
second_level_key not in parameters[map_name][top_level_key]:
561+
if (
562+
map_name not in parameters
563+
or top_level_key not in parameters[map_name]
564+
or second_level_key not in parameters[map_name][top_level_key]
565+
):
553566
return input_dict
554567

555568
return parameters[map_name][top_level_key][second_level_key]

0 commit comments

Comments
 (0)