Script 'mail_helper' called by obssrc Hello community, here is the log from the commit of package python-shtab for openSUSE:Factory checked in at 2026-12-01 17:19:13 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-shtab (Old) and /work/SRC/openSUSE:Factory/.python-shtab.new.1340718 (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-shtab" Tue Dec 1 17:19:13 2026 rev:7 rq:1401694 version:1.14.0 Changes: -------- --- /work/SRC/openSUSE:Factory/python-shtab/python-shtab.changes 2026-09-08 16:51:37.038675593 +0200 +++ /work/SRC/openSUSE:Factory/.python-shtab.new.1340718/python-shtab.changes 2026-12-01 17:19:22.398579145 +0100 @@ -1,0 +2,20 @@ +Mon Nov 30 14:40:25 UTC 2026 - Dirk Müller <[email protected]> + +- add license + +------------------------------------------------------------------- +Sat Nov 28 19:55:58 UTC 2026 - Atri Bhattacharya <[email protected]> + +- Update to version 1.14.0: + * Support metavar (gh#tqdm/shtab#264). + * Fix zsh registration of compdef after compinit + (gh#tqdm/shtab#277). + * Fix zsh single-pattern glob (gh#tqdm/shtab#271). + * Tidy pty shell tests (partially gh#tqdm/shtab#243, + gh#tqdm/shtab#209) + * Fix powershell case-sensitivity (gh#tqdm/shtab#276). + * Fix powershell positionals after optionals + (gh#tqdm/shtab#269). + * Lazy logging string fixes (gh#tqdm/shtab#265). + +------------------------------------------------------------------- Old: ---- shtab-1.12.1.tar.gz New: ---- shtab-1.14.0.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-shtab.spec ++++++ --- /var/tmp/diff_new_pack.QmXhhm/_old 2026-12-01 17:19:23.084608021 +0100 +++ /var/tmp/diff_new_pack.QmXhhm/_new 2026-12-01 17:19:23.085608064 +0100 @@ -18,7 +18,7 @@ %{?sle15_python_module_pythons} Name: python-shtab -Version: 1.12.1 +Version: 1.14.0 Release: 0 Summary: Automagic shell tab completion for Python CLI applications License: Apache-2.0 @@ -67,6 +67,7 @@ %files %{python_files} %doc README.rst +%license LICENCE %python_alternative %{_bindir}/shtab %{python_sitelib}/shtab %{python_sitelib}/shtab-%{version}.dist-info ++++++ shtab-1.12.1.tar.gz -> shtab-1.14.0.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/.github/SECURITY.md new/shtab-1.14.0/.github/SECURITY.md --- old/shtab-1.12.1/.github/SECURITY.md 1970-01-01 01:00:00.000000000 +0100 +++ new/shtab-1.14.0/.github/SECURITY.md 2026-11-27 13:15:53.867762000 +0100 @@ -0,0 +1,5 @@ +# Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/.github/workflows/test.yml new/shtab-1.14.0/.github/workflows/test.yml --- old/shtab-1.12.1/.github/workflows/test.yml 2026-09-02 00:12:25.930674800 +0200 +++ new/shtab-1.14.0/.github/workflows/test.yml 2026-11-27 13:15:53.867762000 +0100 @@ -11,7 +11,7 @@ matrix: python: ['3.x'] os: [ubuntu, macos, windows] - include: [{python: 3.9, os: ubuntu}] # min supported (see pyproject.toml) + include: [{python: '3.10', os: ubuntu}] # min supported (see pyproject.toml) runs-on: ${{ matrix.os }}-latest steps: - uses: actions/checkout@v7 diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/.pre-commit-config.yaml new/shtab-1.14.0/.pre-commit-config.yaml --- old/shtab-1.12.1/.pre-commit-config.yaml 2026-09-02 00:12:25.930674800 +0200 +++ new/shtab-1.14.0/.pre-commit-config.yaml 2026-11-27 13:15:53.867762000 +0100 @@ -30,7 +30,7 @@ name: pytest language: python entry: pytest - args: [-vv] + args: [-vv, -m, "not slow"] types: [python] pass_filenames: false additional_dependencies: [pytest-cov, click] @@ -44,7 +44,7 @@ - id: bandit args: [-c, pyproject.toml] - repo: https://github.com/PyCQA/flake8 - rev: 7.3.0 + rev: 7.5.0 hooks: - id: flake8 args: [-j8] @@ -53,15 +53,14 @@ - flake8-bugbear - flake8-comprehensions - flake8-debugger - - flake8-isort - flake8-pyproject - repo: https://github.com/asottile/pyupgrade - rev: v3.21.2 + rev: v3.22.0 hooks: - id: pyupgrade - args: [--py39-plus] + args: [--py310-plus] - repo: https://github.com/pre-commit/mirrors-mypy - rev: v2.3.1 + rev: v2.4.1 hooks: - id: mypy additional_dependencies: [types-setuptools] @@ -72,7 +71,7 @@ args: [-i] additional_dependencies: [toml] - repo: https://github.com/PyCQA/isort - rev: 9.0.1 + rev: 10.0.0b3 hooks: - id: isort ci: diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/PKG-INFO new/shtab-1.14.0/PKG-INFO --- old/shtab-1.12.1/PKG-INFO 2026-09-02 00:12:32.241747900 +0200 +++ new/shtab-1.14.0/PKG-INFO 2026-11-27 13:16:03.473056300 +0100 @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: shtab -Version: 1.12.1 +Version: 1.14.0 Summary: Automagic shell tab completion for Python CLI applications Author-email: Casper da Costa-Luis <[email protected]> Maintainer-email: tqdm developers <[email protected]> @@ -29,12 +29,12 @@ Classifier: Programming Language :: Other Scripting Engines Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Unix Shell Classifier: Topic :: Desktop Environment @@ -54,7 +54,7 @@ Classifier: Topic :: System :: System Shells Classifier: Topic :: Terminals Classifier: Topic :: Utilities -Requires-Python: >=3.9 +Requires-Python: >=3.10 Description-Content-Type: text/x-rst License-File: LICENCE Provides-Extra: dev diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/examples/click_process.py new/shtab-1.14.0/examples/click_process.py --- old/shtab-1.12.1/examples/click_process.py 2026-09-02 00:12:25.931413400 +0200 +++ new/shtab-1.14.0/examples/click_process.py 2026-11-27 13:15:53.868256800 +0100 @@ -9,7 +9,7 @@ @click.command('click-process') [email protected]() # magic! [email protected]() # magic! @click.argument('out-dir', type=click.Path(file_okay=False), required=False, **({'help': "Output directory."} if ARG_HELP else {})) @click.option('--config', type=click.File(), help="Config file.") @@ -21,4 +21,4 @@ if __name__ == '__main__': - process() # pylint: disable=no-value-for-parameter + process() # pylint: disable=no-value-for-parameter diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/examples/click_subcommand.py new/shtab-1.14.0/examples/click_subcommand.py --- old/shtab-1.12.1/examples/click_subcommand.py 2026-09-02 00:12:25.932060200 +0200 +++ new/shtab-1.14.0/examples/click_subcommand.py 2026-11-27 13:15:53.868572500 +0100 @@ -24,7 +24,7 @@ print(f"Reading from {config} and writing to {out_dir}") -shtab.click.add_command_to(main) # magic! +shtab.click.add_command_to(main) # magic! if __name__ == '__main__': main() diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/examples/customcomplete.py new/shtab-1.14.0/examples/customcomplete.py --- old/shtab-1.12.1/examples/customcomplete.py 2026-09-02 00:12:25.932060200 +0200 +++ new/shtab-1.14.0/examples/customcomplete.py 2026-11-27 13:15:53.868572500 +0100 @@ -12,7 +12,7 @@ # WARNING: shtab.cmd is (re)run by your shell on each tab press, so could be slow COMPLETE_TOKEN = shtab.cmd("head -c5 /dev/random | base32") # override powershell function to a Windows-compatible approximate equivalent -COMPLETE_TOKEN['preamble']['powershell'] = ( # type: ignore[index] +COMPLETE_TOKEN['preamble']['powershell'] = ( # type: ignore[index] f"function {COMPLETE_TOKEN['powershell']}" " { Get-Random -Count 1 -InputObject (10000..99999) }") @@ -27,7 +27,7 @@ main_parser = argparse.ArgumentParser(prog="customcomplete") subparsers = main_parser.add_subparsers(dest="subcommand", required=True) parser = subparsers.add_parser("completion", help="print tab completion") -shtab.add_argument_to(parser, "shell", parent=main_parser) # magic! +shtab.add_argument_to(parser, "shell", parent=main_parser) # magic! # mypy: disable-error-code="attr-defined" parser = subparsers.add_parser("process", help="parse files") diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/examples/docopt_greeter.py new/shtab-1.14.0/examples/docopt_greeter.py --- old/shtab-1.12.1/examples/docopt_greeter.py 2026-09-02 00:12:25.932060200 +0200 +++ new/shtab-1.14.0/examples/docopt_greeter.py 2026-11-27 13:15:53.868572500 +0100 @@ -17,7 +17,7 @@ import shtab parser = argopt.argopt(__doc__) -shtab.add_argument_to(parser, ["-s", "--print-completion"]) # magic! +shtab.add_argument_to(parser, ["-s", "--print-completion"]) # magic! def main(args=None): diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/examples/pathcomplete.py new/shtab-1.14.0/examples/pathcomplete.py --- old/shtab-1.12.1/examples/pathcomplete.py 2026-09-02 00:12:25.932060200 +0200 +++ new/shtab-1.14.0/examples/pathcomplete.py 2026-11-27 13:15:53.868572500 +0100 @@ -11,7 +11,7 @@ # mypy: disable-error-code="attr-defined" parser = argparse.ArgumentParser(prog="pathcomplete") -shtab.add_argument_to(parser, ["-s", "--print-completion"]) # magic! +shtab.add_argument_to(parser, ["-s", "--print-completion"]) # magic! # file & directory tab complete parser.add_argument("file", nargs="?").complete = shtab.FILE diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/pyproject.toml new/shtab-1.14.0/pyproject.toml --- old/shtab-1.12.1/pyproject.toml 2026-09-02 00:12:25.932060200 +0200 +++ new/shtab-1.14.0/pyproject.toml 2026-11-27 13:15:53.868572500 +0100 @@ -19,7 +19,7 @@ maintainers = [{name = "tqdm developers", email = "[email protected]"}] description = "Automagic shell tab completion for Python CLI applications" readme = "README.rst" -requires-python = ">=3.9" +requires-python = ">=3.10" keywords = ["tab", "completion", "argparse", "shell", "bash", "zsh", "tcsh", "fish", "powershell", "pwsh"] license = {text = "MPL-2.0"} # Trove classifiers (https://pypi.org/pypi?%3Aaction=list_classifiers) @@ -44,12 +44,12 @@ "Programming Language :: Other Scripting Engines", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Unix Shell", "Topic :: Desktop Environment", @@ -86,7 +86,7 @@ exclude = [".git", "__pycache__", "build", "dist", ".eggs"] [tool.yapf] -spaces_before_comment = [15, 20] +spaces_before_comment = 2 arithmetic_precedence_indication = true allow_split_before_dict_value = false coalesce_brackets = true @@ -110,6 +110,7 @@ [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-v --tb=short -rxs -W=error --durations=5 --cov=shtab --cov-fail-under=85" +markers = ["slow: spawns shell pty/subprocess"] [tool.coverage.run] branch = true diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/shtab/__init__.py new/shtab-1.14.0/shtab/__init__.py --- old/shtab-1.12.1/shtab/__init__.py 2026-09-02 00:12:25.932060200 +0200 +++ new/shtab-1.14.0/shtab/__init__.py 2026-11-27 13:15:53.868572500 +0100 @@ -5,6 +5,7 @@ _ActionsContainer, _AppendAction, _AppendConstAction, _CountAction, _HelpAction, _StoreConstAction, _VersionAction) from collections import defaultdict +from collections.abc import Callable from contextlib import contextmanager from functools import total_ordering from importlib.metadata import PackageNotFoundError, version @@ -12,9 +13,8 @@ from shlex import join, quote from string import Template from textwrap import dedent -from typing import Any, Callable +from typing import Any, TypeVar, Union from typing import Optional as Opt -from typing import TypeVar, Union try: __version__ = version('shtab') @@ -70,7 +70,7 @@ """ return { "bash": f"_shtab_glob_compgen_{sha(patterns)}", - "zsh": f"_files -g '({'|'.join(patterns)})'", + "zsh": f"_files -g '{' '.join(patterns)}'", "tcsh": f"f:{{{','.join(patterns)}}}", "fish": f"(_shtab_glob_compgen_{sha(patterns)})", "powershell": f"_shtab_glob_compgen_{sha(patterns)}", @@ -87,10 +87,15 @@ "fish": dedent(f""" function _shtab_glob_compgen_{sha(patterns)} set comp (commandline -ct) - for pattern in {join(patterns)} - __fish_complete_path "$comp" | string match -e -- "$pattern" + for candidate in (__fish_complete_path "$comp") + set -l candidate_path (string split -m1 \\t -- "$candidate")[1] + for pattern in {join(patterns)} '*/' # recurse into subdirs + if string match -q -- "$pattern" "$candidate_path" + printf '%s\\n' "$candidate" + break + end + end end - __fish_complete_path "$comp" | string match -e "*/" # recurse into subdirs end """), "powershell": dedent(rf""" @@ -214,11 +219,11 @@ def complete2pattern(opt_complete: CompleteType, shell: str, choice_type2fn: dict[str, str], preambles: list[str]) -> str: if isinstance(opt_complete, dict): - if preamble := opt_complete.get("preamble", {}).get(shell, ""): # type: ignore[union-attr] + if preamble := opt_complete.get("preamble", {}).get(shell, ""): # type: ignore[union-attr] preambles.append(preamble) if isinstance(opt_complete, dict): - return opt_complete.get(shell, "") # type: ignore[return-value] + return opt_complete.get(shell, "") # type: ignore[return-value] return choice_type2fn[opt_complete] @@ -280,7 +285,7 @@ compgens.append(f"{prefix}_pos_{i}_COMPGEN={quote(comp_pattern)}") elif positional.choices: # choices (including subparsers & shtab `.complete` functions) - log.debug(f"choices:{prefix}:{sorted(positional.choices)}") + log.debug("choices:%s:%s", prefix, sorted(positional.choices, key=str)) if is_subparser(positional): public_cmds = get_public_subcommands(positional) this_positional_choices = [] @@ -288,7 +293,7 @@ if isinstance(choice, Choice): # append special completion type to `compgens` # NOTE: overrides `.complete` attribute - log.debug(f"Choice.{choice.type}:{prefix}:{positional.dest}") + log.debug("Choice.%s:%s:%s", choice.type, prefix, positional.dest) compgens.append(f"{prefix}_pos_{i}_COMPGEN=" f"{quote(choice_type2fn[choice.type])}") elif is_subparser(positional): @@ -313,7 +318,7 @@ if discovered_subparsers: subparsers.append(f"{prefix}_subparsers=({join(discovered_subparsers)})") - log.debug(f"subcommands:{prefix}:{discovered_subparsers}") + log.debug("subcommands:%s:%s", prefix, discovered_subparsers) # optional arguments option_strings_list = join( @@ -337,7 +342,7 @@ # append special completion type to `compgens` # NOTE: overrides `.complete` attribute if isinstance(choice, Choice): - log.debug(f"Choice.{choice.type}:{prefix}:{optional.dest}") + log.debug("Choice.%s:%s:%s", choice.type, prefix, optional.dest) func_str = choice_type2fn[choice.type] compgens.append(f"{prefix}_{wordify(option_string)}_COMPGEN=" f"{quote(func_str)}") @@ -534,10 +539,15 @@ compgen -W "${current_action_choices[*]}" -- "$completing_word") fi + if [[ ${#COMPREPLY[@]} = 0 ]]; then + # native fallback matches are not necessarily filenames (e.g. variables) + compopt +o filenames 2>/dev/null || : # bash>=4 + fi + return 0 } -complete -F ${root_prefix} ${prog}""").safe_substitute( +complete -o bashdefault -F ${root_prefix} ${prog}""").safe_substitute( subparsers="\n".join(subparsers), option_strings="\n".join(option_strings), compgens="\n".join(compgens), @@ -558,7 +568,7 @@ formatter = parser._get_formatter() backup_width = formatter._width try: - formatter._width = 999 # large number to effectively disable wrapping + formatter._width = 999 # large number to effectively disable wrapping def inner(str_or_parser): return head( @@ -640,7 +650,7 @@ for sub in parser._get_positional_actions(): if sub.help == SUPPRESS or not is_subparser(sub): continue - log.debug(f"subparser:choices:{prefix}:{sorted(sub.choices)}") + log.debug("subparser:choices:%s:%s", prefix, sorted(sub.choices)) public_cmds = get_public_subcommands(sub) for cmd, subparser in sub.choices.items(): if cmd not in public_cmds: @@ -773,7 +783,17 @@ if [[ $zsh_eval_context[-1] == eval ]]; then # eval/source/. command, register function for later - compdef ${root_prefix} -N ${prog} + ${root_prefix}_register() { + # `compdef` is defined by `compinit` + if (( $+functions[compdef] )); then + compdef ${root_prefix} -N ${prog} + # drop registration hook (avoid multiple `compdef` calls) + add-zsh-hook -d precmd ${root_prefix}_register + fi + } + # register completer before next prompt + autoload -Uz add-zsh-hook + add-zsh-hook precmd ${root_prefix}_register else # autoload from fpath, call function directly ${root_prefix} "$@\" @@ -939,8 +959,8 @@ prog = parser.prog prefix = wordify(f"_shtab_{root_prefix or prog}") completions = [] - commands = [] # all (sub)command paths, e.g. ["sub", "sub subsub"] - opts_with_value = set() # option strings which consume a following value token + commands = [] # all (sub)command paths, e.g. ["sub", "sub subsub"] + opts_with_value = set() # option strings which consume a following value token preambles = [preamble] if preamble else [] choice_type2fn = {k: v["fish"] for k, v in CHOICE_FUNCTIONS.items()} @@ -996,8 +1016,8 @@ output.append(f'-d {quote(desc)}') completions.append(' '.join(output)) - index = 0 # the next positional slot (number of preceding positional arguments) - open_ended = False # an earlier positional consumes any number of tokens + index = 0 # the next positional slot (number of preceding positional arguments) + open_ended = False # an earlier positional consumes any number of tokens for positional in cparser._get_positional_actions(): if positional.help == SUPPRESS: @@ -1006,7 +1026,7 @@ if is_subparser(positional): public_cmds = get_public_subcommands(positional) pos_test = pos_condition(index, 1, open_ended) - for subcmd, subparser in positional.choices.items(): # type: ignore[union-attr] + for subcmd, subparser in positional.choices.items(): # type: ignore[union-attr] if subcmd not in public_cmds: continue log.debug("%s| | SubParser: %s", log_prefix, subcmd) @@ -1132,24 +1152,19 @@ return f"@({escaped})" -def _powershell_hashtable(d): - """Serialize a dict[str, list[str]] to PowerShell @{} syntax.""" - if not d: - return "@{}" - entries = [ - f" {_powershell_escape(key)} = {_powershell_list(values)}" - for key, values in sorted(d.items())] - return "@{\n" + "\n".join(entries) + "\n}" - - -def _powershell_flat_hashtable(d): - """Serialize a dict[str, str] to PowerShell @{} syntax.""" - if not d: - return "@{}" - entries = [ - f" {_powershell_escape(key)} = {_powershell_escape(value)}" - for key, value in sorted(d.items())] - return "@{\n" + "\n".join(entries) + "\n}" +def _powershell_ordinal_hashtable(entries): + """Serialize (key, value) pairs to a case-sensitive PowerShell hashtable.""" + table = "[System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)" + if not entries: + return table + lines = [f" $table[{key}] = {value}" for key, value in entries] + return "& {\n $table = " + table + "\n" + "\n".join(lines) + "\n $table\n}" + + +def _powershell_hashtable(d, value=_powershell_list): + """Serialize dict[str, str | list[str]] to a PowerShell hashtable.""" + return _powershell_ordinal_hashtable([ + (_powershell_escape(key), value(values)) for key, values in sorted(d.items())]) def get_powershell_commands(root_parser, root_prefix, choice_functions=None): @@ -1187,7 +1202,7 @@ if comp_pattern: compgens[action_key] = comp_pattern elif positional.choices: - log.debug(f"choices:{prefix}:{sorted(positional.choices)}") + log.debug("choices:%s:%s", prefix, sorted(positional.choices, key=str)) this_positional_choices = [] for choice in positional.choices: if isinstance(positional.choices, dict): @@ -1216,7 +1231,7 @@ nargs[action_key] = str(positional.nargs) if discovered_subparsers: subparsers[prefix] = discovered_subparsers - log.debug(f"subcommands:{prefix}:{discovered_subparsers}") + log.debug("subcommands:%s:%s", prefix, discovered_subparsers) option_strings[prefix] = sum( (opt.option_strings for opt in parser._get_optional_actions() if opt.help != SUPPRESS), []) @@ -1366,6 +1381,11 @@ $currentActionNargs = Get-ActionNargs $currentActionKey $currentActionArgsConsumed = 0 $currentActionIsPositional = $false + if ($currentActionNargs -eq '0') { + $currentActionKey = "${prefix}_pos_${completedPositionals}" + $currentActionNargs = Get-ActionNargs $currentActionKey + $currentActionIsPositional = $true + } continue } # Consume argument for current action @@ -1460,10 +1480,10 @@ """.replace("⁠\n", "")).safe_substitute( subparsers_ht=_powershell_hashtable(subparsers), option_strings_ht=_powershell_hashtable(option_strings), - compgens_ht=_powershell_flat_hashtable(compgens), + compgens_ht=_powershell_hashtable(compgens, _powershell_escape), choices_ht=_powershell_hashtable(choices), - nargs_ht=_powershell_flat_hashtable(nargs), - help_ht=_powershell_flat_hashtable(help_text), + nargs_ht=_powershell_hashtable(nargs, _powershell_escape), + help_ht=_powershell_hashtable(help_text, _powershell_escape), preamble=f"\n# Custom Preamble\n{preamble}\n# End Custom Preamble\n" if preamble else "", root_prefix=root_prefix, prog=parser.prog, @@ -1500,8 +1520,7 @@ ) -def completion_action(parent: Opt[ArgumentParser] = None, preamble: Union[str, dict[str, - str]] = ""): +def completion_action(parent: Opt[ArgumentParser] = None, preamble: (str | dict[str, str]) = ""): class PrintCompletionAction(_ShtabPrintCompletionAction): def __call__(self, parser, namespace, values, option_string=None): print(complete(parent or parser, values, preamble=preamble)) @@ -1512,10 +1531,11 @@ def add_argument_to( parser: _ActionsContainerT, - option_string: Union[str, list[str]] = "--print-completion", - help: str = "print shell completion script", # pylint: disable=W0622 + option_string: str | list[str] = "--print-completion", + help: str = "print shell completion script", # pylint: disable=W0622 parent: Opt[ArgumentParser] = None, - preamble: Union[str, dict[str, str]] = "", + preamble: str | dict[str, str] = "", + metavar: Opt[str] = None, ) -> _ActionsContainerT: """ option_string: @@ -1525,14 +1545,16 @@ required in subcommand mode preamble: see `complete` for details + metavar: + replaces shell choices list in help output """ if isinstance(option_string, str): option_string = [option_string] kwargs = { - "choices": SUPPORTED_SHELLS, "default": None, "help": help, + "choices": SUPPORTED_SHELLS, "default": None, "help": help, "metavar": metavar, "action": completion_action(parent, preamble)} - if option_string[0][0] != "-": # subparser mode + if option_string[0][0] != "-": # subparser mode kwargs.update(default=SUPPORTED_SHELLS[0], nargs="?") if parent is None: raise ValueError("subcommand mode: parent required") diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/shtab/click.py new/shtab-1.14.0/shtab/click.py --- old/shtab-1.12.1/shtab/click.py 2026-09-02 00:12:25.932720400 +0200 +++ new/shtab-1.14.0/shtab/click.py 2026-11-27 13:15:53.869113200 +0100 @@ -82,12 +82,12 @@ log.debug("parser:%s", command.name) parser = argparse.ArgumentParser(prog=command.name, description=command.help) for param in command.params: - if getattr(param, 'deprecated', False): # click>=8.2 + if getattr(param, 'deprecated', False): # click>=8.2 continue - if getattr(param, 'hidden', False): # pallets/click#3788 + if getattr(param, 'hidden', False): # pallets/click#3788 continue - spec = {'help': getattr(param, 'help', None)} # click>=8.5 + spec = {'help': getattr(param, 'help', None)} # click>=8.5 if param.param_type_name == 'option': log.debug("optional:%s", param.opts) if param.is_flag: @@ -118,7 +118,7 @@ subparsers = parser.add_subparsers(dest=command.name, help=command.short_help, description=command.help, required=True) for name, subcmd in command.commands.items(): - if subcmd.hidden or getattr(subcmd, 'deprecated', False): # click>=8.2 + if subcmd.hidden or getattr(subcmd, 'deprecated', False): # click>=8.2 continue log.debug("subcommand:%s", name) subparser = subparsers.add_parser(name, help=subcmd.short_help, diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/shtab.egg-info/PKG-INFO new/shtab-1.14.0/shtab.egg-info/PKG-INFO --- old/shtab-1.12.1/shtab.egg-info/PKG-INFO 2026-09-02 00:12:32.217190700 +0200 +++ new/shtab-1.14.0/shtab.egg-info/PKG-INFO 2026-11-27 13:16:03.454428700 +0100 @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: shtab -Version: 1.12.1 +Version: 1.14.0 Summary: Automagic shell tab completion for Python CLI applications Author-email: Casper da Costa-Luis <[email protected]> Maintainer-email: tqdm developers <[email protected]> @@ -29,12 +29,12 @@ Classifier: Programming Language :: Other Scripting Engines Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: 3.10 Classifier: Programming Language :: Python :: 3.11 Classifier: Programming Language :: Python :: 3.12 Classifier: Programming Language :: Python :: 3.13 Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: 3.15 Classifier: Programming Language :: Python :: 3 :: Only Classifier: Programming Language :: Unix Shell Classifier: Topic :: Desktop Environment @@ -54,7 +54,7 @@ Classifier: Topic :: System :: System Shells Classifier: Topic :: Terminals Classifier: Topic :: Utilities -Requires-Python: >=3.9 +Requires-Python: >=3.10 Description-Content-Type: text/x-rst License-File: LICENCE Provides-Extra: dev diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/shtab.egg-info/SOURCES.txt new/shtab-1.14.0/shtab.egg-info/SOURCES.txt --- old/shtab-1.12.1/shtab.egg-info/SOURCES.txt 2026-09-02 00:12:32.228237400 +0200 +++ new/shtab-1.14.0/shtab.egg-info/SOURCES.txt 2026-11-27 13:16:03.464698800 +0100 @@ -7,6 +7,7 @@ README.rst pyproject.toml .github/FUNDING.yml +.github/SECURITY.md .github/ISSUE_TEMPLATE/config.yml .github/workflows/test.yml docs/index.md @@ -36,5 +37,6 @@ shtab.egg-info/scm_version.json shtab.egg-info/top_level.txt tests/__init__.py +tests/conftest.py tests/test_click.py tests/test_shtab.py \ No newline at end of file diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/shtab.egg-info/scm_file_list.json new/shtab-1.14.0/shtab.egg-info/scm_file_list.json --- old/shtab-1.12.1/shtab.egg-info/scm_file_list.json 2026-09-02 00:12:32.214971800 +0200 +++ new/shtab-1.14.0/shtab.egg-info/scm_file_list.json 2026-11-27 13:16:03.452734700 +0100 @@ -2,6 +2,7 @@ "files": [ ".github/FUNDING.yml", ".github/ISSUE_TEMPLATE/config.yml", + ".github/SECURITY.md", ".github/workflows/test.yml", ".gitignore", ".mailmap", @@ -30,6 +31,7 @@ "shtab/main.py", "shtab/py.typed", "tests/__init__.py", + "tests/conftest.py", "tests/test_click.py", "tests/test_shtab.py" ] diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/shtab.egg-info/scm_version.json new/shtab-1.14.0/shtab.egg-info/scm_version.json --- old/shtab-1.12.1/shtab.egg-info/scm_version.json 2026-09-02 00:12:32.208140900 +0200 +++ new/shtab-1.14.0/shtab.egg-info/scm_version.json 2026-11-27 13:16:03.446634300 +0100 @@ -1,8 +1,8 @@ { - "tag": "1.12.1", + "tag": "1.14.0", "distance": 0, - "node": "ge1ab40616e77298204a61e1aad50d6f6e90e9217", + "node": "g259fa6c2b2850c40513eb3a8aa46759394aa372e", "dirty": false, "branch": "HEAD", - "node_date": "2026-09-01" + "node_date": "2026-11-27" } diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/tests/conftest.py new/shtab-1.14.0/tests/conftest.py --- old/shtab-1.12.1/tests/conftest.py 1970-01-01 01:00:00.000000000 +0100 +++ new/shtab-1.14.0/tests/conftest.py 2026-11-27 13:15:53.869290800 +0100 @@ -0,0 +1,11 @@ +import pytest + +SLOW_SHELL_SPAWNERS = { + "powershell_candidates", "ps_cands", "bash_candidates", "zsh_candidates", "tcsh_candidates"} + + +def pytest_collection_modifyitems(config, items): + for item in items: + func = getattr(item, "function", None) + if func is not None and set(func.__code__.co_names) & SLOW_SHELL_SPAWNERS: + item.add_marker(pytest.mark.slow) diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/tests/test_click.py new/shtab-1.14.0/tests/test_click.py --- old/shtab-1.12.1/tests/test_click.py 2026-09-02 00:12:25.932957600 +0200 +++ new/shtab-1.14.0/tests/test_click.py 2026-11-27 13:15:53.869290800 +0100 @@ -5,8 +5,8 @@ from examples import click_process, click_subcommand from shtab.main import main -from .test_shtab import no_log_info # noqa: F401, pylint: disable=unused-import, yapf: disable -from .test_shtab import fix_shell +# pylint: disable-next=unused-import +from .test_shtab import fix_shell, no_log_info # noqa: F401 ARG_HELP = version('click') >= '8.5' diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/shtab-1.12.1/tests/test_shtab.py new/shtab-1.14.0/tests/test_shtab.py --- old/shtab-1.12.1/tests/test_shtab.py 2026-09-02 00:12:25.932957600 +0200 +++ new/shtab-1.14.0/tests/test_shtab.py 2026-11-27 13:15:53.869290800 +0100 @@ -8,6 +8,7 @@ import subprocess import time from argparse import SUPPRESS, Action, ArgumentParser +from enum import Enum import pytest @@ -86,7 +87,7 @@ captured = capsys.readouterr() assert not captured.err expected = { - 'bash': "complete -F _shtab_shtab shtab", 'zsh': "_shtab_shtab_commands()", + 'bash': "complete -o bashdefault -F _shtab_shtab shtab", 'zsh': "_shtab_shtab_commands()", 'tcsh': "complete shtab", 'fish': "complete -c shtab", 'powershell': "Register-ArgumentCompleter -Native -CommandName shtab"} assert expected[shell] in captured.out @@ -100,7 +101,7 @@ captured = capsys.readouterr() assert not captured.err expected = { - 'bash': "complete -F _shtab_shtab shtab", 'zsh': "_shtab_shtab_commands()", + 'bash': "complete -o bashdefault -F _shtab_shtab shtab", 'zsh': "_shtab_shtab_commands()", 'tcsh': "complete shtab", 'fish': "complete -c shtab", 'powershell': "Register-ArgumentCompleter -Native -CommandName shtab"} if output in ("-", "stdout"): @@ -116,7 +117,7 @@ captured = capsys.readouterr() assert not captured.err if shell == 'bash': - assert "complete -F _shtab_shtab foo" in captured.out + assert "complete -o bashdefault -F _shtab_shtab foo" in captured.out else: pytest.skip("WiP") @@ -129,7 +130,7 @@ assert not captured.err script_py = [i.strip() for i in captured.out.splitlines() if "script.py" in i and i[0] != '#'] if shell == 'bash': - assert script_py == ["complete -F _shtab_shtab script.py"] + assert script_py == ["complete -o bashdefault -F _shtab_shtab script.py"] elif shell == 'zsh': assert captured.out.startswith("#compdef script.py") assert script_py == [ @@ -259,11 +260,33 @@ subprocess.check_call(['zsh', '-nc', completion]) script = tmp_path / "completion.zsh" script.write_text(completion) - # `eval` so the script registers itself rather than running `compdef` (unavailable here) - values = subprocess.check_output( - ['zsh', '-f', '-c', f'eval "$(<{script})" 2>/dev/null; print -rl -- "${{(@){name}}}"'], - text=True) - return values.splitlines() + # `eval` so the script registers a hook rather than running `compdef` (unavailable here) + proc = subprocess.run( + ['zsh', '-f', '-c', f'eval "$(<{script})" && print -rl -- "${{(@){name}}}"'], text=True, + capture_output=True) + # `eval` before `compinit` must not fail on a missing `compdef` (#277) + assert proc.returncode == 0 and not proc.stderr, proc.stderr + return proc.stdout.splitlines() + + +def test_zsh_eval_registers_after_compinit(tmp_path): + """`compinit` running after `eval`""" + if not shutil.which('zsh'): + pytest.skip("zsh not available") + script = tmp_path / "completion.zsh" + script.write_text(complete(ArgumentParser(prog="test"), "zsh")) + dump = tmp_path / ".zcompdump" + # `zsh -c` never reaches a prompt, so run prompt hooks the way zsh's prompt loop does + values = subprocess.check_output([ + 'zsh', '-f', '-c', f"""\ +eval "$(<{script})" +autoload -Uz compinit +compinit -u -d {dump} +for hook in $precmd_functions; do "$hook"; done +print -r -- "${{_comps[test]}}" +print -r -- "${{precmd_functions}}" +"""], text=True) + assert values.splitlines() == ["_shtab_test", ""] @pytest.mark.parametrize("help_text", [ @@ -302,6 +325,25 @@ pytest.skip("WiP") +@fix_shell +def test_unorderable_choices(shell): + class Color(Enum): + RED = 1 + GREEN = 2 + + def __str__(self): + return self.name + + parser = ArgumentParser(prog="myprog", add_help=False) + parser.add_argument("color", type=Color.__getitem__, choices=list(Color)) + completion = complete(parser, shell) + if shell == 'bash': + shell = Bash(completion) + shell.compgen('-W "${_shtab_myprog_pos_0_choices[*]}"', "R", "RED") + else: + assert "GREEN" in completion + + def test_zsh_remainder_custom_complete_has_optional_message_colon(): parser = ArgumentParser(prog="test") parser.add_argument("command", nargs=1).complete = {'zsh': "{_command_names -e}"} @@ -334,6 +376,78 @@ return [line.split("\t")[0] for line in proc.splitlines() if line.strip()] [email protected]("case", ["relative", "absolute", "prefix", "no_match", "nested"]) +def test_fish_glob_filters_paths(case, change_dir): + """Glob completion filters the whole path but retains directories (#261).""" + for name in ("a.yaml", "b.json", "config.yml", "settings.toml", "notes.txt", "a.yaml.bak", + "with space.yaml"): + (change_dir / name).touch() + for name in ("subdir", "space dir", "space dir/deeper folder"): + (change_dir / name).mkdir() + (change_dir / "space dir/nested.yaml").touch() + (change_dir / "space dir/no.txt").touch() + parser = ArgumentParser(prog="pathcomplete") + parser.add_argument("--config").complete = shtab.glob("*.toml", "*.yml", "*.yaml", "*.json") + completion = complete(parser, 'fish') + expected = { + "a.yaml", "b.json", "config.yml", "settings.toml", "with space.yaml", "subdir/", + "space dir/"} + prefix = "" + if case == "absolute": + prefix = str(change_dir) + "/" + expected = {prefix + name for name in expected} + elif case == "prefix": + prefix, expected = "a", {"a.yaml"} + elif case == "no_match": + prefix, expected = "notes", set() + elif case == "nested": + prefix = "space\\ dir/" + expected = {"space dir/nested.yaml", "space dir/deeper folder/"} + assert set(fish_candidates(completion, f"pathcomplete --config {prefix}")) == expected + + +def test_fish_glob_matches_paths_not_descriptions(): + """Description text is preserved but cannot make a nonmatching path match.""" + if not shutil.which('fish'): + pytest.skip("fish not available") + parser = ArgumentParser(prog="pathcomplete") + parser.add_argument("--config").complete = shtab.glob("*.yaml") + completion = complete(parser, 'fish') + script = completion + """ +function __fish_complete_path + printf '%s\\n' 'a.yaml\tYAML document\t' 'notes.txt\tlooks.yaml\t' 'subdir/\tDirectory\t' +end +complete -C 'pathcomplete --config ' +""" + output = subprocess.check_output(['fish', '-c', script], text=True) + assert "a.yaml\tYAML document" in output + assert "subdir/\tDirectory" in output + assert "notes.txt" not in output + + +def test_zsh_glob_spec(tmp_path): + """glob patterns must be passed to `_files -g` as filename patterns, not a qualifier.""" + parser = ArgumentParser(prog="test", add_help=False) + parser.add_argument("--config").complete = shtab.glob("*.toml", "*.yml") + completion = complete(parser, "zsh") + specs = zsh_specs(completion, "_shtab_test_options", tmp_path) + assert specs == ["--config[config]:config:_files -g '*.toml *.yml'"] + + [email protected]("patterns, expected", [ + (("*.toml",), ["a.toml"]), + (("*.toml", "*.yml", "*.json"), ["a.toml", "b.yml", "c.json"]),]) +def test_zsh_glob_completion(change_dir, patterns, expected): + """Glob completion in zsh must actually complete matching files (single pattern too).""" + for name in ("a.toml", "b.yml", "c.json", "d.txt"): + (change_dir / name).touch() + parser = ArgumentParser(prog="globprog", add_help=False) + parser.add_argument("--config").complete = shtab.glob(*patterns) + completion = complete(parser, "zsh") + assert sorted(zsh_candidates(completion, "globprog --config ", change_dir, + "globprog")) == sorted(expected) + + def powershell_candidates(completion, cmdline): """Source `completion` in PowerShell, then return the completion candidates for `cmdline`.""" if not shutil.which('pwsh'): @@ -350,68 +464,188 @@ return [line for line in proc.splitlines() if line.strip()] -def tcsh_candidates(completion, cmdlines, cwd): - """ - Return pty-driven completion candidates for each of `cmdlines`. +def ps_cands(change_dir, parser): + """Create `target_dir` and return a `candidates(cmdline)` helper for `parser` (PowerShell).""" + (change_dir / "target_dir").mkdir() + completion = complete(parser, 'powershell') + return lambda cmdline: powershell_candidates(completion, cmdline) - Reason: tcsh has no `complete -C` equivalent. + +def clean_ansi(chunk): + return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]|[\a\r\b]", "", chunk.decode('utf-8', 'replace')) + + +class PtyShell: """ - pty = pytest.importorskip('pty') - if not shutil.which('tcsh'): - pytest.skip("tcsh not available") - script = cwd / "completion.tcsh" - script.write_text(completion) - prompt = "|candidates|" - pid, fd = pty.fork() - if pid == 0: # child - os.chdir(cwd) - os.environ['TERM'] = 'xterm' - os.environ['COLUMNS'] = '999' - os.execvp('tcsh', ['tcsh', '-f', '-i']) - output = "" - - def clean(chunk): - return re.sub(r"\x1b\[[0-9;]*[A-Za-z]|[\a\r\b]", "", chunk.decode('utf-8', 'replace')) - - def read(num_prompts, timeout=10.0): - """read until `timeout` elapses or `num_prompts` seen, then drain""" - nonlocal output + Fork `shell` in a pty under `cwd`, and drive interactive completion. + """ + shell: str | None = None + args: tuple[str, ...] = () + term: str = 'dumb' + + def __init__(self, cwd): + self.cwd = cwd + self.output = "" + + def __enter__(self): + pty = pytest.importorskip('pty') + if not shutil.which(self.shell): + pytest.skip(f"{self.shell} not available") + self.pid, self.fd = pty.fork() + if self.pid == 0: # child + os.chdir(self.cwd) + os.environ['TERM'] = self.term + os.environ['COLUMNS'] = '999' + os.execvp(self.shell, [self.shell, *self.args]) + return self + + def __exit__(self, *exc): + os.close(self.fd) + os.kill(self.pid, signal.SIGKILL) + os.waitpid(self.pid, 0) + + def write(self, data): + os.write(self.fd, data.encode() if isinstance(data, str) else data) + + def _read(self): + try: + chunk = os.read(self.fd, 1 << 16) + except OSError: + return None + return chunk or None + + def read_until(self, condition, timeout=10.0, drain=0.2): + """read until `condition()` or `timeout`, then drain remaining output""" deadline = time.time() + timeout - while output.count(prompt) < num_prompts and time.time() < deadline: - if select.select([fd], [], [], 0.1)[0]: - try: - chunk = os.read(fd, 1 << 16) - except OSError: + while not condition() and time.time() < deadline: + if select.select([self.fd], [], [], 0.1)[0]: + if (chunk := self._read()) is None: break - if not chunk: + self.output += clean_ansi(chunk) + # a command just finished, give shell time to enable its line editor again + while select.select([self.fd], [], [], drain)[0]: + if (chunk := self._read()) is None: + break + self.output += clean_ansi(chunk) + return self.output + + def read_idle(self, idle=0.6, timeout=10.0): + """read until output is quiet for `idle` seconds, or `timeout`""" + last = time.time() + deadline = time.time() + timeout + while time.time() < deadline: + if select.select([self.fd], [], [], 0.1)[0]: + if (chunk := self._read()) is None: break - output += clean(chunk) - # a command just finished, give tcsh a moment to enable its line editor again - while select.select([fd], [], [], 0.2)[0]: - output += clean(os.read(fd, 1 << 16)) - return output + self.output += clean_ansi(chunk) + last = time.time() + elif time.time() - last > idle: + break + return self.output - candidates = [] - try: + +class TcshShell(PtyShell): + """tcsh has no `complete -C` equivalent, so drive it with `autolist`.""" + shell, args, term = 'tcsh', ('-f', '-i'), 'xterm' + + def run(self, completion, cmdlines): + script = self.cwd / "completion.tcsh" + script.write_text(completion) + prompt = "|candidates|" # tcsh echoes what is typed, so the command setting the prompt must not contain it verbatim - os.write( - fd, - f'set autolist\nsource {script}\nset prompt="{prompt[:1]}""{prompt[1:]}"\n'.encode()) - read(1) + self.write(f'set autolist\nsource {script}\nset prompt="{prompt[:1]}""{prompt[1:]}"\n') + self.read_until(lambda: self.output.count(prompt) >= 1) + candidates = [] for cmdline in cmdlines: - seen = len(output) + seen, prompts = len(self.output), self.output.count(prompt) # `autolist` lists the candidates, ^U then discards the line, \n asks for a new prompt - os.write(fd, cmdline.encode() + b"\t\x15\n") - chunk = read(output.count(prompt) + 1)[seen:].replace(prompt, "\n") + self.write(cmdline + "\t\x15\n") + chunk = self.read_until( + lambda prompts=prompts: self.output.count(prompt) > prompts)[seen:] # drop the echoed command line & the re-drawn prompt, leaving the listed candidates candidates.append([ - word for line in chunk.splitlines() if line.strip() and cmdline.strip() not in line - for word in line.split()]) - finally: - os.close(fd) - os.kill(pid, signal.SIGKILL) - os.waitpid(pid, 0) - return candidates + word for line in chunk.replace(prompt, "\n").splitlines() + if line.strip() and cmdline.strip() not in line for word in line.split()]) + return candidates + + +class ZshShell(PtyShell): + """zsh needs interactive ZLE, so drive it with `compadd` wrapped to record candidates.""" + shell, args = 'zsh', ('-f', '-i') + + def run(self, completion, cmdline, prog): + script = self.cwd / "completion.zsh" + script.write_text(completion) + candidate_file = self.cwd / "zsh_candidates.txt" + setup = self.cwd / "zsh_setup.zsh" + setup.write_text("setopt zle\n" + "bindkey -e\n" + "autoload -Uz compinit\n" + "compinit -u -d {cwd}/.zcompdump\n" + "compadd() {{\n" + " local -a _cap\n" + ' builtin compadd -O _cap "$@"\n' + " local _c\n" + ' for _c in "$_cap[@]"; do print -r -- "$_c" >> {candidate_file}; done\n' + ' builtin compadd "$@"\n' + "}}\n" + 'eval "$(<{script})"\n' + "{prog}() {{ :; }}\n".format(cwd=self.cwd, candidate_file=candidate_file, + script=script, prog=prog)) + prompt = "|READY|" + self.write(f'PROMPT="{prompt}"\n') + self.write(f'. "{setup}"\n') + self.read_until(lambda: prompt in self.output) + # reset candidates, trigger completion on argument, clear line + candidate_file.write_text("") + self.write(cmdline + "\t") + self.read_idle() + self.write("\x15\n") + self.read_idle(idle=0.2) + return candidate_file.read_text().splitlines() if candidate_file.exists() else [] + + +class BashShell(PtyShell): + """ + readline's post-processing (e.g. `-o filenames` appending `/` to dirs) + happens after `COMPREPLY` (invisible to `compgen`), so drive bash in a pty. + """ + shell, args = 'bash', ('--norc', '--noprofile', '-i') + + def run(self, completion, cmdlines): + script = self.cwd / "completion.bash" + script.write_text(completion) + prompt = "|candidates|" + self.write(f"source {script}; PS1='{prompt}'\n") + self.read_until(lambda: self.output.count(prompt) >= 1, drain=0.3) + candidates = [] + for cmdline in cmdlines: + seen = len(self.output) + self.write(cmdline + "\t") + # typed line (echoed back) + readline's insertion + self.read_until(lambda cmdline=cmdline, seen=seen: cmdline in self.output[seen:], + drain=0.3) + candidates.append(self.output[seen:]) + self.write("\x15exit\n") # discard the line & quit + self.read_until(lambda: True) + return candidates + + +def tcsh_candidates(completion, cmdlines, cwd): + """Return pty-driven completion candidates for each of `cmdlines`.""" + with TcshShell(cwd) as shell: + return shell.run(completion, cmdlines) + + +def zsh_candidates(completion, cmdline, cwd, prog): + """ + Drive an interactive zsh and return the candidates it offers for `cmdline`. + + `completion` is sourced into a fresh zsh, whose `compadd` is wrapped to record + the candidate strings the completion functions hand to it. + """ + with ZshShell(cwd) as shell: + return shell.run(completion, cmdline, prog) @pytest.fixture(scope="module") @@ -484,68 +718,9 @@ def bash_candidates(completion, cmdlines, cwd): - """ - Return pty-driven completion candidates for each of `cmdlines`. - - Reason: readline's post-processing (e.g. `-o filenames` appending `/` to dirs) - happens after `COMPREPLY` and is thus invisible to `compgen`-based tests. - """ - pty = pytest.importorskip('pty') - if not shutil.which('bash'): - pytest.skip("bash not available") - script = cwd / "completion.bash" - script.write_text(completion) - prompt = "|candidates|" - pid, fd = pty.fork() - if pid == 0: # child - os.chdir(cwd) - os.environ['TERM'] = 'dumb' - os.environ['COLUMNS'] = '999' - os.execvp('bash', ['bash', '--norc', '--noprofile', '-i']) - output = "" - - def clean(chunk): - return re.sub(r"\x1b\[[0-9;?]*[A-Za-z]|[\a\r\b]", "", chunk.decode('utf-8', 'replace')) - - def read(condition, timeout=10.0): - """read until `timeout` elapses or `condition()`, then drain""" - nonlocal output - deadline = time.time() + timeout - while not condition() and time.time() < deadline: - if select.select([fd], [], [], 0.1)[0]: - try: - chunk = os.read(fd, 1 << 16) - except OSError: - break - if not chunk: - break - output += clean(chunk) - while select.select([fd], [], [], 0.3)[0]: - try: - chunk = os.read(fd, 1 << 16) - except OSError: - break - if not chunk: - break - output += clean(chunk) - - candidates = [] - try: - os.write(fd, f"source {script}; PS1='{prompt}'\n".encode()) - read(lambda: output.count(prompt) >= 1) - for cmdline in cmdlines: - seen = len(output) - os.write(fd, cmdline.encode() + b"\t") - # the typed line is echoed back, followed by whatever readline inserted - read(lambda cmdline=cmdline, seen=seen: cmdline in output[seen:]) - candidates.append(output[seen:]) - os.write(fd, b"\x15exit\n") # discard the line & quit - read(lambda: True) - finally: - os.close(fd) - os.kill(pid, signal.SIGKILL) - os.waitpid(pid, 0) - return candidates + """Return pty-driven completion candidates for each of `cmdlines`.""" + with BashShell(cwd) as shell: + return shell.run(completion, cmdlines) def test_bash_dir_collision(change_dir, test_parser): @@ -557,21 +732,90 @@ (change_dir / "create").mkdir() (change_dir / "subdir").mkdir() completion = complete(test_parser, 'bash') - assert "complete -F _shtab_myprog myprog" in completion, \ + assert "complete -o bashdefault -F _shtab_myprog myprog" in completion, \ "`-o filenames` must not apply readline filename post-processing globally" lines = bash_candidates(completion, ["myprog cre", "myprog create alpha sub"], change_dir) assert lines == [ - "myprog create ", # choices should take priority over dirs - "myprog create alpha subdir/", # dirs should still have trailing `/` + "myprog create ", # choices should take priority over dirs + "myprog create alpha subdir/", # dirs should still have trailing `/` ] [email protected]( + "action", ["store_true", "store_false", "count", "store_const", "append_const", "custom"]) +def test_powershell_flag_before_positional(action, change_dir): + class CustomFlagAction(Action): + def __init__(self, option_strings, dest, **kwargs): + super().__init__(option_strings, dest, nargs=0, **kwargs) + + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, True) + + parser = ArgumentParser(prog="myprog") + if action == "custom": + parser.add_argument("--flag", action=CustomFlagAction) + elif action in ("store_const", "append_const"): + parser.add_argument("--flag", action=action, const=True) + else: + parser.add_argument("--flag", action=action) + parser.add_argument("dest").complete = shtab.DIRECTORY + cands = ps_cands(change_dir, parser) + assert cands("myprog --flag target_") == [f"target_dir{os.sep}"] + + +def test_powershell_flags_preserve_positional_progress(change_dir): + parser = ArgumentParser(prog="myprog") + parser.add_argument("--force", action="store_true") + parser.add_argument("-v", action="count") + parser.add_argument("mode", choices=["fast", "slow"]) + parser.add_argument("dest").complete = shtab.DIRECTORY + cands = ps_cands(change_dir, parser) + assert cands("myprog --force -v -v f") == ["fast"] + assert cands("myprog fast --force -v target_") == [f"target_dir{os.sep}"] + + +def test_powershell_flag_before_subcommand(change_dir): + parser = ArgumentParser(prog="myprog") + parser.add_argument("--force", action="store_true") + child = parser.add_subparsers(dest="command").add_parser("create", help="create a destination") + child.add_argument("--force", action="store_true") + child.add_argument("dest").complete = shtab.DIRECTORY + cands = ps_cands(change_dir, parser) + assert cands("myprog --force cr") == ["create"] + assert cands("myprog --force create --force target_") == [f"target_dir{os.sep}"] + + +def test_powershell_value_option_still_consumes_its_argument(change_dir): + parser = ArgumentParser(prog="myprog") + parser.add_argument("--force", action="store_true") + parser.add_argument("--format", choices=["json", "yaml"]) + parser.add_argument("dest").complete = shtab.DIRECTORY + cands = ps_cands(change_dir, parser) + assert cands("myprog --format j") == ["json"] + assert cands("myprog --force --format j") == ["json"] + assert cands("myprog --format json target_") == [f"target_dir{os.sep}"] + assert cands("myprog --format json --force target_") == [f"target_dir{os.sep}"] + + def test_powershell_single_token(test_parser, change_dir): completion = complete(test_parser, 'powershell') assert powershell_candidates(completion, "myprog --") == ["--help", "--repo"] assert powershell_candidates(completion, "myprog c") == ["create"] +def test_powershell_case_sensitive_keys(): + """Names differing only in case must not clash (#267)""" + parser = ArgumentParser(prog="myprog") + parser.add_argument("-c", action="store_true", help="lower case") + parser.add_argument("-C", help="upper case") + subparsers = parser.add_subparsers() + subparsers.add_parser("a", help="lower a") + subparsers.add_parser("A", help="upper A") + completion = complete(parser, 'powershell') + assert powershell_candidates(completion, "myprog -") == ["-h", "--help", "-c", "-C"] + assert powershell_candidates(completion, "myprog ") == ["a", "A"] + + def test_fish_global_option_value(test_parser): """Subcommands complete after `--global-opt value` (#228)""" completion = complete(test_parser, 'fish') @@ -766,6 +1010,39 @@ assert shtab.add_argument_to(group) is group, "should return same object" [email protected]("metavar", ["SHELL", "<shell>"]) [email protected]("grouped", [False, True]) +def test_add_argument_to_optional_metavar(metavar, grouped, capsys): + parser = ArgumentParser(prog="test") + target = parser.add_argument_group("completion") if grouped else parser + assert shtab.add_argument_to(target, ["-s", "--shell"], metavar=metavar) is target + assert f"--shell {metavar}" in parser.format_help() + with pytest.raises(SystemExit) as exc: + parser.parse_args(["--shell", "bash"]) + assert exc.value.code == 0 + assert capsys.readouterr().out.rstrip() == shtab.complete(parser, "bash").rstrip() + with pytest.raises(SystemExit) as exc: + parser.parse_args(["--shell", "invalid-shell"]) + assert exc.value.code == 2 + assert "invalid choice" in capsys.readouterr().err + + +def test_add_argument_to_positional_metavar(capsys): + parser = ArgumentParser(prog="test") + sub = parser.add_subparsers().add_parser("completion") + shtab.add_argument_to(sub, "shell", parent=parser, metavar="SHELL") + assert "[SHELL]" in sub.format_help() + for args in (["completion", "bash"], ["completion"]): + with pytest.raises(SystemExit) as exc: + parser.parse_args(args) + assert exc.value.code == 0 + assert capsys.readouterr().out.rstrip() == shtab.complete(parser, "bash").rstrip() + with pytest.raises(SystemExit) as exc: + parser.parse_args(["completion", "invalid-shell"]) + assert exc.value.code == 2 + assert "invalid choice" in capsys.readouterr().err + + @fix_shell def test_add_argument_to_positional(shell, capsys): parser = ArgumentParser(prog="test") @@ -852,6 +1129,34 @@ shell.test('"${COMPREPLY[*]}" = "--wdir"') [email protected]("previous", ["", "--pid ", "--file ", "--directory ", "-- ", "> "]) [email protected]("word,expected", [ + ("$SHTAB_TEST_VAR", "$SHTAB_TEST_VARIABLE "), + ("${SHTAB_TEST_VAR", "${SHTAB_TEST_VARIABLE} "), + ('"$SHTAB_TEST_VAR', '"$SHTAB_TEST_VARIABLE" '), + ('"${SHTAB_TEST_VAR', '"${SHTAB_TEST_VARIABLE}" '),]) +def test_bash_variable_completion(change_dir, monkeypatch, previous, word, expected): + monkeypatch.setenv("INPUTRC", os.devnull) + monkeypatch.setenv("HISTFILE", os.devnull) + parser = ArgumentParser(prog="test") + parser.add_argument("--pid", type=int) + parser.add_argument("--file").complete = shtab.FILE + parser.add_argument("--directory").complete = shtab.DIRECTORY + completion = shtab.complete(parser, shell="bash", preamble="export SHTAB_TEST_VARIABLE=123") + lines = bash_candidates(completion, [f"test {previous}{word}"], change_dir) + assert lines == [f"test {previous}{expected}"] + + +def test_bash_fallback_does_not_complete_filenames(change_dir, monkeypatch): + monkeypatch.setenv("INPUTRC", os.devnull) + monkeypatch.setenv("HISTFILE", os.devnull) + parser = ArgumentParser(prog="test") + parser.add_argument("--pid", type=int) + (change_dir / "test_file.txt").touch() + completion = shtab.complete(parser, shell="bash") + assert bash_candidates(completion, ["test --pid test_f"], change_dir) == ["test --pid test_f"] + + @fix_shell def test_fallbacks(shell, test_parser): completion = complete(test_parser, shell)
