File: cmd.go

package info (click to toggle)
golang-github-cosiner-argv 0.1.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 96 kB
  • sloc: makefile: 2
file content (67 lines) | stat: -rw-r--r-- 1,038 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package argv

import (
	"errors"
	"io"
	"os"
	"os/exec"
)

func Cmds(args ...[]string) ([]*exec.Cmd, error) {
	var cmds []*exec.Cmd
	for _, argv := range args {
		if len(argv) == 0 {
			return nil, errors.New("invalid cmd")
		}

		cmds = append(cmds, exec.Command(argv[0], argv[1:]...))
	}
	return cmds, nil
}

func Pipe(stdin io.Reader, stdout, stderr io.Writer, cmds ...*exec.Cmd) error {
	if stdin == nil {
		stdin = os.Stdin
	}
	if stdout == nil {
		stdout = os.Stdout
	}
	if stderr == nil {
		stderr = os.Stderr
	}
	l := len(cmds)
	if l == 0 {
		return nil
	}
	var err error
	for i := 0; i < l; i++ {
		if i == 0 {
			cmds[i].Stdin = stdin
		} else {
			cmds[i].Stdin, err = cmds[i-1].StdoutPipe()
			if stderr != nil {
				break
			}
		}
		cmds[i].Stderr = stderr
		if i == l-1 {
			cmds[i].Stdout = stdout
		}
	}
	if err != nil {
		return err
	}
	for i := range cmds {
		err = cmds[i].Start()
		if err != nil {
			return err
		}
	}
	for i := range cmds {
		err = cmds[i].Wait()
		if err != nil {
			return err
		}
	}
	return nil
}