Skip to content

Commit

Permalink
remove use of black, use ruff for formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
ITProKyle committed Jan 31, 2025
1 parent 3c5667b commit c7802be
Show file tree
Hide file tree
Showing 83 changed files with 354 additions and 252 deletions.
1 change: 0 additions & 1 deletion .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
"hashicorp.terraform",
"lextudio.restructuredtext",
"mohsen1.prettify-json",
"ms-python.black-formatter",
"ms-python.vscode-pylance",
"oderwat.indent-rainbow",
"redhat.vscode-yaml",
Expand Down
1 change: 0 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"charliermarsh.ruff",
"editorconfig.editorconfig",
"lextudio.restructuredtext",
"ms-python.black-formatter",
"ms-python.python",
"ms-python.vscode-pylance",
"redhat.vscode-yaml",
Expand Down
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
"source.fixAll.ruff": "explicit",
"source.organizeImports": "always"
},
"editor.defaultFormatter": "ms-python.black-formatter",
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.detectIndentation": false,
"editor.formatOnSave": true,
"editor.insertSpaces": true,
"editor.rulers": [
81,
88,
98
100
],
"editor.tabSize": 4
},
Expand Down
18 changes: 7 additions & 11 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,21 @@ docs: ## delete current HTML docs & build fresh HTML docs
docs-changes: ## build HTML docs; only builds changes detected by Sphinx
@$(MAKE) --no-print-directory -C docs html

fix: fix-ruff fix-black run-pre-commit ## run all automatic fixes

fix-black: ## automatically fix all black errors
@poetry run black .
fix: fix-ruff run-pre-commit ## run all automatic fixes

fix-imports: ## automatically fix all import sorting errors
@poetry run ruff check . --fix-only --fixable I001

fix-ruff: ## automatically fix everything ruff can fix (implies fix-imports)
fix-formatting: ## automatically fix ruff formatting issues
@poetry run ruff format .

fix-ruff: fix-formatting ## automatically fix everything ruff can fix (implies fix-imports)
@poetry run ruff check . --fix-only

fix-ruff-tests:
@poetry run ruff check ./tests --fix-only --unsafe-fixes

lint: lint-black lint-ruff lint-pyright ## run all linters

lint-black: ## run black
@echo "Running black... If this fails, run 'make fix-black' to resolve."
@poetry run black . --check --color --diff
@echo ""
lint: lint-ruff lint-pyright ## run all linters

lint-pyright: ## run pyright
@echo "Running pyright..."
Expand All @@ -79,6 +74,7 @@ lint-pyright: ## run pyright

