sarugaku / shellingham

Tool to Detect Surrounding Shell
ISC License
227 stars 33 forks source link

Can we correctly detect the full path of the shell for windows? #42

Closed matthewdeanmartin closed 3 years ago

matthewdeanmartin commented 3 years ago

For example, psutil seems to have no problem finding the parent shell.

I'm hoping that shellingham's window support can be extended because what I really would like is for poetry to work on windows via (git-bash, cygwin, mingw) See bug filed over there. In poetry's case, if they'd just use shell=True when launching the subprocess, the shell detection wouldn't matter.

But if shellingham could return the actual path of the shell instead of just it's name, maybe poetry would just start working.

from typing import Tuple, List

import os

import psutil

SHELL_NAMES = {
    'sh', 'bash', 'dash', 'ash',    # Bourne.
    'csh', 'tcsh',                  # C.
    'ksh', 'zsh', 'fish',           # Common alternatives.
    'cmd', 'powershell', 'pwsh',    # Microsoft.
    'elvish', 'xonsh',              # More exotic.
}

def find_shell_for_windows() -> Tuple[str,str]:
    names_paths:List[Tuple[str,str]]=[]
    current_process = psutil.Process(os.getppid())
    process_name, process_path = current_process.name(), current_process.exe()
    names_paths.append((process_name, process_path))
    for parent in current_process.parents():
        names_paths.append((parent.name(), parent.exe()))
    for n,p in names_paths:
        if n.lower() in SHELL_NAMES or n.lower().replace(".exe","") in SHELL_NAMES:
            return n,p
    return ["",""]

if __name__ == '__main__':
    print(find_shell_for_windows())

results

$ python ./detect_shell.py ('bash.exe', 'C:\Program Files\Git\usr\bin\bash.exe')

And then bash is launched from powershell via & "C:\Program Files\Git\usr\bin\bash.exe" --login

uranusjr commented 3 years ago

It is definitely possible, I just didn't feel the need to implement it. I don't want to use psutil either since I want to keep the package Python-only. Feel free to send in a PR if the criteria are met.

matthewdeanmartin commented 3 years ago

This PR addresses this issue. The macos detect fails in the GH action, but has been failing for months.

I don't know anything about the nt.py code, so I left most of there & redirected the function to windows.py. Feel free to replace nt.py with windows.py.

https://github.com/sarugaku/shellingham/pull/43

uranusjr commented 3 years ago

Released as 1.4.0.