internal/control/query.go

6521399c1c78577eb00f1bcf8947c0900b9cb62e
gitbay/internal/control/query.go

530 lines · 16497 bytes

  1package control
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"io"
  7	"regexp"
  8	"strconv"
  9	"strings"
 10
 11	"gitbay.org/gitbay/internal/protocol"
 12	"gitbay.org/gitbay/internal/store"
 13)
 14
 15func init() {
 16	register(Command{Path: []string{"query", "save"},
 17		Summary: "save an issue and merge request query across repositories under a name",
 18		Usage:   "query save <name> <query>... [--force]",
 19		Flags: []Flag{
 20			{"--force", "", "replace a query of the same name", ""},
 21		},
 22		Examples: []string{
 23			"query save mine is:open assignee:@me",
 24			`query save triage "repo:krz/*" is:issue is:open no:label`,
 25			`query save v2 owner:krz is:open label:bug label:"needs review" milestone:v2`,
 26			"query save mine-merged is:merged author:@me --force",
 27		},
 28		Run: runQuerySave})
 29	register(Command{Path: []string{"query", "list"},
 30		Summary:  "list your saved queries",
 31		Usage:    "query list",
 32		Examples: []string{"query list"},
 33		ReadOnly: true, Run: runQueryList})
 34	register(Command{Path: []string{"query", "show"},
 35		Summary:  "show a saved query and how many rows it matches",
 36		Usage:    "query show <name>",
 37		Examples: []string{"query show mine"},
 38		ReadOnly: true, Run: runQueryShow})
 39	register(Command{Path: []string{"query", "run"},
 40		Summary: "list the issues and merge requests a saved query matches",
 41		Usage:   "query run <name> [--limit <n>] [--cursor <c>]",
 42		Flags: []Flag{
 43			{"--limit", "<n>", "rows per page", strconv.Itoa(queryDefaultLimit)},
 44			{"--cursor", "<c>", "continue from the previous page", ""},
 45		},
 46		Examples: []string{"query run mine --limit 20"},
 47		ReadOnly: true, Run: runQueryRun})
 48	register(Command{Path: []string{"query", "remove"},
 49		Summary:  "delete a saved query",
 50		Usage:    "query remove <name>",
 51		Examples: []string{"query remove mine"},
 52		Run:      runQueryRemove})
 53	register(Command{Path: []string{"query", "pin"},
 54		Summary:  "show a saved query on your dashboard",
 55		Usage:    "query pin <name>",
 56		Examples: []string{"query pin mine"},
 57		Run:      func(c *Ctx, args []string) int { return runQueryPin(c, args, true) }})
 58	register(Command{Path: []string{"query", "unpin"},
 59		Summary:  "take a saved query off your dashboard",
 60		Usage:    "query unpin <name>",
 61		Examples: []string{"query unpin mine"},
 62		Run:      func(c *Ctx, args []string) int { return runQueryPin(c, args, false) }})
 63}
 64
 65// queryDefaultLimit is a page when --limit is not given. A query spans
 66// every repository the caller reads, so its listing is always paged.
 67const queryDefaultLimit = 50
 68
 69// dashboardQueryItems is how many rows of each pinned query the
 70// dashboard carries.
 71const dashboardQueryItems = 5
 72
 73// Every pinned query is run on each dashboard read, so an account keeps
 74// a bounded number of each.
 75const (
 76	maxSavedQueries  = 50
 77	maxPinnedQueries = 10
 78)
 79
 80var queryNamePat = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
 81
 82// SavedQueryOut is one saved query. Count is filled by query show.
 83type SavedQueryOut struct {
 84	Name   string `json:"name"`
 85	Query  string `json:"query"`
 86	Pinned bool   `json:"pinned"`
 87	Count  *int   `json:"count,omitempty"`
 88}
 89
 90// QueryItem is one row of a cross-repository listing, naming its
 91// repository.
 92type QueryItem struct {
 93	Kind      string `json:"kind"` // issue or mr
 94	Repo      string `json:"repo"`
 95	Number    int64  `json:"number"`
 96	Title     string `json:"title"`
 97	State     string `json:"state"`
 98	Draft     bool   `json:"draft,omitempty"`
 99	Author    string `json:"author"`
100	Milestone string `json:"milestone,omitempty"`
101	CreatedAt string `json:"created_at"`
102	UpdatedAt string `json:"updated_at"`
103}
104
105// Ref is the item as a person writes it: owner/name#n or owner/name!n.
106func (it QueryItem) Ref() string {
107	return fmt.Sprintf("%s%s%d", it.Repo, SearchMarker(it.Kind), it.Number)
108}
109
110// DashboardQuery is a pinned query on the dashboard: its first rows and
111// how many it matches in all. Error is set, and the rest empty, when the
112// saved text no longer parses.
113type DashboardQuery struct {
114	Name  string      `json:"name"`
115	Query string      `json:"query"`
116	Count int         `json:"count"`
117	Items []QueryItem `json:"items"`
118	Error string      `json:"error,omitempty"`
119}
120
121func queryItems(items []store.Item) []QueryItem {
122	out := make([]QueryItem, 0, len(items))
123	for _, it := range items {
124		out = append(out, QueryItem{Kind: it.Kind, Repo: it.RepoPath, Number: it.Number, Title: it.Title,
125			State: it.State, Draft: it.Draft, Author: it.Author, Milestone: it.Milestone,
126			CreatedAt: it.CreatedAt, UpdatedAt: it.UpdatedAt})
127	}
128	return out
129}
130
131// PinnedQueries runs each of user's pinned queries for the dashboard. It
132// is exported for the web dashboard, which reads the store directly.
133func PinnedQueries(st *store.Store, user store.User) ([]DashboardQuery, error) {
134	saved, err := st.SavedQueries(user.ID, true)
135	if err != nil {
136		return nil, err
137	}
138	out := []DashboardQuery{}
139	for _, sq := range saved {
140		d := DashboardQuery{Name: sq.Name, Query: sq.Query, Items: []QueryItem{}}
141		q, err := ParseItemQuery(sq.Query)
142		if err != nil {
143			d.Error = err.Error()
144			out = append(out, d)
145			continue
146		}
147		f := q.Filter(user.Username, true, true)
148		if d.Count, err = st.CountItems(user.ID, f); err != nil {
149			return nil, err
150		}
151		items, err := st.QueryItems(user.ID, f, nil, dashboardQueryItems)
152		if err != nil {
153			return nil, err
154		}
155		d.Items = queryItems(items)
156		out = append(out, d)
157	}
158	return out, nil
159}
160
161// RunAdHocQuery evaluates an unsaved cross-repository query for the web
162// queries page using the same parser, visibility filter, and cursor as query run.
163func RunAdHocQuery(st *store.Store, user store.User, rawQuery, cursor string, limit int) ([]QueryItem, int, string, error) {
164	q, err := ParseItemQuery(rawQuery)
165	if err != nil {
166		return nil, 0, "", err
167	}
168	var after *store.ItemCursor
169	if cursor != "" {
170		key, err := decodeCursor("query", cursor)
171		if err != nil {
172			return nil, 0, "", errors.New("bad cursor")
173		}
174		if after, err = decodeItemCursor(key); err != nil {
175			return nil, 0, "", err
176		}
177	}
178	if limit <= 0 {
179		limit = queryDefaultLimit
180	}
181	f := q.Filter(user.Username, true, true)
182	total, err := st.CountItems(user.ID, f)
183	if err != nil {
184		return nil, 0, "", err
185	}
186	items, err := st.QueryItems(user.ID, f, after, limit+1)
187	if err != nil {
188		return nil, 0, "", err
189	}
190	next := ""
191	if len(items) > limit {
192		items = items[:limit]
193		next = encodeItemCursor(items[len(items)-1].Cursor())
194	}
195	return queryItems(items), total, next, nil
196}
197
198func encodeItemCursor(k store.ItemCursor) string {
199	return encodeCursor("query", fmt.Sprintf("%s|%d|%d", k.CreatedAt, k.Kind, k.ID))
200}
201
202func decodeItemCursor(key string) (*store.ItemCursor, error) {
203	parts := strings.Split(key, "|")
204	if len(parts) != 3 {
205		return nil, errors.New("bad cursor")
206	}
207	kind, err1 := strconv.Atoi(parts[1])
208	id, err2 := strconv.ParseInt(parts[2], 10, 64)
209	if err1 != nil || err2 != nil || (kind != 0 && kind != 1) || parts[0] == "" {
210		return nil, errors.New("bad cursor")
211	}
212	return &store.ItemCursor{CreatedAt: parts[0], Kind: kind, ID: id}, nil
213}
214
215// savedQuery loads one of the caller's queries and parses it.
216func savedQuery(c *Ctx, name string) (store.SavedQuery, ItemQuery, int) {
217	sq, err := c.Store.SavedQueryByName(c.User.ID, name)
218	if errors.Is(err, store.ErrNotFound) {
219		return sq, ItemQuery{}, c.fail(protocol.ExitNotFound, "no saved query %q; query list shows yours", name)
220	}
221	if err != nil {
222		return sq, ItemQuery{}, c.fail(protocol.ExitFailure, "%v", err)
223	}
224	q, err := ParseItemQuery(sq.Query)
225	if err != nil {
226		return sq, q, c.fail(protocol.ExitFailure, "saved query %s no longer parses (%v); save it again with --force", name, err)
227	}
228	return sq, q, -1
229}
230
231// runItemQuery lists what q matches in the tables issues and mrs allow,
232// one page at a time. The output is always the paged shape.
233func runItemQuery(c *Ctx, q ItemQuery, issues, mrs bool, p page, title string) int {
234	var after *store.ItemCursor
235	if p.key != "" {
236		var err error
237		if after, err = decodeItemCursor(p.key); err != nil {
238			return c.fail(protocol.ExitUsage, "bad cursor")
239		}
240	}
241	if p.limit == 0 {
242		p.limit = queryDefaultLimit
243	}
244	p.active = true
245	items, err := c.Store.QueryItems(c.User.ID, q.Filter(c.User.Username, issues, mrs), after, p.queryLimit())
246	if err != nil {
247		return c.fail(protocol.ExitFailure, "%v", err)
248	}
249	next := ""
250	if len(items) > p.limit {
251		items = items[:p.limit]
252		next = encodeItemCursor(items[len(items)-1].Cursor())
253	}
254	ds := queryItems(items)
255	return c.emitPageView(p, ds, next, func(w io.Writer) {
256		tb := c.table(w, "REF", "STATE", "TITLE", "AUTHOR")
257		for _, d := range ds {
258			state := d.State
259			if d.Draft {
260				state = "draft"
261			}
262			tb.row(cRef(d.Ref()), cState(state), cFlex(d.Title), cText(d.Author))
263		}
264		tb.flush()
265	}, func() screen {
266		rows := make([]row, len(ds))
267		for i, d := range ds {
268			state := d.State
269			if d.Draft {
270				state = "draft"
271			}
272			page := "issues"
273			if d.Kind == "mr" {
274				page = "mrs"
275			}
276			rows[i] = rowOf(cLink(d.Ref(), c.siteURL(d.Repo, page, strconv.FormatInt(d.Number, 10))), cGlyph(state), cFlex(d.Title),
277				cMeta(d.Author, d.Milestone, relAge(d.UpdatedAt, termNow())))
278		}
279		s := listScreen(title, rows)
280		if len(ds) > 0 {
281			s.actions = []action{{"Read", []string{ds[0].Kind, "show", ds[0].Repo, strconv.FormatInt(ds[0].Number, 10)}}}
282		}
283		return s
284	})
285}
286
287// usesQuery reports whether issue list or mr list was given a query,
288// which changes the cursor they page with.
289func usesQuery(args []string) bool {
290	for _, a := range args {
291		if a == "--query" || a == "--q" {
292			return true
293		}
294	}
295	return false
296}
297
298// listByQuery is issue list and mr list given --query or --q: the query
299// spans repositories, so it takes none as an argument and no other
300// filter flag. kind is the command's noun.
301func listByQuery(c *Ctx, fl flags, kind string, p page) int {
302	if fl.Has("--query") && fl.Has("--q") {
303		return c.usageWith("--query and --q are two ways to give one query; pass one")
304	}
305	if len(fl.Pos) > 0 {
306		return c.usageWith("a query spans repositories; name them in it (repo:" + fl.Pos[0] + ") rather than as an argument")
307	}
308	for _, f := range []string{"--state", "--label", "--assignee", "--author", "--milestone", "--search"} {
309		if fl.Has(f) {
310			return c.usageWith(f + " does not combine with a query; put it in the query")
311		}
312	}
313	var q ItemQuery
314	if fl.Has("--query") {
315		var code int
316		if _, q, code = savedQuery(c, fl.Value("--query")); code >= 0 {
317			return code
318		}
319	} else {
320		var err error
321		if q, err = ParseItemQuery(fl.Value("--q")); err != nil {
322			return c.fail(protocol.ExitUsage, "%v", err)
323		}
324	}
325	issues, mrs := q.Selects()
326	if kind == "issue" && !issues {
327		return c.usageWith("that query matches only merge requests; use mr list or query run")
328	}
329	if kind == "mr" && !mrs {
330		return c.usageWith("that query matches only issues; use issue list or query run")
331	}
332	return runItemQuery(c, q, kind == "issue", kind == "mr", p, "Results")
333}
334
335func savedQueryOut(sq store.SavedQuery) SavedQueryOut {
336	return SavedQueryOut{Name: sq.Name, Query: sq.Query, Pinned: sq.Pinned}
337}
338
339func runQuerySave(c *Ctx, args []string) int {
340	fl, err := c.parseArgs(args, flagSpec{Bools: []string{"--force"}, MaxPos: -1, Usage: c.Cmd.Usage})
341	if err != nil {
342		return c.fail(protocol.ExitUsage, "%v", err)
343	}
344	if len(fl.Pos) < 2 {
345		return c.usage()
346	}
347	name := fl.Pos[0]
348	if !queryNamePat.MatchString(name) {
349		return c.fail(protocol.ExitUsage, "invalid query name %q: lowercase letters, digits, '.', '-', '_'; must start with a letter or digit; max 64 chars", name)
350	}
351	q, err := ParseItemQuery(fl.Pos[1:]...)
352	if err != nil {
353		return c.fail(protocol.ExitUsage, "%v", err)
354	}
355	if _, err := c.Store.SavedQueryByName(c.User.ID, name); errors.Is(err, store.ErrNotFound) {
356		saved, _, err := c.Store.CountSavedQueries(c.User.ID)
357		if err != nil {
358			return c.fail(protocol.ExitFailure, "%v", err)
359		}
360		if saved >= maxSavedQueries {
361			return c.fail(protocol.ExitUsage, "saved query limit reached (%d); remove one first", maxSavedQueries)
362		}
363	} else if err != nil {
364		return c.fail(protocol.ExitFailure, "%v", err)
365	}
366	err = c.Store.SaveQuery(c.User.ID, name, q.String(), fl.Has("--force"))
367	if errors.Is(err, store.ErrExists) {
368		return c.fail(protocol.ExitFailure, "you already have a query named %s; pass --force to replace it", name)
369	}
370	if err != nil {
371		return c.fail(protocol.ExitFailure, "%v", err)
372	}
373	sq, err := c.Store.SavedQueryByName(c.User.ID, name)
374	if err != nil {
375		return c.fail(protocol.ExitFailure, "%v", err)
376	}
377	return c.emit(savedQueryOut(sq), func(w io.Writer) {
378		fmt.Fprintf(w, "saved %s: %s\n", sq.Name, sq.Query)
379	})
380}
381
382func runQueryList(c *Ctx, args []string) int {
383	if len(args) != 0 {
384		return c.usage()
385	}
386	saved, err := c.Store.SavedQueries(c.User.ID, false)
387	if err != nil {
388		return c.fail(protocol.ExitFailure, "%v", err)
389	}
390	ds := []SavedQueryOut{}
391	for _, sq := range saved {
392		ds = append(ds, savedQueryOut(sq))
393	}
394	return c.emitView(ds, func(w io.Writer) {
395		tb := c.table(w, "NAME", "PINNED", "QUERY")
396		for _, d := range ds {
397			pinned := ""
398			if d.Pinned {
399				pinned = "pinned"
400			}
401			tb.row(cRef(d.Name), cText(pinned), cFlex(d.Query))
402		}
403		tb.flush()
404	}, func() screen {
405		rows := make([]row, len(ds))
406		for i, d := range ds {
407			pinned := ""
408			if d.Pinned {
409				pinned = "pinned"
410			}
411			rows[i] = rowOf(cRef(d.Name), cFlex(d.Query), cMeta(pinned))
412		}
413		s := listScreen("Saved queries", rows)
414		if len(ds) > 0 {
415			s.actions = []action{
416				{"Queries", []string{"query", "run", ds[0].Name}},
417				{"Queries", []string{"query", "pin", ds[0].Name}},
418			}
419		}
420		return s
421	})
422}
423
424func runQueryShow(c *Ctx, args []string) int {
425	if len(args) != 1 {
426		return c.usage()
427	}
428	sq, q, code := savedQuery(c, args[0])
429	if code >= 0 {
430		return code
431	}
432	n, err := c.Store.CountItems(c.User.ID, q.Filter(c.User.Username, true, true))
433	if err != nil {
434		return c.fail(protocol.ExitFailure, "%v", err)
435	}
436	d := savedQueryOut(sq)
437	d.Count = &n
438	return c.emitView(d, func(w io.Writer) {
439		v := c.view(w)
440		v.title(d.Name, "", "")
441		pinned := "no"
442		if d.Pinned {
443			pinned = "yes"
444		}
445		v.fields("query", d.Query, "matches", strconv.Itoa(n), "pinned", pinned)
446	}, func() screen {
447		pin, pinned := "pin", "no"
448		if d.Pinned {
449			pin, pinned = "unpin", "yes"
450		}
451		return screen{fields: []field{
452			{"Query", []cell{cRef(d.Name), cText(d.Query)}},
453			{"Matches", []cell{cText(strconv.Itoa(n))}},
454			{"Pinned", []cell{cText(pinned)}},
455		}, actions: []action{
456			{"Queries", []string{"query", "run", d.Name}},
457			{"Queries", []string{"query", pin, d.Name}},
458		}}
459	})
460}
461
462func runQueryRun(c *Ctx, args []string) int {
463	rest, p, code := parsePageFlags(c, args, "query", false)
464	if code >= 0 {
465		return code
466	}
467	if len(rest) != 1 {
468		return c.usage()
469	}
470	_, q, code := savedQuery(c, rest[0])
471	if code >= 0 {
472		return code
473	}
474	return runItemQuery(c, q, true, true, p, rest[0])
475}
476
477func runQueryRemove(c *Ctx, args []string) int {
478	if len(args) != 1 {
479		return c.usage()
480	}
481	err := c.Store.RemoveSavedQuery(c.User.ID, args[0])
482	if errors.Is(err, store.ErrNotFound) {
483		return c.fail(protocol.ExitNotFound, "no saved query %q; query list shows yours", args[0])
484	}
485	if err != nil {
486		return c.fail(protocol.ExitFailure, "%v", err)
487	}
488	return c.emit(map[string]string{"removed": args[0]}, func(w io.Writer) {
489		fmt.Fprintf(w, "removed %s\n", args[0])
490	})
491}
492
493func runQueryPin(c *Ctx, args []string, pinned bool) int {
494	if len(args) != 1 {
495		return c.usage()
496	}
497	sq, err := c.Store.SavedQueryByName(c.User.ID, args[0])
498	if errors.Is(err, store.ErrNotFound) {
499		return c.fail(protocol.ExitNotFound, "no saved query %q; query list shows yours", args[0])
500	}
501	if err != nil {
502		return c.fail(protocol.ExitFailure, "%v", err)
503	}
504	if pinned && !sq.Pinned {
505		_, n, err := c.Store.CountSavedQueries(c.User.ID)
506		if err != nil {
507			return c.fail(protocol.ExitFailure, "%v", err)
508		}
509		if n >= maxPinnedQueries {
510			return c.fail(protocol.ExitUsage, "pinned query limit reached (%d); unpin one first", maxPinnedQueries)
511		}
512	}
513	err = c.Store.PinSavedQuery(c.User.ID, args[0], pinned)
514	if errors.Is(err, store.ErrNotFound) {
515		return c.fail(protocol.ExitNotFound, "no saved query %q; query list shows yours", args[0])
516	}
517	if err != nil {
518		return c.fail(protocol.ExitFailure, "%v", err)
519	}
520	if sq, err = c.Store.SavedQueryByName(c.User.ID, args[0]); err != nil {
521		return c.fail(protocol.ExitFailure, "%v", err)
522	}
523	return c.emit(savedQueryOut(sq), func(w io.Writer) {
524		verb := "unpinned"
525		if pinned {
526			verb = "pinned"
527		}
528		fmt.Fprintf(w, "%s %s\n", verb, sq.Name)
529	})
530}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form