Skip to content
Myr

proxy.go

This file

Path

src/proxy.go

162 lines · 4.1 KiB · Go

Last changed by

Do not unset FZF_DEFAULT_* variables when using winptyJunegunn Choibefore adoption0a8ff78

History of this file

Take it

1package fzf23import (4	"bufio"5	"errors"6	"fmt"7	"io"8	"os"9	"os/exec"10	"os/signal"11	"path/filepath"12	"regexp"13	"strings"14	"time"1516	"github.com/junegunn/fzf/src/tui"17	"github.com/junegunn/fzf/src/util"18)1920const becomeSuffix = ".become"2122func escapeSingleQuote(str string) string {23	return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"24}2526func fifo(name string) (string, error) {27	ns := time.Now().UnixNano()28	output := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-%s-%d", name, ns))29	output, err := mkfifo(output, 0600)30	if err != nil {31		return output, err32	}33	return output, nil34}3536func runProxy(commandPrefix string, cmdBuilder func(temp string, needBash bool) (*exec.Cmd, error), opts *Options, withExports bool) (int, error) {37	output, err := fifo("proxy-output")38	if err != nil {39		return ExitError, err40	}41	defer os.Remove(output)4243	// Take the output44	go func() {45		withOutputPipe(output, func(outputFile io.ReadCloser) {46			if opts.Output == nil {47				io.Copy(os.Stdout, outputFile)48			} else {49				reader := bufio.NewReader(outputFile)50				sep := opts.PrintSep[0]51				for {52					item, err := reader.ReadString(sep)53					if err != nil {54						break55					}56					opts.Output <- item57				}58			}59		})60	}()6162	var command, input string63	commandPrefix += ` --no-force-tty-in --proxy-script "$0"`64	if opts.Input == nil && (opts.ForceTtyIn || util.IsTty(os.Stdin)) {65		command = fmt.Sprintf(`%s > %q`, commandPrefix, output)66	} else {67		input, err = fifo("proxy-input")68		if err != nil {69			return ExitError, err70		}71		defer os.Remove(input)7273		go func() {74			withInputPipe(input, func(inputFile io.WriteCloser) {75				if opts.Input == nil {76					io.Copy(inputFile, os.Stdin)77				} else {78					for item := range opts.Input {79						fmt.Fprint(inputFile, item+opts.PrintSep)80					}81				}82			})83		}()8485		if withExports {86			command = fmt.Sprintf(`%s < %q > %q`, commandPrefix, input, output)87		} else {88			// For mintty: cannot directly read named pipe from Go code89			command = fmt.Sprintf(`command cat %q | %s > %q`, input, commandPrefix, output)90		}91	}9293	// Write the command to a temporary file and run it with sh to ensure POSIX compliance.94	var exports []string95	needBash := false96	if withExports {97		// Nullify FZF_DEFAULT_* variables as tmux popup may inject them even when undefined.98		exports = []string{"FZF_DEFAULT_COMMAND=", "FZF_DEFAULT_OPTS=", "FZF_DEFAULT_OPTS_FILE="}99		validIdentifier := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)100		for _, pairStr := range os.Environ() {101			pair := strings.SplitN(pairStr, "=", 2)102			if validIdentifier.MatchString(pair[0]) {103				exports = append(exports, fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1])))104			} else if strings.HasPrefix(pair[0], "BASH_FUNC_") && strings.HasSuffix(pair[0], "%%") {105				name := pair[0][10 : len(pair[0])-2]106				exports = append(exports, name+pair[1])107				exports = append(exports, "export -f "+name)108				needBash = true109			}110		}111	}112	temp := WriteTemporaryFile(append(exports, command), "\n")113	defer os.Remove(temp)114115	cmd, err := cmdBuilder(temp, needBash)116	if err != nil {117		return ExitError, err118	}119	cmd.Stderr = os.Stderr120	intChan := make(chan os.Signal, 1)121	defer close(intChan)122	go func() {123		if sig, valid := <-intChan; valid {124			cmd.Process.Signal(sig)125		}126	}()127	signal.Notify(intChan, os.Interrupt)128	if err := cmd.Run(); err != nil {129		if exitError, ok := err.(*exec.ExitError); ok {130			code := exitError.ExitCode()131			if code == ExitBecome {132				becomeFile := temp + becomeSuffix133				data, err := os.ReadFile(becomeFile)134				os.Remove(becomeFile)135				if err != nil {136					return ExitError, err137				}138				elems := strings.Split(string(data), "\x00")139				if len(elems) < 1 {140					return ExitError, errors.New("invalid become command")141				}142				command := elems[0]143				env := []string{}144				if len(elems) > 1 {145					env = elems[1:]146				}147				executor := util.NewExecutor(opts.WithShell)148				ttyin, err := tui.TtyIn(opts.TtyDefault)149				if err != nil {150					return ExitError, err151				}152				os.Remove(temp)153				os.Remove(input)154				os.Remove(output)155				executor.Become(ttyin, env, command)156			}157			return code, err158		}159	}160161	return ExitOk, nil162}