Skip to content

Commit

Permalink
Apply use-pathlib rules
Browse files Browse the repository at this point in the history
  • Loading branch information
Secrus committed Jan 16, 2025
1 parent 2e8e4e0 commit 69a44f5
Show file tree
Hide file tree
Showing 22 changed files with 84 additions and 116 deletions.
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ extend-exclude = [
# External to the project's coding standards
"tests/fixtures/git/*",
"tests/fixtures/project_with_setup*/*",
"tests/fixtures/extended_with_no_setup/*"
]
fix = true
line-length = 88
Expand All @@ -119,6 +120,7 @@ extend-select = [
"N", # pep8-naming
"PIE", # flake8-pie
"PGH", # pygrep
"PTH", # flake8-use-pathlib
"RUF", # ruff checks
"SIM", # flake8-simplify
"T20", # flake8-print
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Config:
"virtualenvs": {
"create": True,
"in-project": None,
"path": os.path.join("{cache-dir}", "virtualenvs"),
"path": os.path.join("{cache-dir}", "virtualenvs"), # noqa: PTH118
"options": {
"always-copy": False,
"system-site-packages": False,
Expand Down
5 changes: 2 additions & 3 deletions src/poetry/inspection/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,8 @@ def _find_dist_info(path: Path) -> Iterator[Path]:
"""
pattern = "**/*.*-info"
# Sometimes pathlib will fail on recursive symbolic links, so we need to work
# around it and use the glob module instead. Note that this does not happen with
# pathlib2 so it's safe to use it for Python < 3.4.
directories = glob.iglob(path.joinpath(pattern).as_posix(), recursive=True)
# around it and use the glob module instead. This bug is fixed in Python 3.13.
directories = glob.iglob(path.joinpath(pattern).as_posix(), recursive=True) # noqa: PTH207

for d in directories:
yield Path(d)
Expand Down
2 changes: 1 addition & 1 deletion src/poetry/masonry/builders/editable.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def _setup_build(self) -> None:
pip_install(self._path, self._env, upgrade=True, editable=True)
finally:
if not has_setup:
os.remove(setup)
setup.unlink()

def _add_pth(self) -> list[Path]:
paths = {
Expand Down
4 changes: 2 additions & 2 deletions src/poetry/packages/locker.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def _write_lock_data(self, data: TOMLDocument) -> None:
# we do that part for ourselves here, which only takes about 10 ms.

# get original line endings
with open(self.lock, encoding="utf-8", newline="") as f:
with self.lock.open(encoding="utf-8", newline="") as f:
line = f.readline()
linesep = "\r\n" if line.endswith("\r\n") else "\n"

Expand All @@ -254,7 +254,7 @@ def _write_lock_data(self, data: TOMLDocument) -> None:
content = content.replace("\r\n", "\n")
elif linesep == "\r\n":
content = re.sub(r"(?<!\r)\n", "\r\n", content)
with open(self.lock, "w", encoding="utf-8", newline="") as f:
with self.lock.open("w", encoding="utf-8", newline="") as f:
f.write(content)

else:
Expand Down
8 changes: 4 additions & 4 deletions src/poetry/utils/env/env_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,14 +493,14 @@ def create_venv(
# but others can symlink *to* the venv Python,
# so we can't just use sys.executable.
# So we just check every item in the symlink tree (generally <= 3)
p = os.path.normcase(sys.executable)
p = Path(os.path.normcase(sys.executable))
paths = [p]
while os.path.islink(p):
p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
while p.is_symlink():
p = Path(os.path.normcase(p.parent / p.readlink()))
paths.append(p)

p_venv = os.path.normcase(str(venv))
if any(p.startswith(p_venv) for p in paths):
if any(str(p).startswith(p_venv) for p in paths):
# Running properly in the virtualenv, don't need to do anything
return self.get_system_env()

Expand Down
2 changes: 1 addition & 1 deletion src/poetry/utils/env/virtual_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def is_venv(self) -> bool:

def is_sane(self) -> bool:
# A virtualenv is considered sane if "python" exists.
return os.path.exists(self.python)
return self.python.exists()

def _run(self, cmd: list[str], **kwargs: Any) -> str:
kwargs["env"] = self.get_temp_environ(environ=kwargs.get("env"))
Expand Down
9 changes: 5 additions & 4 deletions src/poetry/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,12 @@ def _on_rm_error(


def _on_rm_error(func: Callable[[str], None], path: str, exc_info: Any) -> None:
if not os.path.exists(path):
path_p = Path(path)
if not path_p.exists():
return

os.chmod(path, stat.S_IWRITE)
func(path)
path_p.chmod(stat.S_IWRITE)
func(str(path_p))


def remove_directory(path: Path, force: bool = False) -> None:
Expand All @@ -107,7 +108,7 @@ def remove_directory(path: Path, force: bool = False) -> None:
Internally, all arguments are passed to `shutil.rmtree`.
"""
if path.is_symlink():
return os.unlink(path)
return path.unlink()

kwargs: dict[str, Any] = {}
if force:
Expand Down
6 changes: 2 additions & 4 deletions tests/console/commands/env/helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

import os

from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
Expand Down Expand Up @@ -38,8 +36,8 @@ def check_output(cmd: list[str], *args: Any, **kwargs: Any) -> str:
return f"{version.major}.{version.minor}"

if "import sys; print(sys.executable)" in python_cmd:
executable = cmd[0]
basename = os.path.basename(executable)
executable = Path(cmd[0])
basename = executable.name
return f"/usr/bin/{basename}"

if "print(sys.base_prefix)" in python_cmd:
Expand Down
4 changes: 2 additions & 2 deletions tests/console/commands/self/test_add_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def test_add_existing_plugin_warns_about_no_operation(
installed: TestRepository,
) -> None:
pyproject = SelfCommand.get_default_system_pyproject_file()
with open(pyproject, "w", encoding="utf-8", newline="") as f:
with pyproject.open("w", encoding="utf-8", newline="") as f:
f.write(
f"""\
[tool.poetry]
Expand Down Expand Up @@ -236,7 +236,7 @@ def test_add_existing_plugin_updates_if_requested(
installed: TestRepository,
) -> None:
pyproject = SelfCommand.get_default_system_pyproject_file()
with open(pyproject, "w", encoding="utf-8", newline="") as f:
with pyproject.open("w", encoding="utf-8", newline="") as f:
f.write(
f"""\
[tool.poetry]
Expand Down
2 changes: 1 addition & 1 deletion tests/console/commands/self/test_remove_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def install_plugin(installed: Repository) -> None:
)
content = Factory.create_pyproject_from_package(package)
system_pyproject_file = SelfCommand.get_default_system_pyproject_file()
with open(system_pyproject_file, "w", encoding="utf-8", newline="") as f:
with system_pyproject_file.open("w", encoding="utf-8", newline="") as f:
f.write(content.as_string())

lock_content = {
Expand Down
4 changes: 2 additions & 2 deletions tests/console/commands/self/test_self_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def test_generate_system_pyproject_carriage_returns(
cmd.system_pyproject.write_text(example_system_pyproject + "\n", encoding="utf-8")
cmd.generate_system_pyproject()

with open(
cmd.system_pyproject, newline="", encoding="utf-8"
with cmd.system_pyproject.open(
newline="", encoding="utf-8"
) as f: # do not translate newlines
generated = f.read()

Expand Down
12 changes: 6 additions & 6 deletions tests/console/commands/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_list_displays_default_value_if_not_set(
tester.execute("--list")

cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs"))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118
expected = f"""cache-dir = {cache_dir}
installer.max-workers = null
installer.no-binary = null
Expand Down Expand Up @@ -85,7 +85,7 @@ def test_list_displays_set_get_setting(
tester.execute("--list")

cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs"))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118
expected = f"""cache-dir = {cache_dir}
installer.max-workers = null
installer.no-binary = null
Expand Down Expand Up @@ -138,7 +138,7 @@ def test_unset_setting(
tester.execute("virtualenvs.path --unset")
tester.execute("--list")
cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs"))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118
expected = f"""cache-dir = {cache_dir}
installer.max-workers = null
installer.no-binary = null
Expand Down Expand Up @@ -169,7 +169,7 @@ def test_unset_repo_setting(
tester.execute("repositories.foo.url --unset ")
tester.execute("--list")
cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs"))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118
expected = f"""cache-dir = {cache_dir}
installer.max-workers = null
installer.no-binary = null
Expand Down Expand Up @@ -298,7 +298,7 @@ def test_list_displays_set_get_local_setting(
tester.execute("--list")

cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs"))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118
expected = f"""cache-dir = {cache_dir}
installer.max-workers = null
installer.no-binary = null
Expand Down Expand Up @@ -337,7 +337,7 @@ def test_list_must_not_display_sources_from_pyproject_toml(
tester.execute("--list")

cache_dir = json.dumps(str(config_cache_dir))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs"))
venv_path = json.dumps(os.path.join("{cache-dir}", "virtualenvs")) # noqa: PTH118
expected = f"""cache-dir = {cache_dir}
installer.max-workers = null
installer.no-binary = null
Expand Down
4 changes: 2 additions & 2 deletions tests/console/commands/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,10 +936,10 @@ def test_init_existing_pyproject_consistent_linesep(
[tool.black]
line-length = 88
""".replace("\n", linesep)
with open(pyproject_file, "w", newline="", encoding="utf-8") as f:
with pyproject_file.open("w", newline="", encoding="utf-8") as f:
f.write(existing_section)
tester.execute(inputs=init_basic_inputs)
with open(pyproject_file, newline="", encoding="utf-8") as f:
with pyproject_file.open(newline="", encoding="utf-8") as f:
content = f.read()
init_basic_toml = init_basic_toml.replace("\n", linesep)
assert f"{existing_section}{linesep}{init_basic_toml}" in content
Expand Down
9 changes: 4 additions & 5 deletions tests/installation/test_chef.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import os
import shutil
import tempfile

Expand Down Expand Up @@ -77,7 +76,7 @@ def test_prepare_directory(

assert wheel.parent.parent == Path(tempfile.gettempdir())
# cleanup generated tmp dir artifact
os.unlink(wheel)
wheel.unlink()


def test_prepare_directory_with_extensions(
Expand All @@ -99,7 +98,7 @@ def test_prepare_directory_with_extensions(
assert wheel.name == f"extended-0.1-{env.supported_tags[0]}.whl"

# cleanup generated tmp dir artifact
os.unlink(wheel)
wheel.unlink()


def test_prepare_directory_editable(
Expand All @@ -122,7 +121,7 @@ def test_prepare_directory_editable(
assert "simple_project.pth" in z.namelist()

# cleanup generated tmp dir artifact
os.unlink(wheel)
wheel.unlink()


def test_prepare_directory_script(
Expand Down Expand Up @@ -168,4 +167,4 @@ def __get__(

assert wheel.parent.parent == Path(tempfile.gettempdir())
# cleanup generated tmp dir artifact
os.unlink(wheel)
wheel.unlink()
2 changes: 1 addition & 1 deletion tests/installation/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ def verify_installed_distribution(
record_file = distribution._path.joinpath( # type: ignore[attr-defined]
"RECORD"
)
with open(record_file, encoding="utf-8", newline="") as f:
with record_file.open(encoding="utf-8", newline="") as f:
reader = csv.reader(f)
rows = list(reader)
assert all(len(row) == 3 for row in rows)
Expand Down
3 changes: 1 addition & 2 deletions tests/installation/test_wheel_installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ def test_default_installation_dist_info_dir_content(default_installation: Path)

def test_installer_file_contains_valid_version(default_installation: Path) -> None:
installer_file = default_installation / "demo-0.1.0.dist-info" / "INSTALLER"
with open(installer_file, encoding="utf-8") as f:
installer_content = f.read()
installer_content = installer_file.read_text(encoding="utf-8")
match = re.match(r"Poetry (?P<version>.*)", installer_content)
assert match
parse_constraint(match.group("version")) # must not raise an error
Expand Down
2 changes: 1 addition & 1 deletion tests/masonry/builders/test_editable_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def test_builder_installs_proper_files_for_standard_packages(
"""
assert metadata == dist_info.joinpath("METADATA").read_text(encoding="utf-8")

with open(dist_info.joinpath("RECORD"), encoding="utf-8", newline="") as f:
with dist_info.joinpath("RECORD").open(encoding="utf-8", newline="") as f:
reader = csv.reader(f)
records = list(reader)

Expand Down
Loading

0 comments on commit 69a44f5

Please sign in to comment.