Skip to content
Myr

:sparkles: Make installed completion lazy load (#92)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* :sparkles: Re-implement completion install to lazy load to support completion for programs under environments * :white_check_mark: Update tests for new lazy loaded completion * :white_check_mark: Update test after removing period from message

authored by Sebastián Ramírez · committed by GitHub · parent 9cc3ebe · Browse files · 4 files+157 added−198 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+157 added−198 removed

  • tests:+27 added−137 removed
  • other:+130 added−61 removed

4 files+157 added−198 removed

deleted:tests/test_completion/test_completion_install_source.py-109 removed
1import os2import subprocess34from first_steps import tutorial001 as mod567def test_completion_install_source_bash():8 result = subprocess.run(9 ["coverage", "run", mod.__file__],10 stdout=subprocess.PIPE,11 stderr=subprocess.PIPE,12 encoding="utf-8",13 env={14 **os.environ,15 "_TUTORIAL001.PY_COMPLETE": "install-source_bash",16 "_TYPER_COMPLETE_TESTING": "True",17 },18 )19 assert (20 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py 2>/dev/null)"'21 in result.stdout22 )232425def test_completion_install_source_zsh():26 result = subprocess.run(27 ["coverage", "run", mod.__file__],28 stdout=subprocess.PIPE,29 stderr=subprocess.PIPE,30 encoding="utf-8",31 env={32 **os.environ,33 "_TUTORIAL001.PY_COMPLETE": "install-source_zsh",34 "_TYPER_COMPLETE_TESTING": "True",35 },36 )37 assert (38 'eval "$(_TUTORIAL001.PY_COMPLETE=source_zsh tutorial001.py 2>/dev/null)"'39 in result.stdout40 )414243def test_completion_install_source_fish():44 result = subprocess.run(45 ["coverage", "run", mod.__file__],46 stdout=subprocess.PIPE,47 stderr=subprocess.PIPE,48 encoding="utf-8",49 env={50 **os.environ,51 "_TUTORIAL001.PY_COMPLETE": "install-source_fish",52 "_TYPER_COMPLETE_TESTING": "True",53 },54 )55 assert (56 "eval (env _TUTORIAL001.PY_COMPLETE=source_fish tutorial001.py 2>/dev/null)"57 in result.stdout58 )596061def test_completion_install_source_powershell():62 result = subprocess.run(63 ["coverage", "run", mod.__file__],64 stdout=subprocess.PIPE,65 stderr=subprocess.PIPE,66 encoding="utf-8",67 env={68 **os.environ,69 "_TUTORIAL001.PY_COMPLETE": "install-source_powershell",70 "_TYPER_COMPLETE_TESTING": "True",71 },72 )73 assert (74 "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"75 in result.stdout76 )777879def test_completion_install_source_pwsh():80 result = subprocess.run(81 ["coverage", "run", mod.__file__],82 stdout=subprocess.PIPE,83 stderr=subprocess.PIPE,84 encoding="utf-8",85 env={86 **os.environ,87 "_TUTORIAL001.PY_COMPLETE": "install-source_pwsh",88 "_TYPER_COMPLETE_TESTING": "True",89 },90 )91 assert (92 "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"93 in result.stdout94 )959697def test_completion_install_source_noshell():98 result = subprocess.run(99 ["coverage", "run", mod.__file__],100 stdout=subprocess.PIPE,101 stderr=subprocess.PIPE,102 encoding="utf-8",103 env={104 **os.environ,105 "_TUTORIAL001.PY_COMPLETE": "install-source_noshell",106 "_TYPER_COMPLETE_TESTING": "True",107 },108 )109 assert "" in result.stdout
modified:tests/test_completion/test_completion_install.py+24 added-23 removed
45 unmodified lines
46 },47 )48 new_text = bash_completion_path.read_text()49 bash_completion_path.write_text(text)50 install_script = (51 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py 2>/dev/null)'52 )53 assert install_script not in text54 assert install_script in new_text50 install_source = ".bash_completions/tutorial001.py.sh"51 assert install_source not in text52 assert install_source in new_text53 assert "completion installed in" in result.stdout56 assert "Completion will take effect once you restart the terminal." in result.stdout54 assert "Completion will take effect once you restart the terminal" in result.stdout55 install_source_path = Path.home() / install_source56 assert install_source_path.is_file()57 install_content = install_source_path.read_text()58 install_source_path.unlink()59 assert (60 "complete -o default -F _tutorial001py_completion tutorial001.py"61 in install_content62 )636465def test_completion_install_zsh():66 completion_path: Path = Path.home() / ".zshrc"
12 unmodified lines
79 },80 )81 new_text = completion_path.read_text()82 completion_path.write_text(text)77 install_script = (78 'eval "$(_TUTORIAL001.PY_COMPLETE=source_zsh tutorial001.py 2>/dev/null)"'79 )80 assert install_script not in text81 assert install_script in new_text83 zfunc_fragment = "fpath+=~/.zfunc"84 assert zfunc_fragment in new_text85 assert "completion installed in" in result.stdout83 assert "Completion will take effect once you restart the terminal." in result.stdout86 assert "Completion will take effect once you restart the terminal" in result.stdout87 install_source_path = Path.home() / ".zfunc/_tutorial001.py"88 assert install_source_path.is_file()89 install_content = install_source_path.read_text()90 install_source_path.unlink()91 assert "compdef _tutorial001py_completion tutorial001.py" in install_content929394def test_completion_install_fish():95 script_path = Path(mod.__file__)96 completion_path: Path = Path.home() / f".config/fish/completions/{script_path.name}.fish"89 text = ""90 if completion_path.is_file(): # pragma: nocover91 text = completion_path.read_text()97 result = subprocess.run(98 ["coverage", "run", mod.__file__, "--install-completion", "fish"],99 stdout=subprocess.PIPE,100 stderr=subprocess.PIPE,
4 unmodified lines
105 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",106 },107 )108 new_text = completion_path.read_text()104 completion_path.write_text(text)105 install_script = (106 "eval (env _TUTORIAL001.PY_COMPLETE=source_fish tutorial001.py 2>/dev/null)"107 )108 assert install_script not in text109 assert install_script in new_text109 completion_path.unlink()110 assert "complete --command tutorial001.py" in new_text111 assert "completion installed in" in result.stdout111 assert "Completion will take effect once you restart the terminal." in result.stdout112 assert "Completion will take effect once you restart the terminal" in result.stdout113114115runner = CliRunner()116app = typer.Typer()
26 unmodified lines
143 completion_path.write_text(text)144 assert install_script not in text145 assert install_script in new_text146 assert "completion installed in" in result.stdout146 assert "Completion will take effect once you restart the terminal." in result.stdout147 assert "Completion will take effect once you restart the terminal" in result.stdout
modified:tests/test_completion/test_completion.py+3 added-5 removed
37 unmodified lines
38 env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True"},39 )40 new_text = bash_completion_path.read_text()41 bash_completion_path.write_text(text)42 assert (43 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py 2>/dev/null)'44 in new_text45 )42 assert "source" in new_text43 assert ".bash_completions/tutorial001.py.sh" in new_text44 assert "completion installed in" in result.stdout47 assert "Completion will take effect once you restart the terminal." in result.stdout45 assert "Completion will take effect once you restart the terminal" in result.stdout464748def test_completion_invalid_instruction():49 result = subprocess.run(
126 unmodified lines
modified:typer/completion.py+130 added-61 removed
37 unmodified lines
38 if isinstance(value, str):39 shell, path = install(shell=value)40 else:41 shell, path = install()42 click.secho(f"{shell} completion installed in {path}.", fg="green")43 click.echo("Completion will take effect once you restart the terminal.")42 click.secho(f"{shell} completion installed in {path}", fg="green")43 click.echo("Completion will take effect once you restart the terminal")44 sys.exit(0)454647def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
5 unmodified lines
53 if isinstance(value, str):54 shell = value55 elif shellingham:56 shell, _ = shellingham.detect_shell()57 script_content = get_completion_script(prog_name, complete_var, shell)57 script_content = get_completion_script(58 prog_name=prog_name, complete_var=complete_var, shell=shell59 )60 click.echo(script_content)61 sys.exit(0)6263
101 unmodified lines
165 if complete_var is None:166 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())167 if shell is None and shellingham is not None:168 shell, _ = shellingham.detect_shell()167 mode = None169 if shell == "bash":169 path_obj = Path.home() / ".bashrc"170 mode = mode or "a"170 installed_path = install_bash(171 prog_name=prog_name, complete_var=complete_var, shell=shell172 )173 return shell, installed_path174 elif shell == "zsh":172 path_obj = Path.home() / ".zshrc"173 mode = mode or "a"175 installed_path = install_zsh(176 prog_name=prog_name, complete_var=complete_var, shell=shell177 )178 return shell, installed_path179 elif shell == "fish":175 path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"176 mode = mode or "w"180 installed_path = install_fish(181 prog_name=prog_name, complete_var=complete_var, shell=shell182 )183 return shell, installed_path184 elif shell in {"powershell", "pwsh"}:178 subprocess.run(179 [180 shell,181 "-Command",182 "Set-ExecutionPolicy",183 "Unrestricted",184 "-Scope",185 "CurrentUser",186 ]185 installed_path = install_powershell(186 prog_name=prog_name, complete_var=complete_var, shell=shell187 )188 result = subprocess.run(189 [shell, "-NoProfile", "-Command", "echo", "$profile"],190 check=True,191 stdout=subprocess.PIPE,192 )193 if result.returncode != 0: # pragma: nocover194 click.echo("Couldn't get PowerShell user profile", err=True)195 raise click.exceptions.Exit(result.returncode)196 path_str = ""197 if isinstance(result.stdout, str): # pragma: nocover198 path_str = result.stdout199 if isinstance(result.stdout, bytes):200 try:201 # PowerShell would be predominant in Windows202 path_str = result.stdout.decode("windows-1252")203 except UnicodeDecodeError: # pragma: nocover204 try:205 path_str = result.stdout.decode("utf8")206 except UnicodeDecodeError:207 click.echo("Couldn't decode the path automatically", err=True)208 raise click.exceptions.Exit(1)209 path_obj = Path(path_str.strip())210 mode = mode or "a"188 return shell, installed_path189 else:190 click.echo(f"Shell {shell} is not supported.")191 raise click.exceptions.Exit(1)192193194def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path:195 # Ref: https://github.com/scop/bash-completion#faq196 # It seems bash-completion is the official completion system for bash:197 # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html198 # But installing in the locations from the docs doesn't seem to have effect199 completion_path = Path.home() / f".bash_completions/{prog_name}.sh"200 rc_path = Path.home() / ".bashrc"201 rc_path.parent.mkdir(parents=True, exist_ok=True)202 rc_content = ""203 if rc_path.is_file():204 rc_content = rc_path.read_text()205 completion_init_lines = [f"source {completion_path}"]206 for line in completion_init_lines:207 if line not in rc_content:208 rc_content += f"\n{line}"209 rc_content += "\n"210 rc_path.write_text(rc_content)211 # Install completion212 completion_path.parent.mkdir(parents=True, exist_ok=True)213 script_content = get_completion_script(214 prog_name=prog_name, complete_var=complete_var, shell=shell215 )216 completion_path.write_text(script_content)217 return completion_path218219220def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path:221 # Setup Zsh and load ~/.zfunc222 zshrc_path = Path.home() / ".zshrc"223 zshrc_path.parent.mkdir(parents=True, exist_ok=True)224 zshrc_content = ""225 if zshrc_path.is_file():226 zshrc_content = zshrc_path.read_text()227 completion_init_lines = [228 "autoload -Uz compinit",229 "compinit",230 "zstyle ':completion:*' menu select",231 "fpath+=~/.zfunc",232 ]233 for line in completion_init_lines:234 if line not in zshrc_content:235 zshrc_content += f"\n{line}"236 zshrc_content += "\n"237 zshrc_path.write_text(zshrc_content)238 # Install completion under ~/.zfunc/239 path_obj = Path.home() / f".zfunc/_{prog_name}"240 path_obj.parent.mkdir(parents=True, exist_ok=True)241 script_content = get_completion_script(242 prog_name=prog_name, complete_var=complete_var, shell=shell243 )244 path_obj.write_text(script_content)245 return path_obj246247248def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path:249 path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"250 parent_dir: Path = path_obj.parent251 parent_dir.mkdir(parents=True, exist_ok=True)216 script_content = get_installable_script(prog_name, complete_var, shell)217 with path_obj.open(mode=mode) as f:218 f.write(f"{script_content}\n")219 return shell, path_obj252 script_content = get_completion_script(253 prog_name=prog_name, complete_var=complete_var, shell=shell254 )255 path_obj.write_text(f"{script_content}\n")256 return path_obj257258222def get_installable_script(prog_name: str, complete_var: str, shell: str) -> str:223 if shell == "bash":224 return f'eval "$({complete_var}=source_bash {prog_name} 2>/dev/null)"'225 elif shell == "zsh":226 return f'eval "$({complete_var}=source_zsh {prog_name} 2>/dev/null)"'227 elif shell == "fish":228 return f"eval (env {complete_var}=source_fish {prog_name} 2>/dev/null)"229 elif shell in {"powershell", "pwsh"}:230 return get_completion_script(prog_name, complete_var, shell)231 return ""259def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path:260 subprocess.run(261 [262 shell,263 "-Command",264 "Set-ExecutionPolicy",265 "Unrestricted",266 "-Scope",267 "CurrentUser",268 ]269 )270 result = subprocess.run(271 [shell, "-NoProfile", "-Command", "echo", "$profile"],272 check=True,273 stdout=subprocess.PIPE,274 )275 if result.returncode != 0: # pragma: nocover276 click.echo("Couldn't get PowerShell user profile", err=True)277 raise click.exceptions.Exit(result.returncode)278 path_str = ""279 if isinstance(result.stdout, str): # pragma: nocover280 path_str = result.stdout281 if isinstance(result.stdout, bytes):282 try:283 # PowerShell would be predominant in Windows284 path_str = result.stdout.decode("windows-1252")285 except UnicodeDecodeError: # pragma: nocover286 try:287 path_str = result.stdout.decode("utf8")288 except UnicodeDecodeError:289 click.echo("Couldn't decode the path automatically", err=True)290 raise click.exceptions.Exit(1)291 path_obj = Path(path_str.strip())292 parent_dir: Path = path_obj.parent293 parent_dir.mkdir(parents=True, exist_ok=True)294 script_content = get_completion_script(295 prog_name=prog_name, complete_var=complete_var, shell=shell296 )297 with path_obj.open(mode="a") as f:298 f.write(f"{script_content}\n")299 return path_obj300301302def do_bash_complete(cli: click.Command, prog_name: str) -> bool:303 cwords = click.parser.split_arg_string(os.getenv("COMP_WORDS", ""))
103 unmodified lines
407 "pwsh": COMPLETION_SCRIPT_POWER_SHELL,408}409410343def get_completion_script(prog_name: str, complete_var: str, shell: str) -> str:411def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:412 cf_name = click._bashcomplete._invalid_ident_char_re.sub(413 "", prog_name.replace("-", "_")414 )415 script = _completion_scripts.get(shell)
17 unmodified lines
433 click.echo("Invalid completion instruction.", err=True)434 sys.exit(1)435 command, shell = complete_instr.split("_", 1)436 if command == "source":369 click.echo(get_completion_script(prog_name, complete_var, shell))437 click.echo(438 get_completion_script(439 prog_name=prog_name, complete_var=complete_var, shell=shell440 )441 )442 return True371 elif command == "install-source":372 click.echo(get_installable_script(prog_name, complete_var, shell))373 return True443 elif command == "complete":444 return do_shell_complete(cli=cli, prog_name=prog_name, shell=shell)445 return False446
20 unmodified lines