Skip to content

Commit

Permalink
up: sys/cmdr - add more methods to Task, update some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Oct 18, 2022
1 parent d769fc1 commit f13aac2
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
27 changes: 26 additions & 1 deletion sysutil/cmdr/cmd.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmdr

import (
"context"
"fmt"
"io"
"os"
Expand All @@ -15,6 +16,7 @@ type Cmd struct {
*exec.Cmd
// Name of the command
Name string
// inited bool

// RunBefore hook
RunBefore func(c *Cmd)
Expand All @@ -28,12 +30,29 @@ func WrapGoCmd(cmd *exec.Cmd) *Cmd {
}

// NewCmd instance
//
// see exec.Command
func NewCmd(bin string, args ...string) *Cmd {
return &Cmd{
// inited: true,
Cmd: exec.Command(bin, args...),
}
}

// CmdWithCtx create new instance with context.
//
// see exec.CommandContext
func CmdWithCtx(ctx context.Context, bin string, args ...string) *Cmd {
return &Cmd{
// inited: true,
Cmd: exec.CommandContext(ctx, bin, args...),
}
}

// -------------------------------------------------
// config the command
// -------------------------------------------------

// OnBefore exec add hook
func (c *Cmd) OnBefore(fn func(c *Cmd)) *Cmd {
c.RunBefore = fn
Expand Down Expand Up @@ -68,6 +87,12 @@ func (c *Cmd) lookPath(name string) {
}
}

// WithGoCmd and returns the current instance.
func (c *Cmd) WithGoCmd(ec *exec.Cmd) *Cmd {
c.Cmd = ec
return c
}

// WithWorkDir returns the current object
func (c *Cmd) WithWorkDir(dir string) *Cmd {
c.Dir = dir
Expand All @@ -87,7 +112,7 @@ func (c *Cmd) WithStdin(in io.Reader) *Cmd {
return c
}

// WithOutput returns the current argument
// WithOutput returns the current instance
func (c *Cmd) WithOutput(out, errOut io.Writer) *Cmd {
c.Stdout = out
if errOut != nil {
Expand Down
5 changes: 5 additions & 0 deletions sysutil/cmdr/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ func (t *Task) Err() error {
return t.err
}

// IsSuccess of task
func (t *Task) IsSuccess() bool {
return t.err == nil
}

// Runner use for batch run multi task commands
type Runner struct {
prev *Task
Expand Down
1 change: 1 addition & 0 deletions sysutil/cmdr/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func TestRunner_Run(t *testing.T) {
task, err := rr.Task("task1")
assert.NoErr(t, err)
assert.NoErr(t, task.Err())
assert.True(t, task.IsSuccess())

ids := rr.TaskIDs()
// dump.P(rr.TaskIDs())
Expand Down

0 comments on commit f13aac2

Please sign in to comment.