Skip to content

Commit

Permalink
chore: lint with Ruff (#1715)
Browse files Browse the repository at this point in the history
  • Loading branch information
frostming committed Feb 16, 2023
1 parent 8875807 commit f6cc4eb
Show file tree
Hide file tree
Showing 118 changed files with 790 additions and 2,196 deletions.
18 changes: 6 additions & 12 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
ci:
autoupdate_schedule: monthly
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.246'
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix, --show-fixes]

- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
Expand All @@ -11,18 +17,6 @@ repos:
hooks:
- id: codespell # See setup.cfg for args

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies:
- flake8-bugbear

- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.991
hooks:
Expand Down
47 changes: 13 additions & 34 deletions install-pdm.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@

def _call_subprocess(args: list[str]) -> int:
try:
return subprocess.run(
args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True
).returncode
return subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True).returncode
except subprocess.CalledProcessError as e:
print(f"An error occurred when executing {args}:", file=sys.stderr)
print(e.output.decode("utf-8"), file=sys.stderr)
Expand Down Expand Up @@ -100,7 +98,7 @@ def _get_win_folder_from_registry(csidl_name: str) -> str:
return dir

try:
from ctypes import windll # noqa
from ctypes import windll # noqa: F401

_get_win_folder = _get_win_folder_with_ctypes
except ImportError:
Expand All @@ -110,14 +108,10 @@ def _remove_path_windows(target: Path) -> None:
value = os.path.normcase(target)

with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root:
with winreg.OpenKey(
root, "Environment", 0, winreg.KEY_ALL_ACCESS
) as env_key:
with winreg.OpenKey(root, "Environment", 0, winreg.KEY_ALL_ACCESS) as env_key:
try:
old_value, type_ = winreg.QueryValueEx(env_key, "PATH")
paths = [
os.path.normcase(item) for item in old_value.split(os.pathsep)
]
paths = [os.path.normcase(item) for item in old_value.split(os.pathsep)]
if value not in paths:
return

Expand All @@ -132,14 +126,10 @@ def _add_to_path(target: Path) -> None:

if WINDOWS:
with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as root:
with winreg.OpenKey(
root, "Environment", 0, winreg.KEY_ALL_ACCESS
) as env_key:
with winreg.OpenKey(root, "Environment", 0, winreg.KEY_ALL_ACCESS) as env_key:
try:
old_value, type_ = winreg.QueryValueEx(env_key, "PATH")
if value in [
os.path.normcase(item) for item in old_value.split(os.pathsep)
]:
if value in [os.path.normcase(item) for item in old_value.split(os.pathsep)]:
return
except FileNotFoundError:
old_value, type_ = "", winreg.REG_EXPAND_SZ
Expand Down Expand Up @@ -224,9 +214,7 @@ def sort_version(v: str) -> tuple:
parts.append(rest)
return tuple(parts)

releases = sorted(
filter(version_okay, metadata["releases"]), key=sort_version, reverse=True
)
releases = sorted(filter(version_okay, metadata["releases"]), key=sort_version, reverse=True)

return releases[0]

Expand Down Expand Up @@ -266,16 +254,11 @@ def _make_env(self) -> Path:
import virtualenv
except ModuleNotFoundError:
python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
url = (
"https://bootstrap.pypa.io/virtualenv/"
f"{python_version}/virtualenv.pyz"
)
url = f"https://bootstrap.pypa.io/virtualenv/{python_version}/virtualenv.pyz"
with TemporaryDirectory(prefix="pdm-installer-") as tempdir:
virtualenv_zip = Path(tempdir) / "virtualenv.pyz"
urllib.request.urlretrieve(url, virtualenv_zip)
_call_subprocess(
[sys.executable, str(virtualenv_zip), str(venv_path)]
)
_call_subprocess([sys.executable, str(virtualenv_zip), str(venv_path)])
else:
virtualenv.cli_run([str(venv_path)])

Expand Down Expand Up @@ -311,7 +294,7 @@ def _install(self, venv_path: Path) -> None:
else:
req = "pdm"
args = [req] + [d for d in self.additional_deps if d]
pip_cmd = [str(venv_python), "-m", "pip", "install"] + args
pip_cmd = [str(venv_python), "-m", "pip", "install", *args]
_call_subprocess(pip_cmd)

