Vectrum
Sign In
46 lines · 1.3 KB · Go
package ui

import (
	"fmt"
	"io"
	"strings"
)

// diff colours are separate from the palette so a unified diff reads the same
// way it does in git.
var (
	green = "\x1b[32m"
	red   = "\x1b[31m"
)

func init() {
	if color.reset == "" { // not a terminal, or NO_COLOR
		green, red = "", ""
	}
}

// WriteDiff renders a unified diff with colour. Anything that is not a diff is
// written through unchanged, so a tool result that is a plain message still
// reads normally.
func WriteDiff(w io.Writer, s string) {
	for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
		switch {
		case strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "---"):
			fmt.Fprintf(w, "%s%s%s\n", color.bold, line, color.reset)
		case strings.HasPrefix(line, "@@"):
			fmt.Fprintf(w, "%s%s%s\n", color.cyan, line, color.reset)
		case strings.HasPrefix(line, "+"):
			fmt.Fprintf(w, "%s%s%s\n", green, line, color.reset)
		case strings.HasPrefix(line, "-"):
			fmt.Fprintf(w, "%s%s%s\n", red, line, color.reset)
		default:
			fmt.Fprintf(w, "%s\n", line)
		}
	}
}

// looksLikeDiff reports whether s is a unified diff, so tool output can be
// rendered appropriately without the tool having to say which it is.
func looksLikeDiff(s string) bool {
	return strings.HasPrefix(s, "--- ") && strings.Contains(s, "\n@@ ")
}