Exemplo n.º 1
0
    def get(cls):  # type: () -> Shell
        """
        Retrieve the current shell.
        """
        if cls._shell is not None:
            return cls._shell

        try:
            name, path = detect_shell(os.getpid())
        except (RuntimeError, ShellDetectionFailure):
            shell = None

            if os.name == "posix":
                shell = os.environ.get("SHELL")
            elif os.name == "nt":
                shell = os.environ.get("COMSPEC")

            if not shell:
                raise RuntimeError("Unable to detect the current shell.")

            name, path = Path(shell).stem, shell

        cls._shell = cls(name, path)

        return cls._shell
Exemplo n.º 2
0
Arquivo: actions.py Projeto: ulwlu/pdm
def print_pep582_command(ui: termui.UI, shell: str = "AUTO"):
    """Print the export PYTHONPATH line to be evaluated by the shell."""
    import shellingham

    if os.name == "nt":
        try:
            set_env_in_reg("PYTHONPATH", PEP582_PATH)
        except PermissionError:
            ui.echo(
                termui.red(
                    "Permission denied, please run the terminal as administrator."
                ),
                err=True,
            )
        ui.echo(
            termui.green("The environment variable has been saved, "
                         "please restart the session to take effect."))
        return
    lib_path = PEP582_PATH.replace("'", "\\'")
    if shell == "AUTO":
        shell = shellingham.detect_shell()[0]
    shell = shell.lower()
    if shell in ("zsh", "bash"):
        result = f"export PYTHONPATH='{lib_path}':$PYTHONPATH"
    elif shell == "fish":
        result = f"set -x PYTHONPATH '{lib_path}' $PYTHONPATH"
    elif shell in ("tcsh", "csh"):
        result = f"setenv PYTHONPATH '{lib_path}':$PYTHONPATH"
    else:
        raise PdmUsageError(
            f"Unsupported shell: {shell}, please specify another shell "
            "via `--pep582 <SHELL>`")
    ui.echo(result)
Exemplo n.º 3
0
def install(
    shell: Optional[str] = None,
    prog_name: Optional[str] = None,
    complete_var: Optional[str] = None,
) -> Tuple[str, Path]:
    prog_name = prog_name or click.get_current_context().find_root().info_name
    assert prog_name
    if complete_var is None:
        complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
    if shell is None and shellingham is not None:
        shell, _ = shellingham.detect_shell()
    if shell == "bash":
        installed_path = install_bash(
            prog_name=prog_name, complete_var=complete_var, shell=shell
        )
        return shell, installed_path
    elif shell == "zsh":
        installed_path = install_zsh(
            prog_name=prog_name, complete_var=complete_var, shell=shell
        )
        return shell, installed_path
    elif shell == "fish":
        installed_path = install_fish(
            prog_name=prog_name, complete_var=complete_var, shell=shell
        )
        return shell, installed_path
    elif shell in {"powershell", "pwsh"}:
        installed_path = install_powershell(
            prog_name=prog_name, complete_var=complete_var, shell=shell
        )
        return shell, installed_path
    else:
        click.echo(f"Shell {shell} is not supported.")
        raise click.exceptions.Exit(1)
Exemplo n.º 4
0
def getShell():
    user_shell = None
    try:
        user_shell = shellingham.detect_shell()[1]
    except shellingham.ShellDetectionFailure:
        user_shell = provide_default_shell()[1]

    return user_shell
Exemplo n.º 5
0
def _enable_auto_complete():
    try:
        current_shell = shellingham.detect_shell()[0]
        if current_shell != 'bash':
            click_completion.init()
    except ShellDetectionFailure:
        click_completion.init()
    except Exception:
        pass
Exemplo n.º 6
0
def get_current_shell():
    """Detect current shell with `shellingham`
    Note:
        On POSIX you might mostly get login shell instead of current shell.
        see rezup/launch/README#shell-detection
    """
    try:
        name, full_path = shellingham.detect_shell()
        return name, full_path
    except shellingham.ShellDetectionFailure:
        return provide_default(), None
Exemplo n.º 7
0
    def handle(self, project: Project, options: argparse.Namespace) -> None:
        import shellingham

        shell = options.shell or shellingham.detect_shell()[0]
        if shell not in self.SUPPORTED_SHELLS:
            raise PdmUsageError(f"Unsupported shell: {shell}")
        suffix = "ps1" if shell == "powershell" else shell
        completion = importlib.resources.read_text("pdm.cli.completions",
                                                   f"pdm.{suffix}")
        project.core.ui.echo(
            completion.replace("%{python_executable}", sys.executable))
Exemplo n.º 8
0
def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
    if not value or ctx.resilient_parsing:
        return value  # pragma no cover
    prog_name = ctx.find_root().info_name
    assert prog_name
    complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
    if isinstance(value, str):
        shell = value
    elif shellingham:
        shell, _ = shellingham.detect_shell()
    script_content = get_completion_script(prog_name, complete_var, shell)
    click.echo(script_content)
    sys.exit(0)
