Skip to content
Myr

util_unix.go

This file

Path

src/util/util_unix.go

94 lines · 2.2 KiB · Go

Last changed by

Not known.

History of this file

Take it

1//go:build !windows23package util45import (6	"fmt"7	"os"8	"os/exec"9	"strings"10	"syscall"1112	"github.com/junegunn/go-shellwords"13	"golang.org/x/sys/unix"14)1516type Executor struct {17	shell   string18	args    []string19	escaper *strings.Replacer20}2122func NewExecutor(withShell string) *Executor {23	shell := os.Getenv("SHELL")24	args, err := shellwords.Parse(withShell)25	if err == nil && len(args) > 0 {26		shell = args[0]27		args = args[1:]28	} else {29		if len(shell) == 0 {30			shell = "sh"31		}32		args = []string{"-c"}33	}3435	var escaper *strings.Replacer36	tokens := strings.Split(shell, "/")37	if tokens[len(tokens)-1] == "fish" {38		// https://fishshell.com/docs/current/language.html#quotes39		// > The only meaningful escape sequences in single quotes are \', which40		// > escapes a single quote and \\, which escapes the backslash symbol.41		escaper = strings.NewReplacer("\\", "\\\\", "'", "\\'")42	} else {43		escaper = strings.NewReplacer("'", "'\\''")44	}45	return &Executor{shell, args, escaper}46}4748// ExecCommand executes the given command with $SHELL49func (x *Executor) ExecCommand(command string, setpgid bool) *exec.Cmd {50	cmd := exec.Command(x.shell, append(x.args, command)...)51	if setpgid {52		cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}53	}54	return cmd55}5657func (x *Executor) QuoteEntry(entry string) string {58	return "'" + x.escaper.Replace(entry) + "'"59}6061func (x *Executor) Become(stdin *os.File, environ []string, command string) {62	shellPath, err := exec.LookPath(x.shell)63	if err != nil {64		fmt.Fprintf(os.Stderr, "fzf (become): %s\n", err.Error())65		os.Exit(127)66	}67	args := append([]string{shellPath}, append(x.args, command)...)68	SetStdin(stdin)69	syscall.Exec(shellPath, args, environ)70}7172// KillCommand kills the process for the given command73func KillCommand(cmd *exec.Cmd) error {74	return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)75}7677// IsWindows returns true on Windows78func IsWindows() bool {79	return false80}8182// SetNonblock executes syscall.SetNonblock on file descriptor83func SetNonblock(file *os.File, nonblock bool) {84	syscall.SetNonblock(int(file.Fd()), nonblock)85}8687// Read executes syscall.Read on file descriptor88func Read(fd int, b []byte) (int, error) {89	return syscall.Read(int(fd), b)90}9192func SetStdin(file *os.File) {93	unix.Dup2(int(file.Fd()), 0)94}