0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-11-22 10:20:39 +00:00
wp-plugin-go/types/command.go

68 lines
1.4 KiB
Go
Raw Normal View History

2024-05-05 12:55:58 +00:00
package types
import (
"fmt"
"io"
"os"
"strings"
"golang.org/x/sys/execabs"
)
2024-05-05 12:55:58 +00:00
2024-05-07 08:10:59 +00:00
// Cmd represents a command to be executed. It extends the execabs.Cmd struct
// and adds fields for controlling the command's execution, such as whether
// it should be executed in private mode (with output discarded) and whether
// its execution should be traced.
2024-05-05 12:55:58 +00:00
type Cmd struct {
*execabs.Cmd
2024-05-07 08:10:59 +00:00
Private bool
Trace *bool
TraceWriter io.Writer
}
2024-05-07 08:10:59 +00:00
// Run executes the command and waits for it to complete.
// If the Trace field is nil, it is set to true.
// The Env, Stdout, and Stderr fields are set to their default values if they are nil.
// If the Private field is true, the Stdout field is set to io.Discard.
// If the Trace field is true, the command line is printed to Stdout.
func (c *Cmd) Run() error {
if c.Trace == nil {
c.SetTrace(true)
}
if c.Env == nil {
c.Env = os.Environ()
}
if c.Stdout == nil {
c.Stdout = os.Stdout
}
if c.Stderr == nil {
c.Stderr = os.Stderr
}
if c.Private {
c.Stdout = io.Discard
}
2024-05-07 08:10:59 +00:00
if c.TraceWriter == nil {
c.TraceWriter = os.Stdout
}
if *c.Trace {
2024-05-07 08:10:59 +00:00
fmt.Fprintf(c.TraceWriter, "+ %s\n", strings.Join(c.Args, " "))
}
if err := c.Start(); err != nil {
return err
}
return c.Wait()
}
2024-05-07 08:10:59 +00:00
// SetTrace sets the Trace field of the Cmd to the provided boolean value.
func (c *Cmd) SetTrace(trace bool) {
c.Trace = &trace
2024-05-05 12:55:58 +00:00
}