diff --git a/cmd/mecha/flash.go b/cmd/mecha/flash.go index 00c41ee..3fa4c43 100644 --- a/cmd/mecha/flash.go +++ b/cmd/mecha/flash.go @@ -1,10 +1,11 @@ package main import ( - "bufio" "bytes" "fmt" + "io" "log" + "os" "os/exec" "github.com/urfave/cli/v2" @@ -15,45 +16,31 @@ func flash(cCtx *cli.Context) error { return fmt.Errorf("target board required") } - if cCtx.Bool("monitor") { - return flashAndMonitor(cCtx) - } - targetName := cCtx.Args().First() - var stdout, stderr bytes.Buffer - cmd := exec.Command("tinygo", "flash", "-size", "short", "-target", targetName, ".") - cmd.Stdout = &stdout - cmd.Stderr = &stderr - if err := cmd.Run(); err != nil { - log.Fatalf("tinygo flash -size short -target %s .: %v\n%s%s", targetName, err, stderr.Bytes(), stdout.Bytes()) + var cmd *exec.Cmd + if cCtx.Bool("monitor") { + cmd = exec.Command("tinygo", "flash", "-size", "short", "-target", targetName, "-monitor", ".") + } else { + cmd = exec.Command("tinygo", "flash", "-size", "short", "-target", targetName, ".") } - fmt.Println(stdout.String()) - - return nil -} - -func flashAndMonitor(cCtx *cli.Context) error { - targetName := cCtx.Args().First() + var stdoutBuf, stderrBuf bytes.Buffer + cmd.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) + cmd.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) - var stderr bytes.Buffer - cmd := exec.Command("tinygo", "flash", "-size", "short", "-target", targetName, "-monitor", ".") - cmd.Stderr = &stderr - stdout, err := cmd.StdoutPipe() - if err != nil { - return err - } - - if err := cmd.Start(); err != nil { - log.Fatalf("tinygo flash -size short -target %s .: %v\n%s", targetName, err, stderr.Bytes()) + if err := cmd.Run(); err != nil { + log.Fatalf("tinygo flash -size short -target %s .: %v\n", targetName, err) //, stderr.Bytes()) } // print the monitoring output - scanner := bufio.NewScanner(stdout) - for scanner.Scan() { - m := scanner.Text() - fmt.Println(m) + if cCtx.Bool("monitor") { + outStr, errStr := stdoutBuf.String(), stderrBuf.String() + if errStr != "" { + fmt.Println(errStr) + } else { + fmt.Println(outStr) + } } return nil