Skip to content

Commit

Permalink
Adopt ruff format (#15499)
Browse files Browse the repository at this point in the history
  • Loading branch information
jtpio committed Dec 7, 2023
1 parent 9b67ba1 commit 5ec3aa4
Show file tree
Hide file tree
Showing 17 changed files with 38 additions and 50 deletions.
6 changes: 1 addition & 5 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.11.0
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.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 @@ -396,7 +396,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
8 changes: 5 additions & 3 deletions jupyterlab/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2054,7 +2054,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 @@ -2363,7 +2365,7 @@ def _is_locked(name, locked=None) -> LockStatus:
continue
if name == lock:
return LockStatus(entire_extension_locked=True)
extension_part = lock.partition(':')[0]
extension_part = lock.partition(":")[0]
if name == extension_part:
locked_plugins.add(lock)

Expand Down Expand Up @@ -2415,7 +2417,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
4 changes: 2 additions & 2 deletions jupyterlab/extensions/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,10 @@ def _find_locked(self, plugins_or_extensions: List[str]) -> FrozenSet[str]:
return set(plugins_or_extensions)
locked_subset = set()
extensions_with_locked_plugins = {
plugin.split(':')[0] for plugin in self.options.lock_rules
plugin.split(":")[0] for plugin in self.options.lock_rules
}
for plugin in plugins_or_extensions:
if ':' in plugin:
if ":" in plugin:
# check directly if this is a plugin identifier (has colon)
if plugin in self.options.lock_rules:
locked_subset.add(plugin)
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
4 changes: 2 additions & 2 deletions jupyterlab/labapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -751,8 +751,8 @@ def initialize_handlers(self): # noqa
r"/custom/(.*)(?<!\.js)$",
self.serverapp.web_app.settings["static_handler_class"],
{
'path': self.serverapp.web_app.settings['static_custom_path'],
'no_cache_paths': ['/'], # don't cache anything in custom
"path": self.serverapp.web_app.settings["static_custom_path"],
"no_cache_paths": ["/"], # don't cache anything in custom
},
)
)
Expand Down
4 changes: 2 additions & 2 deletions jupyterlab/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def labserverapp(jp_serverapp, make_labserver_extension_app):
r"/custom/(.*)(?<!\.js)$",
jp_serverapp.web_app.settings["static_handler_class"],
{
'path': jp_serverapp.web_app.settings['static_custom_path'],
'no_cache_paths': ['/'], # don't cache anything in custom
"path": jp_serverapp.web_app.settings["static_custom_path"],
"no_cache_paths": ["/"], # don't cache anything in custom
},
),
(
Expand Down
2 changes: 1 addition & 1 deletion jupyterlab/tests/test_custom_css_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def jp_server_config(jp_server_config, tmp_path):
async def test_CustomCssHandler(tmp_path, jp_serverapp, labserverapp, jp_fetch):
custom_path = tmp_path / "config" / "custom"
# Check we are placing the custom.css file in the appropriate folder
assert str(custom_path) in jp_serverapp.web_app.settings['static_custom_path']
assert str(custom_path) in jp_serverapp.web_app.settings["static_custom_path"]
custom_path.mkdir(parents=True, exist_ok=True)
(custom_path / "custom.css").write_text(CUSTOM_CSS)
response = await jp_fetch("custom", "custom.css", method="GET")
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
17 changes: 3 additions & 14 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ dev = [
"hatch",
"bump2version",
"ruff==0.1.6",
"black[jupyter]==23.11.0"
]

[tool.check-wheel-contents]
Expand Down Expand Up @@ -240,21 +239,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 @@ -271,7 +260,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

0 comments on commit 5ec3aa4

Please sign in to comment.