Exemplo n.º 9
0
Arquivo: pew.py Projeto: vjpr/pew
def _detect_shell():
    shell = os.environ.get('SHELL', None)
    if not shell:
        if 'CMDER_ROOT' in os.environ:
            shell = 'Cmder'
        elif windows:
            try:
                _, shell = shellingham.detect_shell()
            except shellingham.ShellDetectionFailure:
                shell = os.environ.get('COMSPEC', 'cmd.exe')
        else:
            shell = 'sh'
    return shell
Exemplo n.º 10
0
Arquivo: pew.py Projeto: berdario/pew
def _detect_shell():
    shell = os.environ.get('SHELL', None)
    if not shell:
        if 'CMDER_ROOT' in os.environ:
            shell = 'Cmder'
        elif windows:
            try:
                _, shell = shellingham.detect_shell()
            except shellingham.ShellDetectionFailure:
                shell = os.environ.get('COMSPEC', 'cmd.exe')
        else:
            shell = 'sh'
    return shell
Exemplo n.º 11
0
 def get_activate_command(self, venv: Path) -> str:
     shell, _ = shellingham.detect_shell()
     if shell == "fish":
         command, filename = "source", "activate.fish"
     elif shell == "csh":
         command, filename = "source", "activate.csh"
     elif shell in ["powershell", "pwsh"]:
         command, filename = ".", "Activate.ps1"
     else:
         command, filename = "source", "activate"
     activate_script = venv / BIN_DIR / filename
     if activate_script.exists():
         return f"{command} {shlex.quote(str(activate_script))}"
     # Conda backed virtualenvs don't have activate scripts
     return f"conda activate {shlex.quote(str(venv))}"
Exemplo n.º 12
0
    def get(cls):  # type: () -> Shell
        """
        Retrieve the current shell.
        """
        if cls._shell is not None:
            return cls._shell

        try:
            name, path = detect_shell(os.getpid())
        except (RuntimeError, ShellDetectionFailure):
            raise RuntimeError("Unable to detect the current shell.")

        cls._shell = cls(name, path)

        return cls._shell
Exemplo n.º 13
0
    def get(cls):  # type: () -> Shell
        """
        Retrieve the current shell.
        """
        if cls._shell is not None:
            return cls._shell

        try:
            name, path = detect_shell(os.getpid())
        except (RuntimeError, ShellDetectionFailure):
            raise RuntimeError("Unable to detect the current shell.")

        cls._shell = cls(name, path)

        return cls._shell
Exemplo n.º 14
0
def get_shell():
    try:
        name, path = detect_shell(os.getpid())
    except (RuntimeError, ShellDetectionFailure):
        shell = None

        if os.name == "posix":
            shell = os.environ.get("SHELL")
        elif os.name == "nt":
            shell = os.environ.get("COMSPEC")

        if not shell:
            raise RuntimeError("Unable to detect the current shell.")

        name, path = Path(shell).stem, shell
    return name, path
Exemplo n.º 15
0
def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
    if not value or ctx.resilient_parsing:
        return value  # pragma no cover
    prog_name = ctx.find_root().info_name
    assert prog_name
    complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
    shell = ""
    test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
    if isinstance(value, str):
        shell = value
    elif shellingham and not test_disable_detection:
        shell, _ = shellingham.detect_shell()
    script_content = get_completion_script(
        prog_name=prog_name, complete_var=complete_var, shell=shell
    )
    click.echo(script_content)
    sys.exit(0)
Exemplo n.º 16
0
def print_pep582_command(shell: str = "AUTO"):
    """Print the export PYTHONPATH line to be evaluated by the shell."""
    import shellingham

    if os.name == "nt":
        set_env_in_reg("PYTHONPATH", PEP582_PATH)
        return
    lib_path = PEP582_PATH.replace("'", "\\'")
    if shell == "AUTO":
        shell = shellingham.detect_shell()[0]
    shell = shell.lower()
    if shell in ("zsh", "bash"):
        result = f"export PYTHONPATH='{lib_path}':$PYTHONPATH"
    elif shell == "fish":
        result = f"set -x PYTHONPATH '{lib_path}' $PYTHONPATH"
    elif shell in ("tcsh", "csh"):
        result = f"setenv PYTHONPATH '{lib_path}':$PYTHONPATH"
    else:
        raise PdmUsageError(
            f"Unsupported shell: {shell}, please specify another shell "
            "via `--pep582 <SHELL>`")
    stream.echo(result)
