From bf0e4c5bddd982fe7deefdf458c7c3ae38fcf147 Mon Sep 17 00:00:00 2001 From: Eugene Kalinin Date: Sat, 31 Oct 2026 15:27:18 +0300 Subject: [PATCH 1/4] feat(nodeenv): print shell completion scripts with shtab --print-completion SHELL prints a completion script for bash, zsh, fish or PowerShell, made by shtab from the same parser that reads the command line. shtab is an optional dependency, installed with the completion extra, and only this flag imports it: without shtab the flag stays in --help and exits with the pip command to run. Out of the box shtab leaves fish and zsh with no candidates after the options that take a path, which is worse than no script at all, so the flag marks the file and directory options. It also suggests latest, lts and system for --node and latest for --npm. The script always completes nodeenv, also when python -m nodeenv prints it. Fixes #351 --- CHANGES | 4 + README.rst | 54 +++++ nodeenv.py | 48 ++++ requirements-dev.txt | 2 +- setup.py | 2 +- tests/test_completion.py | 460 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 568 insertions(+), 2 deletions(-) create mode 100644 tests/test_completion.py diff --git a/CHANGES b/CHANGES index d96adbf..18023bc 100644 --- a/CHANGES +++ b/CHANGES @@ -4,6 +4,10 @@ Nodeenv changelog Version [unreleased] -------------------- +- `--print-completion SHELL` prints a completion script for bash, zsh, + fish or PowerShell. It needs shtab, installed with + `pip install "nodeenv[completion]"` + `#351 `_ - `--prebuilt` installs no longer fail when the environment path or the node.js version contains `[`, `*` or `?` `#441 `_ diff --git a/README.rst b/README.rst index 7f6df92..9a3e418 100644 --- a/README.rst +++ b/README.rst @@ -100,6 +100,56 @@ In an unactivated PowerShell environment, use .. _pip: https://pypi.org/project/pip/ .. _pipx: https://pipx.pypa.io/ +Shell completion +^^^^^^^^^^^^^^^^ + +``nodeenv --print-completion SHELL`` prints a completion script for bash, +zsh, fish or PowerShell. It needs `shtab`_, which the ``completion`` extra +installs:: + + $ python -m pip install "nodeenv[completion]" + +With pipx, add shtab to nodeenv's environment instead:: + + $ pipx inject nodeenv shtab + +Then save the script where your shell loads it from. + +bash:: + + $ mkdir -p ~/.local/share/bash_completion + $ nodeenv --print-completion bash > ~/.local/share/bash_completion/nodeenv + $ echo 'source ~/.local/share/bash_completion/nodeenv' >> ~/.bashrc + +zsh, as ``_nodeenv`` in a directory on ``fpath``:: + + $ mkdir -p ~/.zfunc + $ nodeenv --print-completion zsh > ~/.zfunc/_nodeenv + +and in ``~/.zshrc``, before ``compinit`` runs:: + + fpath=(~/.zfunc $fpath) + +Instead of the file, ``~/.zshrc`` can run +``eval "$(nodeenv --print-completion zsh)"`` after ``compinit``, at the +cost of starting nodeenv in every new shell. Sourcing the script does not +work in zsh. + +fish:: + + $ nodeenv --print-completion fish > ~/.config/fish/completions/nodeenv.fish + +PowerShell:: + + PS> mkdir -Force ~\.config\powershell\completions + PS> nodeenv --print-completion powershell > ~\.config\powershell\completions\nodeenv.ps1 + +and in ``$PROFILE``:: + + . ~\.config\powershell\completions\nodeenv.ps1 + +.. _shtab: https://pypi.org/project/shtab/ + Dependency ---------- @@ -478,6 +528,10 @@ Other options $ SSL_CERT_FILE=$(python -c 'import certifi; print(certifi.where())') nodeenv env +``--print-completion=SHELL`` + Print the completion script for ``bash``, ``zsh``, ``fish`` or + ``powershell`` and exit. Needs shtab, see `Shell completion`_. + ``--version`` Show program version and exit. diff --git a/nodeenv.py b/nodeenv.py index 3154e8b..05eb525 100644 --- a/nodeenv.py +++ b/nodeenv.py @@ -422,6 +422,47 @@ def emit(self, record): logger = create_logger() +class PrintCompletionAction(argparse.Action): + """ + Print the shell completion script made by shtab and exit. + + shtab is imported only here, so nodeenv works without it. + """ + # options completed with file and with directory names + file_dests = ('requirements', 'local_requirements', 'config_file', + 'make_path') + dir_dests = ('python_virtualenv', 'env_dir') + + def __call__(self, parser, namespace, values, option_string=None): + try: + import shtab + except ImportError: + parser.error('shtab is not installed, run: ' + 'pip install "nodeenv[completion]"') + if values not in shtab.SUPPORTED_SHELLS or not hasattr(shtab, 'cmd'): + parser.error('the installed shtab cannot complete %s, run: ' + 'pip install -U "nodeenv[completion]"' % values) + + node_versions = 'echo latest; echo lts' + if not is_WIN: + # system node.js is not supported on Windows + node_versions += '; echo system' + for action in parser._actions: + if action.dest in self.file_dests: + action.complete = shtab.FILE + elif action.dest in self.dir_dests: + action.complete = shtab.DIRECTORY + elif action.dest == 'node': + action.complete = shtab.cmd(node_versions) + elif action.dest == 'npm': + action.complete = shtab.cmd('echo latest') + + # complete `nodeenv`, whatever command line started this run + parser.prog = 'nodeenv' + print(shtab.complete(parser, values)) + parser.exit() + + def make_parser(): """ Make a command line argument parser. @@ -432,6 +473,13 @@ def make_parser(): parser.add_argument( '--version', action='version', version=nodeenv_version) + parser.add_argument( + '--print-completion', action=PrintCompletionAction, + choices=('bash', 'zsh', 'fish', 'powershell'), metavar='SHELL', + help='Print the completion script for SHELL (bash, zsh, fish or ' + 'powershell) and exit. Needs shtab: ' + 'pip install "nodeenv[completion]"') + parser.add_argument( '-n', '--node', dest='node', metavar='NODE_VER', default=Config.node, help='The node.js version to use, e.g., ' diff --git a/requirements-dev.txt b/requirements-dev.txt index ac4466c..1fc46ae 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,4 @@ --e . +-e .[completion] coverage flake8 diff --git a/setup.py b/setup.py index 8b5cc0f..1bb945e 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ def read_file(file_name): author='Eugene Kalinin', author_email='e.v.kalinin@gmail.com', install_requires=[], - extras_require={'certifi': ['certifi']}, + extras_require={'certifi': ['certifi'], 'completion': ['shtab>=1.12.1']}, python_requires='>=3.10', description="Node.js virtual environment builder", long_description=ldesc, diff --git a/tests/test_completion.py b/tests/test_completion.py new file mode 100644 index 0000000..fb571bb --- /dev/null +++ b/tests/test_completion.py @@ -0,0 +1,460 @@ +""" +Tests for `nodeenv --print-completion SHELL`. + +The unit tests check the flag itself. The behavioural tests load the +printed script into bash, zsh, fish and PowerShell, ask the shell for the +candidates of a command line and check what it offers. +""" +import os +import select +import shutil +import subprocess +import sys +import time +import types + +from unittest import mock +import pytest + +import nodeenv + +shtab = pytest.importorskip('shtab') + +# CI sets this so a missing shell fails the run instead of skipping it +REQUIRE_SHELLS = os.environ.get('NODEENV_REQUIRE_SHELLS') == '1' + +# Require CI shells at collection time, before launching any subprocess +if REQUIRE_SHELLS: + _required = ('bash', 'zsh', 'fish', 'pwsh') + if nodeenv.is_WIN: + _required = ('pwsh',) + _missing = [name for name in _required if not shutil.which(name)] + if _missing: + raise RuntimeError('missing shells: %s' % ', '.join(_missing)) + +posix_only = pytest.mark.skipif( + nodeenv.is_WIN, reason='the shell under test is POSIX only') + +# options that take free text, there is nothing to complete for them +FREE_TEXT = ('mirror', 'jobs', 'load_average', 'prompt') + +NO_OPTIONS = {'--no-clean-src', '--no-npm-clean', '--no-parallel-extract'} + +# command line -> (candidates that must be offered, candidates that must +# not be); None in place of the second set means nothing else may be offered +CASES = { + 'nodeenv --no-': (NO_OPTIONS, None), + 'nodeenv -r ': ({'requirements.txt'}, set()), + 'nodeenv -p ': ({'envs'}, {'requirements.txt'}), + 'nodeenv --force ': ({'envs'}, set()), + 'nodeenv --node ': ( + {'latest', 'lts'} if nodeenv.is_WIN else {'latest', 'lts', 'system'}, + None), + 'nodeenv -n l': ({'latest', 'lts'}, None), + 'nodeenv --npm ': ({'latest'}, None), +} + +every_case = pytest.mark.parametrize('line', sorted(CASES)) + +# the file each shell loads the script from +SCRIPT_NAMES = { + 'bash': 'nodeenv.bash', + 'zsh': '_nodeenv', + 'fish': 'nodeenv.fish', + 'powershell': 'nodeenv.ps1', +} + + +def _binary(name): + """Path to the shell, or skip when it is not installed.""" + path = shutil.which(name) + if path: + return path + return pytest.skip('%s is not installed' % name) + + +def _names(candidates): + """Candidates without `./` or `.\\` in front and `/` or `\\` at the end.""" + result = set() + for candidate in candidates: + for prefix in ('./', '.\\'): + if candidate.startswith(prefix): + candidate = candidate[len(prefix):] + candidate = candidate.rstrip('/\\') + if candidate: + result.add(candidate) + return result + + +def _check(line, candidates): + offered, absent = CASES[line] + got = _names(candidates) + if absent is None: + assert got == offered + return + assert offered <= got + assert not absent & got + + +def _completion_action(parser): + return [a for a in parser._actions if a.dest == 'print_completion'][0] + + +def _print_in_process(shell, capsys): + """The script printed by the flag, as a string.""" + with pytest.raises(SystemExit) as excinfo: + nodeenv.make_parser().parse_args(['--print-completion', shell]) + assert excinfo.value.code == 0 + return capsys.readouterr().out + + +@pytest.fixture(scope='module') +def scripts(tmp_path_factory): + """ + Path to the script `python nodeenv.py --print-completion SHELL` + prints, made once per shell. + + Running the file rather than the `nodeenv` command also checks that + the script completes `nodeenv` and not `nodeenv.py`. + """ + made = {} + base = tmp_path_factory.mktemp('scripts') + + def get(shell): + if shell not in made: + out = subprocess.check_output( + [sys.executable, nodeenv.__file__, + '--print-completion', shell]) + path = base / shell / SCRIPT_NAMES[shell] + path.parent.mkdir() + path.write_bytes(out) + made[shell] = str(path) + return made[shell] + + return get + + +@pytest.fixture +def workdir(tmpdir): + """ + A directory with one file and one directory to complete, an empty + home and a stub `nodeenv` on PATH. + + The fish header of shtab asks for the command on PATH, and PowerShell + may not call a native completer for a command it cannot find. + """ + work = tmpdir.join('work').ensure(dir=True) + work.join('requirements.txt').write('') + work.join('envs').ensure(dir=True) + home = tmpdir.join('home').ensure(dir=True) + stub_dir = tmpdir.join('bin').ensure(dir=True) + if nodeenv.is_WIN: + stub_dir.join('nodeenv.cmd').write('@exit /b 0\r\n') + else: + stub = stub_dir.join('nodeenv') + stub.write('#!/bin/sh\nexit 0\n') + stub.chmod(0o755) + + # no user rc files, and bash sources BASH_ENV for `bash -c` + env = dict(os.environ) + env.pop('BASH_ENV', None) + env.update( + HOME=str(home), XDG_CONFIG_HOME=str(home), ZDOTDIR=str(home), + PATH=str(stub_dir) + os.pathsep + os.environ.get('PATH', '')) + return types.SimpleNamespace(path=str(work), home=str(home), env=env) + + +def _fish(script, line, workdir): + out = subprocess.check_output( + [_binary('fish'), '--no-config', '-c', + 'source $argv[1]; complete -C $argv[2]', script, line], + cwd=workdir.path, env=workdir.env) + return [row.split('\t')[0] for row in out.decode('utf-8').splitlines()] + + +# Calls the function the script registers for `nodeenv` the way bash does +# on Tab: $1 is the script, the rest are the words of the command line. +BASH_DRIVER = r''' +source "$1" +shift +spec=$(complete -p nodeenv) || exit 1 +fn=${spec##*-F } +fn=${fn%% *} +COMP_WORDS=("$@") +COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 )) +COMP_LINE="$*" +COMP_POINT=${#COMP_LINE} +"$fn" nodeenv "${COMP_WORDS[COMP_CWORD]}" "${COMP_WORDS[COMP_CWORD-1]}" +printf '%s\n' "${COMPREPLY[@]}" +''' + + +def _bash(script, line, workdir): + out = subprocess.check_output( + [_binary('bash'), '-c', BASH_DRIVER, 'bash', script] + + line.split(' '), + cwd=workdir.path, env=workdir.env) + return out.decode('utf-8').splitlines() + + +PWSH_DRIVER = ( + '. $env:NODEENV_TEST_SCRIPT; ' + '$line = $env:NODEENV_TEST_LINE; ' + '(TabExpansion2 -inputScript $line -cursorColumn $line.Length)' + '.CompletionMatches | ForEach-Object CompletionText') + + +def _pwsh(script, line, workdir): + env = dict(workdir.env, NODEENV_TEST_SCRIPT=script, + NODEENV_TEST_LINE=line) + out = subprocess.check_output( + [_binary('pwsh'), '-NoProfile', '-NonInteractive', '-Command', + PWSH_DRIVER], + cwd=workdir.path, env=env) + return out.decode('utf-8').splitlines() + + +# Sourced by an interactive zsh: loads the script the way README tells +# users to, then records every match completion adds into a file. +ZSH_SETUP = '''\ +bindkey -e +%(load)s +_nodeenv_capture() { + compadd() { + local -a matches + builtin compadd -O matches "$@" + print -rl -- $matches >> '%(capture)s' + builtin compadd "$@" + } +} +compprefuncs=(_nodeenv_capture) +print -r -- READY-$((6 * 7)) +''' + +ZSH_LOADERS = { + # the script as _nodeenv in a directory on fpath + 'fpath': ("fpath=('%(dir)s' $fpath)\n" + "autoload -Uz compinit && compinit -u -D"), + # the script evaluated after compinit + 'eval': ("autoload -Uz compinit && compinit -u -D\n" + "eval \"$(<'%(script)s')\""), +} + +ZSH_TIMEOUT = 20 + +# zsh turns bracketed paste on when its line editor starts reading a line +BRACKETED_PASTE = b'\x1b[?2004h' + + +def _read_until(fd, marker, output, start=0): + """ + Read the terminal until `marker` shows up in it after `start`, and + return the position right after the marker. + + The command line zsh echoes back holds `$((6 * 7))`, so only the output + of the command itself can contain READY-42 or DONE-42. + """ + deadline = time.time() + ZSH_TIMEOUT + while output.find(marker, start) < 0: + if time.time() > deadline: + raise AssertionError('no %r from zsh, got: %r' % ( + marker, bytes(output[-2000:]))) + ready, _, _ = select.select([fd], [], [], 0.1) + if ready: + try: + output.extend(os.read(fd, 65536)) + except OSError: + raise AssertionError('zsh exited: %r' % bytes(output)) + return output.find(marker, start) + len(marker) + + +def _zsh(script, line, workdir, load='fpath'): + """ + Type `line` and Tab into an interactive zsh and return the matches. + + zsh only completes in its line editor, so it runs on a pseudo terminal. + After Tab the test kills the line and runs a command that prints a + marker: zsh handles keys in order, so the marker means completion has + finished and every match is in the capture file. + """ + import pty + + capture = os.path.join(workdir.home, 'candidates') + setup = os.path.join(workdir.home, 'setup.zsh') + with open(setup, 'w') as f: + f.write(ZSH_SETUP % { + 'load': ZSH_LOADERS[load] % { + 'dir': os.path.dirname(script), 'script': script}, + 'capture': capture, + }) + + master, slave = pty.openpty() + proc = subprocess.Popen( + [_binary('zsh'), '-f', '-i'], + stdin=slave, stdout=slave, stderr=slave, + cwd=workdir.path, env=dict(workdir.env, TERM='xterm'), + close_fds=True) + os.close(slave) + output = bytearray() + try: + os.write(master, ("source '%s'\n" % setup).encode()) + ready = _read_until(master, b'READY-42', output) + # Keys typed before the line editor takes the terminal go through + # the terminal driver, which keeps Ctrl+U for itself + _read_until(master, BRACKETED_PASTE, output, ready) + # Ctrl+U kills the line in the emacs keymap + os.write(master, ( + line + '\t\x15print -r -- DONE-$((6 * 7))\n').encode()) + _read_until(master, b'DONE-42', output) + finally: + proc.kill() + proc.wait() + os.close(master) + + if not os.path.exists(capture): + return [] + with open(capture) as f: + return f.read().splitlines() + + +def test_help_shows_the_flag_without_shtab(): + with mock.patch.dict(sys.modules, {'shtab': None}): + help_text = nodeenv.make_parser().format_help() + assert '--print-completion SHELL' in help_text + assert 'powershell' in help_text + + +def test_unknown_shell_is_rejected(capsys): + with pytest.raises(SystemExit) as excinfo: + nodeenv.make_parser().parse_args(['--print-completion', 'tcsh']) + assert excinfo.value.code == 2 + assert 'powershell' in capsys.readouterr().err + + +@pytest.mark.parametrize('shell', ('bash', 'zsh', 'fish', 'powershell')) +def test_main_prints_the_script_without_dest_dir( + shell, tmpdir, monkeypatch, capsys): + monkeypatch.chdir(tmpdir) + argv = ['nodeenv', '--print-completion', shell] + with mock.patch.object(sys, 'argv', argv): + with pytest.raises(SystemExit) as excinfo: + nodeenv.main() + assert excinfo.value.code == 0 + assert 'nodeenv' in capsys.readouterr().out + assert tmpdir.listdir() == [] + + +def test_without_shtab_names_the_extra(capsys): + with mock.patch.dict(sys.modules, {'shtab': None}): + with pytest.raises(SystemExit) as excinfo: + nodeenv.make_parser().parse_args(['--print-completion', 'fish']) + assert excinfo.value.code == 2 + out, err = capsys.readouterr() + assert out == '' + assert 'pip install "nodeenv[completion]"' in err + + +def _shtab_without_powershell(monkeypatch): + # shtab 1.11 knows fish, but not PowerShell (1.12) + monkeypatch.setattr( + shtab, 'SUPPORTED_SHELLS', ['bash', 'zsh', 'tcsh', 'fish']) + return 'powershell' + + +def _shtab_without_cmd(monkeypatch): + # shtab 1.9 knows fish, but not shtab.cmd (1.10) + monkeypatch.delattr(shtab, 'cmd') + return 'fish' + + +@pytest.mark.parametrize( + 'make_old', (_shtab_without_powershell, _shtab_without_cmd), + ids=('no-powershell', 'no-cmd')) +def test_old_shtab_asks_for_an_upgrade(make_old, monkeypatch, capsys): + shell = make_old(monkeypatch) + with pytest.raises(SystemExit) as excinfo: + nodeenv.make_parser().parse_args(['--print-completion', shell]) + assert excinfo.value.code == 2 + out, err = capsys.readouterr() + assert out == '' + assert 'pip install -U "nodeenv[completion]"' in err + + +def test_every_option_with_a_value_is_classified(): + """ + A new option that takes a path has to be marked, or fish and zsh + offer nothing after it. + """ + parser = nodeenv.make_parser() + action = _completion_action(parser) + marked = set(action.file_dests + action.dir_dests + ('node', 'npm')) + for option in parser._actions: + if option.nargs == 0 or option.choices: + continue + assert option.dest in marked | set(FREE_TEXT), option.dest + if not nodeenv.is_WIN: + # a renamed dest would silently lose its mark + assert marked <= set(a.dest for a in parser._actions) + + +@posix_only +@every_case +def test_fish(line, scripts, workdir): + _check(line, _fish(scripts('fish'), line, workdir)) + + +@posix_only +@every_case +def test_bash(line, scripts, workdir): + _check(line, _bash(scripts('bash'), line, workdir)) + + +@posix_only +@every_case +def test_zsh(line, scripts, workdir): + _check(line, _zsh(scripts('zsh'), line, workdir)) + + +@posix_only +def test_zsh_eval(scripts, workdir): + line = 'nodeenv --no-' + _check(line, _zsh(scripts('zsh'), line, workdir, load='eval')) + + +@every_case +def test_pwsh(line, scripts, workdir): + _check(line, _pwsh(scripts('powershell'), line, workdir)) + + +@posix_only +def test_module_run_completes_nodeenv(workdir, tmpdir): + env = dict(os.environ, PYTHONPATH=os.path.dirname(nodeenv.__file__)) + out = subprocess.check_output( + [sys.executable, '-m', 'nodeenv', '--print-completion', 'fish'], + cwd=str(tmpdir), env=env) + script = tmpdir.join('nodeenv.fish') + script.write_binary(out) + assert _names(_fish(str(script), 'nodeenv --no-', workdir)) == NO_OPTIONS + + +@posix_only +def test_windows_script(scripts, workdir, tmpdir, capsys): + """ + The script follows the platform it is printed on: no `system` node and + no Unix-only options on Windows. + """ + with mock.patch.object(nodeenv, 'is_WIN', True): + out = _print_in_process('fish', capsys) + script = tmpdir.join('nodeenv.fish') + script.write(out) + + node = _fish(str(script), 'nodeenv --node ', workdir) + assert _names(node) == {'latest', 'lts'} + # a prefix every option matches, so fish does not fall back to fuzzy + # matching + unix_only = {'--source', '--jobs', '--make'} + windows = _names(_fish(str(script), 'nodeenv --', workdir)) + assert '--prebuilt' in windows + assert not unix_only & windows + unix = _names(_fish(scripts('fish'), 'nodeenv --', workdir)) + assert unix_only <= unix From 7a78d9c20ee558df5a92118cfd7d83bf05099016 Mon Sep 17 00:00:00 2001 From: Eugene Kalinin Date: Sat, 31 Oct 2026 15:27:23 +0300 Subject: [PATCH 2/4] chore(ci): run the shell completion tests The activate-shells job already installs zsh and fish, and the ubuntu image ships bash and pwsh, so it runs tests/test_completion.py with NODEENV_REQUIRE_SHELLS=1: a missing shell fails the job instead of skipping its tests. --- .github/workflows/tests.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 449c8ef..2e4c7ce 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -64,6 +64,12 @@ jobs: run: | pytest tests/test_activate_shells.py -v + - name: Run shell completion tests + env: + NODEENV_REQUIRE_SHELLS: '1' + run: | + pytest tests/test_completion.py -v + # The only job that builds real node environments: the tests marked # `integration` are deselected everywhere else. Deliberately ubuntu # only - the install path is also platform specific, so macOS and From b8c699e93a969b90c8b90fde327f126c3f1dabdc Mon Sep 17 00:00:00 2001 From: Eugene Kalinin Date: Sat, 31 Oct 2026 15:51:49 +0300 Subject: [PATCH 3/4] fix(nodeenv): leave -c out of the PowerShell completion script pwsh refused the script: shtab keys its PowerShell tables by option string, PowerShell hash keys ignore case, and -c (--clean-src) clashed with -C (--config-file). The PowerShell script now leaves out -c; --clean-src and -C still complete. The other shells get the same script as before. --- nodeenv.py | 5 +++++ tests/test_completion.py | 2 ++ 2 files changed, 7 insertions(+) diff --git a/nodeenv.py b/nodeenv.py index 05eb525..0fc7362 100644 --- a/nodeenv.py +++ b/nodeenv.py @@ -456,6 +456,11 @@ def __call__(self, parser, namespace, values, option_string=None): action.complete = shtab.cmd(node_versions) elif action.dest == 'npm': action.complete = shtab.cmd('echo latest') + # shtab keys its PowerShell tables by option string, and + # PowerShell keys ignore case, so -c would clash with -C + if values == 'powershell' and action.dest == 'clean_src': + action.option_strings = [ + s for s in action.option_strings if s != '-c'] # complete `nodeenv`, whatever command line started this run parser.prog = 'nodeenv' diff --git a/tests/test_completion.py b/tests/test_completion.py index fb571bb..4c065f8 100644 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -44,6 +44,8 @@ # not be); None in place of the second set means nothing else may be offered CASES = { 'nodeenv --no-': (NO_OPTIONS, None), + 'nodeenv --clean': ({'--clean-src'}, None), + 'nodeenv -C ': ({'requirements.txt'}, set()), 'nodeenv -r ': ({'requirements.txt'}, set()), 'nodeenv -p ': ({'envs'}, {'requirements.txt'}), 'nodeenv --force ': ({'envs'}, set()), From df194b2ebc93e8ac9d58a785c6cd5c0bfcb69c8f Mon Sep 17 00:00:00 2001 From: Eugene Kalinin Date: Sat, 31 Oct 2026 16:08:11 +0300 Subject: [PATCH 4/4] fix(nodeenv): leave PowerShell out of shell completion for now shtab's PowerShell script had a second bug after the -c workaround: the completer switches to an option it meets and only goes back to the positional arguments once the option has taken its values, which a flag without a value never does. DEST_DIR was not completed after --force, --prebuilt and the like. --print-completion now offers bash, zsh and fish, and the -c workaround goes away with PowerShell. Without PowerShell the completion extra needs shtab 1.11, which passes tests/test_completion.py. PowerShell can come back once shtab fixes both bugs (https://github.com/tqdm/shtab/issues/267 for the first one). --- CHANGES | 5 +-- README.rst | 16 ++----- nodeenv.py | 12 ++---- setup.py | 2 +- tests/test_completion.py | 91 ++++++++++++---------------------------- 5 files changed, 36 insertions(+), 90 deletions(-) diff --git a/CHANGES b/CHANGES index 18023bc..6953da9 100644 --- a/CHANGES +++ b/CHANGES @@ -4,9 +4,8 @@ Nodeenv changelog Version [unreleased] -------------------- -- `--print-completion SHELL` prints a completion script for bash, zsh, - fish or PowerShell. It needs shtab, installed with - `pip install "nodeenv[completion]"` +- `--print-completion SHELL` prints a completion script for bash, zsh or + fish. It needs shtab, installed with `pip install "nodeenv[completion]"` `#351 `_ - `--prebuilt` installs no longer fail when the environment path or the node.js version contains `[`, `*` or `?` diff --git a/README.rst b/README.rst index 9a3e418..05e5cf1 100644 --- a/README.rst +++ b/README.rst @@ -104,8 +104,7 @@ Shell completion ^^^^^^^^^^^^^^^^ ``nodeenv --print-completion SHELL`` prints a completion script for bash, -zsh, fish or PowerShell. It needs `shtab`_, which the ``completion`` extra -installs:: +zsh or fish. It needs `shtab`_, which the ``completion`` extra installs:: $ python -m pip install "nodeenv[completion]" @@ -139,15 +138,6 @@ fish:: $ nodeenv --print-completion fish > ~/.config/fish/completions/nodeenv.fish -PowerShell:: - - PS> mkdir -Force ~\.config\powershell\completions - PS> nodeenv --print-completion powershell > ~\.config\powershell\completions\nodeenv.ps1 - -and in ``$PROFILE``:: - - . ~\.config\powershell\completions\nodeenv.ps1 - .. _shtab: https://pypi.org/project/shtab/ @@ -529,8 +519,8 @@ Other options $ SSL_CERT_FILE=$(python -c 'import certifi; print(certifi.where())') nodeenv env ``--print-completion=SHELL`` - Print the completion script for ``bash``, ``zsh``, ``fish`` or - ``powershell`` and exit. Needs shtab, see `Shell completion`_. + Print the completion script for ``bash``, ``zsh`` or ``fish`` and + exit. Needs shtab, see `Shell completion`_. ``--version`` Show program version and exit. diff --git a/nodeenv.py b/nodeenv.py index 0fc7362..1f77a23 100644 --- a/nodeenv.py +++ b/nodeenv.py @@ -456,11 +456,6 @@ def __call__(self, parser, namespace, values, option_string=None): action.complete = shtab.cmd(node_versions) elif action.dest == 'npm': action.complete = shtab.cmd('echo latest') - # shtab keys its PowerShell tables by option string, and - # PowerShell keys ignore case, so -c would clash with -C - if values == 'powershell' and action.dest == 'clean_src': - action.option_strings = [ - s for s in action.option_strings if s != '-c'] # complete `nodeenv`, whatever command line started this run parser.prog = 'nodeenv' @@ -480,10 +475,9 @@ def make_parser(): parser.add_argument( '--print-completion', action=PrintCompletionAction, - choices=('bash', 'zsh', 'fish', 'powershell'), metavar='SHELL', - help='Print the completion script for SHELL (bash, zsh, fish or ' - 'powershell) and exit. Needs shtab: ' - 'pip install "nodeenv[completion]"') + choices=('bash', 'zsh', 'fish'), metavar='SHELL', + help='Print the completion script for SHELL (bash, zsh or fish) ' + 'and exit. Needs shtab: pip install "nodeenv[completion]"') parser.add_argument( '-n', '--node', dest='node', metavar='NODE_VER', default=Config.node, diff --git a/setup.py b/setup.py index 1bb945e..466c3e1 100644 --- a/setup.py +++ b/setup.py @@ -37,7 +37,7 @@ def read_file(file_name): author='Eugene Kalinin', author_email='e.v.kalinin@gmail.com', install_requires=[], - extras_require={'certifi': ['certifi'], 'completion': ['shtab>=1.12.1']}, + extras_require={'certifi': ['certifi'], 'completion': ['shtab>=1.11']}, python_requires='>=3.10', description="Node.js virtual environment builder", long_description=ldesc, diff --git a/tests/test_completion.py b/tests/test_completion.py index 4c065f8..4c07d63 100644 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -2,8 +2,8 @@ Tests for `nodeenv --print-completion SHELL`. The unit tests check the flag itself. The behavioural tests load the -printed script into bash, zsh, fish and PowerShell, ask the shell for the -candidates of a command line and check what it offers. +printed script into bash, zsh and fish, ask the shell for the candidates +of a command line and check what it offers. """ import os import select @@ -24,11 +24,9 @@ REQUIRE_SHELLS = os.environ.get('NODEENV_REQUIRE_SHELLS') == '1' # Require CI shells at collection time, before launching any subprocess -if REQUIRE_SHELLS: - _required = ('bash', 'zsh', 'fish', 'pwsh') - if nodeenv.is_WIN: - _required = ('pwsh',) - _missing = [name for name in _required if not shutil.which(name)] +if REQUIRE_SHELLS and not nodeenv.is_WIN: + _missing = [name for name in ('bash', 'zsh', 'fish') + if not shutil.which(name)] if _missing: raise RuntimeError('missing shells: %s' % ', '.join(_missing)) @@ -44,14 +42,11 @@ # not be); None in place of the second set means nothing else may be offered CASES = { 'nodeenv --no-': (NO_OPTIONS, None), - 'nodeenv --clean': ({'--clean-src'}, None), 'nodeenv -C ': ({'requirements.txt'}, set()), 'nodeenv -r ': ({'requirements.txt'}, set()), 'nodeenv -p ': ({'envs'}, {'requirements.txt'}), 'nodeenv --force ': ({'envs'}, set()), - 'nodeenv --node ': ( - {'latest', 'lts'} if nodeenv.is_WIN else {'latest', 'lts', 'system'}, - None), + 'nodeenv --node ': ({'latest', 'lts', 'system'}, None), 'nodeenv -n l': ({'latest', 'lts'}, None), 'nodeenv --npm ': ({'latest'}, None), } @@ -63,7 +58,6 @@ 'bash': 'nodeenv.bash', 'zsh': '_nodeenv', 'fish': 'nodeenv.fish', - 'powershell': 'nodeenv.ps1', } @@ -76,16 +70,8 @@ def _binary(name): def _names(candidates): - """Candidates without `./` or `.\\` in front and `/` or `\\` at the end.""" - result = set() - for candidate in candidates: - for prefix in ('./', '.\\'): - if candidate.startswith(prefix): - candidate = candidate[len(prefix):] - candidate = candidate.rstrip('/\\') - if candidate: - result.add(candidate) - return result + """Candidates as a set, without the `/` fish puts after directories.""" + return set(c.rstrip('/') for c in candidates if c) def _check(line, candidates): @@ -142,20 +128,16 @@ def workdir(tmpdir): A directory with one file and one directory to complete, an empty home and a stub `nodeenv` on PATH. - The fish header of shtab asks for the command on PATH, and PowerShell - may not call a native completer for a command it cannot find. + The fish header of shtab asks for the command on PATH. """ work = tmpdir.join('work').ensure(dir=True) work.join('requirements.txt').write('') work.join('envs').ensure(dir=True) home = tmpdir.join('home').ensure(dir=True) stub_dir = tmpdir.join('bin').ensure(dir=True) - if nodeenv.is_WIN: - stub_dir.join('nodeenv.cmd').write('@exit /b 0\r\n') - else: - stub = stub_dir.join('nodeenv') - stub.write('#!/bin/sh\nexit 0\n') - stub.chmod(0o755) + stub = stub_dir.join('nodeenv') + stub.write('#!/bin/sh\nexit 0\n') + stub.chmod(0o755) # no user rc files, and bash sources BASH_ENV for `bash -c` env = dict(os.environ) @@ -199,23 +181,6 @@ def _bash(script, line, workdir): return out.decode('utf-8').splitlines() -PWSH_DRIVER = ( - '. $env:NODEENV_TEST_SCRIPT; ' - '$line = $env:NODEENV_TEST_LINE; ' - '(TabExpansion2 -inputScript $line -cursorColumn $line.Length)' - '.CompletionMatches | ForEach-Object CompletionText') - - -def _pwsh(script, line, workdir): - env = dict(workdir.env, NODEENV_TEST_SCRIPT=script, - NODEENV_TEST_LINE=line) - out = subprocess.check_output( - [_binary('pwsh'), '-NoProfile', '-NonInteractive', '-Command', - PWSH_DRIVER], - cwd=workdir.path, env=env) - return out.decode('utf-8').splitlines() - - # Sourced by an interactive zsh: loads the script the way README tells # users to, then records every match completion adds into a file. ZSH_SETUP = '''\ @@ -323,17 +288,21 @@ def test_help_shows_the_flag_without_shtab(): with mock.patch.dict(sys.modules, {'shtab': None}): help_text = nodeenv.make_parser().format_help() assert '--print-completion SHELL' in help_text - assert 'powershell' in help_text + # argparse wraps the help, so compare it with whitespace collapsed + assert '(bash, zsh or fish)' in ' '.join(help_text.split()) -def test_unknown_shell_is_rejected(capsys): +@pytest.mark.parametrize('shell', ('tcsh', 'powershell')) +def test_unsupported_shell_is_rejected(shell, capsys): with pytest.raises(SystemExit) as excinfo: - nodeenv.make_parser().parse_args(['--print-completion', 'tcsh']) + nodeenv.make_parser().parse_args(['--print-completion', shell]) assert excinfo.value.code == 2 - assert 'powershell' in capsys.readouterr().err + err = capsys.readouterr().err + assert 'invalid choice' in err + assert 'fish' in err -@pytest.mark.parametrize('shell', ('bash', 'zsh', 'fish', 'powershell')) +@pytest.mark.parametrize('shell', ('bash', 'zsh', 'fish')) def test_main_prints_the_script_without_dest_dir( shell, tmpdir, monkeypatch, capsys): monkeypatch.chdir(tmpdir) @@ -356,11 +325,10 @@ def test_without_shtab_names_the_extra(capsys): assert 'pip install "nodeenv[completion]"' in err -def _shtab_without_powershell(monkeypatch): - # shtab 1.11 knows fish, but not PowerShell (1.12) - monkeypatch.setattr( - shtab, 'SUPPORTED_SHELLS', ['bash', 'zsh', 'tcsh', 'fish']) - return 'powershell' +def _shtab_without_fish(monkeypatch): + # shtab 1.8 knows bash, zsh and tcsh, but not fish (1.9) + monkeypatch.setattr(shtab, 'SUPPORTED_SHELLS', ['bash', 'zsh', 'tcsh']) + return 'fish' def _shtab_without_cmd(monkeypatch): @@ -370,8 +338,8 @@ def _shtab_without_cmd(monkeypatch): @pytest.mark.parametrize( - 'make_old', (_shtab_without_powershell, _shtab_without_cmd), - ids=('no-powershell', 'no-cmd')) + 'make_old', (_shtab_without_fish, _shtab_without_cmd), + ids=('no-fish', 'no-cmd')) def test_old_shtab_asks_for_an_upgrade(make_old, monkeypatch, capsys): shell = make_old(monkeypatch) with pytest.raises(SystemExit) as excinfo: @@ -423,11 +391,6 @@ def test_zsh_eval(scripts, workdir): _check(line, _zsh(scripts('zsh'), line, workdir, load='eval')) -@every_case -def test_pwsh(line, scripts, workdir): - _check(line, _pwsh(scripts('powershell'), line, workdir)) - - @posix_only def test_module_run_completes_nodeenv(workdir, tmpdir): env = dict(os.environ, PYTHONPATH=os.path.dirname(nodeenv.__file__))