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
Provenance
- Commit
573df52- Tree
0bd1185- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
aee417c
12 files changed+315 added−157 removed
modified:src/util/util.go+2 added-1 removed
137 unmodified lines138 }139 140 // IsTty returns true if stdin is a terminal141 func IsTty() bool {142- return isatty.IsTerminal(os.Stdin.Fd())142+ fd := os.Stdin.Fd()143+ return isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd)144 }145 146 // ToTty returns true if stdout is a terminal147 func ToTty() bool {44 unmodified linesmodified:src/core.go+5 added-1 removed
19 unmodified lines20 21 // Run starts fzf22 func 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 }26 27+ if os.Getenv("TERM_PROGRAM") == "mintty" && !opts.NoWinpty {28+ return runWinpty(os.Args, opts)29+ }30+31 if err := postProcessOptions(opts); err != nil {32 return ExitError, err33 }34 387 unmodified linesmodified:src/options.go+6 added-3 removed
379 unmodified lines380 // Options stores the values of command-line options381 type Options struct {382 Input chan string383 Output chan string384+ NoWinpty bool385 Tmux *tmuxOptions385- TmuxScript string386+ ProxyScript string387 Bash bool388 Zsh bool389 Fish bool390 Fuzzy bool1492 unmodified lines1883 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 err2 unmodified lines1895 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 = true881 unmodified linesadded:src/proxy_unix.go+38 added
1+//go:build !windows2+3+package fzf4+5+import (6+ "io"7+ "os"8+9+ "golang.org/x/sys/unix"10+)11+12+func sh() (string, error) {13+ return "sh", nil14+}15+16+func mkfifo(path string, mode uint32) (string, error) {17+ return path, unix.Mkfifo(path, mode)18+}19+20+func 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+}29+30+func 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 windows2+3+package fzf4+5+import (6+ "fmt"7+ "io"8+ "os/exec"9+ "strconv"10+ "strings"11+ "sync/atomic"12+)13+14+var shPath atomic.Value15+16+func sh() (string, error) {17+ if cached := shPath.Load(); cached != nil {18+ return cached.(string), nil19+ }20+21+ cmd := exec.Command("cygpath", "-w", "/usr/bin/sh")22+ bytes, err := cmd.Output()23+ if err != nil {24+ return "", err25+ }26+27+ sh := strings.TrimSpace(string(bytes))28+ shPath.Store(sh)29+ return sh, nil30+}31+32+func 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+}44+45+func 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+ }58+59+ task(outputFile)60+ cmd.Wait()61+ return nil62+}63+64+func 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
1+package fzf2+3+import (4+ "bufio"5+ "errors"6+ "fmt"7+ "io"8+ "os"9+ "os/exec"10+ "path/filepath"11+ "strings"12+ "time"13+14+ "github.com/junegunn/fzf/src/tui"15+ "github.com/junegunn/fzf/src/util"16+)17+18+const becomeSuffix = ".become"19+20+func escapeSingleQuote(str string) string {21+ return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"22+}23+24+func 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+}33+34+func 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)40+41+ // 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+ }()59+60+ 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)70+71+ 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+ }()82+83+ 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+ }90+91+ // 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)103+104+ 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+ }130+131+ return ExitOk, nil132+}modified:src/terminal.go+4 added-4 removed
320 unmodified lines321 areaColumns int322 forcePreview bool323 clickHeaderLine int324 clickHeaderColumn int325- tmuxScript string325+ proxyScript string326 }327 328 type selectedItem struct {329 at time.Time464 unmodified lines794 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 lines3607 if t.history != nil {3608 t.history.append(string(t.input))3609 }3610 3611- 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 linesdeleted:src/tmux_unix.go-9 removed
1-//go:build !windows2-3-package fzf4-5-import "golang.org/x/sys/unix"6-7-func mkfifo(path string, mode uint32) error {8- return unix.Mkfifo(path, mode)9-}deleted:src/tmux_windows.go-17 removed
1-//go:build windows2-3-package fzf4-5-import (6- "os/exec"7- "strconv"8-)9-10-func 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
1 package fzf2 3 import (4- "bufio"5- "errors"6- "fmt"7- "io"4 "os"5 "os/exec"10- "path/filepath"11- "strings"12- "time"6 7 "github.com/junegunn/fzf/src/tui"15- "github.com/junegunn/fzf/src/util"8 )9 18-func escapeSingleQuote(str string) string {19- return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"20-}21-10 func runTmux(args []string, opts *Options) (int, error) {23- ns := time.Now().UnixNano()24-25- 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)30-31- // Find fzf executable32- fzf := "fzf"33- if found, err := os.Executable(); err == nil {34- fzf = found35- }36-11 // 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`22 51- // 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)61-62- 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- }()76-77- command = fmt.Sprintf(`%q%s < %q > %q`, fzf, argStr, input, output)78- }79-23 // Get current directory24 dir, err := os.Getwd()25 if err != nil {26 dir = "."21 unmodified lines48 }49 tmuxArgs = append(tmuxArgs, "-w"+opts.Tmux.width.String())50 tmuxArgs = append(tmuxArgs, "-h"+opts.Tmux.height.String())51 109- // 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)119-120- // 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- }139-140- outputFile.Close()141- }()142-143- 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- }168-169- 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 windows2+3+package fzf4+5+import (6+ "fmt"7+ "os"8+ "os/exec"9+)10+11+func runWinpty(args []string, opts *Options) (int, error) {12+ sh, err := sh()13+ if err != nil {14+ return ExitError, err15+ }16+17+ argStr := escapeSingleQuote(args[0])18+ for _, arg := range args[1:] {19+ argStr += " " + escapeSingleQuote(arg)20+ }21+ argStr += ` --no-winpty --no-height`22+23+ 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 !windows2+3+package fzf4+5+import "errors"6+7+func runWinpty(_ []string, _ *Options) (int, error) {8+ return ExitError, errors.New("Not supported")9+}