summaryrefslogtreecommitdiff
path: root/src/winpty_windows.go
blob: aba02ce22103335c11862aa709c94630747b67c3 (plain)
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
//go:build windows

package fzf

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/junegunn/fzf/src/util"
)

func isMintty345() bool {
	return util.CompareVersions(os.Getenv("TERM_PROGRAM_VERSION"), "3.4.5") >= 0
}

func needWinpty(opts *Options) bool {
	if os.Getenv("TERM_PROGRAM") != "mintty" {
		return false
	}
	if isMintty345() {
		/*
		 See: https://github.com/junegunn/fzf/issues/3809

		 "MSYS=enable_pcon" allows fzf to run properly on mintty 3.4.5 or later.
		*/
		if strings.Contains(os.Getenv("MSYS"), "enable_pcon") {
			return false
		}

		// Setting the environment variable here unfortunately doesn't help,
		// so we need to start a child process with "MSYS=enable_pcon"
		//   os.Setenv("MSYS", "enable_pcon")
		return true
	}
	if opts.NoWinpty {
		return false
	}
	if _, err := exec.LookPath("winpty"); err != nil {
		return false
	}
	return true
}

func runWinpty(args []string, opts *Options) (int, error) {
	argStr := escapeSingleQuote(args[0])
	for _, arg := range args[1:] {
		argStr += " " + escapeSingleQuote(arg)
	}
	argStr += ` --no-winpty`

	if isMintty345() {
		return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {
			sh, err := sh(needBash)
			if err != nil {
				return nil, err
			}

			cmd := exec.Command(sh, temp)
			cmd.Env = append(os.Environ(), "MSYS=enable_pcon")
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			return cmd, nil
		}, opts, false)
	}

	return runProxy(argStr, func(temp string, needBash bool) (*exec.Cmd, error) {
		sh, err := sh(needBash)
		if err != nil {
			return nil, err
		}

		cmd := exec.Command(sh, "-c", fmt.Sprintf(`winpty < /dev/tty > /dev/tty -- sh %q`, temp))
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		return cmd, nil
	}, opts, false)
}