Debian Codegraph @

src/util/util_windows.go

raw
1 //go:build windows
2
3 package util
4
5 import (
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "regexp"
11 "strings"
12 "sync/atomic"
13 "syscall"
14
15 "golang.org/x/sys/windows"
16 )
17
18 type shellType int
19
20 const (
21 shellTypeUnknown shellType = iota
22 shellTypeCmd
23 shellTypePowerShell
24 shellTypePwsh
25 )
26
27 var escapeRegex = regexp.MustCompile(`[&|<>()^%!"]`)
28
29 type Executor struct {
30 shell string
31 shellType shellType
32 args []string
33 shellPath atomic.Value
34 }
35
36 func NewExecutor(withShell string) *Executor {
37 shell := os.Getenv("SHELL")
38 args := strings.Fields(withShell)
39 if len(args) > 0 {
40 shell = args[0]
41 } else if len(shell) == 0 {
42 shell = "cmd"
43 }
44
45 shellType := shellTypeUnknown
46 basename := filepath.Base(shell)
47 if len(args) > 0 {
48 args = args[1:]
49 } else if strings.HasPrefix(basename, "cmd") {
50 shellType = shellTypeCmd
51 args = []string{"/s/c"}
52 } else if strings.HasPrefix(basename, "pwsh") {
53 shellType = shellTypePwsh
54 args = []string{"-NoProfile", "-Command"}
55 } else if strings.HasPrefix(basename, "powershell") {
56 shellType = shellTypePowerShell
57 args = []string{"-NoProfile", "-Command"}
58 } else {
59 args = []string{"-c"}
60 }
61 return &Executor{shell: shell, shellType: shellType, args: args}
62 }
63
64 // ExecCommand executes the given command with $SHELL
65 //
66 // On Windows, setpgid controls whether the spawned process is placed in a new
67 // process group (so that it can be signaled independently, e.g. for previews).
68 // However, we only do this for "pwsh" and non-standard shells, because cmd.exe
69 // and Windows PowerShell ("powershell.exe") don't always exit on Ctrl-Break.
70 //
71 // NOTE: For "powershell", we should ideally set output encoding to UTF8,
72 // but it is left as is now because no adverse effect has been observed.
73 func (x *Executor) ExecCommand(command string, setpgid bool) *exec.Cmd {
74 shell := x.shell
75 if cached := x.shellPath.Load(); cached != nil {
76 shell = cached.(string)
77 } else {
78 if strings.Contains(shell, "/") {
79 out, err := exec.Command("cygpath", "-w", shell).Output()
80 if err == nil {
81 shell = strings.Trim(string(out), "\n")
82 }
83 }
84 x.shellPath.Store(shell)
85 }
86
87 var creationFlags uint32
88 // Set new process group for pwsh (PowerShell 7+) and unknown/posix-ish shells
89 if setpgid && (x.shellType == shellTypePwsh || x.shellType == shellTypeUnknown) {
90 creationFlags = windows.CREATE_NEW_PROCESS_GROUP
91 }
92
93 var cmd *exec.Cmd
94 if x.shellType == shellTypeCmd {
95 cmd = exec.Command(shell)
96 cmd.SysProcAttr = &syscall.SysProcAttr{
97 HideWindow: false,
98 CmdLine: fmt.Sprintf(`%s "%s"`, strings.Join(x.args, " "), command),
99 CreationFlags: creationFlags,
100 }
101 } else {
102 args := x.args
103 if setpgid && x.shellType == shellTypePwsh {
104 // pwsh needs -NonInteractive flag to exit on Ctrl-Break
105 args = append([]string{"-NonInteractive"}, x.args...)
106 }
107 cmd = exec.Command(shell, append(args, command)...)
108 cmd.SysProcAttr = &syscall.SysProcAttr{
109 HideWindow: false,
110 CreationFlags: creationFlags,
111 }
112 }
113 return cmd
114 }
115
116 func (x *Executor) Become(stdin *os.File, environ []string, command string) {
117 cmd := x.ExecCommand(command, false)
118 cmd.Stdin = stdin
119 cmd.Stdout = os.Stdout
120 cmd.Stderr = os.Stderr
121 cmd.Env = environ
122 err := cmd.Start()
123 if err != nil {
124 fmt.Fprintf(os.Stderr, "fzf (become): %s\n", err.Error())
125 os.Exit(127)
126 }
127 err = cmd.Wait()
128 if err != nil {
129 if exitError, ok := err.(*exec.ExitError); ok {
130 os.Exit(exitError.ExitCode())
131 }
132 }
133 os.Exit(0)
134 }
135
136 func escapeArg(s string) string {
137 b := make([]byte, 0, len(s)+2)
138 b = append(b, '"')
139 slashes := 0
140 for i := 0; i < len(s); i++ {
141 c := s[i]
142 switch c {
143 default:
144 slashes = 0
145 case '\\':
146 slashes++
147 case '"':
148 for ; slashes > 0; slashes-- {
149 b = append(b, '\\')
150 }
151 b = append(b, '\\')
152 }
153 b = append(b, c)
154 }
155 for ; slashes > 0; slashes-- {
156 b = append(b, '\\')
157 }
158 b = append(b, '"')
159 return escapeRegex.ReplaceAllStringFunc(string(b), func(match string) string {
160 return "^" + match
161 })
162 }
163
164 func (x *Executor) QuoteEntry(entry string) string {
165 switch x.shellType {
166 case shellTypeCmd:
167 /* Manually tested with the following commands:
168 fzf --preview "echo {}"
169 fzf --preview "type {}"
170 echo .git\refs\| fzf --preview "dir {}"
171 echo .git\refs\\| fzf --preview "dir {}"
172 echo .git\refs\\\| fzf --preview "dir {}"
173 reg query HKCU | fzf --reverse --bind "enter:reload(reg query {})"
174 fzf --disabled --preview "echo {q} {n} {}" --query "&|<>()@^%!"
175 fd -H --no-ignore -td -d 4 | fzf --preview "dir {}"
176 fd -H --no-ignore -td -d 4 | fzf --preview "eza {}" --preview-window up
177 fd -H --no-ignore -td -d 4 | fzf --preview "eza --color=always --tree --level=3 --icons=always {}"
178 fd -H --no-ignore -td -d 4 | fzf --preview ".\eza.exe --color=always --tree --level=3 --icons=always {}" --with-shell "powershell -NoProfile -Command"
179 */
180 return escapeArg(entry)
181 case shellTypePowerShell, shellTypePwsh:
182 escaped := strings.ReplaceAll(entry, `"`, `\"`)
183 return "'" + strings.ReplaceAll(escaped, "'", "''") + "'"
184 default:
185 return "'" + strings.ReplaceAll(entry, "'", "'\\''") + "'"
186 }
187 }
188
189 // KillCommand kills the process for the given command
190 func KillCommand(cmd *exec.Cmd) error {
191 // Safely handle nil command or process.
192 if cmd == nil || cmd.Process == nil {
193 return nil
194 }
195 // If it has its own process group, we can send it Ctrl-Break
196 if cmd.SysProcAttr != nil && cmd.SysProcAttr.CreationFlags&windows.CREATE_NEW_PROCESS_GROUP != 0 {
197 if err := windows.GenerateConsoleCtrlEvent(windows.CTRL_BREAK_EVENT, uint32(cmd.Process.Pid)); err == nil {
198 return nil
199 }
200 }
201 // If it's the same process group, or if sending the console control event
202 // fails (e.g., no console, different console, or process already exited),
203 // fall back to a standard kill. This probably won't *help* if there's I/O
204 // going on, because Wait() will still hang until the I/O finishes unless we
205 // hard-kill the entire process group. But it doesn't hurt to try!
206 return cmd.Process.Kill()
207 }
208
209 // IsWindows returns true on Windows
210 func IsWindows() bool {
211 return true
212 }
213
214 // SetNonblock executes syscall.SetNonblock on file descriptor
215 func SetNonblock(file *os.File, nonblock bool) {
216 syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock)
217 }
218
219 // Read executes syscall.Read on file descriptor
220 func Read(fd int, b []byte) (int, error) {
221 return syscall.Read(syscall.Handle(fd), b)
222 }
223
224 func SetStdin(file *os.File) {
225 // No-op
226 }