Skip to content

Commit

Permalink
Merge pull request #5873 from cclauss/ruff-rules-SIM
Browse files Browse the repository at this point in the history
ruff rules SIM
  • Loading branch information
matteius committed Aug 30, 2023
2 parents a6cf499 + 22223f0 commit 16334c9
Show file tree
Hide file tree
Showing 29 changed files with 195 additions and 235 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ repos:
exclude: .patch

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.285
rev: v0.0.286
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
8 changes: 4 additions & 4 deletions pipenv/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def expand_egg_links(self) -> None:
if not loc.exists():
continue
for pth in loc.iterdir():
if not pth.suffix == ".egg-link":
if pth.suffix != ".egg-link":
continue
contents = [
normalize_path(line.strip()) for line in pth.read_text().splitlines()
Expand Down Expand Up @@ -688,10 +688,10 @@ def get_package_requirements(self, pkg=None):

tree = PackageDAG.from_pkgs(packages).sort()
branch_keys = {r.key for r in flatten(tree.values())}
if pkg is not None:
nodes = [p for p in tree.keys() if p.key == pkg]
if pkg is None:
nodes = [p for p in tree if p.key not in branch_keys]
else:
nodes = [p for p in tree.keys() if p.key not in branch_keys]
nodes = [p for p in tree if p.key == pkg]
key_tree = {k.key: v for k, v in tree.items()}

return [self._get_requirements_for_package(p, key_tree) for p in nodes]
Expand Down
6 changes: 3 additions & 3 deletions pipenv/environments.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def __init__(self) -> None:
_spinners.SPINNERS[None] = {"interval": 80, "frames": " "}
self.PIPENV_SPINNER = None
else:
pipenv_spinner = "dots" if not os.name == "nt" else "bouncingBar"
pipenv_spinner = "bouncingBar" if os.name == "nt" else "dots"
self.PIPENV_SPINNER = get_from_env(
"SPINNER", check_for_negation=False, default=pipenv_spinner
)
Expand Down Expand Up @@ -397,10 +397,10 @@ def __init__(self) -> None:
del self.PIPENV_VERBOSE

def is_verbose(self, threshold=1):
return self.PIPENV_VERBOSITY >= threshold
return threshold <= self.PIPENV_VERBOSITY

def is_quiet(self, threshold=-1):
return self.PIPENV_VERBOSITY <= threshold
return threshold >= self.PIPENV_VERBOSITY


def is_using_venv() -> bool:
Expand Down
15 changes: 7 additions & 8 deletions pipenv/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
except ImportError:
from pipenv.vendor import tomli as toml

import contextlib

from pipenv.cmdparse import Script
from pipenv.environment import Environment
from pipenv.environments import Setting, is_in_virtualenv, normalize_pipfile_path
Expand Down Expand Up @@ -208,10 +210,8 @@ def __init__(self, python_version=None, chdir=True):

# Hack to skip this during pipenv run, or -r.
if ("run" not in sys.argv) and chdir:
try:
with contextlib.suppress(TypeError, AttributeError):
os.chdir(self.project_directory)
except (TypeError, AttributeError):
pass

def path_to(self, p: str) -> str:
"""Returns the absolute path to a given relative path."""
Expand Down Expand Up @@ -1079,7 +1079,7 @@ def get_package_name_in_pipfile(self, package_name, category):
if section is None:
section = {}
package_name = pep423_name(package_name)
for name in section.keys():
for name in section:
if pep423_name(name) == package_name:
return name
return None
Expand Down Expand Up @@ -1218,10 +1218,9 @@ def add_index_to_pipfile(self, index, verify_ssl=True):
try:
source = self.get_source(url=index)
except SourceNotFound:
try:
with contextlib.suppress(SourceNotFound):
source = self.get_source(name=index)
except SourceNotFound:
pass

if source is not None:
return source["name"]
source = {"url": index, "verify_ssl": verify_ssl}
Expand Down Expand Up @@ -1312,7 +1311,7 @@ def proper_case_section(self, section):
"""
# Casing for section.
changed_values = False
unknown_names = [k for k in section.keys() if k not in set(self.proper_names)]
unknown_names = [k for k in section if k not in set(self.proper_names)]
# Replace each package with proper casing.
for dep in unknown_names:
try:
Expand Down
10 changes: 4 additions & 6 deletions pipenv/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ def pipfile_name(self):

@property
def is_in_pipfile(self):
return True if self.pipfile_name else False
return bool(self.pipfile_name)

@property
def pipfile_packages(self):
Expand Down Expand Up @@ -315,7 +315,7 @@ def create(
def clean_specifier(specifier):
from pipenv.patched.pip._vendor.packaging.specifiers import Specifier

if not any(specifier.startswith(k) for k in Specifier._operators.keys()):
if not any(specifier.startswith(k) for k in Specifier._operators):
if specifier.strip().lower() in ["any", "<any>", "*"]:
return "*"
specifier = f"=={specifier}"
Expand All @@ -327,14 +327,12 @@ def clean_specifier(specifier):
def strip_version(specifier):
from pipenv.patched.pip._vendor.packaging.specifiers import Specifier

op = next(
iter(k for k in Specifier._operators.keys() if specifier.startswith(k)), None
)
op = next(iter(k for k in Specifier._operators if specifier.startswith(k)), None)
if op:
specifier = specifier[len(op) :]
while op:
op = next(
iter(k for k in Specifier._operators.keys() if specifier.startswith(k)),
iter(k for k in Specifier._operators if specifier.startswith(k)),
None,
)
if op:
Expand Down
2 changes: 1 addition & 1 deletion pipenv/routines/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def do_graph(project, bare=False, json=False, json_tree=False, reverse=False):
except RuntimeError:
pass
else:
if not os.name == "nt": # bugfix #4388
if os.name != "nt": # bugfix #4388
python_path = Path(python_path).as_posix()
pipdeptree_path = Path(pipdeptree_path).as_posix()

Expand Down
13 changes: 6 additions & 7 deletions pipenv/routines/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,13 +604,12 @@ def do_init(
if categories is None:
categories = []

if not system and not project.s.PIPENV_USE_SYSTEM:
if not project.virtualenv_exists:
try:
do_create_virtualenv(project, python=python, pypi_mirror=pypi_mirror)
except KeyboardInterrupt:
cleanup_virtualenv(project, bare=False)
sys.exit(1)
if not system and not project.s.PIPENV_USE_SYSTEM and not project.virtualenv_exists:
try:
do_create_virtualenv(project, python=python, pypi_mirror=pypi_mirror)
except KeyboardInterrupt:
cleanup_virtualenv(project, bare=False)
sys.exit(1)
# Ensure the Pipfile exists.
if not deploy:
ensure_pipfile(project, system=system)
Expand Down
6 changes: 3 additions & 3 deletions pipenv/routines/lock.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import contextlib

from pipenv.utils.dependencies import (
get_pipfile_category_using_lockfile_section,
)
Expand Down Expand Up @@ -54,10 +56,8 @@ def do_lock(
)

# Prune old lockfile category as new one will be created.
try:
with contextlib.suppress(KeyError):
old_lock_data = lockfile.pop(category)
except KeyError:
pass

from pipenv.utils.resolver import venv_resolve_deps

Expand Down
23 changes: 11 additions & 12 deletions pipenv/utils/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,14 @@ def load_dot_env(project, as_dict=False, quiet=False):

def ensure_environment():
# Skip this on Windows...
if os.name != "nt":
if "LANG" not in os.environ:
click.echo(
"{}: the environment variable {} is not set!"
"\nWe recommend setting this in {} (or equivalent) for "
"proper expected behavior.".format(
click.style("Warning", fg="red", bold=True),
click.style("LANG", bold=True),
click.style("~/.profile", fg="green"),
),
err=True,
)
if os.name != "nt" and "LANG" not in os.environ:
click.echo(
"{}: the environment variable {} is not set!"
"\nWe recommend setting this in {} (or equivalent) for "
"proper expected behavior.".format(
click.style("Warning", fg="red", bold=True),
click.style("LANG", bold=True),
click.style("~/.profile", fg="green"),
),
err=True,
)
7 changes: 2 additions & 5 deletions pipenv/utils/fileutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,9 @@ def create_tracked_tempdir(*args: Any, **kwargs: Any) -> str:
def check_for_unc_path(path):
# type: (Path) -> bool
"""Checks to see if a pathlib `Path` object is a unc path or not."""
if (
return bool(
os.name == "nt"
and len(path.drive) > 2
and not path.drive[0].isalpha()
and path.drive[1] != ":"
):
return True
else:
return False
)
13 changes: 6 additions & 7 deletions pipenv/utils/funktools.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,13 +348,12 @@ def handle_remove_readonly(func, path, exc):
try:
func(path)
except (OSError, FileNotFoundError, PermissionError) as e: # noqa:B014
if e.errno in PERM_ERRORS:
if e.errno != errno.ENOENT: # File still exists
warnings.warn(
default_warning_message.format(path),
ResourceWarning,
stacklevel=2,
)
if e.errno in PERM_ERRORS and e.errno != errno.ENOENT: # File still exists
warnings.warn(
default_warning_message.format(path),
ResourceWarning,
stacklevel=2,
)
return
else:
raise exc_exception
17 changes: 6 additions & 11 deletions pipenv/utils/locking.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import itertools
import os
import stat
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from json import JSONDecodeError
from pathlib import Path
from tempfile import NamedTemporaryFile
Expand Down Expand Up @@ -61,10 +61,7 @@ def format_requirement_for_lockfile(
if req.link and req.link.is_vcs:
vcs = req.link.scheme.split("+", 1)[0]
entry["ref"] = determine_vcs_revision_hash(req, vcs, pipfile_entry.get("ref"))
if name in original_deps:
entry[vcs] = original_deps[name]
else:
entry[vcs] = req.link.url
entry[vcs] = original_deps.get(name, req.link.url)
if pipfile_entry.get("subdirectory"):
entry["subdirectory"] = pipfile_entry["subdirectory"]
if req.req:
Expand Down Expand Up @@ -218,18 +215,16 @@ def atomic_open_for_write(target, binary=False, newline=None, encoding=None) ->
delete=False,
)
# set permissions to 0644
try:
with suppress(OSError):
os.chmod(f.name, stat.S_IWUSR | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
except OSError:
pass

try:
yield f
except BaseException:
f.close()
try:
with suppress(OSError):
os.remove(f.name)
except OSError:
pass

raise
else:
f.close()
Expand Down
9 changes: 4 additions & 5 deletions pipenv/utils/markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def make_marker(cls, marker_string):
@classmethod
def from_pipfile(cls, name, pipfile):
attr_fields = list(cls.__fields__)
found_keys = [k for k in pipfile.keys() if k in attr_fields]
found_keys = [k for k in pipfile if k in attr_fields]
marker_strings = [f"{k} {pipfile[k]}" for k in found_keys]
if pipfile.get("markers"):
marker_strings.append(pipfile.get("markers"))
Expand Down Expand Up @@ -399,9 +399,8 @@ def _markers_contains_key(markers, key):
for element in reversed(markers):
if isinstance(element, tuple) and element[0].value == key:
return True
elif isinstance(element, list):
if _markers_contains_key(element, key):
return True
elif isinstance(element, list) and _markers_contains_key(element, key):
return True
return False


Expand Down Expand Up @@ -628,7 +627,7 @@ def normalize_marker_str(marker) -> str:


def marker_from_specifier(spec) -> Marker:
if not any(spec.startswith(k) for k in Specifier._operators.keys()):
if not any(spec.startswith(k) for k in Specifier._operators):
if spec.strip().lower() in ["any", "<any>", "*"]:
return None
spec = f"=={spec}"
Expand Down
2 changes: 1 addition & 1 deletion pipenv/utils/pip.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def get_pip_args(
"src_dir": src_dir,
}
arg_set = ["--no-input"] if project.settings.get("disable_pip_input", True) else []
for key in arg_map.keys():
for key in arg_map:
if key in locals() and locals().get(key):
arg_set.extend(arg_map.get(key))
arg_set += extra_pip_args or []
Expand Down
23 changes: 9 additions & 14 deletions pipenv/utils/pipfile.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import io
import itertools
import os
Expand Down Expand Up @@ -55,11 +56,10 @@ def find_pipfile(max_depth=3):
for c, _, _ in walk_up(os.getcwd()):
i += 1

if i < max_depth:
if "Pipfile":
p = os.path.join(c, "Pipfile")
if os.path.isfile(p):
return p
if i < max_depth and "Pipfile":
p = os.path.join(c, "Pipfile")
if os.path.isfile(p):
return p
raise RuntimeError("No Pipfile found!")


Expand Down Expand Up @@ -190,10 +190,8 @@ def validate(cls, data):
for key, klass in pipfiles.PIPFILE_SECTIONS.items():
if key not in data or key == "sources":
continue
try:
with contextlib.suppress(Exception):
klass.validate(data[key])
except Exception:
pass

@classmethod
def ensure_package_sections(cls, data):
Expand All @@ -207,9 +205,7 @@ def ensure_package_sections(cls, data):
sections are present
:rtype: :class:`~tomlkit.toml_document.TOMLDocument`
"""
package_keys = (
k for k in pipfiles.PIPFILE_SECTIONS.keys() if k.endswith("packages")
)
package_keys = (k for k in pipfiles.PIPFILE_SECTIONS if k.endswith("packages"))
for key in package_keys:
if key not in data:
data.update({key: tomlkit.table()})
Expand Down Expand Up @@ -401,9 +397,8 @@ def load_projectfile(cls, path, create=False):
project_path = pipfile_path.parent
if not project_path.exists():
raise FileNotFoundError("%s is not a valid project path!" % path)
elif not pipfile_path.exists() or not pipfile_path.is_file():
if not create:
raise RequirementError("%s is not a valid Pipfile" % pipfile_path)
elif (not pipfile_path.exists() or not pipfile_path.is_file()) and not create:
raise RequirementError("%s is not a valid Pipfile" % pipfile_path)
return cls.read_projectfile(pipfile_path.as_posix())

@classmethod
Expand Down

0 comments on commit 16334c9

Please sign in to comment.