Expose RunProcessOnce and PlainLogger

This commit is contained in:
Brian Picciano 2022-01-22 20:36:07 -07:00
parent fd793d4f81
commit 3057f470d4
2 changed files with 33 additions and 2 deletions

View File

@ -1,5 +1,10 @@
package pmuxproc package pmuxproc
import (
"fmt"
"io"
)
// Logger is used by RunProcess to log process details in realtime. You can use // Logger is used by RunProcess to log process details in realtime. You can use
// a new(NullLogger) if you don't care. // a new(NullLogger) if you don't care.
type Logger interface { type Logger interface {
@ -12,3 +17,17 @@ type NullLogger struct{}
func (*NullLogger) Println(string) {} func (*NullLogger) Println(string) {}
func (*NullLogger) Printf(string, ...interface{}) {} func (*NullLogger) Printf(string, ...interface{}) {}
// PlainLogger implements Logger by writing each line directly to the given
// io.Writer as-is.
type PlainLogger struct {
io.Writer
}
func (l PlainLogger) Println(line string) {
fmt.Fprintln(l, line)
}
func (l PlainLogger) Printf(str string, args ...interface{}) {
fmt.Fprintf(l, str, args...)
}

View File

@ -57,7 +57,18 @@ func (cfg Config) withDefaults() Config {
return cfg return cfg
} }
func runProcessOnce(ctx context.Context, logger Logger, cfg Config) error { // RunProcessOnce runs the process described by the Config (though it doesn't
// use all fields from the Config). The process is killed if the context is
// canceled.
//
// It returns nil if the process exits normally with a zero status. It returns
// an error otherwise.
//
// The stdout and stderr of the process will be written to the given Logger, as
// well as various runtime events.
func RunProcessOnce(ctx context.Context, logger Logger, cfg Config) error {
cfg = cfg.withDefaults()
var wg sync.WaitGroup var wg sync.WaitGroup
@ -111,6 +122,7 @@ func runProcessOnce(ctx context.Context, logger Logger, cfg Config) error {
// in order to ensure this go-routine always gets cleaned up. // in order to ensure this go-routine always gets cleaned up.
stopCh := make(chan struct{}) stopCh := make(chan struct{})
defer close(stopCh) defer close(stopCh)
go func(proc *os.Process) { go func(proc *os.Process) {
select { select {
case <-ctx.Done(): case <-ctx.Done():
@ -154,7 +166,7 @@ func RunProcess(ctx context.Context, logger Logger, cfg Config) {
for { for {
start := time.Now() start := time.Now()
err := runProcessOnce(ctx, logger, cfg) err := RunProcessOnce(ctx, logger, cfg)
took := time.Since(start) took := time.Since(start)
if err != nil { if err != nil {