Skip to content

Commit 1a362c0

Browse files
Merge pull request #176 from python-discord/ruff-migration
Ruff migration
2 parents e92119e + 8419e49 commit 1a362c0

29 files changed

+319
-478
lines changed

.github/workflows/docs.yaml

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,20 +11,19 @@ jobs:
1111
runs-on: ubuntu-latest
1212

1313
steps:
14-
- uses: actions/checkout@v2
14+
- uses: actions/checkout@v3
1515

1616
- name: Install Python Dependencies
17-
uses: HassanAbouelela/actions/setup-python@setup-python_v1.3.2
17+
uses: HassanAbouelela/actions/setup-python@setup-python_v1.4.0
1818
with:
19-
dev: true
2019
python_version: "3.11"
2120
install_args: "--extras async-rediscache --only main --only doc"
2221

2322
- name: Generate HTML Site
2423
run: sphinx-build -nW -j auto -b html docs docs/build
2524

2625
- name: Upload Build Artifact
27-
uses: actions/upload-artifact@v2
26+
uses: actions/upload-artifact@v3
2827
with:
2928
name: docs-latest
3029
path: docs/build/*
@@ -34,14 +33,13 @@ jobs:
3433
runs-on: ubuntu-latest
3534

3635
steps:
37-
- uses: actions/checkout@v2
36+
- uses: actions/checkout@v3
3837
with:
3938
fetch-depth: 0 # We need to check out the entire repository to find all tags
4039

4140
- name: Install Python Dependencies
42-
uses: HassanAbouelela/actions/setup-python@setup-python_v1.3.2
41+
uses: HassanAbouelela/actions/setup-python@setup-python_v1.4.0
4342
with:
44-
dev: true
4543
python_version: "3.11"
4644
install_args: "--extras async-rediscache"
4745

@@ -57,13 +55,13 @@ jobs:
5755
rm -r docs/build/**/.doctrees
5856
5957
- name: Upload Build Artifact
60-
uses: actions/upload-artifact@v2
58+
uses: actions/upload-artifact@v3
6159
with:
6260
name: docs
6361
path: docs/build/*
6462

6563
- name: Deploy To GitHub Pages
66-
uses: JamesIves/github-pages-deploy-action@4.1.7
64+
uses: JamesIves/github-pages-deploy-action@v4
6765
with:
6866
branch: docs
6967
folder: docs/build

.github/workflows/lint-test.yaml

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,17 @@ jobs:
1313
runs-on: ubuntu-latest
1414
steps:
1515
- name: Install Python Dependencies
16-
uses: HassanAbouelela/actions/setup-python@setup-python_v1.3.2
16+
uses: HassanAbouelela/actions/setup-python@setup-python_v1.4.0
1717
with:
18-
# Set dev=true to run pre-commit which is a dev dependency
19-
dev: true
2018
python_version: ${{ matrix.python_version }}
2119
install_args: "--extras async-rediscache --only main --only lint --only test"
2220

23-
# We will not run `flake8` here, as we will use a separate flake8
24-
# action.
2521
- name: Run pre-commit hooks
26-
run: SKIP=flake8 pre-commit run --all-files
22+
run: SKIP=ruff pre-commit run --all-files
2723

28-
# Run flake8 and have it format the linting errors in the format of
29-
# the GitHub Workflow command to register error annotations. This
30-
# means that our flake8 output is automatically added as an error
31-
# annotation to both the run result and in the "Files" tab of a
32-
# pull request.
33-
#
34-
# Format used:
35-
# ::error file={filename},line={line},col={col}::{message}
36-
- name: Run flake8
37-
run: "flake8 \
38-
--format='::error file=%(path)s,line=%(row)d,col=%(col)d::[flake8] %(code)s: %(text)s'"
24+
# Run `ruff` using github formatting to enable automatic inline annotations.
25+
- name: Run ruff
26+
run: "ruff check --format=github ."
3927

4028
- name: Run tests and generate coverage report
4129
run: python -m pytest -n auto --cov pydis_core -q
@@ -60,7 +48,7 @@ jobs:
6048
- name: Upload a Build Artifact
6149
if: always() && steps.prepare-artifact.outcome == 'success'
6250
continue-on-error: true
63-
uses: actions/upload-artifact@v2
51+
uses: actions/upload-artifact@v3
6452
with:
6553
name: pull-request-payload
6654
path: pull_request_payload.json

.pre-commit-config.yaml

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,25 @@ repos:
55
- id: check-merge-conflict
66
- id: check-toml
77
- id: check-yaml
8-
args: [--unsafe] # Required due to custom constructors (e.g. !ENV)
98
- id: end-of-file-fixer
109
- id: trailing-whitespace
1110
args: [--markdown-linebreak-ext=md]
12-
- repo: https://github.com/pre-commit/pygrep-hooks
13-
rev: v1.9.0
14-
hooks:
15-
- id: python-check-blanket-noqa
11+
1612
- repo: local
1713
hooks:
18-
- id: flake8
19-
name: Flake8
20-
description: This hook runs flake8 within our project's poetry environment.
21-
entry: poetry run flake8
14+
- id: isort
15+
name: isort
16+
description: This hook runs isort within our project's environment.
17+
entry: poetry run isort
2218
language: system
2319
types: [python]
2420
require_serial: true
21+
22+
- id: ruff
23+
name: ruff
24+
description: Run ruff linting
25+
entry: poetry run ruff check --force-exclude
26+
language: system
27+
'types_or': [python, pyi]
28+
require_serial: true
29+
args: [--fix, --exit-non-zero-on-fix]

dev/bot/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,4 @@ class Bot(pydis_core.BotBase):
2121
async def setup_hook(self) -> None:
2222
"""Load extensions on startup."""
2323
await super().setup_hook()
24-
asyncio.create_task(self.load_extensions(sys.modules[__name__]))
24+
await self.load_extensions(sys.modules[__name__])

dev/bot/__main__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from discord.ext import commands
88

99
import pydis_core
10+
1011
from . import Bot
1112

1213
dotenv.load_dotenv()
@@ -17,7 +18,7 @@
1718

1819
bot = Bot(
1920
guild_id=int(os.getenv("GUILD_ID")),
20-
http_session=None, # type: ignore # We need to instantiate the session in an async context
21+
http_session=None, # type: ignore We need to instantiate the session in an async context
2122
allowed_roles=roles,
2223
command_prefix=commands.when_mentioned_or(os.getenv("PREFIX", "!")),
2324
intents=discord.Intents.all(),

dev/bot/cog.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def __init__(self, _bot: Bot):
1212
@commands.Cog.listener()
1313
async def on_ready(self) -> None:
1414
"""Print a message when the client (re)connects."""
15-
print("Client is ready.")
15+
print("Client is ready.") # noqa: T201
1616

1717
@commands.command()
1818
async def reload(self, ctx: commands.Context) -> None:

docs/changelog.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
44
Changelog
55
=========
6+
- :feature:`176` Migrate repo to use ruff for linting
7+
8+
69
- :release:`9.6.0 <6th May 2023>`
710
- :feature:`175` Log when waiting for the guild to be available before loading cogs
811
- :support:`175` Bump Discord.py to :literal-url:`2.2.3 <https://github.com/Rapptz/discord.py/releases/tag/v2.2.3>`.

docs/conf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Configuration file for the Sphinx documentation builder.
22
# https://www.sphinx-doc.org/en/master/usage/configuration.html
33

4+
import contextlib
45
import functools
56
import os.path
67
import shutil
@@ -16,7 +17,7 @@
1617
logger = sphinx.util.logging.getLogger(__name__)
1718

1819
# Handle the path not being set correctly in actions.
19-
sys.path.insert(0, os.path.abspath('..'))
20+
sys.path.insert(0, os.path.abspath(".."))
2021

2122
from docs import utils # noqa: E402
2223

@@ -209,10 +210,9 @@ def _releases_setup(app: Sphinx) -> dict:
209210
smv_branch_whitelist = "main"
210211
if os.getenv("BUILD_DOCS_FOR_HEAD", "False").lower() == "true":
211212
if not (branch := os.getenv("BRANCH_NAME")):
212-
try:
213+
with contextlib.suppress(git.InvalidGitRepositoryError):
213214
branch = git.Repo(PROJECT_ROOT).active_branch.name
214-
except git.InvalidGitRepositoryError:
215-
pass
215+
216216

217217
if branch:
218218
logger.info(f"Adding branch {branch} to build whitelist.")

docs/netlify_build.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,5 @@
2222

2323
if __name__ == "__main__":
2424
# Run the build script
25-
print("Build started")
26-
subprocess.run([sys.executable, OUTPUT.absolute()])
25+
print("Build started") # noqa: T201
26+
subprocess.run([sys.executable, OUTPUT.absolute()]) # noqa: S603

docs/utils.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,15 @@ def get_build_root() -> Path:
3030
def is_attribute(module: types.ModuleType, parameter: str) -> bool:
3131
"""Returns true if `parameter` is an attribute of `module`."""
3232
docs = docstring_parser.parse(inspect.getdoc(module), docstring_parser.DocstringStyle.GOOGLE)
33-
for param in docs.params:
33+
for param in docs.params: # noqa: SIM110
3434
# The docstring_parser library can mis-parse arguments like `arg (:obj:`str`)` as `arg (`
3535
# which would create a false-negative below, so we just strip away the extra parenthesis.
3636
if param.args[0] == "attribute" and param.arg_name.rstrip(" (") == parameter:
3737
return True
38-
3938
return False
4039

4140

42-
def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typing.Optional[str]:
41+
def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> str | None:
4342
"""
4443
Function called by linkcode to get the URL for a given resource.
4544
@@ -79,8 +78,7 @@ def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typin
7978
# This could be caused by trying to link a class attribute
8079
if is_attribute(symbol[-1], name):
8180
break
82-
else:
83-
raise e
81+
raise e
8482

8583
symbol_name = name
8684

@@ -97,8 +95,8 @@ def linkcode_resolve(repo_link: str, domain: str, info: dict[str, str]) -> typin
9795
pos = _global_assign_pos(source, symbol_name)
9896
if pos is None:
9997
raise Exception(f"Could not find symbol `{symbol_name}` in {module.__name__}.")
100-
else:
101-
start, end = pos
98+
99+
start, end = pos
102100
_, offset = inspect.getsourcelines(symbol[-2])
103101
if offset != 0:
104102
offset -= 1
@@ -126,7 +124,7 @@ class NodeWithBody(typing.Protocol):
126124
body: list[ast.AST]
127125

128126

129-
def _global_assign_pos(ast_: NodeWithBody, name: str) -> typing.Union[tuple[int, int], None]:
127+
def _global_assign_pos(ast_: NodeWithBody, name: str) -> tuple[int, int] | None:
130128
"""
131129
Find the first instance where the `name` global is defined in `ast_`.
132130
@@ -149,6 +147,7 @@ def _global_assign_pos(ast_: NodeWithBody, name: str) -> typing.Union[tuple[int,
149147
pos_in_if = _global_assign_pos(ast_obj, name)
150148
if pos_in_if is not None:
151149
return pos_in_if
150+
return None
152151

153152

154153
def cleanup() -> None:
@@ -200,7 +199,7 @@ def build_api_doc() -> None:
200199
logger.info(f"Skipping api-doc for {output_folder.as_posix()} as it already exists.")
201200
return
202201

203-
result = subprocess.run(cmd, cwd=build_root, stdout=subprocess.PIPE, check=True, env=os.environ)
202+
result = subprocess.run(cmd, cwd=build_root, stdout=subprocess.PIPE, check=True, env=os.environ) # noqa: S603
204203
logger.debug("api-doc Output:\n" + result.stdout.decode(encoding="utf-8") + "\n")
205204

206205
cleanup()

0 commit comments

Comments
 (0)