fix: Fix the issue of abnormal context in the cmd method (#10939)

This commit is contained in:
ssongliu 2025-11-13 14:37:28 +08:00 committed by GitHub
parent 0bc9e85734
commit e7810febd6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -94,21 +94,23 @@ func (c *CommandHelper) RunWithStdoutBashCf(command string, arg ...interface{})
func (c *CommandHelper) run(name string, arg ...string) (string, error) {
var cmd *exec.Cmd
var newContext context.Context
var cancel context.CancelFunc
if c.timeout != 0 {
if c.context == nil {
c.context, cancel = context.WithTimeout(context.Background(), c.timeout)
newContext, cancel = context.WithTimeout(context.Background(), c.timeout)
defer cancel()
} else {
c.context, cancel = context.WithTimeout(c.context, c.timeout)
newContext, cancel = context.WithTimeout(c.context, c.timeout)
defer cancel()
}
cmd = exec.CommandContext(c.context, name, arg...)
cmd = exec.CommandContext(newContext, name, arg...)
} else {
if c.context == nil {
cmd = exec.Command(name, arg...)
} else {
newContext = c.context
cmd = exec.CommandContext(c.context, name, arg...)
}
}
@ -148,7 +150,7 @@ func (c *CommandHelper) run(name string, arg ...string) (string, error) {
customWriter.Flush()
}
if c.timeout != 0 {
if c.context != nil && errors.Is(c.context.Err(), context.DeadlineExceeded) {
if newContext != nil && errors.Is(newContext.Err(), context.DeadlineExceeded) {
return "", buserr.New("ErrCmdTimeout")
}
}