[docs]classPowerShellComplete(DjangoTyperShellCompleter):""" This completer class supports the PowerShell_ versions < 6. See :class:`~PwshComplete` for versions >= 6. Completion scripts are installed into the user's profile file. Returned suggestions are delimited by ``:::``. Each suggestion is one one line. """name="powershell"""" shell executable. """template="shell_complete/powershell.ps1"""" The template used to render the powershell completion script. """supports_scripts=False""" PowerShell does not support script invocations. """color=False""" PowerShell_ does support ansi control codes in completion suggestions, but we disable them by default. """defformat_completion(self,item:CompletionItem)->str:return":::".join([item.type,self.process_rich_text(item.value)," ".join([ln.strip()forlninself.process_rich_text(item.helpor" ").splitlines()]),])defset_execution_policy(self)->None:subprocess.run([self.name,"-Command","Set-ExecutionPolicy","Unrestricted","-Scope","CurrentUser",])defget_user_profile(self)->Path:result=subprocess.run([self.name,"-NoProfile","-Command","echo","$profile"],check=True,stdout=subprocess.PIPE,)ifresult.returncode==0:forencodingin["windows-1252","utf8","cp850"]:try:returnPath(result.stdout.decode(encoding).strip())exceptUnicodeDecodeError:# pragma: no coverpassraiseRuntimeError("Unable to find the PowerShell user profile.")# pragma: no coverdefinstall(self,prompt:bool=True)->t.List[Path]:assertself.prog_nameself.uninstall()self.set_execution_policy()profile=self.get_user_profile()start_line=0ifnotprofile.exists()elseprofile.read_text().count("\n")+1source=self.source()ifself.prompt(prompt=prompt,source=source,file=profile,start_line=start_line):profile.parent.mkdir(parents=True,exist_ok=True)withprofile.open(mode="a")asf:f.writelines(["",self.source()])return[profile]return[]defuninstall(self)->None:# annoyingly, powershell has one profile script for all completion commands# so we have to find our entry and remove itassertself.prog_nameself.set_execution_policy()profile=self.get_user_profile()ifnotprofile.exists():returnedited_lines=[]mark=Nonewithopen(profile,"rt",encoding="utf-8")aspwr_sh:forlineinpwr_sh.readlines():edited_lines.append(line)ifline.startswith("Import-Module PSReadLine"):mark=len(edited_lines)-1elif(markisnotNoneandline.startswith("Register-ArgumentCompleter")andf" {self.command.manage_script_name} "inline):edited_lines=edited_lines[:mark]mark=Noneifedited_lines:withopen(profile,"wt",encoding="utf-8")aspwr_sh:pwr_sh.writelines(edited_lines)else:profile.unlink()
[docs]classPwshComplete(PowerShellComplete):""" This completer class supports the PowerShell_ versions >= 6. See :class:`~PowerShellComplete` for versions < 6. All behaviors are the same as :class:`~PowerShellComplete`, except that ``pwsh`` is used instead of ``powershell``. """name="pwsh"""" shell executable. """