Skip to content
Myr

proxy.go

This file

Path

src/proxy.go

267 lines · 6.7 KiB · Go

Last changed by

Separate floating pane border label from pane titleJunegunn Choibefore adoption50e6c02

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	"sync"15	"time"1617	"github.com/junegunn/fzf/src/tui"18	"github.com/junegunn/fzf/src/util"19)2021const becomeSuffix = ".become"2223// Withheld from the environment replay below, so an outer value cannot24// override what the floating pane set25const internalEnvPrefix = "__FZF_INTERNAL_"2627func escapeSingleQuote(str string) string {28	return "'" + strings.ReplaceAll(str, "'", "'\\''") + "'"29}3031// Read and remove, so preview and execute commands do not inherit it32func takeEnv(name string) string {33	value := os.Getenv(name)34	os.Unsetenv(name)35	return value36}3738// Applies label updates off the event loop, which would block on the fork39type labelUpdater struct {40	set     func(string)41	mu      sync.Mutex42	pending *string43	running bool44}4546// A queue of one: a burst collapses to the newest label. A goroutine per47// update could apply them out of order48func (u *labelUpdater) update(label string) {49	u.mu.Lock()50	defer u.mu.Unlock()51	u.pending = &label52	if u.running {53		return54	}55	u.running = true56	go u.run()57}5859// Ends once caught up, so nothing needs cancelling when Run returns60func (u *labelUpdater) run() {61	for {62		u.mu.Lock()63		label := u.pending64		if label == nil {65			u.running = false66			u.mu.Unlock()67			return68		}69		u.pending = nil70		u.mu.Unlock()71		u.set(*label)72	}73}7475// Updates the label on the native border, or nil when it is not fzf's to update76func nativeLabelSetter() func(string) {77	// Read both, so neither is left behind78	tmuxPane, zellijPane := takeEnv(tmuxBorderLabelEnv), takeEnv(zellijBorderLabelEnv)79	var set func(string)80	switch {81	case tmuxPane != "":82		set = func(label string) { setTmuxBorderLabel(tmuxPane, label) }83	case zellijPane != "":84		set = func(label string) { setZellijBorderLabel(zellijPane, label) }85	default:86		return nil87	}88	updater := &labelUpdater{set: set}89	return updater.update90}9192func popupArgStr(args []string, opts *Options) (string, string) {93	fzf, rest := args[0], args[1:]94	args = []string{"--bind=ctrl-z:ignore"}95	if !opts.Tmux.border && (opts.BorderShape == tui.BorderUndefined || opts.BorderShape == tui.BorderLine) {96		if tui.DefaultBorderShape == tui.BorderRounded {97			rest = append(rest, "--border=rounded")98		} else {99			rest = append(rest, "--border=sharp")100		}101	}102	if opts.Tmux.border && opts.Margin == defaultMargin() {103		args = append(args, "--margin=0,1")104	}105	argStr := escapeSingleQuote(fzf)106	for _, arg := range append(args, rest...) {107		argStr += " " + escapeSingleQuote(arg)108	}109	argStr += ` --no-popup --no-height`110111	dir, err := os.Getwd()112	if err != nil {113		dir = "."114	}115	return argStr, dir116}117118func fifo(name string) (string, error) {119	ns := time.Now().UnixNano()120	output := filepath.Join(os.TempDir(), fmt.Sprintf("fzf-%s-%d", name, ns))121	output, err := mkfifo(output, 0600)122	if err != nil {123		return output, err124	}125	return output, nil126}127128func runProxy(commandPrefix string, cmdBuilder func(temp string, needBash bool) (*exec.Cmd, error), opts *Options, withExports bool) (int, error) {129	output, err := fifo("proxy-output")130	if err != nil {131		return ExitError, err132	}133	defer os.Remove(output)134135	// Take the output136	go func() {137		withOutputPipe(output, func(outputFile io.ReadCloser) {138			if opts.Output == nil {139				io.Copy(os.Stdout, outputFile)140			} else {141				reader := bufio.NewReader(outputFile)142				sep := opts.PrintSep[0]143				for {144					item, err := reader.ReadString(sep)145					if err != nil {146						break147					}148					opts.Output <- item149				}150			}151		})152	}()153154	var command, input string155	commandPrefix += ` --no-force-tty-in --proxy-script "$0"`156	if opts.Input == nil && (opts.ForceTtyIn || util.IsTty(os.Stdin)) {157		command = fmt.Sprintf(`%s > %q`, commandPrefix, output)158	} else {159		input, err = fifo("proxy-input")160		if err != nil {161			return ExitError, err162		}163		defer os.Remove(input)164165		go func() {166			withInputPipe(input, func(inputFile io.WriteCloser) {167				if opts.Input == nil {168					io.Copy(inputFile, os.Stdin)169				} else {170					for item := range opts.Input {171						fmt.Fprint(inputFile, item+opts.PrintSep)172					}173				}174			})175		}()176177		if withExports {178			command = fmt.Sprintf(`%s < %q > %q`, commandPrefix, input, output)179		} else {180			// For mintty: cannot directly read named pipe from Go code181			command = fmt.Sprintf(`command cat %q | %s > %q`, input, commandPrefix, output)182		}183	}184185	// Write the command to a temporary file and run it with sh to ensure POSIX compliance.186	var exports []string187	needBash := false188	if withExports {189		// Nullify FZF_DEFAULT_* variables as tmux popup may inject them even when undefined.190		exports = []string{"FZF_DEFAULT_COMMAND=", "FZF_DEFAULT_OPTS=", "FZF_DEFAULT_OPTS_FILE="}191		validIdentifier := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`)192		for _, pairStr := range os.Environ() {193			pair := strings.SplitN(pairStr, "=", 2)194			if strings.HasPrefix(pair[0], internalEnvPrefix) {195				continue196			}197			if validIdentifier.MatchString(pair[0]) {198				exports = append(exports, fmt.Sprintf("export %s=%s", pair[0], escapeSingleQuote(pair[1])))199			} else if strings.HasPrefix(pair[0], "BASH_FUNC_") && strings.HasSuffix(pair[0], "%%") {200				name := pair[0][10 : len(pair[0])-2]201				exports = append(exports, name+pair[1])202				exports = append(exports, "export -f "+name)203				needBash = true204			}205		}206	}207	temp := WriteTemporaryFile(append(exports, command), "\n")208	defer os.Remove(temp)209210	// Pre-create the become file so that another user on a shared TMPDIR211	// cannot plant a file or a symbolic link at the predictable path while212	// fzf is running213	becomeFile := temp + becomeSuffix214	becomeF, err := os.OpenFile(becomeFile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)215	if err != nil {216		return ExitError, err217	}218	becomeF.Close()219	defer os.Remove(becomeFile)220221	cmd, err := cmdBuilder(temp, needBash)222	if err != nil {223		return ExitError, err224	}225	cmd.Stderr = os.Stderr226	intChan := make(chan os.Signal, 1)227	defer close(intChan)228	go func() {229		if sig, valid := <-intChan; valid {230			cmd.Process.Signal(sig)231		}232	}()233	signal.Notify(intChan, os.Interrupt)234	if err := cmd.Run(); err != nil {235		if exitError, ok := err.(*exec.ExitError); ok {236			code := exitError.ExitCode()237			if code == ExitBecome {238				data, err := os.ReadFile(becomeFile)239				os.Remove(becomeFile)240				if err != nil {241					return ExitError, err242				}243				if len(data) == 0 {244					return ExitError, errors.New("invalid become command")245				}246				elems := strings.Split(string(data), "\x00")247				command := elems[0]248				env := []string{}249				if len(elems) > 1 {250					env = elems[1:]251				}252				executor := util.NewExecutor(opts.WithShell)253				ttyin, err := tui.TtyIn(opts.TtyDefault)254				if err != nil {255					return ExitError, err256				}257				os.Remove(temp)258				os.Remove(input)259				os.Remove(output)260				executor.Become(ttyin, env, command)261			}262			return code, err263		}264	}265266	return ExitOk, nil267}