Use pre-commit to run pep8 checks

Change-Id: Icfbdee104baa60f1507ce61f06797d0adb3e947d
Signed-off-by: Takashi Kajinami <kajinamit@oss.nttdata.com>
This commit is contained in:
Takashi Kajinami
2025-10-03 00:12:54 +09:00
parent 7ffb5dd3c2
commit ea0bfd8e20
8 changed files with 61 additions and 73 deletions

View File

@@ -1,29 +1,31 @@
--- ---
default_language_version:
# force all unspecified python hooks to run python3
python: python3
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0 rev: v6.0.0
hooks: hooks:
- id: trailing-whitespace - id: trailing-whitespace
# Replaces or checks mixed line ending
- id: mixed-line-ending - id: mixed-line-ending
args: ['--fix', 'lf'] args: ['--fix', 'lf']
exclude: '.*\.(svg)$' exclude: '.*\.(svg)$'
- id: check-byte-order-marker - id: fix-byte-order-marker
- id: check-executables-have-shebangs - id: check-executables-have-shebangs
- id: check-merge-conflict - id: check-merge-conflict
- id: debug-statements - id: debug-statements
- id: check-yaml - id: check-yaml
files: .*\.(yaml|yml)$ files: .*\.(yaml|yml)$
exclude: 'rally-scenarios/heat-fakevirt.yaml' exclude: 'rally-scenarios/heat-fakevirt.yaml'
- repo: local - repo: https://opendev.org/openstack/hacking
rev: 6.1.0
hooks: hooks:
- id: flake8 - id: hacking
name: flake8 additional_dependencies: []
additional_dependencies: - repo: https://github.com/PyCQA/bandit
- hacking>=6.1.0,<6.2.0 rev: 1.8.6
language: python hooks:
entry: flake8 - id: bandit
files: '^.*\.py$' args: ['-c', 'pyproject.toml']
exclude: '^(doc|releasenotes|tools)/.*$' - repo: https://github.com/PyCQA/doc8
rev: v1.1.2
hooks:
- id: doc8

View File

@@ -65,7 +65,8 @@ logging.set_defaults(
logging_context_format_string="%(levelname)s (%(module)s:" logging_context_format_string="%(levelname)s (%(module)s:"
"%(lineno)d) %(message)s", "%(lineno)d) %(message)s",
default_log_levels=(logging.get_default_log_levels() + default_log_levels=(logging.get_default_log_levels() +
extra_log_level_defaults)) extra_log_level_defaults)
)
logging.setup(cfg.CONF, 'heat-keystone-setup-domain', logging.setup(cfg.CONF, 'heat-keystone-setup-domain',
version.version_info.version_string()) version.version_info.version_string())
@@ -102,7 +103,6 @@ def main():
'project_domain_name': PROJECT_DOMAIN_NAME 'project_domain_name': PROJECT_DOMAIN_NAME
} }
if insecure: if insecure:
client_kwargs['verify'] = False client_kwargs['verify'] = False
else: else:

View File

@@ -1,3 +1,18 @@
[build-system] [build-system]
requires = ["pbr>=6.0.0", "setuptools>=64.0.0"] requires = ["pbr>=6.0.0", "setuptools>=64.0.0"]
build-backend = "pbr.build" build-backend = "pbr.build"
[tool.bandit]
# B101: Test for use of assert
# B104: Test for binding to all interfaces
# B107: Test for use of hard-coded password argument defaults
# B110: Try, Except, Pass detected.
# B310: Audit url open for permitted schemes
# B311: Standard pseudo-random generators are not suitable for security/cryptographic purposes
# B404: Import of subprocess module
# B504: Test for SSL use with no version specified
# B506: Test for use of yaml load
# B603: Test for use of subprocess with shell equals true
# B607: Test for starting a process with a partial path
skips = ['B101', 'B104', 'B107', 'B110', 'B310', 'B311', 'B404', 'B504', 'B506', 'B603', 'B607']
exclude_dirs = ['tests']

