go-test-color/main.go

103 lines
1.8 KiB
Go
Raw Normal View History

2020-11-11 15:36:53 +00:00
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"github.com/fatih/color"
)
func main() {
2020-11-12 10:02:24 +00:00
code := runGoTest()
os.Exit(code)
}
// Run go test with args
2020-11-12 10:02:24 +00:00
func runGoTest() int {
// Pass all args
2020-11-11 15:36:53 +00:00
args := []string{"test"}
args = append(args, os.Args[1:]...)
cmd := exec.Command("go", args...)
2021-05-30 15:45:31 +00:00
// Output pipe
outReader, outWriter := io.Pipe()
defer outReader.Close()
defer outWriter.Close()
2020-11-11 15:36:53 +00:00
// Error pipe
errReader, errWriter := io.Pipe()
defer errReader.Close()
defer errWriter.Close()
// Redirect cmd pipes to our pipes
cmd.Stdout = outWriter
cmd.Stderr = errWriter
2020-11-11 15:36:53 +00:00
// See https://stackoverflow.com/questions/8875038/redirect-stdout-pipe-of-child-process-in-go
if err := cmd.Start(); err != nil {
log.Printf("Failed to start: %s", err)
return 1
}
defer func() {
if err := cmd.Wait(); err != nil {
log.Printf("Failed to wait: %s", err)
}
}()
go colorOutputReader(outReader)
go colorErrorReader(errReader)
2020-11-12 10:02:24 +00:00
return 0
}
2020-11-11 15:36:53 +00:00
func colorOutputReader(reader io.Reader) {
scanner := bufio.NewScanner(reader)
2020-11-11 15:36:53 +00:00
for scanner.Scan() {
line := scanner.Text()
2022-07-23 14:30:03 +00:00
line = strings.TrimSpace(line)
2022-07-23 14:30:03 +00:00
if strings.HasPrefix(line, "--- PASS") ||
strings.HasPrefix(line, "PASS") ||
strings.HasPrefix(line, "ok") {
color.Green("%s\n", line)
continue
2020-11-11 15:36:53 +00:00
}
2022-07-23 14:30:03 +00:00
if strings.HasPrefix(line, "--- SKIP") {
color.Yellow("%s\n", line)
continue
}
if strings.HasPrefix(line, "--- FAIL") ||
strings.HasPrefix(line, "FAIL") {
color.Red("%s\n", line)
continue
2020-11-11 15:36:53 +00:00
}
fmt.Println(line)
}
if err := scanner.Err(); err != nil {
log.Printf("scanner error: %s", err)
}
}
func colorErrorReader(reader io.Reader) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Text()
color.Red("%s\n", line)
2020-11-11 15:36:53 +00:00
}
if err := scanner.Err(); err != nil {
log.Printf("scanner error: %s", err)
}
2020-11-11 15:36:53 +00:00
}