Skip to content
quarry Artifact [9f6574a550]
Login

Artifact [9f6574a550]

Artifact 9f6574a550a015c8c99f3def3de1ed2cce2f00a632d40f70372734a1bc1de5b6:


package index

import (
	"path/filepath"
	"slices"
	"strings"
	"testing"
)

// compactFixture is a small history with a branch, a merge, a renamed
// directory's worth of paths and a counted file, folded the way a
// crosslink rebuild folds it.
func compactFixture(t *testing.T) *Index {
	t.Helper()
	ix := openIndex(t)
	recs := []CheckinRecord{
		{Hash: "c1", Date: "2026-01-01T00:00:01", User: "dan", Comment: "alpha first\nsecond line",
			Changes: []string{"a.go", "dir/x"}, Lines: map[string]LineCount{"a.go": {Added: 3, Removed: 0}, "dir/x": {Added: 5, Removed: 1}}},
		{Hash: "b1", Date: "2026-01-01T00:00:02", User: "dan", Comment: "beta on a branch", Parents: []string{"c1"},
			Changes: []string{"a.go"}, Lines: map[string]LineCount{"a.go": {Added: 1, Removed: 1}}},
		{Hash: "c2", Date: "2026-01-01T00:00:03", User: "ann", Comment: "gamma elsewhere", Parents: []string{"c1"},
			Changes: []string{"b.txt"}},
		{Hash: "c3", Date: "2026-01-01T00:00:04", User: "ann", Comment: "delta merge", Parents: []string{"c2", "b1"},
			Changes: []string{"a.go", "dir/y"}, Lines: map[string]LineCount{"a.go": {Added: 2, Removed: 2}, "dir/y": {Added: 7, Removed: 0}}},
	}
	if err := ix.FoldCheckins(recs); err != nil {
		t.Fatal(err)
	}
	return ix
}

