added trace

master
Paulo Simão 2021-10-27 20:37:33 -03:00
parent 5bac0b2643
commit bcfdbd4327
1 changed files with 88 additions and 0 deletions

88
lib.go
View File

@ -305,6 +305,94 @@ func Exec(str string, opts ...*Opts) ([]*exec.Cmd, error) {
}
func ExecStr(str string, opts ...*Opts) (string, error) {
sb := strings.Builder{}
wd, err := os.Getwd()
if err != nil {
return "", err
}
ret := make([]*exec.Cmd, 0)
opt := &Opts{
Await: false,
Wd: wd,
SetupProc: func(cmd *exec.Cmd) {
},
}
if opts != nil && len(opts) > 0 {
opt = opts[0]
}
if opt.SetupProc == nil {
opt.SetupProc = func(cmd *exec.Cmd) {
}
}
if opt.Trace {
bs := debug.Stack()
log.Printf("Running: %s\n%s", str, string(bs))
}
cmdwd := opt.Wd
prepCmd := func(l Line) *exec.Cmd {
cmd := exec.Command(l.Tokens[0], l.Tokens[1:]...)
cmd.Stdout = log.Writer()
cmd.Stderr = log.Writer()
cmd.Dir = cmdwd
opt.SetupProc(cmd)
ret = append(ret, cmd)
return cmd
}
lines, err := Lines(str)
if err != nil {
return "", err
}
for _, l := range lines {
switch l.LType {
case LINETYPE_COMMENT:
continue
case LINETYPE_CHANGEWD:
if filepath.IsAbs(l.Tokens[1]) {
cmdwd = l.Tokens[1]
} else {
cmdwd, err = filepath.Abs(filepath.Join(wd, l.Tokens[1]))
if err != nil {
return "", err
}
}
log.Printf("CMDWD NOW IS: %s", cmdwd)
continue
case LINETYPE_SERIAL, LINETYPE_PARALLEL:
cmd := prepCmd(l)
if opt.Debug {
log.Printf("Running %s from dir %s with params %v", cmd.Path, cmd.Dir, cmd.Args)
}
bs, err := cmd.CombinedOutput()
sb.Write(bs)
sb.WriteString("\n")
if opt.Debug {
if err != nil {
log.Printf("Error running: %s: %s", cmd.Path, err.Error())
}
}
if err != nil {
return "", err
}
}
}
return sb.String(), err
}
// Kill call OS to kill pid
func Kill(p int) error {
switch runtime.GOOS {