package main
import (
"cmp"
"context"
"errors"
"fmt"
"io"
"maps"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"testing"
"time"
"golang.org/x/term"
)
const port = "8000"
// printCoverage prints per-file coverage percentages to stdout.
keys := slices.Collect(maps.Keys(cs.cov))
maxPathLen := len(slices.MaxFunc(keys, func(a, b string) int {
return cmp.Compare(len(a), len(b))
}))
maxPathLen = max(maxPathLen, 5) // 5 == len("Total")
divider := strings.Repeat("—", maxPathLen + 9) + "\n" // 9 == 2 spaces + len("100.00%")
ew := newErrorWriter(w)
ew.write("File")
ew.write(strings.Repeat(" ", maxPathLen - 4 + 1))
ew.write("Coverage\n")
ew.write(divider)
for _, path := range cs.sort() {
cov := cs.cov[path]
percent := 0.0
if cov.total > 0 {
percent = float64(cov.covered) / float64(cov.total) * 100
}
writeRow(ew, path, percent, maxPathLen)
}
totalPercent := 0.0
totalCovered := cs.totalCovered.Load()
totalStatements := cs.totalStatements.Load()
if totalStatements > 0 {
totalPercent = float64(totalCovered) / float64(totalStatements) * 100
}
ew.write(divider)
writeRow(ew, "Total", totalPercent, maxPathLen)
return ew.err()
}
// writeRow writes a single padded, color-coded (green ≥ 50%, red < 50%) coverage row.
const (
green = "\033[32m"
red = "\033[31m"
)
ew.write(path)
ew.write(strings.Repeat(" ", maxPathLen - len(path) + 2))
pct := strconv.FormatFloat(percent, 'f', 2, 64) + "%"
colorCode := green
if percent < 50 { colorCode = red }
ew.write(strings.Repeat(" ", 7 - len(pct))) // 7 == len("100.00%")
ew.writeColor(pct, colorCode)
ew.write("\n")
}
// maybeOpenBrowser opens the generated index.html file in the
// default browser when stdout is a TTY and -n is not set.
if fv.noBrowser ||
!rg.write ||
!isTerm(os.Stdin) {
return nil
}
if fv.httpServer {
return launchHTTPServer(runner, rg.outRoot.Name())
}
absPath, err := filepath.Abs(filepath.Join(rg.outRoot.Name(), "index.html"))
if err != nil {
return err
}
if runtime.GOOS == "linux" {
absPath = "file://" + absPath // Linux requires explicit file:// scheme prefix
}
return openBrowser(runner, absPath)
}
// launchHTTPServer launches an HTTP server when -s is set and -n is not set.
url := "http://localhost:" + port
if portInUse(port) {
if isTerm(os.Stderr) {
msg := fmt.Sprintf("port %s is already in use", port)
if pid, err := findPortPID(runner, port); err == nil {
msg += fmt.Sprintf(" (PID: %d)", pid)
}
fmt.Fprintf(os.Stderr, "%s; opening browser\n", msg)
}
return openBrowser(runner, url)
}
exe, err := os.Executable()
if err != nil { return err }
cmd := exec.Command(exe, "-s", "-outdir", outDir) // #nosec G204 G702 - exe is os.Executable() (absolute path); outDir is user-specified but confined to outRoot
if err := runner.Start(cmd); err != nil { return err }
if isTerm(os.Stderr) {
fmt.Fprintf(os.Stderr, "HTTP server listening on %s (PID: %d)\n", url, cmd.Process.Pid)
}
return openBrowser(runner, url)
}
// serveFiles serves the generated HTML files until the context is canceled.
if _, err := os.Stat(dir); err != nil {
fmt.Fprintf(os.Stderr, "cannot serve %q: %v\n", dir, err)
os.Exit(1)
}
ln, err := net.Listen("tcp", "127.0.0.1:" + port)
if err != nil {
fmt.Fprintf(os.Stderr, "cannot listen on port %s: %v\n", port, err)
os.Exit(1)
}
srv := &http.Server{
Handler: http.FileServer(http.Dir(dir)),
ReadHeaderTimeout: 10 * time.Second, // satisfy GOSEC G112
}
go func() {
if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
}
}()
<-ctx.Done()
if err := srv.Shutdown(ctx); err != nil && !errors.Is(err, context.Canceled) {
fmt.Fprintf(os.Stderr, "shutdown error: %v\n", err)
}
}
// openBrowser opens the default browser with the specified URL.
var cmd *exec.Cmd
switch os := runtime.GOOS; os {
case "darwin":
cmd = exec.Command("open", url) // #nosec G204 G702 - no shell (no injection); url confined to outRoot (no path escape)
case "windows":
cmd = exec.Command("explorer.exe", url) // #nosec G204 G702 - no shell (no injection); url confined to outRoot (no path escape)
case "linux":
cmd = exec.Command("xdg-open", url) // #nosec G204 G702 - no shell (no injection); url confined to outRoot (no path escape)
default:
return fmt.Errorf("unrecognized OS: %s", os)
}
return runner.Run(cmd)
}
// findPortPID searches for a process listening on the specified port and returns its PID if found.
out, err := runner.Output(exec.Command("lsof", "-ti", "tcp:" + port, "-sTCP:LISTEN")) // #nosec G204 - port is a const defined in launchHTTPServer()
if err != nil { return -1, err }
var pid int
if _, err := fmt.Sscanf(strings.TrimSpace(string(out)), "%d", &pid); err != nil {
return -1, err
}
return pid, nil
}
// portInUse reports whether any process is listening on the specified port.
ln, err := net.Listen("tcp", "127.0.0.1:" + port)
if err != nil { return true }
_ = ln.Close()
return false
}
// isTerm determines if the specified writer is connected to a terminal.
if testing.Testing() ||
os.Getenv("GITHUB_ACTIONS") == "true" || // https://docs.github.com/actions/reference/workflows-and-actions/variables
os.Getenv("CI" ) == "true" { return false }
fd := getFD(v)
if fd < 0 { return false }
return term.IsTerminal(fd)
}
// getFD returns the file descriptor of the provided argument.
if f, ok := v.(interface{ Fd() uintptr }); ok { return int(f.Fd()) }
return -1
}