// An index written under another schema version has no way to take this
// code's tables on top of its own: it comes back, on open, with the new
// shape and nothing of the old rows, ready for the rebuild that Stale
// asks for.
func TestAnOldSchemaIndexComesBackWithTheNewTables(t *testing.T) {
	path := filepath.Join(t.TempDir(), "index.db")
	ix, err := Open(path)
	if err != nil {
		t.Fatal(err)
	}
	if err := dropDerived(ix.w); err != nil {
		t.Fatal(err)
	}
	for _, q := range []string{
		`CREATE TABLE checkin (hash TEXT PRIMARY KEY, date TEXT NOT NULL, user TEXT NOT NULL,
			comment TEXT NOT NULL, branch TEXT NOT NULL DEFAULT 'trunk')`,
		`CREATE TABLE filechange (path TEXT NOT NULL, checkin TEXT NOT NULL, date TEXT NOT NULL,
			dir INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (path, checkin))`,
		`CREATE TABLE search_doc (hash TEXT PRIMARY KEY, kind TEXT NOT NULL, ref TEXT NOT NULL,
			label TEXT NOT NULL, text TEXT NOT NULL)`,
		`INSERT INTO checkin (hash, date, user, comment) VALUES ('old', '2026-01-01', 'u', 'm')`,
		`PRAGMA user_version = 4`,
	} {
		if _, err := ix.w.Exec(q); err != nil {
			t.Fatal(err)
		}
	}
	ix.Close()

	again, err := Open(path)
	if err != nil {
		t.Fatalf("FAIL: an old-shaped file did not open: %v", err)
	}
	defer again.Close()
	if !again.Stale() {
		t.Errorf("FAIL: an index of schema 4 is not stale")
	}
	has := func(typ, name string) bool {
		var n int
		if err := again.w.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = ? AND name = ?`, typ, name).Scan(&n); err != nil {
			t.Fatal(err)
		}
		return n == 1
	}
	for _, tbl := range []string{"checkin_ghost", "checkin_parent", "checkin_sym", "filechange", "search_doc"} {
		if !has("table", tbl) {
			t.Errorf("FAIL: table %s missing after the old file was opened", tbl)
		}
	}
	if !has("view", "search_all") {
		t.Errorf("FAIL: view search_all missing")
	}
	for _, col := range []struct{ table, name string }{
		{"checkin", "id"}, {"filechange", "ci"}, {"checkin_parent", "child"}, {"checkin_sym", "ci"}, {"search_doc", "id"},
	} {
		var n int
		if err := again.w.QueryRow(`SELECT count(*) FROM pragma_table_info(?) WHERE name = ?`, col.table, col.name).Scan(&n); err != nil {
			t.Fatal(err)
		}
		if n != 1 {
			t.Errorf("FAIL: %s has no column %s", col.table, col.name)
		}
	}
	var rows int
	if err := again.w.QueryRow(`SELECT count(*) FROM checkin`).Scan(&rows); err != nil {
		t.Fatal(err)
	}
	if rows != 0 {
		t.Errorf("FAIL: %d rows of the old shape survived", rows)
	}
	var user int
	if err := again.w.QueryRow(`PRAGMA user_version`).Scan(&user); err != nil {
		t.Fatal(err)
	}
	if user != schemaVersion {
		t.Errorf("FAIL: user_version = %d, want %d", user, schemaVersion)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A check-in's words are found in checkin itself: there is no second
// copy to find them in, a changed comment is found under its new words
// only, and the hit is labelled with the first line.
func TestACheckinCommentIsSearchedWhereItIsStored(t *testing.T) {
	ix := compactFixture(t)
	var docs int
	if err := ix.db.QueryRow(`SELECT count(*) FROM search_doc WHERE kind = 'checkin'`).Scan(&docs); err != nil {
		t.Fatal(err)
	}
	if docs != 0 {
		t.Errorf("FAIL: %d search_doc rows for check-ins; their text is checkin.comment", docs)
	}
	hits, err := ix.Search("second", "checkin", 10)
	if err != nil {
		t.Fatal(err)
	}
	if len(hits) != 1 || hits[0].Kind != "checkin" || hits[0].Ref != "c1" || hits[0].Label != "alpha first" ||
		!strings.Contains(hits[0].Snippet, "⟦second⟧") {
		t.Errorf("FAIL: a word on a comment's second line found %+v", hits)
	}
	if n, err := ix.SearchCount("delta", ""); err != nil || n != 1 {
		t.Errorf("FAIL: SearchCount = %d, %v; want 1", n, err)
	}
	found, err := ix.TimelineFind(TimelineFilter{}, "gam", 10)
	if err != nil || len(found) != 1 || found[0].Hash != "c2" {
		t.Errorf("FAIL: TimelineFind on a prefix = %+v, %v", found, err)
	}

	// The comment changes: the old words go and the new ones arrive, and
	// the search index still agrees with its content.
	if err := ix.FoldCheckins([]CheckinRecord{{Hash: "c2", Date: "2026-01-01T00:00:03", User: "ann",
		Comment: "epsilon replaced", Parents: []string{"c1"}, Changes: []string{"b.txt"}}}); err != nil {
		t.Fatal(err)
	}
	if old, _ := ix.Search("gamma", "", 10); len(old) != 0 {
		t.Errorf("FAIL: the replaced comment is still found: %+v", old)
	}
	if fresh, _ := ix.Search("epsilon", "", 10); len(fresh) != 1 || fresh[0].Ref != "c2" {
		t.Errorf("FAIL: the new comment is not found: %+v", fresh)
	}
	if _, err := ix.w.Exec(`INSERT INTO search_fts(search_fts, rank) VALUES('integrity-check', 1)`); err != nil {
		t.Errorf("FAIL: the search index disagrees with its content: %v", err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A file's history, a check-in's changed files and their counts are the
// answers the integer-keyed tables must keep giving.
func TestFileHistoryAndChangedFilesAreUnchangedByCheckinIDs(t *testing.T) {
	ix := compactFixture(t)
	hist := func(path string) []string {
		es, _, err := ix.Timeline(TimelineFilter{Limit: 50, Path: path})
		if err != nil {
			t.Fatal(err)
		}
		var out []string
		for _, e := range es {
			out = append(out, e.Hash)
		}
		return out
	}
	for _, c := range []struct {
		path string
		want []string
	}{
		{"a.go", []string{"c3", "b1", "c1"}},
		{"dir", []string{"c3", "c1"}},
		{"dir/y", []string{"c3"}},
		{"b.txt", []string{"c2"}},
	} {
		if got := hist(c.path); !slices.Equal(got, c.want) {
			t.Errorf("FAIL: history of %s = %v, want %v", c.path, got, c.want)
		}
	}
	// The path's own graph: c3 follows b1 and (through c2, which never
	// touched a.go) c1.
	es, _, err := ix.Timeline(TimelineFilter{Limit: 50, Path: "a.go"})
	if err != nil {
		t.Fatal(err)
	}
	if len(es) != 3 || !slices.Equal(es[0].Parents, []string{"c1", "b1"}) {
		t.Errorf("FAIL: the path graph below c3 = %+v", es)
	}
	lines, err := ix.CheckinFileLines("c3")
	if err != nil {
		t.Fatal(err)
	}
	if len(lines) != 2 || lines["a.go"] != (LineCount{Added: 2, Removed: 2}) || lines["dir/y"] != (LineCount{Added: 7}) {
		t.Errorf("FAIL: changed files of c3 = %v", lines)
	}
	stats, err := ix.ChangeStats([]string{"c1", "c2", "c3"}, "")
	if err != nil {
		t.Fatal(err)
	}
	if st := stats["c1"]; st.Files != 2 || st.Added != 8 || st.Removed != 1 || !st.Counted {
		t.Errorf("FAIL: stats of c1 = %+v", st)
	}
	if st := stats["c2"]; st.Files != 1 || st.Counted {
		t.Errorf("FAIL: stats of c2 = %+v (an uncounted file)", st)
	}
	under, err := ix.ChangeStats([]string{"c3"}, "dir")
	if err != nil || under["c3"].Files != 1 {
		t.Errorf("FAIL: c3 under dir = %+v, %v", under, err)
	}
	for path, want := range map[string]string{"dir": "dir", "dir/x": "file", "nope": ""} {
		if got, err := ix.PathKind(path); err != nil || got != want {
			t.Errorf("FAIL: PathKind(%s) = %q, %v; want %q", path, got, err, want)
		}
	}
	last, err := ix.LastChanges([]string{"dir", "a.go", "b.txt"})
	if err != nil {
		t.Fatal(err)
	}
	if last["dir"].Date != "2026-01-01T00:00:04" || last["a.go"].User != "ann" || last["b.txt"].Date != "2026-01-01T00:00:03" {
		t.Errorf("FAIL: LastChanges = %+v", last)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A parent named before it arrives holds an id of its own, and the
// check-in that arrives takes it over: the edge needs no rewriting and
// the hash is reported as missing only while it is.
func TestAParentThatArrivesLateKeepsItsID(t *testing.T) {
	ix := openIndex(t)
	if err := ix.FoldCheckins([]CheckinRecord{{Hash: "kid", Date: "2026-01-02T00:00:00", User: "u",
		Comment: "child", Parents: []string{"dad"}}}); err != nil {
		t.Fatal(err)
	}
	if d, err := ix.DanglingParents(10); err != nil || !slices.Equal(d, []string{"dad"}) {
		t.Fatalf("FAIL: dangling before = %v, %v", d, err)
	}
	if ps, err := ix.ParentsOf("kid"); err != nil || !slices.Equal(ps, []string{"dad"}) {
		t.Errorf("FAIL: ParentsOf while missing = %v, %v", ps, err)
	}
	var ghost int64
	if err := ix.db.QueryRow(`SELECT id FROM checkin_ghost WHERE hash = 'dad'`).Scan(&ghost); err != nil {
		t.Fatal(err)
	}
	if ghost >= 0 {
		t.Errorf("FAIL: a ghost's id is %d, want negative", ghost)
	}
	if err := ix.FoldCheckins([]CheckinRecord{{Hash: "dad", Date: "2026-01-01T00:00:00", User: "u", Comment: "parent"}}); err != nil {
		t.Fatal(err)
	}
	var id int64
	if err := ix.db.QueryRow(`SELECT id FROM checkin WHERE hash = 'dad'`).Scan(&id); err != nil {
		t.Fatal(err)
	}
	if id != ghost {
		t.Errorf("FAIL: the arrived check-in has id %d, want its ghost's %d", id, ghost)
	}
	if d, err := ix.DanglingParents(10); err != nil || len(d) != 0 {
		t.Errorf("FAIL: dangling after = %v, %v", d, err)
	}
	if ps, err := ix.ParentsOf("kid"); err != nil || !slices.Equal(ps, []string{"dad"}) {
		t.Errorf("FAIL: ParentsOf after = %v, %v", ps, err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// A check-in's event row carries neither its comment nor a second copy
// of its hash; the timeline puts both back from the hash.
func TestACheckinEventHoldsNeitherCommentNorSecondHash(t *testing.T) {
	ix := compactFixture(t)
	var kind, ref, comment string
	if err := ix.db.QueryRow(`SELECT kind, ref, comment FROM event WHERE hash = 'c1'`).Scan(&kind, &ref, &comment); err != nil {
		t.Fatal(err)
	}
	if kind != "ci" || ref != "" || comment != "" {
		t.Errorf("FAIL: event row = %q %q %q", kind, ref, comment)
	}
	es, _, err := ix.Timeline(TimelineFilter{Limit: 10})
	if err != nil || len(es) != 4 {
		t.Fatalf("FAIL: timeline = %+v, %v", es, err)
	}
	for _, e := range es {
		var want string
		if err := ix.db.QueryRow(`SELECT comment FROM checkin WHERE hash = ?`, e.Hash).Scan(&want); err != nil {
			t.Fatal(err)
		}
		if e.Comment != want || e.Ref != e.Hash {
			t.Errorf("FAIL: %s rendered comment %q ref %q, want %q and its hash", e.Hash, e.Comment, e.Ref, want)
		}
	}
	if k, r, ok, err := ix.EventByPrefix("c1"); err != nil || !ok || k != "ci" || r != "c1" {
		t.Errorf("FAIL: EventByPrefix = %q %q %v %v", k, r, ok, err)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}