Exemplo n.º 17
0
    def _shell_info(self) -> Tuple[str, str]:
        # detect by shellingham
        try:
            name, path = detect_shell()
        except (ShellDetectionFailure, RuntimeError):
            pass
        else:
            return name, path

        # detect by env
        for env in ('SHELL', 'COMSPEC'):
            path = os.environ.get(env)
            if path:
                return Path(path).stem, path

        # try to find any known shell
        for name in sorted(self.shells):
            path = shutil.which(name)
            if path is not None:
                return name, path

        raise OSError('cannot detect shell')
Exemplo n.º 18
0
def spawn_shell(command, cwd: Optional[Union[Path, str]] = None) -> spawn:
    try:
        name, path = detect_shell(os.getpid())
    except (RuntimeError, ShellDetectionFailure):
        shell = None

        if os.name == "posix":
            shell = os.environ.get("SHELL")
        elif os.name == "nt":
            shell = os.environ.get("COMSPEC")

        if not shell:
            raise RuntimeError("Unable to detect the current shell.")

        name, path = Path(shell).stem, shell

    c = pexpect.spawn(path, args=["-i"])
    c.sendline(command)
    if cwd:
        c.sendline(f"cd {cwd}")
    c.interact(escape_character=None)
    yield c

    sys.exit(c.exitstatus)
Exemplo n.º 19
0
def get_auto_shell():
    """Returns the current shell

    This feature depends on psutil and will not work if it is not available"""
    return shellingham.detect_shell()[0]
Exemplo n.º 20
0
    def handle(self, project: Project, options: argparse.Namespace) -> None:
        import shellingham
        from pycomplete import Completer

        completer = Completer(project.core.parser)
        stream.echo(completer.render(options.shell or shellingham.detect_shell()[0]))
Exemplo n.º 21
0
def install(
    shell: Optional[str] = None,
    prog_name: Optional[str] = None,
    complete_var: Optional[str] = None,
) -> Tuple[str, Path]:
    prog_name = prog_name or click.get_current_context().find_root().info_name
    assert prog_name
    if complete_var is None:
        complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
    if shell is None and shellingham is not None:
        shell, _ = shellingham.detect_shell()
    mode = None
    if shell == "bash":
        path_obj = Path.home() / ".bash_completion"
        mode = mode or "a"
    elif shell == "zsh":
        path_obj = Path.home() / ".zshrc"
        mode = mode or "a"
    elif shell == "fish":
        path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"
        mode = mode or "w"
    elif shell in {"powershell", "pwsh"}:
        subprocess.run(
            [
                shell,
                "-Command",
                "Set-ExecutionPolicy",
                "Unrestricted",
                "-Scope",
                "CurrentUser",
            ]
        )
        result = subprocess.run(
            [shell, "-NoProfile", "-Command", "echo", "$profile"],
            check=True,
            stdout=subprocess.PIPE,
        )
        if result.returncode != 0:  # pragma: nocover
            click.echo("Couldn't get PowerShell user profile", err=True)
            raise click.exceptions.Exit(result.returncode)
        path_str = ""
        if isinstance(result.stdout, str):  # pragma: nocover
            path_str = result.stdout
        if isinstance(result.stdout, bytes):
            try:
                # PowerShell would be predominant in Windows
                path_str = result.stdout.decode("windows-1252")
            except UnicodeDecodeError:  # pragma: nocover
                try:
                    path_str = result.stdout.decode("utf8")
                except UnicodeDecodeError:
                    click.echo("Couldn't decode the path automatically", err=True)
                    raise click.exceptions.Exit(1)
        path_obj = Path(path_str.strip())
        mode = mode or "a"
    else:
        click.echo(f"Shell {shell} is not supported.")
        raise click.exceptions.Exit(1)
    parent_dir: Path = path_obj.parent
    parent_dir.mkdir(parents=True, exist_ok=True)
    script_content = get_installable_script(prog_name, complete_var, shell)
    with path_obj.open(mode=mode) as f:
        f.write(f"{script_content}\n")
    return shell, path_obj
Exemplo n.º 22
0
COLORS = __all__[:-2]

is_ipython = "get_ipython" in dir()

if (
    os.environ.get("CMDER_ROOT")
    or os.environ.get("VSCODE_PID")
    or os.environ.get("TERM_PROGRAM") == "Hyper"
):
    is_native_powershell = False
else:
    is_native_powershell = True

try:
    is_powershell = "powershell" in shellingham.detect_shell()[0]
except shellingham.ShellDetectionFailure:
    is_powershell = False

if is_ipython or (is_powershell and is_native_powershell):
    """when ipython is fired lot of variables like _oh, etc are used.
       There are so many ways to find current python interpreter is ipython.
       get_ipython is easiest is most appealing for readers to understand.
    """
    DISABLE_COLOR = True
else:
    DISABLE_COLOR = False


class ColoredString(object):
    """Enhanced string for __len__ operations on Colored output."""
Exemplo n.º 23
0
def get_auto_shell():
    """Returns the current shell"""
    return shellingham.detect_shell()[0]