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

refactor: drop path.py #592

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,13 @@ jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-20.04, windows-2019]
python-version: ["3.7", "3.8", "3.9", "3.10"]
include:
- os: macos-latest
python-version: "3.9"
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
Expand Down
17 changes: 7 additions & 10 deletions nox/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@

import os
import shlex
import shutil
import sys
from typing import Any, Iterable, Sequence

import py

from nox.logger import logger
from nox.popen import popen

Expand All @@ -40,18 +39,16 @@ def __init__(self, reason: str | None = None) -> None:

def which(program: str, paths: list[str] | None) -> str:
"""Finds the full path to an executable."""
full_path = None

if paths:
full_path = py.path.local.sysfind(program, paths=paths)

if full_path:
return full_path.strpath
if paths is not None:
full_path = shutil.which(program, path=os.pathsep.join(paths))
if full_path:
return full_path

full_path = py.path.local.sysfind(program)
full_path = shutil.which(program)

if full_path:
return full_path.strpath
return full_path

logger.error(f"Program {program} not found.")
raise CommandFailed(f"Program {program} not found")
Expand Down
22 changes: 15 additions & 7 deletions nox/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from __future__ import annotations

import argparse
import contextlib
import enum
import hashlib
import os
Expand All @@ -23,9 +24,7 @@
import sys
import unicodedata
from types import TracebackType
from typing import Any, Callable, Iterable, Mapping, Sequence

import py
from typing import Any, Callable, Generator, Iterable, Mapping, Sequence

import nox.command
from nox import _typing
Expand All @@ -37,6 +36,17 @@
from nox.manifest import Manifest


@contextlib.contextmanager
def _chdir(path: str) -> Generator[None, None, None]:
"""Change the current working directory to the given path. Follows Python 3.11's chdir behavior."""
cwd = os.getcwd()
try:
os.chdir(path)
yield
finally:
os.chdir(cwd)


def _normalize_path(envdir: str, path: str | bytes) -> str:
"""Normalizes a string to be a "safe" filesystem path for a virtualenv."""
if isinstance(path, bytes):
Expand Down Expand Up @@ -713,11 +723,9 @@ def execute(self) -> Result:
try:
# By default, Nox should quietly change to the directory where
# the noxfile.py file is located.
cwd = py.path.local(
os.path.realpath(os.path.dirname(self.global_config.noxfile))
).as_cwd()
cwd_str = os.path.realpath(os.path.dirname(self.global_config.noxfile))

with cwd:
with _chdir(cwd_str):
self._create_venv()
session = Session(self)
self.func(session)
Expand Down
34 changes: 18 additions & 16 deletions nox/virtualenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@
import platform
import re
import shutil
import subprocess
import sys
from socket import gethostbyname
from typing import Any, Mapping

import py

import nox
import nox.command
from nox.logger import logger
Expand Down Expand Up @@ -109,12 +108,16 @@ def locate_via_py(version: str) -> str | None:
if it is found.
"""
script = "import sys; print(sys.executable)"
py_exe = py.path.local.sysfind("py")
py_exe = shutil.which("py")
if py_exe is not None:
try:
return py_exe.sysexec("-" + version, "-c", script).strip()
except py.process.cmdexec.Error:
return None
ret = subprocess.run(
[py_exe, f"-{version}", "-c", script],
check=False,
text=True,
capture_output=True,
)
if ret.returncode == 0 and ret.stdout:
return ret.stdout.strip()
return None


Expand All @@ -138,15 +141,14 @@ def locate_using_path_and_version(version: str) -> str | None:
return None

script = "import platform; print(platform.python_version())"
path_python = py.path.local.sysfind("python")
path_python = shutil.which("python")
if path_python:
try:
prefix = f"{version}."
version_string = path_python.sysexec("-c", script).strip()
if version_string.startswith(prefix):
return str(path_python)
except py.process.cmdexec.Error:
return None
prefix = f"{version}."
ret = subprocess.run(
[path_python, "-c", script], check=False, text=True, capture_output=True
)
if ret.returncode == 0 and ret.stdout and ret.stdout.strip().startswith(prefix):
return str(path_python)

return None

Expand Down Expand Up @@ -424,7 +426,7 @@ def _resolved_interpreter(self) -> str:
cleaned_interpreter = f"python{xy_version}"

# If the cleaned interpreter is on the PATH, go ahead and return it.
if py.path.local.sysfind(cleaned_interpreter):
if shutil.which(cleaned_interpreter):
self._resolved = cleaned_interpreter
return self._resolved

Expand Down
1 change: 0 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ install_requires =
argcomplete>=1.9.4,<3.0
colorlog>=2.6.1,<7.0.0
packaging>=20.9
py>=1.4.0,<2.0.0
virtualenv>=14.0.0
importlib-metadata;python_version < '3.8'
typing-extensions>=3.7.4;python_version < '3.8'
Expand Down
9 changes: 9 additions & 0 deletions tests/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import logging
import os
import platform
import shutil
import signal
import subprocess
import sys
Expand Down Expand Up @@ -48,6 +49,14 @@ def test_run_defaults(capsys):
assert result is True


@pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
def test_run_not_in_path(capsys):
# Paths falls back on the environment PATH if the command is not found.
result = nox.command.run(["git", "--version"], paths=["."])

assert result is True


def test_run_silent(capsys):
result = nox.command.run([PYTHON, "-c", "print(123)"], silent=True)

Expand Down
Loading