cmd.go 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
package util

import (
	"os/exec"
	"runtime"
	"syscall"
)

// Open a URL in a browser
func Open(url string, cmdContext ExecContext) error {
	var cmd string
	var args []string

	switch runtime.GOOS {
	case "windows":
		cmd = "cmd"
		args = []string{"/c", "start"}
	case "darwin":
		cmd = "Open"
	default: // "linux", "freebsd", "openbsd", "netbsd"
		cmd = "xdg-Open"
	}
	args = append(args, url)
24
	return ExecCommand(cmdContext, cmd, args...).Start()
25 26 27 28 29 30 31 32 33 34 35
}

// Exec is the wrapper of syscall.Exec
func Exec(argv0 string, argv []string, envv []string, systemCallExec SystemCallExec) error {
	if systemCallExec == nil {
		systemCallExec = syscall.Exec
	}

	return systemCallExec(argv0, argv, envv)
}

36 37 38 39 40 41 42 43
// LookPath is the wrapper of exec.LookPath
func LookPath(file string, context LookPathContext) (string, error) {
	if context == nil {
		context = exec.LookPath
	}
	return context(file)
}

44 45 46 47 48 49
// SystemCallExec is the context of syscall.Exec
type SystemCallExec = func(argv0 string, argv []string, envv []string) (err error)

// ExecContext is the context of system command caller
type ExecContext = func(name string, arg ...string) *exec.Cmd

50 51 52
// LookPathContext is the context of look path
type LookPathContext = func(file string) (string, error)

53 54 55 56 57 58
// FakeExecCommandSuccess is a function that initialises a new exec.Cmd, one which will
// simply call TestShellProcessSuccess rather than the command it is provided. It will
// also pass through the command and its arguments as an argument to TestShellProcessSuccess
func FakeExecCommandSuccess(command string, args ...string) *exec.Cmd {
	cs := []string{"-test.run=TestShellProcessSuccess", "--", command}
	cs = append(cs, args...)
59 60
	cmd := exec.Command("go", cs...)
	//cmd := exec.Command(os.Args[0], cs...)
61 62 63 64 65 66 67 68
	cmd.Env = []string{"GO_TEST_PROCESS=1"}
	return cmd
}

// FakeSystemCallExecSuccess is a fake function of syscall.Exec
func FakeSystemCallExecSuccess(argv0 string, argv []string, envv []string) (err error) {
	return
}
69 70 71 72 73

// FakeLookPath is a fake function of exec.LookPath
func FakeLookPath(path string) (string, error) {
	return path, nil
}
74 75 76 77 78 79 80 81

// ExecCommand is a warp of exec.Command
func ExecCommand(context ExecContext, name string, arg ...string) *exec.Cmd {
	if context == nil {
		context = exec.Command
	}
	return context(name, arg...)
}