-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathshell_windows.go
More file actions
90 lines (78 loc) · 2.07 KB
/
shell_windows.go
File metadata and controls
90 lines (78 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package shell
import (
"os"
"path/filepath"
"strings"
"syscall"
"unsafe"
)
var (
supportedShell = []string{"cmd", "powershell"}
)
// re-implementation of private function in https://github.com/golang/go/blob/master/src/syscall/syscall_windows.go
func getProcessEntry(pid int) (pe *syscall.ProcessEntry32, err error) {
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
}
defer func() {
_ = syscall.CloseHandle(syscall.Handle(snapshot))
}()
var processEntry syscall.ProcessEntry32
processEntry.Size = uint32(unsafe.Sizeof(processEntry))
err = syscall.Process32First(snapshot, &processEntry)
if err != nil {
return nil, err
}
for {
if processEntry.ProcessID == uint32(pid) {
pe = &processEntry
return
}
err = syscall.Process32Next(snapshot, &processEntry)
if err != nil {
return nil, err
}
}
}
// getNameAndItsPpid returns the exe file name its parent process id.
func getNameAndItsPpid(pid int) (exefile string, parentid int, err error) {
pe, err := getProcessEntry(pid)
if err != nil {
return "", 0, err
}
name := syscall.UTF16ToString(pe.ExeFile[:])
return name, int(pe.ParentProcessID), nil
}
func detect() (string, error) {
shell := os.Getenv("SHELL")
if shell == "" {
shell, shellppid, err := getNameAndItsPpid(os.Getppid())
if err != nil {
return "cmd", err // defaulting to cmd
}
switch {
case strings.Contains(strings.ToLower(shell), "powershell"):
return "powershell", nil
case strings.Contains(strings.ToLower(shell), "cmd"):
return "cmd", nil
default:
shell, _, err := getNameAndItsPpid(shellppid)
if err != nil {
return "cmd", err // defaulting to cmd
}
switch {
case strings.Contains(strings.ToLower(shell), "powershell"):
return "powershell", nil
case strings.Contains(strings.ToLower(shell), "cmd"):
return "cmd", nil
default:
return "cmd", nil // this could be either powershell or cmd, defaulting to cmd
}
}
}
if os.Getenv("__fish_bin_dir") != "" {
return "fish", nil
}
return filepath.Base(shell), nil
}