Skip to content

Commit

Permalink
Add session.invoked_from (#472)
Browse files Browse the repository at this point in the history
* Add original cwd to session properties

* Fix test

* Rename original_wd to invoked_from

* Hoist invoked_from up to the options parser

* Add test case for hidden options

* Add test case for groupless options

Co-authored-by: Thea Flowers <me@thea.codes>
  • Loading branch information
franekmagiera and theacodes committed Sep 11, 2021
1 parent 9c696e2 commit 74f8793
Show file tree
Hide file tree
Showing 6 changed files with 69 additions and 4 deletions.
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

0 comments on commit 74f8793

Please sign in to comment.