viye/plumbing/shell/shell.go (view raw)
| 1 | package shell |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os/exec" |
| 6 | "strings" |
| 7 | "syscall" |
| 8 | |
| 9 | "github.com/olexsmir/viye/core" |
| 10 | ) |
| 11 | |
| 12 | type Tool struct{} |
| 13 | |
| 14 | func (Tool) Name() string { return "shell($)" } |
| 15 | func (Tool) Match(ctx *core.Context) bool { return isCmd(ctx.Path[0]) || isBGCmd(ctx.Path[0]) } |
| 16 | func (Tool) Execute(ctx *core.Context) (string, error) { |
| 17 | switch { |
| 18 | case isCmd(ctx.Path[0]): |
| 19 | cmd := exec.Command("sh", "-c", strings.TrimPrefix(ctx.Path[0], "$ ")) |
| 20 | cmd.Dir = ctx.Dir |
| 21 | out, _ := cmd.CombinedOutput() |
| 22 | |
| 23 | lines := strings.Split(string(out), "\n") |
| 24 | for i, line := range lines { |
| 25 | if line != "" { |
| 26 | lines[i] = "| " + line |
| 27 | } |
| 28 | } |
| 29 | return strings.Join(lines, "\n"), nil |
| 30 | |
| 31 | case isBGCmd(ctx.Path[0]): |
| 32 | cmd := exec.Command("sh", "-c", strings.TrimPrefix(ctx.Path[0], "$$ ")) |
| 33 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| 34 | cmd.Dir = ctx.Dir |
| 35 | if err := cmd.Start(); err != nil { |
| 36 | return "", err |
| 37 | } |
| 38 | return fmt.Sprintf("| pid: %d", cmd.Process.Pid), nil |
| 39 | |
| 40 | default: |
| 41 | panic("shouldn't have paniced") |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | func isCmd(s string) bool { return strings.HasPrefix(s, "$ ") } |
| 46 | func isBGCmd(s string) bool { return strings.HasPrefix(s, "$$ ") } |