forked from go-gitea/gitea
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
54 lines (44 loc) · 1.53 KB
/
Copy pathcommand.go
File metadata and controls
54 lines (44 loc) · 1.53 KB
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
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package process
import (
"bytes"
"context"
"os/exec"
)
type Cmd struct {
*exec.Cmd
onCancelUserFunc func() error
termGraceful bool
}
func (c *Cmd) WithOnCancelGracefully(userFunc func() error) *Cmd {
c.termGraceful, c.onCancelUserFunc = true, userFunc
return c
}
func (c *Cmd) WithOnCancelForceKill(userFunc func() error) *Cmd {
c.termGraceful, c.onCancelUserFunc = false, userFunc
return c
}
func (c *Cmd) WithDir(dir string) *Cmd {
c.Cmd.Dir = dir
return c
}
func (c *Cmd) OutputString() (string, string, error) {
stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
c.Cmd.Stdout = stdout
c.Cmd.Stderr = stderr
err := c.Cmd.Run()
return stdout.String(), stderr.String(), err
}
// CommandContext returns a wrapped exec.Cmd which kills the process group when the context is canceled.
// By default, it uses graceful termination (SIGTERM) on Unix-like systems to make the subprocesses have chances
// to clean up (e.g. remove temporary files or lock files).
func CommandContext(ctx context.Context, name string, arg ...string) *Cmd {
c := &Cmd{Cmd: exec.CommandContext(ctx, name, arg...)} //nolint:forbidigo // wrap it
setSysProcAttribute(c.Cmd)
c.Cmd.Cancel = c.onCancel
// Unlike exec.CommandContext, we use graceful termination by default to avoid corrupting data or leaving lock files behind.
// If some processes don't respond to SIGTERM, can switch to WithOnCancelForceKill (SIGKILL) to force kill them.
c.termGraceful = true
return c
}