go-test-color/main.go

109 lines
2.0 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"
)
const cmdName = "go-test-color"
2020-11-11 15:36:53 +00:00
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
// Read stdout and stderr
outReader, err := cmd.StdoutPipe()
if err != nil {
log.Printf("%s failed to get stdout pipe: %s", cmdName, err)
return 1
}
errReader, err := cmd.StderrPipe()
if err != nil {
log.Printf("%s failed to get stderr pipe: %s", cmdName, err)
return 1
}
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("%s failed to start: %s", cmdName, err)
return 1
}
// Add color to both stdout and stderr
colorOutputReader(outReader)
colorErrorReader(errReader)
if err := cmd.Wait(); err != nil {
log.Printf("%s failed to wait: %s", cmdName, err)
return 1
}
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)
2023-10-11 08:15:03 +00:00
if strings.HasSuffix(line, "[no test files]") {
continue
}
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
}