From 633f40fded8e7e3c03dc661a27557d8c4a45b1a9 Mon Sep 17 00:00:00 2001 From: MaurĂ­cio Antunes Date: Mon, 31 Oct 2022 07:26:26 -0300 Subject: feat: improve exercise runner output --- exercises/variables/variables1.go | 2 +- src/cmd/run.go | 16 +++++++++------- src/exercises/runner.go | 20 ++++++++++++++++---- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/exercises/variables/variables1.go b/exercises/variables/variables1.go index 50be731..d58a251 100644 --- a/exercises/variables/variables1.go +++ b/exercises/variables/variables1.go @@ -7,6 +7,6 @@ package main import "fmt" func main() { - x = 5 + x := 5 fmt.Printf("x has the value %d", x) } diff --git a/src/cmd/run.go b/src/cmd/run.go index fb62f67..300478f 100644 --- a/src/cmd/run.go +++ b/src/cmd/run.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "os" "github.com/fatih/color" @@ -18,14 +17,17 @@ var cmdRun = &cobra.Command{ Short: "Run a single exercise", Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), Run: func(cmd *cobra.Command, args []string) { - out, err := exercises.Run(args[0]) - fmt.Println(out) + result, err := exercises.Run(args[0]) if err != nil { - color.Red("Your exercise is failing: %s", err) + color.Red("Compilation of %s failed! Compiler error message:\n\n%s", result.Exercise.Path, result.Err) + color.Yellow("If you feel stuck, ask a hint by executing `golings hint %s`", result.Exercise.Name) os.Exit(1) + } else { + color.Green("Congratulations!\n\n") + color.Green("Remove the 'I AM NOT DONE' from the file to keep going\n") + color.Green("Here is the output of your program:\n\n") + color.Cyan(result.Out) + os.Exit(0) } - color.Green("Congratulations!") - color.Green("Remove the 'I AM NOT DONE' from the file to keep going") - os.Exit(0) }, } diff --git a/src/exercises/runner.go b/src/exercises/runner.go index 1490f13..d034093 100644 --- a/src/exercises/runner.go +++ b/src/exercises/runner.go @@ -1,17 +1,29 @@ package exercises import ( + "bytes" "fmt" "os/exec" ) -func Run(name string) (string, error) { +type Result struct { + Exercise Exercise + Out string + Err string +} + +func Run(name string) (Result, error) { exercise, err := Find(name) if err != nil { - return "", err + return Result{}, err } cmd := exec.Command("go", "run", fmt.Sprintf("./%s", exercise.Path)) - cOut, err := cmd.CombinedOutput() - return string(cOut), err + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + + err = cmd.Run() + + return Result{Exercise: exercise, Out: stdout.String(), Err: stderr.String()}, err } -- cgit v1.2.3-70-g09d2