~james/core

core/gitutil/command.go -rw-r--r-- 1.9 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
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
68
69
70
71
72
73
74
75
76
77
package gitutil

import (
	"bytes"
	"context"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"time"
)

// git runs network work in child processes, so killing only git leaves them running

// WaitDelay stops waits on output held open by git's children
const WaitDelay = 10 * time.Second

// LC_ALL=C keeps git's messages in english, callers match on its stderr
func Command(ctx context.Context, args ...string) *exec.Cmd {
	cmd := exec.CommandContext(ctx, "git", args...)
	cmd.Env = append(os.Environ(), "LC_ALL=C")
	return Contain(cmd)
}

// Contain is for sandbox-rebuilt commands and direct git binaries
func Contain(cmd *exec.Cmd) *exec.Cmd {
	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.Setpgid = true
	cmd.WaitDelay = WaitDelay
	// exec rejects Cancel on commands not created with CommandContext
	if cmd.Cancel != nil {
		cmd.Cancel = func() error {
			if cmd.Process == nil {
				return nil
			}
			err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
			if err == syscall.ESRCH {
				return nil
			}
			return err
		}
	}
	return cmd
}

func Run(ctx context.Context, args ...string) error {
	var stderr bytes.Buffer
	cmd := Command(ctx, args...)
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String()))
	}
	return nil
}

func Output(ctx context.Context, args ...string) ([]byte, error) {
	return output(Command(ctx, args...))
}

func OutputOffline(ctx context.Context, args ...string) ([]byte, error) {
	cmd := Command(ctx, args...)
	cmd.Env = append(cmd.Env, "GIT_NO_LAZY_FETCH=1")
	return output(cmd)
}

func output(cmd *exec.Cmd) ([]byte, error) {
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(stderr.String()))
	}
	return stdout.Bytes(), nil
}