gitFlow/internal/presenter/presenter_test.go
dimitar 012fbf8ac5 feat: phase 6 — polish: completions, notifications, themes, rules, docs
Close out the plan with the remaining polish items and a full README.

Shell completions (cmd/gitflow):
- New `completion [bash|zsh|fish|powershell]` command backed by cobra's
  generators, wired into the root command

Desktop notifications (internal/notify):
- Send() dispatches to notify-send (Linux) with an osascript fallback
  (macOS); Windows is a documented no-op for now; missing notifiers are
  silent, never errors
- watch --notify sends a notification listing repositories whose state
  changed since the previous frame

Color themes (internal/presenter):
- ThemeMode (dark/light) with ParseTheme; light uses bright ANSI variants
  (90-97) that stay legible on light backgrounds; threaded through the
  table, compact, and suggestions renderers; new --theme flag validated
  and dumped by config

Custom rules (internal/rules):
- Rule{name, field (ahead|behind|stash|changes), op (==,!=,<,<=,>,>=),
  value, label} with upfront validation in both Validate and Eval
- Config gains a `rules:` section (yaml/env only, no flag), validated at
  load; matches render as a "FLAGS (custom rules)" section via a new
  presenter.Flags renderer, shown in scan and watch frames

Docs:
- readme.md fully rewritten: features, install, usage, examples, flag
  table, status classes, configuration reference, AI agent behavior and
  --ai-execute guardrails, development layout, CI, and future work
- implementation.md gains an Implementation Progress section recording
  every phase branch and the deviations from the original plan

Multi-platform:
- Verified cross-compilation for windows/amd64 and darwin/arm64; the
  notify package is split behind build tags

Testing:
- rules: validation, operator semantics, Eval ordering, invalid-rule
  errors
- presenter: ParseTheme, light-theme bright codes (and absence of
  dark-theme codes), Flags rendering (empty = silent, matches render)
- config: rules loading from file, invalid-rule rejection, bad theme and
  bad provider rejection
- notify: no-op behaviour when no notifier is installed (skipped when one
  is, to avoid firing real notifications)

Verified: go build, go vet, go test -race (10 packages), gofmt clean,
windows/darwin cross-compile, completion generation, rules + light theme
smoke test, watch --notify graceful shutdown (exit 0, no orphans).
2026-08-02 08:52:50 +02:00

237 lines
7.3 KiB
Go

