-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshell.go
81 lines (69 loc) · 1.69 KB
/
shell.go
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
package main
import (
"os"
"os/exec"
"strings"
"github.com/shirou/gopsutil/process"
)
func getShell() string {
knownShells := []string{"bash", "sh", "zsh", "powershell", "cmd", "fish", "tcsh", "csh", "ksh", "dash"}
pid := os.Getppid()
for {
ppid, err := process.NewProcess(int32(pid))
if err != nil {
// If the process does not exist or there's another error, break the loop
break
}
parentProcessName, err := ppid.Name()
if err != nil {
panic(err)
}
parentProcessName = strings.TrimSuffix(parentProcessName, ".exe")
for _, shell := range knownShells {
if parentProcessName == shell {
return shell
}
}
pidInt, err := ppid.Ppid()
if err != nil {
// If there's an error, break the loop
break
}
pid = int(pidInt)
}
return ""
}
var shellCache *string = nil
func getShellCached() string {
if shellCache == nil {
shell := getShell()
shellCache = &shell
}
return *shellCache
}
func getShellVersion(shell string) string {
if shell == "" {
return ""
}
var versionOutput *string = nil
switch shell {
case "powershell":
// read: $PSVersionTable.PSVersion
versionCmd := exec.Command(shell, "-Command", "$PSVersionTable.PSVersion")
versionCmdOutput, err := versionCmd.Output()
if err != nil {
return "Error getting PowerShell version"
}
versionCmdOutputString := string(versionCmdOutput)
versionOutput = &versionCmdOutputString
default:
versionCmd := exec.Command(shell, "--version")
versionCmdOutput, err := versionCmd.Output()
if err != nil {
return "Error getting shell version"
}
versionCmdOutputString := string(versionCmdOutput)
versionOutput = &versionCmdOutputString
}
return strings.TrimSpace(*versionOutput)
}