Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport PR #15499: Adopt ruff format #15564

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 2 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,13 @@ repos:
hooks:
- id: check-github-workflows

- repo: https://github.com/psf/black
rev: 23.10.1
hooks:
- id: black

# Check ruff version is aligned with the one in pyproject.toml
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.4
rev: v0.1.6
hooks:
- id: ruff
args: ["--fix"]
- id: ruff-format

- repo: local
hooks:
Expand Down
1 change: 0 additions & 1 deletion binder/environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ dependencies:
- requests-cache
- virtualenv
# dev
- black-jupyter
- bump2version
- hatch
- pre-commit
Expand Down
4 changes: 3 additions & 1 deletion clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
for root, dnames, _ in os.walk(here):
if "node_modules" in dnames:
subprocess.check_call(
["rmdir", "/s", "/q", "node_modules"], cwd=root, shell=True # noqa S602 S607
["rmdir", "/s", "/q", "node_modules"], # noqa S602 S607
cwd=root,
shell=True, # noqa S602 S607
)
dnames.remove("node_modules")

Expand Down
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def document_plugins_tokens_list(list_path: Path, output_path: Path) -> None:


# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}


def setup(app):
Expand Down
6 changes: 3 additions & 3 deletions docs/source/developer/contributing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ All source code is written in
`TypeScript <https://www.typescriptlang.org/Handbook>`__. See the `Style
Guide <https://github.com/jupyterlab/jupyterlab/wiki/TypeScript-Style-Guide>`__.

All non-python source code is formatted using `prettier <https://prettier.io>`__, and python source code is formatted using `black <https://github.com/psf/black>`__.
All non-python source code is formatted using `prettier <https://prettier.io>`__, and python source code is formatted using `ruff <https://docs.astral.sh/ruff>`__.
When code is modified and committed, all staged files will be
automatically formatted using pre-commit git hooks (with help from
`pre-commit <https://github.com/pre-commit/pre-commit>`__). The benefit of
using a code formatters like ``prettier`` and ``black`` is that it removes the topic of
using a code formatters like ``prettier`` and ``ruff`` is that it removes the topic of
code style from the conversation when reviewing pull requests, thereby
speeding up the review process.

Expand All @@ -121,7 +121,7 @@ You can invoke the pre-commit hook by hand at any time with::

which should run any autoformatting on your code
and tell you about any errors it couldn't fix automatically.
You may also install `black integration <https://github.com/psf/black#editor-integration>`__
You may also install `ruff integration <https://docs.astral.sh/ruff/integrations>`__
into your text editor to format code automatically.

If you have already committed files before setting up the pre-commit
Expand Down
4 changes: 2 additions & 2 deletions examples/example_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

here = Path(__file__).parent.resolve()
TEST_FILE = here / "example.spec.ts"
REF_SNAPSHOT = Path(TEST_FILE.with_suffix('.ts-snapshots').name) / "example-linux.png"
REF_SNAPSHOT = Path(TEST_FILE.with_suffix(".ts-snapshots").name) / "example-linux.png"


def main():
Expand Down Expand Up @@ -96,7 +96,7 @@ async def run_browser(url):

current_env = os.environ.copy()
current_env["BASE_URL"] = url
current_env["TEST_SNAPSHOT"] = '1' if has_snapshot else '0'
current_env["TEST_SNAPSHOT"] = "1" if has_snapshot else "0"
try:
await run_async_process(["npx", "playwright", "test"], env=current_env, cwd=str(target))
finally:
Expand Down
6 changes: 4 additions & 2 deletions jupyterlab/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -1994,7 +1994,9 @@ def _yarn_config(logger):