package presenter
import (
"bytes"
"encoding/json"
"strings"
"testing"
"time"
"gitea.oblak.solutions/dimitar/gitFlow/internal/ai"
"gitea.oblak.solutions/dimitar/gitFlow/internal/rules"
"gitea.oblak.solutions/dimitar/gitFlow/pkg/status"
)
func sampleResult() status.ScanResult {
return status.ScanResult{
ScannedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
ParentDir: "/home/user/projects",
Repos: []status.RepoInfo{
{Path: "/home/user/projects/api", Name: "api", Branch: "main", Status: status.StatusClean},
{
Path: "/home/user/projects/web",
Name: "web",
Branch: "feat/login",
Status: status.StatusModified,
ModifiedFiles: []string{"a.go"},
UntrackedFiles: []string{"b"},
AheadBy: 3,
},
{Path: "/home/user/projects/lib", Name: "lib", Branch: "main", Status: status.StatusBehind, BehindBy: 5},
{Path: "/home/user/projects/legacy", Name: "legacy", Branch: "(detached)", Detached: true, Status: status.StatusDetached},
{Path: "/home/user/projects/broken", Name: "broken", Status: status.StatusError, Error: "git status: fatal: not a git repository"},
},
}
}
func TestParseColorMode(t *testing.T) {
cases := []struct {
in string
want ColorMode
}{
{"auto", ColorAuto},
{"always", ColorAlways},
{"never", ColorNever},
{"bogus", ColorAuto},
}
for _, tc := range cases {
if got := ParseColorMode(tc.in); got != tc.want {
t.Errorf("ParseColorMode(%q) = %v, want %v", tc.in, got, tc.want)
}
}
}
func TestTableFormat(t *testing.T) {
var buf bytes.Buffer
opts := Options{Color: ColorNever}
if err := Present(&buf, "table", sampleResult(), opts); err != nil {
t.Fatalf("Present: %v", err)
}
out := buf.String()
for _, want := range []string{
"REPOSITORY", "BRANCH", "STATUS", "AHEAD/BEHIND", "CHANGES",
"api", "feat/login", "1M 1U", "0/5", "3/0",
"5 repos | 1 clean | 3 need attention | 1 errors",
"not a git repository",
} {
if !strings.Contains(out, want) {
t.Errorf("table output missing %q:\n%s", want, out)
}
}
if strings.Contains(out, "\x1b[") {
t.Errorf("table output contains escape codes with ColorNever:\n%q", out)
}
}
func TestTableColorAlways(t *testing.T) {
t.Setenv("NO_COLOR", "1") // explicit always must win over NO_COLOR
var buf bytes.Buffer
if err := Present(&buf, "table", sampleResult(), Options{Color: ColorAlways}); err != nil {
t.Fatalf("Present: %v", err)
}
if !strings.Contains(buf.String(), "\x1b[") {
t.Error("ColorAlways produced no escape codes")
}
}
func TestTableRespectsNoColor(t *testing.T) {
t.Setenv("NO_COLOR", "1")
var buf bytes.Buffer
// ColorAuto with a non-terminal writer: no color regardless of NO_COLOR,
// but this also verifies NO_COLOR is read without panicking.
if err := Present(&buf, "table", sampleResult(), Options{Color: ColorAuto}); err != nil {
t.Fatalf("Present: %v", err)
}
if strings.Contains(buf.String(), "\x1b[") {
t.Error("auto color on non-TTY writer produced escape codes")
}
}
func TestJSONFormat(t *testing.T) {
var buf bytes.Buffer
if err := Present(&buf, "json", sampleResult(), Options{}); err != nil {
t.Fatalf("Present: %v", err)
}
var doc struct {
ScannedAt time.Time `json:"scanned_at"`
ParentDir string `json:"parent_dir"`
Repos []status.RepoInfo `json:"repos"`
Summary status.Summary `json:"summary"`
}
if err := json.Unmarshal(buf.Bytes(), &doc); err != nil {
t.Fatalf("output is not valid JSON: %v\n%s", err, buf.String())
}
if doc.ParentDir != "/home/user/projects" {
t.Errorf("parent_dir = %q", doc.ParentDir)
}
if len(doc.Repos) != 5 {
t.Errorf("len(repos) = %d, want 5", len(doc.Repos))
}
if doc.Repos[1].Status != status.StatusModified {
t.Errorf("repos[1].status = %v, want modified", doc.Repos[1].Status)
}
if doc.Summary.Total != 5 || doc.Summary.Clean != 1 || doc.Summary.Attention != 3 || doc.Summary.Errored != 1 {
t.Errorf("summary = %+v", doc.Summary)
}
// Status must marshal as a string label, not an int.
if !strings.Contains(buf.String(), `"status": "modified"`) {
t.Errorf("status not marshaled as string label:\n%s", buf.String())
}
}
func TestCompactFormat(t *testing.T) {
var buf bytes.Buffer
if err := Present(&buf, "compact", sampleResult(), Options{Color: ColorNever}); err != nil {
t.Fatalf("Present: %v", err)
}
out := buf.String()
for _, want := range []string{"✓", "✗", "↓", "◉", "!", "+3/-0", "2 change(s)"} {
if !strings.Contains(out, want) {
t.Errorf("compact output missing %q:\n%s", want, out)
}
}
}
func TestForRejectsUnknownFormat(t *testing.T) {
if _, err := For("xml", Options{}); err == nil {
t.Error("For(xml) succeeded, want error")
}
}
func TestParseTheme(t *testing.T) {
cases := []struct {
in string
want ThemeMode
}{
{"dark", ThemeDark},
{"light", ThemeLight},
{"bogus", ThemeDark},
}
for _, tc := range cases {
if got := ParseTheme(tc.in); got != tc.want {
t.Errorf("ParseTheme(%q) = %v, want %v", tc.in, got, tc.want)
}
}
}
func TestLightThemeUsesBrightCodes(t *testing.T) {
t.Setenv("NO_COLOR", "") // light theme must not be disabled by NO_COLOR in always mode
var buf bytes.Buffer
if err := Present(&buf, "table", sampleResult(), Options{Color: ColorAlways, Theme: ThemeLight}); err != nil {
t.Fatalf("Present: %v", err)
}
out := buf.String()
if !strings.Contains(out, "\x1b[92m") && !strings.Contains(out, "\x1b[93m") {
t.Errorf("light theme did not emit bright codes:\n%q", out)
}
if strings.Contains(out, "\x1b[32m") {
t.Errorf("light theme emitted a dark-theme code:\n%q", out)
}
}
func TestFlags(t *testing.T) {
var buf bytes.Buffer
opts := Options{Color: ColorNever}
if err := Flags(&buf, opts, nil); err != nil {
t.Fatalf("Flags(empty): %v", err)
}
if buf.Len() != 0 {
t.Errorf("Flags(empty) wrote %q, want nothing", buf.String())
}
flags := []rules.Flag{
{RepoPath: "/home/user/projects/lib", Label: "stale"},
{RepoPath: "/home/user/projects/web", Label: "dirty"},
}
buf.Reset()
if err := Flags(&buf, opts, flags); err != nil {
t.Fatalf("Flags: %v", err)
}
out := buf.String()
for _, want := range []string{"FLAGS (custom rules)", "stale", "dirty", "REPOSITORY"} {
if !strings.Contains(out, want) {
t.Errorf("flags output missing %q:\n%s", want, out)
}
}
}
func TestSuggestions(t *testing.T) {
sugs := []ai.Suggestion{
{RepoPath: "/home/user/projects/web", Action: "commit", Message: "commit your work", Command: "git add -A && git commit -m wip", Priority: 2},
{RepoPath: "/home/user/projects/lib", Action: "pull", Message: "pull latest", Command: "git pull", Priority: 1},
}
var buf bytes.Buffer
if err := Suggestions(&buf, Options{Color: ColorNever}, sugs); err != nil {
t.Fatalf("Suggestions: %v", err)
}
out := buf.String()
for _, want := range []string{"AI SUGGESTIONS", "commit", "pull", "high", "medium", "git pull"} {
if !strings.Contains(out, want) {
t.Errorf("suggestions output missing %q:\n%s", want, out)
}
}
if strings.Contains(out, "\x1b[") {
t.Errorf("suggestions contain escape codes with ColorNever")
}
}
func TestSuggestionsEmpty(t *testing.T) {
var buf bytes.Buffer
if err := Suggestions(&buf, Options{}, nil); err != nil {
t.Fatalf("Suggestions: %v", err)
}
if !strings.Contains(buf.String(), "no suggestions") {
t.Errorf("empty suggestions message missing: %q", buf.String())
}
}