internal/httpd/searchweb.go

6521399c1c78577eb00f1bcf8947c0900b9cb62e
gitbay/internal/httpd/searchweb.go

189 lines · 5481 bytes

  1package httpd
  2
  3import (
  4	"encoding/json"
  5	"net/http"
  6	"strconv"
  7	"strings"
  8
  9	"gitbay.org/gitbay/internal/control"
 10	"gitbay.org/gitbay/internal/gitutil"
 11	"gitbay.org/gitbay/internal/policy"
 12	"gitbay.org/gitbay/internal/store"
 13)
 14
 15// searchResult is one hit as the template renders it: the link is built
 16// here so the template does not have to know each kind's URL shape.
 17type searchResult struct {
 18	control.SearchResult
 19	Marker string
 20	Href   string
 21}
 22
 23type paletteEntry struct {
 24	Group string `json:"group"`
 25	Label string `json:"label"`
 26	Href  string `json:"href"`
 27}
 28
 29// globalSearch is /search: repositories, issues and merge requests across
 30// the instance. It is readable without a session — a visitor sees exactly
 31// the public rows — so it runs control.Search directly rather than
 32// dispatching a command as a user who may not exist.
 33func (s *Server) globalSearch(w http.ResponseWriter, r *http.Request) {
 34	var viewer store.User
 35	if s.cfg.Web.Mode == "accounts" {
 36		viewer = s.viewer(r)
 37	}
 38	if r.URL.Query().Get("format") == "palette" {
 39		s.servePalette(w, r, viewer)
 40		return
 41	}
 42	q := strings.TrimSpace(r.URL.Query().Get("q"))
 43	kind := r.URL.Query().Get("kind")
 44	if kind != "repo" && kind != "issue" && kind != "mr" {
 45		kind = ""
 46	}
 47	var kinds []string
 48	if kind != "" {
 49		kinds = []string{kind}
 50	}
 51	var results []searchResult
 52	var queryErr string
 53	if q != "" {
 54		if len(q) < 2 || len(q) > 200 {
 55			queryErr = "query must be 2 to 200 characters"
 56		} else {
 57			hits, err := control.Search(s.st, s.cfg.Server.Root, viewer.ID, q, kinds)
 58			if err != nil {
 59				http.Error(w, "internal error", http.StatusInternalServerError)
 60				return
 61			}
 62			for _, h := range hits {
 63				results = append(results, searchResult{h, control.SearchMarker(h.Kind), searchHref(h)})
 64			}
 65		}
 66	}
 67	s.render(w, "globalsearch.html", struct {
 68		basePage
 69		Tab      string
 70		Query    string
 71		Kind     string
 72		QueryErr string
 73		Results  []searchResult
 74	}{s.baseFor(viewer), "sitesearch", q, kind, queryErr, results})
 75}
 76
 77func searchHref(h control.SearchResult) string {
 78	switch h.Kind {
 79	case "issue":
 80		return "/" + h.Repo + "/issues/" + strconv.FormatInt(h.Number, 10)
 81	case "mr":
 82		return "/" + h.Repo + "/mrs/" + strconv.FormatInt(h.Number, 10)
 83	default:
 84		return "/" + h.Repo
 85	}
 86}
 87
 88// servePalette answers Cmd+K / 't' jump queries with files, symbols, issues,
 89// merge requests, and repositories the viewer can read.
 90func (s *Server) servePalette(w http.ResponseWriter, r *http.Request, viewer store.User) {
 91	q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q")))
 92	repoPath := strings.TrimSpace(r.URL.Query().Get("repo"))
 93	var items []paletteEntry
 94
 95	if repoPath != "" {
 96		if repo, err := s.st.RepoByPath(repoPath); err == nil {
 97			grant := ""
 98			if viewer.ID != 0 {
 99				grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
100			}
101			if policy.CanRead(viewer, repo, grant) {
102				dir := control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)
103				ref := strings.TrimSpace(r.URL.Query().Get("ref"))
104				if ref == "" {
105					ref = repo.DefaultBranch
106				}
107				if entries, err := gitutil.ListTreeRecursive(dir, ref, ""); err == nil {
108					count := 0
109					for _, e := range entries {
110						if e.Type != "blob" {
111							continue
112						}
113						if q != "" && !strings.Contains(strings.ToLower(e.Name), q) {
114							continue
115						}
116						items = append(items, paletteEntry{
117							Group: "File",
118							Label: e.Name,
119							Href:  "/" + repo.Path() + "/blob/" + ref + "/" + e.Name,
120						})
121						count++
122						if count >= 40 {
123							break
124						}
125					}
126				}
127				if mrs, err := s.st.QueryMRs(repo.ID, store.MRFilter{State: "open", Limit: 15}); err == nil {
128					for _, m := range mrs {
129						lbl := "!" + strconv.FormatInt(m.Number, 10) + " " + m.Title
130						if q == "" || strings.Contains(strings.ToLower(lbl), q) {
131							items = append(items, paletteEntry{
132								Group: "MR",
133								Label: lbl,
134								Href:  "/" + repo.Path() + "/mrs/" + strconv.FormatInt(m.Number, 10),
135							})
136						}
137					}
138				}
139				if issues, err := s.st.QueryIssues(repo.ID, store.IssueFilter{State: "open", Limit: 15}); err == nil {
140					for _, iss := range issues {
141						lbl := "#" + strconv.FormatInt(iss.Number, 10) + " " + iss.Title
142						if q == "" || strings.Contains(strings.ToLower(lbl), q) {
143							items = append(items, paletteEntry{
144								Group: "Issue",
145								Label: lbl,
146								Href:  "/" + repo.Path() + "/issues/" + strconv.FormatInt(iss.Number, 10),
147							})
148						}
149					}
150				}
151			}
152		}
153	}
154
155	if len(q) >= 2 && len(q) <= 100 {
156		if hits, err := control.Search(s.st, s.cfg.Server.Root, viewer.ID, q, nil); err == nil {
157			for i, h := range hits {
158				if i >= 20 {
159					break
160				}
161				lbl := h.Repo
162				grp := "Repo"
163				if h.Number > 0 {
164					lbl = h.Repo + control.SearchMarker(h.Kind) + strconv.FormatInt(h.Number, 10) + " " + h.Title
165					if h.Kind == "mr" {
166						grp = "MR"
167					} else {
168						grp = "Issue"
169					}
170				}
171				items = append(items, paletteEntry{Group: grp, Label: lbl, Href: searchHref(h)})
172			}
173		}
174	} else if repoPath == "" {
175		if repos, err := s.st.ListPublicReposByActivity(); err == nil {
176			for i, rp := range repos {
177				if i >= 15 {
178					break
179				}
180				if q == "" || strings.Contains(strings.ToLower(rp.Path()), q) {
181					items = append(items, paletteEntry{Group: "Repo", Label: rp.Path(), Href: "/" + rp.Path()})
182				}
183			}
184		}
185	}
186
187	w.Header().Set("Content-Type", "application/json; charset=utf-8")
188	json.NewEncoder(w).Encode(map[string]any{"items": items})
189}
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