try:
output_binary = subprocess.check_output(
[node, YARN_PATH, "config", "--json"], stderr=subprocess.PIPE, cwd=HERE # noqa S603
[node, YARN_PATH, "config", "--json"], # noqa S603
stderr=subprocess.PIPE,
cwd=HERE,
)
output = output_binary.decode("utf-8")
lines = iter(output.splitlines())
Expand Down Expand Up @@ -2328,7 +2330,7 @@ def _log_multiple_compat_errors(logger, errors_map):
[
"\n The following extensions are outdated:",
*outdated,
'\n Consider checking if an update is available for these packages.\n',
"\n Consider checking if an update is available for these packages.\n",
]
)
)
Expand Down
3 changes: 2 additions & 1 deletion jupyterlab/federated_labextensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,8 @@ def _get_labextension_metadata(module): # noqa
try:
package = (
subprocess.check_output(
[sys.executable, "setup.py", "--name"], cwd=mod_path # noqa S603
[sys.executable, "setup.py", "--name"], # noqa S603
cwd=mod_path,
)
.decode("utf8")
.strip()
Expand Down
6 changes: 3 additions & 3 deletions jupyterlab/handlers/announcements.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,18 +238,18 @@ def get_xml_text(attr: str, default: Optional[str] = None) -> str:
return default
else:
error_m = (
f'atom feed entry does not contain a required attribute: {attr}'
f"atom feed entry does not contain a required attribute: {attr}"
)
raise KeyError(error_m)

entry_title = get_xml_text("title")
entry_id = get_xml_text("id")
entry_updated = get_xml_text("updated")
entry_published = get_xml_text("published", entry_updated)
entry_summary = get_xml_text("summary", default='')
entry_summary = get_xml_text("summary", default="")
links = node.findall("atom:link", xml_namespaces)
if len(links) > 1:
alternate = list(filter(lambda elem: elem.get('rel') == 'alternate', links))
alternate = list(filter(lambda elem: elem.get("rel") == "alternate", links))
link_node = alternate[0] if alternate else links[0]
else:
link_node = links[0] if len(links) == 1 else None
Expand Down
2 changes: 0 additions & 2 deletions jupyterlab/tests/test_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,6 @@ async def mock_pkg_metadata(n, l, b): # noqa
"nbformat",
"packaging",
"pexpect",
"black ; extra == 'dev'",
"coverage ; extra == 'dev'",
"jupyter-packaging (~=0.7.9) ; extra == 'dev'",
"jupyterlab (~=3.0) ; extra == 'dev'",
Expand All @@ -248,7 +247,6 @@ async def mock_pkg_metadata(n, l, b): # noqa
"pytest-asyncio ; extra == 'dev'",
"pytest-cov ; extra == 'dev'",
"pytest-tornasync ; extra == 'dev'",
"black ; extra == 'tests'",
"coverage ; extra == 'tests'",
"jupyter-packaging (~=0.7.9) ; extra == 'tests'",
"jupyterlab (~=3.0) ; extra == 'tests'",
Expand Down
13 changes: 7 additions & 6 deletions jupyterlab/upgrade_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ def update_extension( # noqa
if setup_file.exists():
python_name = (
subprocess.check_output(
[sys.executable, "setup.py", "--name"], cwd=target # noqa S603
[sys.executable, "setup.py", "--name"], # noqa: S603
cwd=target,
)
.decode("utf8")
.strip()
Expand Down Expand Up @@ -149,7 +150,7 @@ def update_extension( # noqa
}

template = "https://github.com/jupyterlab/extension-template"
if tuple(copier.__version__.split('.')) < ('8', '0', '0'):
if tuple(copier.__version__.split(".")) < ("8", "0", "0"):
copier.run_auto(template, output_dir, vcs_ref=vcs_ref, data=extra_context, defaults=True)
else:
copier.run_copy(
Expand Down Expand Up @@ -281,7 +282,7 @@ def update_extension( # noqa
pyproject = tomllib.loads(pyproject_file.read_text())

# Backport requirements
requirements_raw = config.get('options', 'install_requires', fallback=None)
requirements_raw = config.get("options", "install_requires", fallback=None)
if requirements_raw is not None:
requirements = list(
filter(
Expand All @@ -297,8 +298,8 @@ def update_extension( # noqa
)

# Backport extras
if config.has_section('options.extras_require'):
for extra, deps_raw in config.items('options.extras_require'):
if config.has_section("options.extras_require"):
for extra, deps_raw in config.items("options.extras_require"):
deps = list(filter(lambda r: r, deps_raw.splitlines()))
if extra in pyproject["project"].get("optional-dependencies", {}):
if pyproject["project"].get("optional-dependencies") is None:
Expand Down Expand Up @@ -339,7 +340,7 @@ def update_extension( # noqa

if answer_file.exists():
msg = "This script won't do anything for copier template, instead execute in your extension directory:\n\n copier update"
if tuple(copier.__version__.split('.')) >= ('8', '0', '0'):
if tuple(copier.__version__.split(".")) >= ("8", "0", "0"):
msg += " --UNSAFE"
print(msg)
else:
Expand Down
19 changes: 4 additions & 15 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,7 @@ dev = [
"coverage",
"hatch",
"bump2version",
"ruff==0.1.4",
"black[jupyter]==23.10.1"
"ruff==0.1.6",
]

[tool.check-wheel-contents]
Expand Down Expand Up @@ -239,21 +238,11 @@ before-build-python = [
]
after-publish-assets = "npm run after:publish:assets"

[tool.black]
line-length = 100
target-version = ["py37"]
skip-string-normalization = true
extend-exclude = '''
(
.*\/css_js_injection.ipynb # Exclude integration test notebook
)
'''

[tool.ruff]
target-version = "py37"
target-version = "py38"
line-length = 100
select = [
"A", "B", "C", "DTZ", "E", "EM", "F", "FBT", "I", "ICN", "ISC", "N",
"A", "B", "C", "DTZ", "E", "EM", "F", "FBT", "I", "ICN", "N",
"PLC", "PLE", "PLR", "PLW", "Q", "RUF", "S", "SIM", "T", "TID", "UP",
"W", "YTT",
]
Expand All @@ -270,7 +259,7 @@ ignore = [
"SIM105",
]

[tool.ruff.per-file-ignores]
[tool.ruff.lint.per-file-ignores]
# F821 Undefined name `c`
"binder/jupyter_config.py" = ["F821"]
# RUF012 Mutable class attributes should be annotated with `typing.ClassVar`
Expand Down
2 changes: 1 addition & 1 deletion scripts/ci_script.sh
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ if [[ $GROUP == lint ]]; then
jlpm run stylelint:check || (echo 'Please run `jlpm run stylelint` locally and push changes' && exit 1)

# Python checks
black --check --diff --color .
ruff format .
ruff .
pipx run 'validate-pyproject[all]' pyproject.toml
fi
Expand Down