View File

@@ -1,7 +1,6 @@
# Hacking already pins down pep8, pyflakes and flake8 # Hacking already pins down pep8, pyflakes and flake8
hacking>=6.1.0,<6.2.0 # Apache-2.0 hacking>=6.1.0,<6.2.0 # Apache-2.0
bandit>=1.8.1 # Apache-2.0
coverage>=4.0 # Apache-2.0 coverage>=4.0 # Apache-2.0
ddt>=1.4.1 # MIT ddt>=1.4.1 # MIT
fixtures>=3.0.0 # Apache-2.0/BSD fixtures>=3.0.0 # Apache-2.0/BSD
@@ -12,7 +11,6 @@ stestr>=2.0.0 # Apache-2.0
testscenarios>=0.4 # Apache-2.0/BSD testscenarios>=0.4 # Apache-2.0/BSD
testtools>=2.2.0 # MIT testtools>=2.2.0 # MIT
testresources>=2.0.0 # Apache-2.0/BSD testresources>=2.0.0 # Apache-2.0/BSD
doc8>=0.8.1 # Apache-2.0
Pygments>=2.2.0 # BSD license Pygments>=2.2.0 # BSD license
# Next are used in integration tests only # Next are used in integration tests only
tempest>=17.1.0 # Apache-2.0 tempest>=17.1.0 # Apache-2.0

View File

