internal/control/query.go

ac8d910ff31c2fadc452928e1d56c64b4af25495
gitbay/internal/control/query.go

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