def _make_bin(self, venv_path: Path) -> Path:
Expand Down Expand Up @@ -370,8 +353,7 @@ def _write_output(self, venv_path: Path, script: Path) -> None:
output = {
"pdm_version": self.version,
"pdm_bin": str(script),
"install_python_version": f"{sys.version_info.major}."
f"{sys.version_info.minor}.{sys.version_info.micro}",
"install_python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
"install_location": str(venv_path),
}
with open(self.output_path, "w") as f:
Expand Down Expand Up @@ -416,8 +398,7 @@ def main():
parser.add_argument(
"-v",
"--version",
help="Specify the version to be installed, "
"or HEAD to install from the main branch",
help="Specify the version to be installed, or HEAD to install from the main branch",
default=os.getenv("PDM_VERSION"),
)
parser.add_argument(
Expand Down Expand Up @@ -451,9 +432,7 @@ def main():
help="Do not add binary to the PATH.",
default=os.getenv("PDM_SKIP_ADD_TO_PATH"),
)
parser.add_argument(
"-o", "--output", help="Output file to write the installation info to"
)
parser.add_argument("-o", "--output", help="Output file to write the installation info to")

options = parser.parse_args()
installer = Installer(
Expand Down
1 change: 1 addition & 0 deletions news/1715.misc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Use `ruff` as the linter.
59 changes: 27 additions & 32 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -106,22 +106,33 @@ workflow = [
]

[tool.black]
line-length = 88
exclude = '''
/(
\.eggs
| \.git
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
| tests/fixtures
)/
'''
line-length = 120
target-version = ["py37", "py38", "py39", "py310"]


[tool.ruff]
line-length = 120
select = [
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"E", # pycodestyle
"F", # pyflakes
"PGH", # pygrep-hooks
"RUF", # ruff
"W", # pycodestyle
"W", # pycodestyle
"YTT", # flake8-2020
]
extend-ignore = ["B019"]
src = ["src"]
extend-exclude = ["tests/fixtures"]
target-version = "py37"

[tool.ruff.mccabe]
max-complexity = 10

[tool.ruff.isort]
known-first-party = ["pdm"]

[tool.towncrier]
package = "pdm"
Expand Down Expand Up @@ -171,22 +182,6 @@ underlines = "-~^"
requires = ["pdm-pep517>=1.0"]
build-backend = "pdm.pep517.api"

[tool.isort]
profile = "black"
atomic = true
skip_glob = ["*/setup.py"]
filter_files = true
known_first_party = ["pdm"]
known_third_party = [
"platformdirs",
"packaging",
"pytest",
"findpython",
"tomlkit",
"unearth",
"requests",
]

[tool.pytest.ini_options]
filterwarnings = [
"ignore::DeprecationWarning"
Expand Down
17 changes: 0 additions & 17 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,20 +1,3 @@
[flake8]
extend-exclude =
tests/fixtures/*,
env,
dist,
build,
__pypackages__,
temp_script.py
max_complexity = 22
max_line_length = 88
ignore =
B019
B020
B028
E203
W503

[codespell]
ignore-words-list = ba,overriden,te

Expand Down
2 changes: 1 addition & 1 deletion src/pdm/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Source(TypedDict, total=False):
url: str
verify_ssl: bool
name: str
type: Literal["index", "find_links"]
type: Literal["index", "find_links"] # noqa: F821
username: str
password: str

Expand Down
14 changes: 4 additions & 10 deletions src/pdm/builders/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ def __init__(self, executable: str, shared: str, overlay: str) -> None:
self.bin_dirs: list[str] = []
self.lib_dirs: list[str] = []
for path in (overlay, shared):
paths = get_sys_config_paths(
executable, vars={"base": path, "platbase": path}, kind="prefix"
)
paths = get_sys_config_paths(executable, vars={"base": path, "platbase": path}, kind="prefix")
self.bin_dirs.append(paths["scripts"])
self.lib_dirs.extend([paths["platlib"], paths["purelib"]])
self.site_dir = os.path.join(overlay, "site")
Expand Down Expand Up @@ -176,9 +174,7 @@ def get_shared_env(cls, key: int) -> str:
@classmethod
def get_overlay_env(cls, key: str) -> str:
if key not in cls._overlay_envs:
cls._overlay_envs[key] = create_tracked_tempdir(
"-overlay", "pdm-build-env-"
)
cls._overlay_envs[key] = create_tracked_tempdir("-overlay", "pdm-build-env-")
return cls._overlay_envs[key]

def __init__(self, src_dir: str | Path, environment: Environment) -> None:
Expand Down Expand Up @@ -240,7 +236,7 @@ def _env_vars(self) -> dict[str, str]:
)
else:
project_libs = self._env.get_paths()["purelib"]
pythonpath = self._prefix.lib_dirs + [project_libs]
pythonpath = [*self._prefix.lib_dirs, project_libs]
if "PYTHONPATH" in os.environ:
pythonpath.append(os.getenv("PYTHONPATH", ""))
env.update(
Expand Down Expand Up @@ -304,9 +300,7 @@ def install(self, requirements: Iterable[str], shared: bool = False) -> None:
if key not in self._shared_envs:
self._shared_envs[key] = path

def prepare_metadata(
self, out_dir: str, config_settings: Mapping[str, Any] | None = None
) -> str:
def prepare_metadata(self, out_dir: str, config_settings: Mapping[str, Any] | None = None) -> str:
"""Prepare metadata and store in the out_dir.
Some backends doesn't provide that API, in that case the metadata will be
retrieved from the built result.
Expand Down
21 changes: 5 additions & 16 deletions src/pdm/builders/editable.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,16 @@ class EditableBuilder(EnvBuilder):

def __init__(self, src_dir: str | Path, environment: Environment) -> None:
super().__init__(src_dir, environment)
if self._hook.build_backend.startswith(
"pdm.pep517"
) and environment.interpreter.version_tuple < (3, 6):
if self._hook.build_backend.startswith("pdm.pep517") and environment.interpreter.version_tuple < (3, 6):
# pdm.pep517 backend is not available on Python 2, use the fallback backend
self.init_build_system(self.FALLBACK_BACKEND)

def prepare_metadata(
self, out_dir: str, config_settings: Mapping[str, Any] | None = None
) -> str:
def prepare_metadata(self, out_dir: str, config_settings: Mapping[str, Any] | None = None) -> str:
self.install(self._requires, shared=True)
try:
requires = self._hook.get_requires_for_build_editable(config_settings)
self.install(requires)
filename = self._hook.prepare_metadata_for_build_editable(
out_dir, config_settings
)
filename = self._hook.prepare_metadata_for_build_editable(out_dir, config_settings)
except HookMissing:
self.init_build_system(self.FALLBACK_BACKEND)
return self.prepare_metadata(out_dir, config_settings)
Expand All @@ -52,14 +46,9 @@ def build(
try:
requires = self._hook.get_requires_for_build_editable(config_settings)
self.install(requires)
filename = self._hook.build_editable(
out_dir, config_settings, metadata_directory
)
filename = self._hook.build_editable(out_dir, config_settings, metadata_directory)
except HookMissing:
logger.warning(
"The build backend doesn't support PEP 660, falling back to "
"setuptools-pep660"
)
logger.warning("The build backend doesn't support PEP 660, falling back to setuptools-pep660")
self.init_build_system(self.FALLBACK_BACKEND)
return self.build(out_dir, config_settings, metadata_directory)
return os.path.join(out_dir, filename)
4 changes: 1 addition & 3 deletions src/pdm/builders/wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
class WheelBuilder(EnvBuilder):
"""Build wheel in isolated env with managed Python."""

def prepare_metadata(
self, out_dir: str, config_settings: Mapping[str, Any] | None = None
) -> str:
def prepare_metadata(self, out_dir: str, config_settings: Mapping[str, Any] | None = None) -> str:
self.install(self._requires, shared=True)
requires = self._hook.get_requires_for_build_wheel(config_settings)
self.install(requires)
Expand Down
Loading

0 comments on commit f6cc4eb

Please sign in to comment.