Skip to content
Myr

Use winpty to launch fzf in Git bash (mintty)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Close #3806 Known limitation: * --height cannot be used

authored by Junegunn Choi · committed by Junegunn Choi · parent aee417c · Browse files · 12 files+315 added−157 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+315 added−157 removed

  • other:+315 added−157 removed

12 files+315 added−157 removed

modified:src/util/util.go+2 added-1 removed
137 unmodified lines
138}139140// IsTty returns true if stdin is a terminal141func IsTty() bool {142 return isatty.IsTerminal(os.Stdin.Fd())142 fd := os.Stdin.Fd()143 return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)144}145146// ToTty returns true if stdout is a terminal147func ToTty() bool {
44 unmodified lines
modified:src/core.go+5 added-1 removed
19 unmodified lines
2021// Run starts fzf22func Run(opts *Options) (int, error) {23 if opts.Tmux != nil && len(os.Getenv("TMUX")) > 0 {24 return runTmux(os.Args[1:], opts)24 return runTmux(os.Args, opts)25 }2627 if os.Getenv("TERM_PROGRAM") == "mintty" && !opts.NoWinpty {28 return runWinpty(os.Args, opts)29 }3031 if err := postProcessOptions(opts); err != nil {32 return ExitError, err33 }34
387 unmodified lines
modified:src/options.go+6 added-3 removed
379 unmodified lines
380// Options stores the values of command-line options381type Options struct {382 Input chan string383 Output chan string384 NoWinpty bool385 Tmux *tmuxOptions385 TmuxScript string386 ProxyScript string387 Bash bool388 Zsh bool389 Fish bool390 Fuzzy bool
1492 unmodified lines
1883 opts.Help = true1884 case "--version":1885 clearExitingOpts()1886 opts.Version = true1887 case "--no-winpty":1888 opts.NoWinpty = true1889 case "--tmux":1890 str, err := nextString(allArgs, &i, "tmux options required")1891 if err != nil {1892 return err
2 unmodified lines
1895 return err1896 }1897 case "--no-tmux":1898 opts.Tmux = nil1896 case "--tmux-script":1897 if opts.TmuxScript, err = nextString(allArgs, &i, ""); err != nil {1899 case "--proxy-script":1900 if opts.ProxyScript, err = nextString(allArgs, &i, ""); err != nil {1901 return err1902 }1903 case "-x", "--extended":1904 opts.Extended = true
881 unmodified lines
added:src/proxy_unix.go+38 added
1//go:build !windows23package fzf45import (6 "io"7 "os"89 "golang.org/x/sys/unix"10)1112func sh() (string, error) {13 return "sh", nil14}1516func mkfifo(path string, mode uint32) (string, error) {17 return path, unix.Mkfifo(path, mode)18}1920func withOutputPipe(output string, task func(io.ReadCloser)) error {21 outputFile, err := os.OpenFile(output, os.O_RDONLY, 0)22 if err != nil {23 return err24 }25 task(outputFile)26 outputFile.Close()27 return nil28}2930func withInputPipe(input string, task func(io.WriteCloser)) error {31 inputFile, err := os.OpenFile(input, os.O_WRONLY, 0)32 if err != nil {33 return err34 }35 task(inputFile)36 inputFile.Close()37 return nil38}
added:src/proxy_windows.go+81 added
1//go:build windows23package fzf45import (6 "fmt"7 "io"8 "os/exec"9 "strconv"10 "strings"11 "sync/atomic"12)1314var shPath atomic.Value1516func sh() (string, error) {17 if cached := shPath.Load(); cached != nil {18 return cached.(string), nil19 }2021 cmd := exec.Command("cygpath", "-w", "/usr/bin/sh")22 bytes, err := cmd.Output()23 if err != nil {24 return "", err25 }2627 sh := strings.TrimSpace(string(bytes))28 shPath.Store(sh)29 return sh, nil30}3132func mkfifo(path string, mode uint32) (string, error) {33 m := strconv.FormatUint(uint64(mode), 8)34 sh, err := sh()35 if err != nil {36 return path, err37 }38 cmd := exec.Command(sh, "-c", fmt.Sprintf(`command mkfifo -m %s %q`, m, path))39 if err := cmd.Run(); err != nil {40 return path, err41 }42 return path + ".lnk", nil43}4445func withOutputPipe(output string, task func(io.ReadCloser)) error {46 sh, err := sh()47 if err != nil {48 return err49 }50 cmd := exec.Command(sh, "-c", fmt.Sprintf(`command cat %q`, output))51 outputFile, err := cmd.StdoutPipe()52 if err != nil {53 return err54 }55 if err := cmd.Start(); err != nil {56 return err57 }5859 task(outputFile)60 cmd.Wait()61 return nil62}6364func withInputPipe(input string, task func(io.WriteCloser)) error {65 sh, err := sh()66 if err != nil {67 return err68 }69 cmd := exec.Command(sh, "-c", fmt.Sprintf(`command cat - > %q`, input))70 inputFile, err := cmd.StdinPipe()71 if err != nil {72 return err73 }74 if err := cmd.Start(); err != nil {75 return err76 }77 task(inputFile)78 inputFile.Close()79 cmd.Wait()80 return nil81}
added:src/proxy.go+132 added
1package fzf23import (4 "bufio"5 "errors"6 "fmt"7 "io"8 "os"9 "os/exec"10 "path/filepath"11 "strings"12 "time"1314 "github.com/junegunn/fzf/src/tui"15 "github.com/junegunn/fzf/src/util"16)1718const becomeSuffix = ".become"1920func escapeSingleQuote(str string) string {21 return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"22}2324func fifo(name string) (string, error) {25 ns := time.Now().UnixNano()26 output := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-%s-%d", name, ns))27 output, err := mkfifo(output, 0600)28 if err != nil {29 return output, err30 }31 return output, nil32}3334func runProxy(commandPrefix string, cmdBuilder func(temp string) *exec.Cmd, opts *Options, withExports bool) (int, error) {35 output, err := fifo("proxy-output")36 if err != nil {37 return ExitError, err38 }39 defer os.Remove(output)4041 // Take the output42 go func() {43 withOutputPipe(output, func(outputFile io.ReadCloser) {44 if opts.Output == nil {45 io.Copy(os.Stdout, outputFile)46 } else {47 reader := bufio.NewReader(outputFile)48 sep := opts.PrintSep[0]49 for {50 item, err := reader.ReadString(sep)51 if err != nil {52 break53 }54 opts.Output <- item55 }56 }57 })58 }()5960 var command string61 commandPrefix += ` --proxy-script "$0"`62 if opts.Input == nil && util.IsTty() {63 command = fmt.Sprintf(`%s > %q`, commandPrefix, output)64 } else {65 input, err := fifo("proxy-input")66 if err != nil {67 return ExitError, err68 }69 defer os.Remove(input)7071 go func() {72 withInputPipe(input, func(inputFile io.WriteCloser) {73 if opts.Input == nil {74 io.Copy(inputFile, os.Stdin)75 } else {76 for item := range opts.Input {77 fmt.Fprint(inputFile, item+opts.PrintSep)78 }79 }80 })81 }()8283 if withExports {84 command = fmt.Sprintf(`%s < %q > %q`, commandPrefix, input, output)85 } else {86 // For mintty: cannot directly read named pipe from Go code87 command = fmt.Sprintf(`command cat %q | %s > %q`, input, commandPrefix, output)88 }89 }9091 // To ensure that the options are processed by a POSIX-compliant shell,92 // we need to write the command to a temporary file and execute it with sh.93 var exports []string94 if withExports {95 exports = os.Environ()96 for idx, pairStr := range exports {97 pair := strings.SplitN(pairStr, "=", 2)98 exports[idx] = fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1]))99 }100 }101 temp := writeTemporaryFile(append(exports, command), "\n")102 defer os.Remove(temp)103104 cmd := cmdBuilder(temp)105 if err := cmd.Run(); err != nil {106 if exitError, ok := err.(*exec.ExitError); ok {107 code := exitError.ExitCode()108 if code == ExitBecome {109 becomeFile := temp + becomeSuffix110 data, err := os.ReadFile(becomeFile)111 os.Remove(becomeFile)112 if err != nil {113 return ExitError, err114 }115 elems := strings.Split(string(data), "\x00")116 if len(elems) < 1 {117 return ExitError, errors.New("invalid become command")118 }119 command := elems[0]120 env := []string{}121 if len(elems) > 1 {122 env = elems[1:]123 }124 executor := util.NewExecutor(opts.WithShell)125 executor.Become(tui.TtyIn(), env, command)126 }127 return code, err128 }129 }130131 return ExitOk, nil132}
modified:src/terminal.go+4 added-4 removed
320 unmodified lines
321 areaColumns int322 forcePreview bool323 clickHeaderLine int324 clickHeaderColumn int325 tmuxScript string325 proxyScript string326}327328type selectedItem struct {329 at time.Time
464 unmodified lines
794 jumping: jumpDisabled,795 jumpLabels: opts.JumpLabels,796 printer: opts.Printer,797 printsep: opts.PrintSep,798 tmuxScript: opts.TmuxScript,798 proxyScript: opts.ProxyScript,799 merger: EmptyMerger(0),800 selected: make(map[int32]selectedItem),801 reqBox: util.NewEventBox(),802 initialPreviewOpts: opts.Preview,
2804 unmodified lines
3607 if t.history != nil {3608 t.history.append(string(t.input))3609 }36103611 if len(t.tmuxScript) > 0 {3611 if len(t.proxyScript) > 0 {3612 data := strings.Join(append([]string{command}, t.environ()...), "\x00")3613 os.WriteFile(t.tmuxScript, []byte(data), 0600)3613 os.WriteFile(t.proxyScript+becomeSuffix, []byte(data), 0600)3614 req(reqBecome)3615 } else {3616 t.executor.Become(t.ttyin, t.environ(), command)3617 }
977 unmodified lines
deleted:src/tmux_unix.go-9 removed
1//go:build !windows23package fzf45import "golang.org/x/sys/unix"67func mkfifo(path string, mode uint32) error {8 return unix.Mkfifo(path, mode)9}
deleted:src/tmux_windows.go-17 removed
1//go:build windows23package fzf45import (6 "os/exec"7 "strconv"8)910func mkfifo(path string, mode uint32) error {11 m := strconv.FormatUint(uint64(mode), 8)12 cmd := exec.Command("mkfifo", "-m", m, path)13 if err := cmd.Run(); err != nil {14 return err15 }16 return nil17}
modified:src/tmux.go+9 added-122 removed
1package fzf23import (4 "bufio"5 "errors"6 "fmt"7 "io"4 "os"5 "os/exec"10 "path/filepath"11 "strings"12 "time"67 "github.com/junegunn/fzf/src/tui"15 "github.com/junegunn/fzf/src/util"8)918func escapeSingleQuote(str string) string {19 return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"20}2110func runTmux(args []string, opts *Options) (int, error) {23 ns := time.Now().UnixNano()2425 output := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-tmux-output-%d", ns))26 if err := mkfifo(output, 0666); err != nil {27 return ExitError, err28 }29 defer os.Remove(output)3031 // Find fzf executable32 fzf := "fzf"33 if found, err := os.Executable(); err == nil {34 fzf = found35 }3611 // Prepare arguments12 fzf := args[0]38 args = append([]string{"--bind=ctrl-z:ignore"}, args...)13 args = append([]string{"--bind=ctrl-z:ignore"}, args[1:]...)14 if opts.BorderShape == tui.BorderUndefined {15 args = append(args, "--border")16 }42 args = append(args, "--no-height")43 args = append(args, "--no-tmux")44 argStr := ""17 argStr := escapeSingleQuote(fzf)18 for _, arg := range args {46 // %q formatting escapes $'foo\nbar' to "foo\nbar"19 argStr += " " + escapeSingleQuote(arg)20 }49 argStr += ` --tmux-script "$0"`21 argStr += ` --no-tmux --no-height`2251 // Build command52 var command string53 if opts.Input == nil && util.IsTty() {54 command = fmt.Sprintf(`%q%s > %q`, fzf, argStr, output)55 } else {56 input := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-tmux-input-%d", ns))57 if err := mkfifo(input, 0644); err != nil {58 return ExitError, err59 }60 defer os.Remove(input)6162 go func() {63 inputFile, err := os.OpenFile(input, os.O_WRONLY, 0)64 if err != nil {65 return66 }67 if opts.Input == nil {68 io.Copy(inputFile, os.Stdin)69 } else {70 for item := range opts.Input {71 fmt.Fprint(inputFile, item+opts.PrintSep)72 }73 }74 inputFile.Close()75 }()7677 command = fmt.Sprintf(`%q%s < %q > %q`, fzf, argStr, input, output)78 }7923 // Get current directory24 dir, err := os.Getwd()25 if err != nil {26 dir = "."
21 unmodified lines
48 }49 tmuxArgs = append(tmuxArgs, "-w"+opts.Tmux.width.String())50 tmuxArgs = append(tmuxArgs, "-h"+opts.Tmux.height.String())51109 // To ensure that the options are processed by a POSIX-compliant shell,110 // we need to write the command to a temporary file and execute it with sh.111 exports := os.Environ()112 for idx, pairStr := range exports {113 pair := strings.SplitN(pairStr, "=", 2)114 exports[idx] = fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1]))115 }116 temp := writeTemporaryFile(append(exports, command), "\n")117 defer os.Remove(temp)118 tmuxArgs = append(tmuxArgs, "sh", temp)119120 // Take the output121 go func() {122 outputFile, err := os.OpenFile(output, os.O_RDONLY, 0)123 if err != nil {124 return125 }126 if opts.Output == nil {127 io.Copy(os.Stdout, outputFile)128 } else {129 reader := bufio.NewReader(outputFile)130 sep := opts.PrintSep[0]131 for {132 item, err := reader.ReadString(sep)133 if err != nil {134 break135 }136 opts.Output <- item137 }138 }139140 outputFile.Close()141 }()142143 cmd := exec.Command("tmux", tmuxArgs...)144 if err := cmd.Run(); err != nil {145 if exitError, ok := err.(*exec.ExitError); ok {146 code := exitError.ExitCode()147 if code == ExitBecome {148 data, err := os.ReadFile(temp)149 if err != nil {150 return ExitError, err151 }152 elems := strings.Split(string(data), "\x00")153 if len(elems) < 1 {154 return ExitError, errors.New("invalid become command")155 }156 command := elems[0]157 env := []string{}158 if len(elems) > 1 {159 env = elems[1:]160 }161 os.Remove(temp)162 executor := util.NewExecutor(opts.WithShell)163 executor.Become(tui.TtyIn(), env, command)164 }165 return code, err166 }167 }168169 return ExitOk, nil52 return runProxy(argStr, func(temp string) *exec.Cmd {53 sh, _ := sh()54 tmuxArgs = append(tmuxArgs, sh, temp)55 return exec.Command("tmux", tmuxArgs...)56 }, opts, true)57}
added:src/winpty_windows.go+29 added
1//go:build windows23package fzf45import (6 "fmt"7 "os"8 "os/exec"9)1011func runWinpty(args []string, opts *Options) (int, error) {12 sh, err := sh()13 if err != nil {14 return ExitError, err15 }1617 argStr := escapeSingleQuote(args[0])18 for _, arg := range args[1:] {19 argStr += " " + escapeSingleQuote(arg)20 }21 argStr += ` --no-winpty --no-height`2223 return runProxy(argStr, func(temp string) *exec.Cmd {24 cmd := exec.Command(sh, "-c", fmt.Sprintf(`winpty < /dev/tty > /dev/tty -- sh %q`, temp))25 cmd.Stdout = os.Stdout26 cmd.Stderr = os.Stderr27 return cmd28 }, opts, false)29}
added:src/winpty.go+9 added
1//go:build !windows23package fzf45import "errors"67func runWinpty(_ []string, _ *Options) (int, error) {8 return ExitError, errors.New("Not supported")9}