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

469 add initial cwd to session properties #472

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions nox/_option_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def __init__(
self,
name: str,
*flags: str,
group: OptionGroup,
group: Optional[OptionGroup],
help: Optional[str] = None,
noxfile: bool = False,
merge_func: Optional[Callable[[Namespace, Namespace], Any]] = None,
Expand Down Expand Up @@ -230,9 +230,15 @@ def parser(self) -> ArgumentParser:
}

for option in self.options.values():
if option.hidden:
if option.hidden is True:
continue

# Every option must have a group (except for hidden options)
if option.group is None:
raise ValueError(
f"Option {option.name} must either have a group or be hidden."
)

argument = groups[option.group.name].add_argument(
*option.flags, help=option.help, default=option.default, **option.kwargs
)
Expand Down
8 changes: 8 additions & 0 deletions nox/_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,14 @@ def _session_completer(
hidden=True,
finalizer_func=_color_finalizer,
),
# Stores the original working directory that Nox was invoked from,
# since it could be different from the Noxfile's directory.
_option_set.Option(
"invoked_from",
group=None,
hidden=True,
default=lambda: os.getcwd(),
),
)


Expand Down
12 changes: 12 additions & 0 deletions nox/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,18 @@ def interactive(self) -> bool:
"""Returns True if Nox is being run in an interactive session or False otherwise."""
return not self._runner.global_config.non_interactive and sys.stdin.isatty()

@property
def invoked_from(self) -> str:
"""The directory that Nox was originally invoked from.

Since you can use the ``--noxfile / -f`` command-line
argument to run a Noxfile in a location different from your shell's
current working directory, Nox automatically changes the working directory
to the Noxfile's directory before running any sessions. This gives
you the original working directory that Nox was invoked form.
"""
return self._runner.global_config.invoked_from

def chdir(self, dir: Union[str, os.PathLike]) -> None:
"""Change the current working directory."""
self.log(f"cd {dir}")
Expand Down
3 changes: 2 additions & 1 deletion nox/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ def load_nox_module(global_config: Namespace) -> Union[types.ModuleType, int]:
# Move to the path where the Noxfile is.
# This will ensure that the Noxfile's path is on sys.path, and that
# import-time path resolutions work the way the Noxfile author would
# guess.
# guess. The original working directory (the directory that Nox was
# invoked from) gets stored by the .invoke_from "option" in _options.
os.chdir(noxfile_parent_dir)
return importlib.machinery.SourceFileLoader(
"user_nox_module", global_config.noxfile
Expand Down
23 changes: 23 additions & 0 deletions tests/test__option_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,29 @@ def test_namespace_non_existant_options_with_values(self):
with pytest.raises(KeyError):
optionset.namespace(non_existant_option="meep")

def test_parser_hidden_option(self):
optionset = _option_set.OptionSet()
optionset.add_options(
_option_set.Option(
"oh_boy_i_am_hidden", hidden=True, group=None, default="meep"
)
)

parser = optionset.parser()
namespace = parser.parse_args([])
optionset._finalize_args(namespace)

assert namespace.oh_boy_i_am_hidden == "meep"

def test_parser_groupless_option(self):
optionset = _option_set.OptionSet()
optionset.add_options(
_option_set.Option("oh_no_i_have_no_group", group=None, default="meep")
)

with pytest.raises(ValueError):
optionset.parser()

def test_session_completer(self):
parsed_args = _options.options.namespace(sessions=(), keywords=(), posargs=[])
all_nox_sessions = _options._session_completer(
Expand Down
17 changes: 16 additions & 1 deletion tests/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ def make_session_and_runner(self):
signatures=["test"],
func=func,
global_config=_options.options.namespace(
posargs=[], error_on_external_run=False, install_only=False
posargs=[],
error_on_external_run=False,
install_only=False,
invoked_from=os.getcwd(),
),
manifest=mock.create_autospec(nox.manifest.Manifest),
)
Expand Down Expand Up @@ -104,6 +107,7 @@ def test_properties(self):
assert session.bin_paths is runner.venv.bin_paths
assert session.bin is runner.venv.bin_paths[0]
assert session.python is runner.func.python
assert session.invoked_from is runner.global_config.invoked_from

def test_no_bin_paths(self):
session, runner = self.make_session_and_runner()
Expand Down Expand Up @@ -155,6 +159,17 @@ def test_chdir(self, tmpdir):
assert os.getcwd() == cdto
os.chdir(current_cwd)

def test_invoked_from(self, tmpdir):
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()

session, _ = self.make_session_and_runner()

session.chdir(cdto)

assert session.invoked_from == current_cwd
os.chdir(current_cwd)

def test_chdir_pathlib(self, tmpdir):
cdto = str(tmpdir.join("cdbby").ensure(dir=True))
current_cwd = os.getcwd()
Expand Down