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
|
// Package sh runs external commands with output streamed live, since a
// post-receive hook's stdout/stderr goes straight back to the pushing client.
package sh
import (
"context"
"fmt"
"io"
"os"
"os/exec"
)
func Run(ctx context.Context, out io.Writer, dir string, name string, args ...string) error {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
cmd.Stdout = out
cmd.Stderr = out
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s %v: %w", name, args, err)
}
return nil
}
// Output runs a command and returns its trimmed stdout, for callers that need
// a value back (e.g. `zfs list -H -o name`) rather than a stream.
func Output(ctx context.Context, dir string, name string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
b, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("%s %v: %w", name, args, err)
}
return string(b), nil
}
// CombinedOutput runs a command and returns its combined stdout+stderr,
// even on failure - for callers that need to inspect the error text itself
// (e.g. distinguishing bmake's "no such target" from a real failure)
// rather than just pass/fail.
func CombinedOutput(ctx context.Context, dir string, name string, args ...string) (string, error) {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
b, err := cmd.CombinedOutput()
return string(b), err
}
// RunWithStdinFile runs a command with stdinPath fed to its stdin, e.g.
// piping a migration file into `sqlite3 db`.
func RunWithStdinFile(ctx context.Context, out io.Writer, dir, stdinPath, name string, args ...string) error {
f, err := os.Open(stdinPath)
if err != nil {
return fmt.Errorf("open %s: %w", stdinPath, err)
}
defer f.Close()
cmd := exec.CommandContext(ctx, name, args...)
cmd.Dir = dir
cmd.Stdin = f
cmd.Stdout = out
cmd.Stderr = out
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s %v < %s: %w", name, args, stdinPath, err)
}
return nil
}
|