lint-ruff: ## run ruff
@echo "Running ruff... If this fails, run 'make fix-ruff' to resolve some error automatically, other require manual action."
@poetry run ruff format . --diff
@poetry run ruff check .
@echo ""

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[![CI/CD](https://github.com/rackspace/runway/workflows/CI/CD/badge.svg?branch=master)](https://github.com/rackspace/runway/actions?query=workflow%3ACI%2FCD)
[![codecov](https://codecov.io/gh/rackspace/runway/branch/master/graph/badge.svg?token=Ku28I0RY80)](https://codecov.io/gh/rackspace/runway)
[![PyPi](https://img.shields.io/pypi/v/runway?style=flat)](https://pypi.org/project/runway/)
[![code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat)](https://github.com/psf/black)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/rackspace/runway/master.svg)](https://results.pre-commit.ci/latest/github/rackspace/runway/master)

![runway-example.gif](https://raw.githubusercontent.com/rackspace/runway/master/docs/source/images/runway-example.gif)
Expand Down
224 changes: 164 additions & 60 deletions poetry.lock

Large diffs are not rendered by default.

30 changes: 7 additions & 23 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ sphinxcontrib-jquery = "^4.1"
sphinxcontrib-programoutput = "^0.17"

[tool.poetry.group.lint.dependencies]
black = "^24.10.0"
ruff = "^0.9.3"

[tool.poetry.group.test.dependencies]
Expand Down Expand Up @@ -122,27 +121,6 @@ runway = "runway._cli.main:cli"
[tool.poetry.urls]
"Bug Tracker" = "https://github.com/rackspace/runway/issues"

[tool.black]
force-exclude = '''
/(
\.eggs
| \.git
| \.demo
| \.hg
| \.mypy_cache
| \.runway
| \.tox
| \.venv
| _build
| build
| dist
| runway/aws_sso_botocore
)/
'''
include = '\.pyi?$'
line-length = 100
target-version = ["py310", "py311", "py312", "py39"]

[tool.coverage.report]
exclude_lines = [
"@overload",
Expand Down Expand Up @@ -236,10 +214,13 @@ extend-exclude = [
"typings",
]
force-exclude = true
line-length = 120
line-length = 100
show-fixes = true
target-version = "py39" # important to set before applying fixes

[tool.ruff.format] # https://docs.astral.sh/ruff/settings/#format
docstring-code-format = true

[tool.ruff.lint] # https://docs.astral.sh/ruff/settings/#lint
extend-safe-fixes = [
"UP006",
Expand Down Expand Up @@ -327,6 +308,9 @@ known-third-party = [
"docker", # NOTE (kyle): the `docker/` directory confuses isort
]

[tool.ruff.lint.pycodestyle] # https://docs.astral.sh/ruff/settings/#lint_pycodestyle_max-line-length
max-line-length = 140

[tool.ruff.lint.pydocstyle] # https://docs.astral.sh/ruff/settings/#lintpydocstyle
convention = "google"

Expand Down
1 change: 1 addition & 0 deletions quickstarts/conduit/update_env_endpoint.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Module with update_api_endpoint."""

import os
import re
import subprocess
Expand Down
4 changes: 2 additions & 2 deletions runway/_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ class PrefixAdaptor(logging.LoggerAdapter): # type: ignore
"""LoggerAdapter that adds prefixes to messages.
Example:
>>> logger = PrefixAdaptor('something', logging.getLogger('example'))
... logger.info('my message')
>>> logger = PrefixAdaptor("something", logging.getLogger("example"))
... logger.info("my message")
"""

Expand Down
1 change: 1 addition & 0 deletions runway/blueprints/k8s/k8s_iam.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Module with k8s IAM resources."""

import awacs.autoscaling
import awacs.sts
from awacs.aws import Allow, PolicyDocument, Statement
Expand Down
1 change: 1 addition & 0 deletions runway/blueprints/k8s/k8s_master.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Module with k8s cluster resources."""

import awacs.iam
from awacs.aws import Allow, Condition, PolicyDocument, Statement, StringLike
from awacs.helpers.trust import make_simple_assume_policy
Expand Down
6 changes: 5 additions & 1 deletion runway/blueprints/k8s/k8s_workers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Module with k8s nodegroup."""

import gzip
import json
import os
Expand All @@ -23,7 +24,10 @@
def get_valid_instance_types() -> Any:
"""Return list of instance types from either a JSON or gzipped JSON file."""
base_path = os.path.join( # noqa: PTH118
os.path.dirname(botocore.__file__), "data", "ec2", "2016-11-15" # noqa: PTH120
os.path.dirname(botocore.__file__), # noqa: PTH120
"data",
"ec2",
"2016-11-15",
)

json_path = os.path.join(base_path, "service-2.json") # noqa: PTH118
Expand Down
5 changes: 2 additions & 3 deletions runway/blueprints/staticsite/staticsite.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Module with static website bucket and CloudFront distribution."""

from __future__ import annotations

import hashlib
Expand Down Expand Up @@ -92,9 +93,7 @@ class StaticSite(Blueprint):
"RoleBoundaryArn": {
"type": str,
"default": "",
"description": "(Optional) IAM Role permissions "
"boundary applied to any created "
"roles.",
"description": "(Optional) IAM Role permissions boundary applied to any created roles.",
},
"WAFWebACL": {
"type": str,
Expand Down
1 change: 1 addition & 0 deletions runway/blueprints/tf_state.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Module with Terraform state resources."""

from __future__ import annotations

from typing import TYPE_CHECKING, ClassVar
Expand Down
4 changes: 3 additions & 1 deletion runway/cfngin/awscli_yamlhelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@


def intrinsics_multi_constructor(
loader: yaml.Loader, tag_prefix: str, node: yaml.Node # noqa: ARG001
loader: yaml.Loader,
tag_prefix: str, # noqa: ARG001
node: yaml.Node,
) -> dict[str, Any]:
"""YAML constructor to parse CloudFormation intrinsics.
Expand Down
3 changes: 1 addition & 2 deletions runway/cfngin/blueprints/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ def validate_variable_type(
value = CFNParameter(name=var_name, value=value)
elif not isinstance(value, var_type):
raise TypeError(
f"Value for variable {var_name} must be of type {var_type}. Actual "
f"type: {type(value)}"
f"Value for variable {var_name} must be of type {var_type}. Actual type: {type(value)}"
)
return value

Expand Down
3 changes: 1 addition & 2 deletions runway/cfngin/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ def __init__(
self.dependency = dependency
self.exception = exception
self.message = (
f"Error detected when adding '{dependency}' "
f"as a dependency of '{stack}': {exception}"
f"Error detected when adding '{dependency}' as a dependency of '{stack}': {exception}"
)
super().__init__()

Expand Down
14 changes: 7 additions & 7 deletions runway/cfngin/hooks/aws_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,7 @@ def _zip_from_file_patterns(
files = list(_find_files(root, includes, excludes, follow_symlinks))
if not files:
raise RuntimeError(
"Empty list of files for Lambda payload. Check "
"your include/exclude options for errors."
"Empty list of files for Lambda payload. Check your include/exclude options for errors."
)

LOGGER.info("adding %d files:", len(files))
Expand Down Expand Up @@ -1028,17 +1027,18 @@ def upload_lambda_functions( # noqa: D417
from troposphere.awslambda import Function
from runway.cfngin.blueprints.base import Blueprint
class LambdaBlueprint(Blueprint):
def create_template(self):
code = self.context.hook_data['lambda']['MyFunction']
code = self.context.hook_data["lambda"]["MyFunction"]
self.template.add_resource(
Function(
'MyFunction',
"MyFunction",
Code=code,
Handler='my_function.handler',
Role='...',
Runtime='python2.7'
Handler="my_function.handler",
Role="...",
Runtime="python2.7",
)
)
Expand Down
2 changes: 1 addition & 1 deletion runway/cfngin/hooks/awslambda/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def post_install_commands(self) -> list[str]:
# wildcards need to exist outside of the quotes to work
# needs to be wrapped in `sh -c` to resolve wildcard
(
f"sh -c 'cp -v \"{extra_file.rstrip('*')}\"* \"{self.DEPENDENCY_DIR}\"'"
f'sh -c \'cp -v "{extra_file.rstrip("*")}"* "{self.DEPENDENCY_DIR}"\''
if extra_file.endswith("*")
else f'sh -c \'cp -v "{extra_file}" "{self.DEPENDENCY_DIR}"\''
)
Expand Down
2 changes: 1 addition & 1 deletion runway/cfngin/hooks/awslambda/type_defs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@


class AwsLambdaHookDeployResponseTypedDict(TypedDict):
"""Dict output of :class:`runway.cfngin.hooks.awslambda.models.response.AwsLambdaHookDeployResponse` using aliases.""" # noqa: E501
"""Dict output of :class:`runway.cfngin.hooks.awslambda.models.response.AwsLambdaHookDeployResponse` using aliases."""

CodeSha256: str
Runtime: str
Expand Down
8 changes: 6 additions & 2 deletions runway/cfngin/hooks/staticsite/auth_at_edge/lambda_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,9 @@ def write(
# to the temporary folder
shutil.copytree(
os.path.join( # noqa: PTH118
os.path.dirname(__file__), "templates", handler # noqa: PTH120
os.path.dirname(__file__), # noqa: PTH120
"templates",
handler,
),
dirpath,
dirs_exist_ok=True,
Expand All @@ -144,7 +146,9 @@ def write(
# Copy the shared jose-dependent util module to the temporary folder
shutil.copyfile(
os.path.join( # noqa: PTH118
os.path.dirname(__file__), "templates", "shared_jose.py" # noqa: PTH120
os.path.dirname(__file__), # noqa: PTH120
"templates",
"shared_jose.py",
),
os.path.join(dirpath, "shared_jose.py"), # noqa: PTH118
)
Expand Down
5 changes: 1 addition & 4 deletions runway/cfngin/hooks/staticsite/cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,7 @@ def warn(context: CfnginContext, *_args: Any, **kwargs: Any) -> bool:
)
functions = get_replicated_function_names(stack.get("Outputs", []))
if functions:
cmd = (
"aws lambda delete-function --function-name $x "
f"--region {context.env.aws_region}"
)
cmd = f"aws lambda delete-function --function-name $x --region {context.env.aws_region}"
LOGGER.warning(
"About to delete the Static Site stack that contains "
"replicated Lambda functions. These functions cannot "
Expand Down
1 change: 0 additions & 1 deletion runway/cfngin/lookups/handlers/ami.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from ...utils import read_value_from_path

if TYPE_CHECKING:

from ....context import CfnginContext


Expand Down
4 changes: 1 addition & 3 deletions runway/cfngin/lookups/handlers/awslambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
from ....utils import load_object_from_string

if TYPE_CHECKING:

from ....config import CfnginConfig
from ....config.models.cfngin import CfnginHookDefinitionModel
from ....context import CfnginContext
Expand Down Expand Up @@ -75,8 +74,7 @@ def get_deployment_package_data(
return _AwsLambdaHookDeployResponse.model_validate(context.hook_data[data_key])
except ValidationError:
raise TypeError(
"expected AwsLambdaHookDeployResponseTypedDict, "
f"not {context.hook_data[data_key]}"
f"expected AwsLambdaHookDeployResponseTypedDict, not {context.hook_data[data_key]}"
) from None

@staticmethod
Expand Down
4 changes: 1 addition & 3 deletions runway/cfngin/lookups/handlers/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from ....lookups.handlers.base import LookupHandler

if TYPE_CHECKING:

from ....context import CfnginContext


Expand Down Expand Up @@ -41,8 +40,7 @@ def handle(cls, value: str, context: CfnginContext | None = None, **_: Any) -> A
env_var_name, default_val = value.split("::", 1)
except ValueError:
raise ValueError(
f"Invalid value for default: {value}. Must be in "
"<env_var>::<default value> format."
f"Invalid value for default: {value}. Must be in <env_var>::<default value> format."
) from None

if context and env_var_name in context.parameters:
Expand Down
4 changes: 1 addition & 3 deletions runway/cfngin/lookups/handlers/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@
_PARAMETER_PATTERN = re.compile(r"{{([::|\w]+)}}")

ParameterizedObjectTypeDef: TypeAlias = "str | Mapping[str, Any] | Sequence[Any] | Any"
ParameterizedObjectReturnTypeDef: TypeAlias = (
"dict[str, ParameterizedObjectReturnTypeDef] | GenericHelperFn | list[ParameterizedObjectReturnTypeDef]"
)
ParameterizedObjectReturnTypeDef: TypeAlias = "dict[str, ParameterizedObjectReturnTypeDef] | GenericHelperFn | list[ParameterizedObjectReturnTypeDef]" # noqa: E501


class ArgsDataModel(BaseModel):
Expand Down
1 change: 0 additions & 1 deletion runway/cfngin/lookups/handlers/hook_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from ....utils import MutableMap

if TYPE_CHECKING:

from ....context import CfnginContext

LOGGER = logging.getLogger(__name__)
Expand Down
Loading

0 comments on commit c7802be

Please sign in to comment.