Skip to content

Commit

Permalink
Replace black+usort with ruff (#66)
Browse files Browse the repository at this point in the history
Implements Ruff to take over code formatting, linting, and import ordering from black and usort.

Resolves #65.
  • Loading branch information
asullivan-blze authored Mar 26, 2024
1 parent 7d2aca6 commit 1eb9040
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 267 deletions.
10 changes: 2 additions & 8 deletions .github/workflows/make-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,10 @@ jobs:
#----------------------------------------------
# run test suite
#----------------------------------------------
# Check code formatting
- run: make test-black
# Check code formatting and import sorting
- run: make test-ruff

# Commented out because we're planning on switching to a different static
# typechecker, and frankly whatever is taking pyright _minutes_ to run is
# a little excessive, for now.
# - run: make test-pyright

# Commented out because I have zero idea why GitHub Actions has an error,
# but locally it does not. Black also does import formatting, so this isn't
# terribly important (for now); maybe isort? Black does call out that it is
# compatible.
# - run: make test-usort
32 changes: 17 additions & 15 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,11 @@ endif
dist: clean
poetry build

# Applys project's required code style
# Applies fixable errors, and formats code
.PHONY: format
format:
poetry run black .
@# This is a workaround for https://github.com/facebook/usort/issues/216
LIBCST_PARSER_TYPE=native poetry run usort format .
poetry run ruff check --fix
poetry run ruff format

# Installs modules to the local system (via pipx; will need Ansible injected)
.PHONY: install
Expand All @@ -69,12 +68,21 @@ install-web-deps:

# Runs all available tests
.PHONY: test
test: test-black test-pyright test-semgrep test-usort
test: test-ruff test-pyright test-semgrep

# Test that code is formatted with black
.PHONY: test-black
test-black: develop
poetry run black . --check
# Run all available Ruff checks
.PHONY: test-ruff
test-ruff: test-ruff-linters test-ruff-formatting

# Run all available Ruff linter checks
.PHONY: test-ruff-linters
test-ruff-linters: develop
poetry run ruff check

# Run all available Ruff formatting checks
.PHONY: test-ruff-formatting
test-ruff-formatting: develop
poetry run ruff format --check

# Perform type analysis
.PHONY: test-pyright
Expand All @@ -95,9 +103,3 @@ ifndef GITHUB_ACTIONS
else
echo Semgrep will run in its own GitHub Actions job.
endif

# Ensure imports are formatted in a uniform way
.PHONY: test-usort
test-usort: develop
@# This is a workaround for https://github.com/facebook/usort/issues/216
LIBCST_PARSER_TYPE=native poetry run usort check .
258 changes: 33 additions & 225 deletions poetry.lock

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,19 @@ pydantic = ">=2.4.2"
tornado = ">=6.2"

[tool.poetry.group.dev.dependencies]
black = ">=24.3.0"
pyright = "==1.1.350"
semgrep = ">=1.66.0"
usort = ">=1.0.8.post1"
ruff = "^0.3.4"

[tool.poetry.scripts]
boardwalk = "boardwalk.cli:cli"
boardwalkd = "boardwalkd.cli:cli"

[tool.ruff]
extend-exclude = [
"typings/*",
]

[tool.pyright]
exclude = [
"build/",
Expand Down
14 changes: 5 additions & 9 deletions src/boardwalk/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,8 @@ class Host(BaseModel, extra=Extra.forbid):
name: str
meta: dict[str, str | int | bool] = {}
remote_mutex_path: str = "/opt/boardwalk.mutex"
remote_alert_msg: str = (
"ALERT: Boardwalk is running a workflow against this host. Services may be interrupted"
)
remote_alert_string_formatted: str = (
f"$(tput -T xterm bold)$(tput -T xterm setaf 1)'{remote_alert_msg}'$(tput -T xterm sgr0)"
)
remote_alert_msg: str = "ALERT: Boardwalk is running a workflow against this host. Services may be interrupted"
remote_alert_string_formatted: str = f"$(tput -T xterm bold)$(tput -T xterm setaf 1)'{remote_alert_msg}'$(tput -T xterm sgr0)"
remote_alert_motd: str = f"#!/bin/sh\necho {remote_alert_string_formatted}"
remote_alert_motd_path: str = "/etc/update-motd.d/99-boardwalk-alert"
remote_alert_wall_cmd: str = f"wall {remote_alert_string_formatted}"
Expand Down Expand Up @@ -288,9 +284,9 @@ def set_remote_state(
tasks=tasks,
)
if not check:
self.ansible_facts["ansible_local"][
"boardwalk_state"
] = remote_state_obj.dict()
self.ansible_facts["ansible_local"]["boardwalk_state"] = (
remote_state_obj.dict()
)
workspace.flush()


Expand Down
2 changes: 1 addition & 1 deletion src/boardwalk/manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def get_ws() -> Workspace:
# Try to import the Boardwalkfile.py
try:
sys.path.append(str(Path.cwd()))
import Boardwalkfile # pyright: ignore [reportMissingImports, reportUnknownVariableType, reportUnusedImport]
import Boardwalkfile # pyright: ignore [reportMissingImports, reportUnknownVariableType, reportUnusedImport] # noqa: F401

sys.path.pop()
except ModuleNotFoundError:
Expand Down
4 changes: 2 additions & 2 deletions src/boardwalkd/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def __init__(self, **kwargs: str):
@classmethod
def severity_level(cls, v: str):
if v not in ["info", "success", "error"]:
raise ValueError(f"invalid severity level")
raise ValueError("invalid severity level")
return v


Expand Down Expand Up @@ -111,7 +111,7 @@ async def api_login(self):
case _:
raise ValueError(f"{self.url.scheme} is not a valid url scheme")

websocket_url = urljoin(websocket_url.geturl(), f"/api/auth/login/socket")
websocket_url = urljoin(websocket_url.geturl(), "/api/auth/login/socket")
conn = await websocket_connect(websocket_url)
while True:
msg = await conn.read_message()
Expand Down
8 changes: 3 additions & 5 deletions src/boardwalkd/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def ui_method_sort_events_by_date(
) -> list[WorkspaceEvent]:
"""Custom UI templating method. Accepts a deque of Workspace events and
sorts them by datetime in ascending order"""
key: Callable[[WorkspaceEvent], datetime] = lambda x: x.create_time # type: ignore
key: Callable[[WorkspaceEvent], datetime] = lambda x: x.create_time # type: ignore # noqa: E731
return sorted(events, key=key, reverse=True)


Expand Down Expand Up @@ -648,9 +648,7 @@ class WorkspaceDetailsApiHandler(APIBaseHandler):
@tornado.web.authenticated
def get(self, workspace: str):
try:
return self.write(
state.workspaces[workspace].details.dict()
) # pyright: ignore [reportUnknownMemberType]
return self.write(state.workspaces[workspace].details.dict()) # pyright: ignore [reportUnknownMemberType]
except KeyError:
return self.send_error(404)

Expand Down Expand Up @@ -1004,7 +1002,7 @@ async def run(

if tls_port_number is not None:
if urlparse(url).scheme != "https":
raise BoardwalkException(f"URL scheme must be HTTPS when TLS is enabled")
raise BoardwalkException("URL scheme must be HTTPS when TLS is enabled")

ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(certfile=tls_crt_path, keyfile=tls_key_path) # type: ignore
Expand Down

0 comments on commit 1eb9040

Please sign in to comment.