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

Run commands from within a specific directory #512

Closed
cblegare opened this issue Dec 9, 2021 · 1 comment · Fixed by #543
Closed

Run commands from within a specific directory #512

cblegare opened this issue Dec 9, 2021 · 1 comment · Fixed by #543

Comments

@cblegare
Copy link

cblegare commented Dec 9, 2021

How would this feature be useful?

Since many commands have specific usages of the current working directory,
running commands from within a specific directory would smooth integrating nox
is existing projects.

Describe the solution you'd like

from pathlib import Path

import nox


@nox.session()
def test(session: nox.Session):
    session.install('pytest')
    python_package_root = Path("somewhere/deep/in/monorepo")
    session.run(sys.executable, "-m", "pytest", cwd=python_package_root)

Describe alternatives you've considered

import os
from pathlib import Path

import nox


@nox.session()
def test(session: nox.Session):
    session.install('pytest')
    python_package_root = Path("somewhere/deep/in/monorepo")
    before_cwd = os.getcwd()
    os.chdir(python_package_root)
    session.run(sys.executable, "-m", "pytest")
    os.chdir(before_cwd)
@cblegare cblegare changed the title Add 'cwd' kwarg to the run() API Run commands from within a specific directory Dec 9, 2021
@cblegare
Copy link
Author

cblegare commented Dec 9, 2021

As a workaround, see the following context manager implementation

from contextlib import contextmanager
from pathlib import Path
from typing import Union
import os

import nox


@nox.session()
def test(session: nox.Session):
    session.install('pytest')
    with current_working_directory(Path("somewhere/deep/in/monorepo")):
        session.run(sys.executable, "-m", "pytest")


@contextmanager
def current_working_directory(path: Union[Path, str]):
    """Sets the cwd within the context

    Args:
        path: The path to the cwd

    Yields:
        None
    """

    origin = Path().absolute()
    try:
        os.chdir(path)
        yield
    finally:
        os.chdir(origin)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
2 participants