@@ -12,13 +12,13 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import sys
import os import os
import yaml
import json
import re import re
import sys
from heat.common import template_format from heat.common import template_format
def main(): def main():
path = sys.argv[1] path = sys.argv[1]
if os.path.isdir(path): if os.path.isdir(path):
@@ -28,15 +28,17 @@ def main():
else: else:
print('File or directory not valid: %s' % path) print('File or directory not valid: %s' % path)
def convert_file(path): def convert_file(path):
f = open(path, 'r') f = open(path, 'r')
print(template_format.convert_json_to_yaml(f.read())) print(template_format.convert_json_to_yaml(f.read()))
def convert_directory(dirpath): def convert_directory(dirpath):
for path in os.listdir(dirpath): for path in os.listdir(dirpath):
if not path.endswith('.template') and not path.endswith('.json'): if not path.endswith('.template') and not path.endswith('.json'):
continue continue
yamlpath = re.sub('\..*$', '.yaml', path) yamlpath = re.sub(r'\..*$', '.yaml', path)
print('Writing to %s' % yamlpath) print('Writing to %s' % yamlpath)
f = open(os.path.join(dirpath, path), 'r') f = open(os.path.join(dirpath, path), 'r')
out = open(os.path.join(dirpath, yamlpath), 'w') out = open(os.path.join(dirpath, yamlpath), 'w')
@@ -44,5 +46,6 @@ def convert_directory(dirpath):
out.write(yml) out.write(yml)
out.close() out.close()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@@ -172,15 +172,15 @@ class HeatCustomGuidelines(object):
while level != 0: while level != 0:
level += len(re.findall(r'(\{|\()', lines[idx])) level += len(re.findall(r'(\{|\()', lines[idx]))
level -= len(re.findall(r'(\}|\))', lines[idx])) level -= len(re.findall(r'(\}|\))', lines[idx]))
if re.search("^((\'|\") )", lines[idx]): if re.search(r"^((\'|\") )", lines[idx]):
kwargs.update( kwargs.update(
{'details': 'line %s' % idx, {'details': 'line %s' % idx,
'message': _('Trailing whitespace should ' 'message': _('Trailing whitespace should '
'be on previous line'), 'be on previous line'),
'snippet': lines[idx]}) 'snippet': lines[idx]})
self.print_guideline_error(**kwargs) self.print_guideline_error(**kwargs)
elif (re.search("(\\S(\'|\"))$", lines[idx - 1]) and elif (re.search(r"(\\S(\'|\"))$", lines[idx - 1]) and
re.search("^((\'|\")\\S)", lines[idx])): re.search(r"^((\'|\")\\S)", lines[idx])):
kwargs.update( kwargs.update(
{'details': 'line %s' % (idx - 1), {'details': 'line %s' % (idx - 1),
'message': _('Omitted whitespace at the ' 'message': _('Omitted whitespace at the '
@@ -192,7 +192,7 @@ class HeatCustomGuidelines(object):
def _check_description_summary(self, description, error_kwargs, def _check_description_summary(self, description, error_kwargs,
error_key): error_key):
if re.search("^[a-z]", description): if re.search(r"^[a-z]", description):
error_kwargs.update( error_kwargs.update(
{'message': _('%s description summary should start ' {'message': _('%s description summary should start '
'with uppercase letter') % error_key.title(), 'with uppercase letter') % error_key.title(),
@@ -246,8 +246,7 @@ class HeatCustomGuidelines(object):
'whitespaces') % error_key.title(), 'whitespaces') % error_key.title(),
'snippet': line}) 'snippet': line})
self.print_guideline_error(**error_kwargs) self.print_guideline_error(**error_kwargs)
if re.search("^(:param|:type|:returns|:rtype|:raises)", if re.search(r"^(:param|:type|:returns|:rtype|:raises)", line):
line):
params = True params = True
if not params and not (doclines[-2].endswith('.') or if not params and not (doclines[-2].endswith('.') or
doclines[-2].endswith('.)')): doclines[-2].endswith('.)')):

37
tox.ini
View File

@@ -19,23 +19,12 @@ passenv =
no_proxy no_proxy
[testenv:pep8] [testenv:pep8]
deps =
{[testenv]deps}
pre-commit
commands = commands =
flake8 heat contrib heat_integrationtests doc/source pre-commit run -a
python tools/custom_guidelines.py --exclude heat/engine/resources/aws python tools/custom_guidelines.py --exclude heat/engine/resources/aws
# The following bandit tests are being skipped:
# B101: Test for use of assert
# B104: Test for binding to all interfaces
# B107: Test for use of hard-coded password argument defaults
# B110: Try, Except, Pass detected.
# B310: Audit url open for permitted schemes
# B311: Standard pseudo-random generators are not suitable for security/cryptographic purposes
# B404: Import of subprocess module
# B504: Test for SSL use with no version specified
# B506: Test for use of yaml load
# B603: Test for use of subprocess with shell equals true
# B607: Test for starting a process with a partial path
bandit -r heat -x tests --skip B101,B104,B107,B110,B310,B311,B404,B504,B506,B603,B607
doc8 {posargs}
[testenv:venv] [testenv:venv]
commands = {posargs} commands = {posargs}
@@ -89,24 +78,6 @@ commands =
commands = commands =
oslopolicy-sample-generator --config-file etc/heat/heat-policy-generator.conf oslopolicy-sample-generator --config-file etc/heat/heat-policy-generator.conf
[testenv:bandit]
deps =
-c{env:TOX_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master}
-r{toxinidir}/test-requirements.txt
# The following bandit tests are being skipped:
# B101: Test for use of assert
# B104: Test for binding to all interfaces
# B110: Try, Except, Pass detected.
# B310: Audit url open for permitted schemes
# B311: Standard pseudo-random generators are not suitable for security/cryptographic purposes
# B404: Import of subprocess module
# B410: Import of lxml module
# B504: Test for SSL use with no version specified
# B506: Test for use of yaml load
# B603: Test for use of subprocess with shell equals true
# B607: Test for starting a process with a partial path
commands = bandit -r heat -x tests --skip B101,B104,B110,B310,B311,B404,B410,B504,B506,B603,B607
[flake8] [flake8]
show-source = true show-source = true
# E123 closing bracket does not match indentation of opening bracket's line # E123 closing bracket does not match indentation of opening bracket's line