Skip to content

Commit

Permalink
cmd/mecha: improve output from mecha flash command and simplify the code
Browse files Browse the repository at this point in the history
Signed-off-by: deadprogram <ron@hybridgroup.com>
  • Loading branch information
deadprogram committed Feb 29, 2024
1 parent 2e047ed commit 08b2935
Showing 1 changed file with 19 additions and 32 deletions.
51 changes: 19 additions & 32 deletions cmd/mecha/flash.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package main

import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"os"
"os/exec"

"github.com/urfave/cli/v2"
Expand All @@ -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
Expand Down

0 comments on commit 08b2935

Please sign in to comment.