package web
import (
"bytes"
"encoding/json"
"html/template"
"slices"
"strings"
"testing"
)
// The two sides each added one field before the same closing brace.
// zit draws the conflict with the brace inside it on both sides.
func braceReport() conflictsReport {
base := []string{"package shop", "", "type Order struct {", "\tTotal float64", "}"}
ours := []string{"package shop", "", "type Order struct {", "\tTotal float64", "\tCoupon string", "}"}
theirs := []string{"package shop", "", "type Order struct {", "\tTotal float64", "\tCurrency string", "}"}
return reportOf("shop.go", base, ours, theirs,
[]regionSpec{{"same", [2]int{0, 4}, [2]int{0, 4}, [2]int{0, 4}}, {"conflict", [2]int{4, 5}, [2]int{4, 6}, [2]int{4, 6}}})
}
type regionSpec struct {
kind string
base, ours, theirs [2]int
}
func reportOf(path string, base, ours, theirs []string, regs []regionSpec) conflictsReport {
var rep conflictsReport
rep.Branch, rep.Target, rep.BranchTip, rep.TargetTip, rep.Verdict = "feat", "trunk", "b1b1b1b1b1b1b1", "c2c2c2c2c2c2c2", "conflict"
raw, _ := json.Marshal(map[string]any{"files": []any{map[string]any{
"path": path, "kind": "text",
"ours": map[string]any{"lines": ours}, "theirs": map[string]any{"lines": theirs}, "base": map[string]any{"lines": base},
"regions": func() []any {
var out []any
for _, r := range regs {
span := func(p [2]int) map[string]int { return map[string]int{"start": p[0], "end": p[1]} }
out = append(out, map[string]any{"kind": r.kind, "base": span(r.base), "ours": span(r.ours), "theirs": span(r.theirs)})
}
return out
}()}}})
_ = json.Unmarshal(raw, &rep)
rep.Branch, rep.Target, rep.BranchTip, rep.TargetTip, rep.Verdict = "feat", "trunk", "b1b1b1b1b1b1b1", "c2c2c2c2c2c2c2", "conflict"
return rep
}
func segText(ls []meldLine) string {
var b strings.Builder
for _, l := range ls {
b.WriteString(string(l.HTML))
}
return b.String()
}
func decodeLines(t *testing.T, j string) []string {
t.Helper()
var out []string
if j == "" {
return nil
}
if err := json.Unmarshal([]byte(j), &out); err != nil {
t.Fatalf("FAIL: %q is not a JSON array: %v", j, err)
}
return out
}
// The brace both sides wrote is drawn once, outside the conflict, on all
// three panes; the block holds one line a side; and the answers a reader
// can give assemble from the markup to the lines of the whole zit region.
func TestMeldNarrowsAConflictToWhatDiffers(t *testing.T) {
f := buildMeldUncached(braceReport(), "/r/shop").Files[0]
if f.Conflicts != 1 {
t.Errorf("FAIL: %d conflicts counted", f.Conflicts)
}
var cf, after *meldSeg
for i := range f.Segs {
if f.Segs[i].Region == 1 {
cf = &f.Segs[i]
if i+1 < len(f.Segs) {
after = &f.Segs[i+1]
}
}
}
if cf == nil || after == nil {
t.Fatalf("FAIL: no conflict block or nothing after it: %+v", f.Segs)
}
if len(cf.L) != 1 || len(cf.R) != 1 || len(cf.M) != 0 {
t.Errorf("FAIL: block holds %d/%d/%d lines", len(cf.L), len(cf.M), len(cf.R))
}
if !strings.Contains(segText(cf.L), "Coupon") || !strings.Contains(segText(cf.R), "Currency") {
t.Error("FAIL: the block does not set Coupon against Currency")
}
if after.Region != -1 || len(after.L) != 1 || len(after.M) != 1 || len(after.R) != 1 || after.LCls != "" || after.MCls != "" || after.RCls != "" {
t.Errorf("FAIL: the brace is not an agreed line on all three panes: %+v", after)
}
if !strings.Contains(segText(after.M), "}") {
t.Error("FAIL: the agreed line is not the brace")
}
if !strings.Contains(cf.Tag, "both added") {
t.Errorf("FAIL: the ancestor of the narrowed part is not nothing: %q", cf.Tag)
}
pre, suf := decodeLines(t, cf.Pre), decodeLines(t, cf.Suf)
if len(pre) != 0 || !slices.Equal(suf, []string{"}"}) || cf.Base != "" {
t.Errorf("FAIL: edges pre=%q suf=%q base=%q", cf.Pre, cf.Suf, cf.Base)
}
// What the script sends: pre + the reader's middle + suf.
ours, theirs := []string{"\tCoupon string"}, []string{"\tCurrency string"}
whole := func(mid ...[]string) []string {
out := slices.Clone(pre)
for _, m := range mid {
out = append(out, m...)
}
return append(out, suf...)
}
want := []string{"\tCurrency string", "\tCoupon string", "}"}
if got := whole(theirs, ours); !slices.Equal(got, want) {
t.Errorf("FAIL: both, theirs first: %q", got)
}
if got := whole(ours, theirs); !slices.Equal(got, []string{"\tCoupon string", "\tCurrency string", "}"}) {
t.Errorf("FAIL: both, ours first: %q", got)
}
if got := whole(ours); !slices.Equal(got, []string{"\tCoupon string", "}"}) {
t.Errorf("FAIL: ours: %q", got)
}
if !t.Failed() {
t.Log("ok")
}
}
// The same conflict on a phone: the brace is context below the block,
// the ancestor block says nothing was there.
func TestMeldPhoneNarrowsToo(t *testing.T) {
pcs := buildMeldUncached(braceReport(), "/r/shop").Files[0].Phone
if len(pcs) != 1 || pcs[0].Region != 1 {
t.Fatalf("FAIL: phone conflicts %+v", pcs)
}
for name, b := range map[string]phoneBlock{"ours": pcs[0].Ours, "theirs": pcs[0].Theirs} {
var conf, ctxAfter int
seenConf := false
for _, l := range b.Lines {
switch {
case !l.Ctx && !l.Gap:
conf++
seenConf = true
case l.Ctx && seenConf:
ctxAfter++
}
}
if conf != 1 || ctxAfter != 1 {
t.Errorf("FAIL: %s block has %d conflict lines and %d context lines after", name, conf, ctxAfter)
}
}
if !slices.ContainsFunc(pcs[0].Base.Lines, func(l phoneLine) bool { return l.Gap }) {
t.Error("FAIL: the ancestor block does not say nothing was there")
}
if !t.Failed() {
t.Log("ok")
}
}
// Each edge case in one table: what is shared at the start and end, and
// what stays in dispute.
func TestNarrowRegionEdgeCases(t *testing.T) {
cases := []struct {
name string
base, ours, theirs []string
pre, suf int
baseMid [2]int
baseDiffers bool
}{
{"nothing shared", []string{"x"}, []string{"a"}, []string{"b"}, 0, 0, [2]int{0, 1}, false},
{"identical sides stay as zit drew them", []string{"x"}, []string{"a", "}"}, []string{"a", "}"}, 0, 0, [2]int{0, 1}, false},
{"ours is a prefix of theirs", nil, []string{"a"}, []string{"a", "b"}, 1, 0, [2]int{0, 0}, true},
{"ours is a suffix of theirs", nil, []string{"}"}, []string{"b", "}"}, 0, 1, [2]int{0, 0}, true},
{"theirs is inside ours", nil, []string{"a", "m", "z"}, []string{"a", "z"}, 1, 1, [2]int{0, 0}, true},
{"edges would overlap", nil, []string{"a", "a"}, []string{"a", "a", "a"}, 2, 0, [2]int{0, 0}, true},
{"shared start and end around different middles", []string{"{", "x", "}"}, []string{"{", "a", "}"}, []string{"{", "b", "}"}, 1, 1, [2]int{1, 2}, false},
{"carriage return is not the same line", []string{"x"}, []string{"a\r"}, []string{"a"}, 0, 0, [2]int{0, 1}, false},
{"whitespace only is not the same line", []string{"x"}, []string{"a "}, []string{"a"}, 0, 0, [2]int{0, 1}, false},
{"ancestor holds the shared line", []string{"}"}, []string{"c", "}"}, []string{"d", "}"}, 0, 1, [2]int{0, 0}, false},
}
for _, c := range cases {
r := narrowRegion(meldRegion{Kind: "conflict", Base: [2]int{0, len(c.base)}, Ours: [2]int{0, len(c.ours)}, Theirs: [2]int{0, len(c.theirs)}}, c.ours, c.theirs, c.base)
if r.Pre != c.pre || r.Suf != c.suf {
t.Errorf("FAIL: %s: pre=%d suf=%d, want %d/%d", c.name, r.Pre, r.Suf, c.pre, c.suf)
continue
}
if r.narrowed() {
if r.BaseMid != c.baseMid || r.BaseDiffers != c.baseDiffers {
t.Errorf("FAIL: %s: baseMid=%v differs=%v", c.name, r.BaseMid, r.BaseDiffers)
}
// No line is counted at both ends.
if r.Pre+r.Suf > min(len(c.ours), len(c.theirs)) {
t.Errorf("FAIL: %s: edges overlap", c.name)
}
// What "both" writes keeps each shared line once.
om, tm := c.ours[r.Pre:len(c.ours)-r.Suf], c.theirs[r.Pre:len(c.theirs)-r.Suf]
both := slices.Concat(r.PreLines, om, tm, r.SufLines)
if len(both) != len(c.ours)+len(c.theirs)-r.Pre-r.Suf {
t.Errorf("FAIL: %s: both writes %d lines", c.name, len(both))
}
} else if r.Base != [2]int{0, len(c.base)} {
t.Errorf("FAIL: %s: an unnarrowed region changed its ancestor", c.name)
}
}
// A region of any other kind is never narrowed.
for _, k := range []string{"ours", "theirs", "both", "same"} {
r := narrowRegion(meldRegion{Kind: k, Ours: [2]int{0, 2}, Theirs: [2]int{0, 2}}, []string{"a", "x"}, []string{"a", "y"}, nil)
if r.narrowed() {
t.Errorf("FAIL: a %s region was narrowed", k)
}
}
// A range past the file is left alone rather than trusted.
if r := narrowRegion(meldRegion{Kind: "conflict", Ours: [2]int{0, 9}, Theirs: [2]int{0, 9}}, []string{"a"}, []string{"a"}, nil); r.narrowed() {
t.Error("FAIL: a range past the file was narrowed")
}
if !t.Failed() {
t.Log("ok")
}
}
// Many regions in one file: narrowing adds agreed segments but no
// conflicts, no region indexes, and every pane's numbers stay in step
// with its own file.
func TestMeldManyRegionsKeepLinesAndCounts(t *testing.T) {
base := []string{"a", "}", "b", "c", "d", "}", "e"}
ours := []string{"a", "o1", "}", "b", "O", "d", "o2", "}", "e"}
theirs := []string{"a", "t1", "}", "b", "T", "d", "t2", "}", "e"}
rep := reportOf("f.go", base, ours, theirs, []regionSpec{
{"same", [2]int{0, 1}, [2]int{0, 1}, [2]int{0, 1}},
{"conflict", [2]int{1, 2}, [2]int{1, 3}, [2]int{1, 3}},
{"same", [2]int{2, 3}, [2]int{3, 4}, [2]int{3, 4}},
{"conflict", [2]int{3, 4}, [2]int{4, 5}, [2]int{4, 5}},
{"same", [2]int{4, 5}, [2]int{5, 6}, [2]int{5, 6}},
{"conflict", [2]int{5, 6}, [2]int{6, 8}, [2]int{6, 8}},
{"same", [2]int{6, 7}, [2]int{8, 9}, [2]int{8, 9}},
})
f := buildMeldUncached(rep, "/r/x").Files[0]
if f.Conflicts != 3 || len(f.Phone) != 3 {
t.Errorf("FAIL: %d conflicts, %d phone blocks", f.Conflicts, len(f.Phone))
}
var regions []int
var m, l, r []int
for _, s := range f.Segs {
if s.Region >= 0 {
regions = append(regions, s.Region)
}
for _, x := range s.M {
m = append(m, x.N)
}
for _, x := range s.L {
l = append(l, x.N)
}
for _, x := range s.R {
r = append(r, x.N)
}
}
if !slices.Equal(regions, []int{1, 3, 5}) {
t.Errorf("FAIL: region indexes %v", regions)
}
// The result is ours' file with each conflict showing the ancestor's
// narrowed lines: a, }, b, c, d, } ... each numbered in turn.
for i := range m {
if m[i] != i+1 {
t.Errorf("FAIL: result numbers %v", m)
break
}
}
for name, ns := range map[string][]int{"ours": l, "theirs": r} {
for i := range ns {
if ns[i] != i+1 {
t.Errorf("FAIL: %s numbers %v", name, ns)
break
}
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A resolver's page carries what the script needs to answer for the
// whole region, only on the result's block; the count of conflicts and
// of region-bearing blocks is what it was.
func TestMeldNarrowedMarkup(t *testing.T) {
v := buildMeld(braceReport(), "/r/shop")
v.CanResolve, v.ResolveURL, v.DraftKey = true, "/r/shop/merge/resolve", meldDraftKey("shop", "merge:feat:trunk", "b", "t")
var b bytes.Buffer
if err := template.Must(base.Clone()).ExecuteTemplate(&b, "meld", v); err != nil {
t.Fatal(err)
}
h := b.String()
if n := strings.Count(h, `data-region="1"`); n != 4 {
t.Errorf("FAIL: %d blocks carry region 1 (three panes and the phone)", n)
}
if n := strings.Count(h, `data-suf="`); n != 1 || strings.Contains(h, `data-pre="`) {
t.Errorf("FAIL: edge attributes: %d suf, pre present=%v", n, strings.Contains(h, `data-pre="`))
}
if !strings.Contains(h, `data-hook="meld-count" data-count="1"`) {
t.Error("FAIL: the conflict count changed")
}
if !strings.HasSuffix(v.DraftKey, "/"+meldDraftVersion) || strings.HasSuffix("meld:shop/x/b/t", "/"+meldDraftVersion) {
t.Error("FAIL: the draft key does not carry the region cut")
}
if !t.Failed() {
t.Log("ok")
}
}