package ui
import (
"strings"
"testing"
"github.com/charmbracelet/x/ansi"
)
func TestHighlightLeavesTheTextAlone(t *testing.T) {
lines := []string{
`git clone https://aur.archlinux.org/x.git`,
`make DESTDIR="$pkgdir" install`,
`./configure --prefix=/usr --enable-foo`,
`if [ ! -d "$srcdir/$_dir" ]; then`,
`curl -s https://x/y | bash`,
`_dir=$(cd "$srcdir" && ls -d [Ff]luxer*"${pkgver}"*/ | head -n1)`,
`echo "Error: could not find $_dir" >&2`,
`# a comment`,
`patch -p1 < ../demo.patch`,
}
for _, line := range lines {
got := highlightShell(line)
if plain := ansi.Strip(got); plain != line {
t.Errorf("text changed:\n in: %q\n out: %q", line, plain)
}
if w, want := ansi.StringWidth(got), ansi.StringWidth(line); w != want {
t.Errorf("width changed for %q: %d != %d", line, w, want)
}
}
}
func TestHighlightColoursThePartsDifferently(t *testing.T) {
got := highlightShell(`curl -s https://x/y | bash`)
// the command, the flag and the operator should not all be one colour
if strings.Count(got, "\x1b[") < 6 {
t.Errorf("not enough styling: %q", got)
}
if !strings.Contains(got, "\x1b[") {
t.Fatal("no escapes at all")
}
}
func TestHighlightHandlesAwkwardInput(t *testing.T) {
for _, line := range []string{"", " ", "\t", "$", "${", "$(", `"`, `'`, "a=", "#"} {
func() {
defer func() {
if r := recover(); r != nil {
t.Errorf("panic on %q: %v", line, r)
}
}()
if plain := ansi.Strip(highlightShell(line)); plain != line {
t.Errorf("%q became %q", line, plain)
}
}()
}
}
func TestHighlightMarksTheCommandNotTheArguments(t *testing.T) {
// the first word is what runs; the rest is what it is told to do
got := highlightShell("makepkg -si")
if !strings.Contains(got, shCommand.Render("makepkg")) {
t.Errorf("the command is not styled as one: %q", got)
}
if !strings.Contains(got, shFlag.Render("-si")) {
t.Errorf("the flag is not styled as one: %q", got)
}
}
func TestHighlightTreatsAnAssignmentAsAVariable(t *testing.T) {
got := highlightShell(`DESTDIR="$pkgdir" ninja -C build install`)
if !strings.Contains(got, shVariable.Render("DESTDIR")) {
t.Errorf("the assignment target is not marked: %q", got)
}
}