internal/control/symbols.go

311 lines · 10948 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"regexp"
  8	"sort"
  9	"strconv"
 10	"strings"
 11
 12	"gitbay.org/gitbay/internal/gitutil"
 13	"gitbay.org/gitbay/internal/policy"
 14	"gitbay.org/gitbay/internal/protocol"
 15	"gitbay.org/gitbay/internal/store"
 16	"gitbay.org/gitbay/internal/symbols"
 17)
 18
 19func init() {
 20	register(Command{Path: []string{"repo", "symbols"},
 21		Summary: "find where a name is defined, from the default branch's symbol index",
 22		Usage:   "repo symbols <owner/name> [--ref <ref>] [--kind <kind>] [--limit <n>] [--cursor <c>] <query>",
 23		Flags: []Flag{
 24			{"--ref", "<ref>", "a ref whose tree is the indexed one; only the default branch is indexed", "the default branch"},
 25			{"--kind", "<kind>", "only this kind: " + strings.Join(symbols.Kinds, ", "), ""},
 26			{"--limit", "<n>", "rows per page", ""},
 27			{"--cursor", "<c>", "continue from the previous page", ""},
 28		},
 29		Examples: []string{
 30			"repo symbols krz/gitbay Dispatch",
 31			"repo symbols krz/gitbay --kind method Ctx.",
 32		},
 33		ReadOnly: true, Run: runRepoSymbols})
 34	register(Command{Path: []string{"repo", "definitions"},
 35		Summary: "where each name a file uses is defined, from the symbol index",
 36		Usage:   "repo definitions <owner/name> <path> [--ref <ref>]",
 37		Flags: []Flag{
 38			{"--ref", "<ref>", "a ref whose tree is the indexed one; only the default branch is indexed", "the default branch"},
 39		},
 40		Examples: []string{"repo definitions krz/gitbay internal/control/control.go"},
 41		ReadOnly: true, Run: runRepoDefinitions})
 42	register(Command{Path: []string{"admin", "symbols", "reindex"},
 43		Summary:  "rebuild a repository's symbol index, even when its tree is already indexed (instance admins)",
 44		Usage:    "admin symbols reindex <owner/name>",
 45		Examples: []string{"admin symbols reindex krz/gitbay"},
 46		Run:      runAdminSymbolsReindex})
 47}
 48
 49// symbolsUnpaged caps a listing given without --limit or --cursor.
 50const symbolsUnpaged = maxPageLimit
 51
 52type symbolOut struct {
 53	Name string `json:"name"`
 54	Kind string `json:"kind"`
 55	Path string `json:"path"`
 56	Line int    `json:"line"`
 57}
 58
 59func runRepoSymbols(c *Ctx, args []string) int {
 60	args, p, code := parsePageFlags(c, args, "symbol", false)
 61	if code >= 0 {
 62		return code
 63	}
 64	f, err := c.parseArgs(args, flagSpec{Values: []string{"--ref", "--kind"}, MaxPos: 2, Usage: c.Cmd.Usage})
 65	if err != nil {
 66		return c.fail(protocol.ExitUsage, "%v", err)
 67	}
 68	path, query, ref, kind := f.pos(0), f.pos(1), f.Value("--ref"), f.Value("--kind")
 69	if path == "" || query == "" {
 70		return c.usage()
 71	}
 72	if len(query) < MinSymbolQuery || len(query) > maxQueryLen {
 73		return c.fail(protocol.ExitUsage, "query must be %d to %d characters", MinSymbolQuery, maxQueryLen)
 74	}
 75	if kind != "" && !symbols.ValidKind(kind) {
 76		return c.fail(protocol.ExitUsage, "--kind must be one of %s", strings.Join(symbols.Kinds, ", "))
 77	}
 78	repo, code := resolveRepo(c, path, policy.CanRead)
 79	if code >= 0 {
 80		return code
 81	}
 82	idx, err := c.Store.SymbolIndexFor(repo.ID)
 83	if errors.Is(err, store.ErrNotFound) {
 84		if f, ferr := c.Store.SymbolFailureFor(repo.ID); ferr == nil {
 85			return c.fail(protocol.ExitFailure, "the symbol index of %s could not be built: %s", repo.Path(), f.Note)
 86		}
 87		return c.fail(protocol.ExitNotFound, "%s has no symbol index yet; one is built after a push to %s", repo.Path(), repo.DefaultBranch)
 88	} else if err != nil {
 89		return c.fail(protocol.ExitFailure, "%v", err)
 90	}
 91	if ref != "" && ref != repo.DefaultBranch {
 92		dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
 93		sha, err := gitutil.ResolveRef(dir, ref)
 94		if err != nil || !IndexedTree(dir, sha, idx) {
 95			return c.fail(protocol.ExitNotFound, "only the default branch, %s, is indexed; %s is not at the indexed tree", repo.DefaultBranch, ref)
 96		}
 97	}
 98	var after int64
 99	if p.key != "" {
100		cursorIdx, id, ok := ParseSymbolCursor(p.key)
101		if !ok {
102			return c.fail(protocol.ExitUsage, "bad cursor")
103		}
104		if cursorIdx != idx.ID {
105			return c.fail(protocol.ExitUsage, "%s", StaleSymbolCursor)
106		}
107		after = id
108	}
109	limit := p.queryLimit()
110	if !p.active {
111		limit = symbolsUnpaged + 1
112	}
113	rows, err := c.Store.SearchSymbols(idx.ID, query, kind, limit, after)
114	if err != nil {
115		return c.fail(protocol.ExitFailure, "%v", err)
116	}
117	capped := !p.active && len(rows) > symbolsUnpaged
118	if capped {
119		rows = rows[:symbolsUnpaged]
120	}
121	rows, next := trimPage(p, rows, "symbol", func(r store.SymbolRow) string {
122		return SymbolCursor(idx.ID, r.ID)
123	})
124	var ds []symbolOut
125	for _, r := range rows {
126		ds = append(ds, symbolOut{r.Name, r.Kind, r.Path, r.Line})
127	}
128	return c.emitPageView(p, ds, next, func(w io.Writer) {
129		tb := c.table(w, "NAME", "KIND", "LOCATION")
130		for _, d := range ds {
131			tb.row(cRef(d.Name), cText(d.Kind), cFlex(fmt.Sprintf("%s:%d", d.Path, d.Line)))
132		}
133		tb.flush()
134		if capped {
135			fmt.Fprintf(c.Stderr, "first %d matches; page with --limit and --cursor\n", symbolsUnpaged)
136		}
137		if idx.State == "partial" {
138			fmt.Fprintf(c.Stderr, "the index is partial: %s\n", idx.Note)
139		}
140	}, func() screen {
141		rows := make([]row, len(ds))
142		for i, d := range ds {
143			rows[i] = rowOf(cRef(d.Name), cText(d.Kind), cFlex(fmt.Sprintf("%s:%d", d.Path, d.Line)))
144		}
145		if capped {
146			fmt.Fprintf(c.Stderr, "first %d matches; page with --limit and --cursor\n", symbolsUnpaged)
147		}
148		if idx.State == "partial" {
149			fmt.Fprintf(c.Stderr, "the index is partial: %s\n", idx.Note)
150		}
151		s := listScreen(fmt.Sprintf("Symbols matching %q", query), rows)
152		if len(ds) > 0 {
153			cat := []string{"repo", "cat", repo.Path(), ds[0].Path}
154			if ref != "" {
155				cat = append(cat, "--ref", ref)
156			}
157			s.actions = []action{{"Read", cat}}
158		}
159		return s
160	})
161}
162
163// MinSymbolQuery is the shortest query repo symbols and the results page
164// take: one character matches too much of an index to be worth a page.
165const MinSymbolQuery = 2
166
167// StaleSymbolCursor is the refusal for a cursor taken from an index that
168// has since been replaced.
169const StaleSymbolCursor = "the symbol index was rebuilt since that cursor; start again without it"
170
171// SymbolCursor is the paging key after row id of index indexID, the form
172// ParseSymbolCursor reads.
173func SymbolCursor(indexID, id int64) string {
174	return strconv.FormatInt(indexID, 10) + "." + strconv.FormatInt(id, 10)
175}
176
177// ParseSymbolCursor reads "<index id>.<row id>". The index id makes a
178// cursor from before a rebuild fail rather than page through the new
179// index from an unrelated row.
180func ParseSymbolCursor(key string) (int64, int64, bool) {
181	a, b, ok := strings.Cut(key, ".")
182	if !ok {
183		return 0, 0, false
184	}
185	idx, err1 := strconv.ParseInt(a, 10, 64)
186	id, err2 := strconv.ParseInt(b, 10, 64)
187	return idx, id, err1 == nil && err2 == nil && id > 0
188}
189
190// IndexedTree reports whether commit sha has the tree idx was built from:
191// the default branch's head when the index is current, or any other
192// commit with the same content. The blob view uses it to decide whether
193// its names can link into the index.
194func IndexedTree(dir, sha string, idx store.SymbolIndex) bool {
195	if sha == idx.Commit {
196		return true
197	}
198	tree, err := gitutil.ResolveTree(dir, sha)
199	return err == nil && tree == idx.Tree
200}
201
202func runAdminSymbolsReindex(c *Ctx, args []string) int {
203	if len(args) != 1 {
204		return c.usage()
205	}
206	repo, code := adminRepo(c, args[0])
207	if code >= 0 {
208		return code
209	}
210	if err := c.Store.RequestSymbolIndex(repo.ID, true); err != nil {
211		return c.fail(protocol.ExitFailure, "%v", err)
212	}
213	return c.emit(map[string]string{"repo": repo.Path(), "state": "queued"}, func(w io.Writer) {
214		fmt.Fprintf(w, "queued a rebuild of the symbol index of %s\n", repo.Path())
215	})
216}
217
218// definitionOut is one name a file uses and where it is defined: the
219// first definition, and Count of them. A client links a name defined once
220// to its line and one defined more often to repo symbols, as the blob page
221// does.
222type definitionOut struct {
223	Name  string `json:"name"`
224	Count int    `json:"count"`
225	Path  string `json:"path"`
226	Line  int    `json:"line"`
227}
228
229// identifier is a name as the index keys it. The blob page takes names
230// from the highlighter's spans; a command has no highlighter, so it takes
231// every identifier, and keywords fall out because nothing defines them.
232var identifier = regexp.MustCompile(`[\p{L}_$][\p{L}\p{N}_$]*`)
233
234// maxDefinitionNames bounds the lookup for one file.
235const maxDefinitionNames = 5000
236
237func runRepoDefinitions(c *Ctx, args []string) int {
238	f, err := c.parseArgs(args, flagSpec{Values: []string{"--ref"}, MaxPos: 2, Usage: c.Cmd.Usage})
239	if err != nil {
240		return c.fail(protocol.ExitUsage, "%v", err)
241	}
242	path, file, ref := f.pos(0), f.pos(1), f.Value("--ref")
243	if path == "" || file == "" {
244		return c.usage()
245	}
246	filePath, ok := cleanRepoPath(file)
247	if !ok || filePath == "" {
248		return c.fail(protocol.ExitUsage, "path must stay inside the repository")
249	}
250	repo, code := resolveRepo(c, path, policy.CanRead)
251	if code >= 0 {
252		return code
253	}
254	idx, err := c.Store.SymbolIndexFor(repo.ID)
255	if errors.Is(err, store.ErrNotFound) {
256		return c.fail(protocol.ExitNotFound, "%s has no symbol index yet; one is built after a push to %s", repo.Path(), repo.DefaultBranch)
257	} else if err != nil {
258		return c.fail(protocol.ExitFailure, "%v", err)
259	}
260	if ref == "" {
261		ref = repo.DefaultBranch
262	}
263	dir := RepoDir(c.Cfg.Server.Root, repo.OwnerName, repo.Name)
264	sha, err := gitutil.ResolveRef(dir, ref)
265	if err != nil || !IndexedTree(dir, sha, idx) {
266		return c.fail(protocol.ExitNotFound, "only the default branch, %s, is indexed; %s is not at the indexed tree", repo.DefaultBranch, ref)
267	}
268	data, err := gitutil.ReadBlob(dir, sha, filePath, c.Cfg.Limits.MaxBlobBytes)
269	if err != nil {
270		return c.fail(protocol.ExitNotFound, "no such file %q in %s at %s", filePath, repo.Path(), ref)
271	}
272	var keys []string
273	if !gitutil.IsBinary(data) {
274		seen := map[string]bool{}
275		for _, name := range identifier.FindAllString(string(data), -1) {
276			if !seen[name] && len(keys) < maxDefinitionNames {
277				seen[name] = true
278				keys = append(keys, name)
279			}
280		}
281	}
282	targets, err := c.Store.SymbolTargets(idx.ID, keys)
283	if err != nil {
284		return c.fail(protocol.ExitFailure, "%v", err)
285	}
286	ds := make([]definitionOut, 0, len(targets))
287	for name, t := range targets {
288		ds = append(ds, definitionOut{name, t.Count, t.Path, t.Line})
289	}
290	sort.Slice(ds, func(i, j int) bool { return ds[i].Name < ds[j].Name })
291	rowsOf := func() []row {
292		rows := make([]row, len(ds))
293		for i, d := range ds {
294			rows[i] = rowOf(cRef(d.Name), cText(strconv.Itoa(d.Count)), cFlex(fmt.Sprintf("%s:%d", d.Path, d.Line)))
295		}
296		return rows
297	}
298	return c.emitView(ds, func(w io.Writer) {
299		tb := c.table(w, "NAME", "DEFINED", "FIRST")
300		for _, d := range ds {
301			tb.row(cRef(d.Name), cText(strconv.Itoa(d.Count)), cFlex(fmt.Sprintf("%s:%d", d.Path, d.Line)))
302		}
303		tb.flush()
304	}, func() screen {
305		s := listScreen("Definitions used in "+filePath, rowsOf())
306		if len(ds) > 0 {
307			s.actions = []action{{"Find", []string{"repo", "symbols", repo.Path(), ds[0].Name}}}
308		}
309		return s
310	})
311}