internal/httpd/web.go

26b59e4e1845ca161d394403e2ef262040feebab
gitbay/internal/httpd/web.go history · blame · raw

808 lines · 22108 bytes

  1package httpd
  2
  3import (
  4	"bytes"
  5	"fmt"
  6
  7	"gitbay.org/gitbay/internal/policy"
  8	"html/template"
  9	"net/http"
 10	"path"
 11	"regexp"
 12	"strconv"
 13	"strings"
 14	"time"
 15
 16	"github.com/alecthomas/chroma/v2/formatters/html"
 17	"github.com/alecthomas/chroma/v2/lexers"
 18	"github.com/alecthomas/chroma/v2/styles"
 19	"github.com/microcosm-cc/bluemonday"
 20	"github.com/niklasfasching/go-org/org"
 21	"github.com/yuin/goldmark"
 22
 23	"gitbay.org/gitbay/internal/control"
 24	"gitbay.org/gitbay/internal/gitutil"
 25	"gitbay.org/gitbay/internal/sig"
 26	"gitbay.org/gitbay/internal/store"
 27	"gitbay.org/gitbay/internal/web"
 28)
 29
 30const maxRenderBytes = 1 << 20 // largest blob rendered inline
 31
 32func (s *Server) render(w http.ResponseWriter, page string, data any) {
 33	var buf bytes.Buffer
 34	if err := web.Render(&buf, page, data); err != nil {
 35		http.Error(w, "template error: "+err.Error(), http.StatusInternalServerError)
 36		return
 37	}
 38	w.Header().Set("Content-Type", "text/html; charset=utf-8")
 39	buf.WriteTo(w)
 40}
 41
 42func (s *Server) siteName() string {
 43	h := strings.TrimPrefix(strings.TrimPrefix(s.cfg.Server.SiteURL, "https://"), "http://")
 44	return strings.TrimSuffix(h, "/")
 45}
 46
 47func (s *Server) stylesheet(w http.ResponseWriter, r *http.Request) {
 48	w.Header().Set("Content-Type", "text/css; charset=utf-8")
 49	w.Write(web.StyleCSS)
 50}
 51
 52func (s *Server) favicon(w http.ResponseWriter, r *http.Request) {
 53	w.Header().Set("Content-Type", "image/svg+xml")
 54	w.Write(web.FaviconSVG)
 55}
 56
 57// describedRepo pairs a repo with its description for listings.
 58type describedRepo struct {
 59	store.Repo
 60	Desc string
 61}
 62
 63func (s *Server) describeAll(repos []store.Repo) []describedRepo {
 64	var out []describedRepo
 65	for _, r := range repos {
 66		out = append(out, describedRepo{r, gitutil.ReadDescription(control.RepoDir(s.cfg.Server.Root, r.OwnerName, r.Name))})
 67	}
 68	return out
 69}
 70
 71func (s *Server) index(w http.ResponseWriter, r *http.Request) {
 72	repos, err := s.st.ListPublicRepos()
 73	if err != nil {
 74		http.Error(w, "internal error", http.StatusInternalServerError)
 75		return
 76	}
 77	var viewer store.User
 78	var mine []store.Repo
 79	if s.cfg.Web.Mode == "accounts" {
 80		if viewer = s.viewer(r); viewer.ID != 0 {
 81			all, err := s.st.ListReposForUser(viewer.ID)
 82			if err == nil {
 83				for _, rp := range all {
 84					if rp.Visibility == "private" {
 85						mine = append(mine, rp)
 86					}
 87				}
 88			}
 89		}
 90	}
 91	s.render(w, "index.html", struct {
 92		Site   string
 93		Viewer string
 94		Repos  []describedRepo
 95		Mine   []describedRepo
 96	}{s.siteName(), viewer.Username, s.describeAll(repos), s.describeAll(mine)})
 97}
 98
 99// repoPage is the shared context for repo-scoped pages.
100type repoPage struct {
101	Site     string
102	Viewer   string
103	Desc     string
104	Repo     store.Repo
105	Ref      string
106	CloneURL string
107	Dir      string
108	Tab      string // active tab in the repo header
109}
110
111// repoFor resolves the repo for a web request; false means 404 was sent.
112// Anonymous visitors see public repos only; in accounts mode a logged-in
113// viewer additionally sees repos their grants allow. Private and missing
114// repos are indistinguishable either way.
115func (s *Server) repoFor(w http.ResponseWriter, r *http.Request, ref string) (repoPage, bool) {
116	var repo store.Repo
117	var viewer store.User
118	if s.cfg.Web.Mode == "accounts" {
119		viewer = s.viewer(r)
120	}
121	repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
122	ok := err == nil
123	if ok {
124		grant := ""
125		if viewer.ID != 0 {
126			grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
127		}
128		ok = policyCanRead(viewer, repo, grant)
129	}
130	if !ok {
131		http.NotFound(w, r)
132		return repoPage{}, false
133	}
134	if ref == "" {
135		ref = repo.DefaultBranch
136	}
137	return repoPage{
138		Site:     s.siteName(),
139		Viewer:   viewer.Username,
140		Desc:     gitutil.ReadDescription(control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)),
141		Repo:     repo,
142		Ref:      ref,
143		CloneURL: s.cfg.Server.SiteURL + "/" + repo.Path() + ".git",
144		Dir:      control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name),
145	}, true
146}
147
148type crumb struct {
149	Name string
150	URL  string
151}
152
153func crumbs(p repoPage, kind, filePath string) []crumb {
154	var cs []crumb
155	base := "/" + p.Repo.Path() + "/" + kind + "/" + p.Ref + "/"
156	acc := ""
157	for _, part := range strings.Split(filePath, "/") {
158		if part == "" {
159			continue
160		}
161		acc = path.Join(acc, part)
162		cs = append(cs, crumb{Name: part, URL: base + acc})
163	}
164	return cs
165}
166
167// ownerPage renders /{owner} for users and orgs: the repositories the
168// viewer may see, org membership either direction. Owner names are not
169// secret (they are on every commit); repository visibility rules hold.
170func (s *Server) ownerPage(w http.ResponseWriter, r *http.Request) {
171	name := r.PathValue("owner")
172	var viewer store.User
173	if s.cfg.Web.Mode == "accounts" {
174		viewer = s.viewer(r)
175	}
176
177	kind := "user"
178	var ownerID int64
179	var members []store.OrgMember
180	var orgs []store.OrgMember
181	if u, err := s.st.UserByUsername(name); err == nil {
182		ownerID = u.ID
183		orgs, _ = s.st.ListOrgsForUser(u.ID)
184	} else if o, err := s.st.OrgByName(name); err == nil {
185		kind, ownerID = "org", o.ID
186		members, _ = s.st.OrgMembers(o.ID)
187	} else {
188		http.NotFound(w, r)
189		return
190	}
191	profile, _ := s.st.OwnerProfile(kind, ownerID)
192
193	all, err := s.st.ListReposForOwner(kind, ownerID)
194	if err != nil {
195		http.Error(w, "internal error", http.StatusInternalServerError)
196		return
197	}
198	var visible []store.Repo
199	for _, repo := range all {
200		grant := ""
201		if viewer.ID != 0 {
202			grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
203		}
204		if policy.CanRead(viewer, repo, grant) {
205			visible = append(visible, repo)
206		}
207	}
208	s.render(w, "owner.html", struct {
209		Site    string
210		Viewer  string
211		Owner   string
212		Kind    string
213		Profile store.Profile
214		Repos   []describedRepo
215		Members []store.OrgMember
216		Orgs    []store.OrgMember
217	}{s.siteName(), viewer.Username, name, kind, profile, s.describeAll(visible), members, orgs})
218}
219
220func (s *Server) repoHome(w http.ResponseWriter, r *http.Request) {
221	p, ok := s.repoFor(w, r, "")
222	if !ok {
223		return
224	}
225	p.Tab = "files"
226	s.renderTree(w, r, p, "")
227}
228
229func (s *Server) tree(w http.ResponseWriter, r *http.Request) {
230	p, ok := s.repoFor(w, r, r.PathValue("ref"))
231	if !ok {
232		return
233	}
234	p.Tab = "files"
235	s.renderTree(w, r, p, strings.Trim(r.PathValue("path"), "/"))
236}
237
238func (s *Server) renderTree(w http.ResponseWriter, r *http.Request, p repoPage, dirPath string) {
239	if _, err := gitutil.ResolveRef(p.Dir, p.Ref); err != nil {
240		// Empty repo: render the page with no entries rather than 404.
241		s.render(w, "tree.html", struct {
242			repoPage
243			Crumbs     []crumb
244			Prefix     string
245			Entries    []gitutil.TreeEntry
246			ReadmeHTML template.HTML
247		}{repoPage: p})
248		return
249	}
250	entries, err := gitutil.ListTree(p.Dir, p.Ref, dirPath)
251	if err != nil {
252		http.NotFound(w, r)
253		return
254	}
255	prefix := ""
256	if dirPath != "" {
257		prefix = dirPath + "/"
258	}
259
260	var readmeHTML template.HTML
261	if name := pickReadme(entries); name != "" {
262		if raw, err := gitutil.ReadBlob(p.Dir, p.Ref, prefix+name, maxRenderBytes); err == nil {
263			readmeHTML = renderReadme(name, raw)
264		}
265	}
266
267	s.render(w, "tree.html", struct {
268		repoPage
269		Crumbs     []crumb
270		Prefix     string
271		Entries    []gitutil.TreeEntry
272		ReadmeHTML template.HTML
273	}{p, crumbs(p, "tree", dirPath), prefix, entries, readmeHTML})
274}
275
276func (s *Server) blob(w http.ResponseWriter, r *http.Request) {
277	p, ok := s.repoFor(w, r, r.PathValue("ref"))
278	if !ok {
279		return
280	}
281	p.Tab = "files"
282	filePath := strings.Trim(r.PathValue("path"), "/")
283	data, err := gitutil.ReadBlob(p.Dir, p.Ref, filePath, maxRenderBytes+1)
284	if err != nil {
285		http.NotFound(w, r)
286		return
287	}
288	binary := gitutil.IsBinary(data) || len(data) > maxRenderBytes
289
290	var codeHTML template.HTML
291	if !binary {
292		codeHTML = highlight(filePath, data)
293	}
294	cs := crumbs(p, "blob", filePath)
295	base := ""
296	if len(cs) > 0 {
297		base = cs[len(cs)-1].Name
298		cs = cs[:len(cs)-1]
299	}
300	s.render(w, "blob.html", struct {
301		repoPage
302		Crumbs   []crumb
303		Base     string
304		Path     string
305		Binary   bool
306		Size     int
307		CodeHTML template.HTML
308	}{p, cs, base, filePath, binary, len(data), codeHTML})
309}
310
311func highlight(filePath string, data []byte) template.HTML {
312	lexer := lexers.Match(filePath)
313	if lexer == nil {
314		lexer = lexers.Fallback
315	}
316	style := styles.Get("friendly")
317	formatter := html.New(html.WithLineNumbers(true), html.LineNumbersInTable(false))
318	iterator, err := lexer.Tokenise(nil, string(data))
319	if err != nil {
320		return template.HTML("<pre>" + template.HTMLEscapeString(string(data)) + "</pre>")
321	}
322	var buf bytes.Buffer
323	if err := formatter.Format(&buf, style, iterator); err != nil {
324		return template.HTML("<pre>" + template.HTMLEscapeString(string(data)) + "</pre>")
325	}
326	return template.HTML(buf.String())
327}
328
329func (s *Server) raw(w http.ResponseWriter, r *http.Request) {
330	p, ok := s.repoFor(w, r, r.PathValue("ref"))
331	if !ok {
332		return
333	}
334	filePath := strings.Trim(r.PathValue("path"), "/")
335	data, err := gitutil.ReadBlob(p.Dir, p.Ref, filePath, s.cfg.Limits.MaxBlobBytes)
336	if err != nil {
337		http.NotFound(w, r)
338		return
339	}
340	// Serve inert: never let repo content execute in the forge's origin.
341	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
342	w.Header().Set("X-Content-Type-Options", "nosniff")
343	w.Write(data)
344}
345
346// readmeRank orders competing README files: richer renderers win.
347var readmeRank = map[string]int{".md": 1, ".markdown": 1, ".org": 2, ".html": 3, ".htm": 3}
348
349// pickReadme returns the best README-ish blob in a tree listing: any file
350// named "readme" or "readme.<ext>" (case-insensitive), preferring formats
351// we can render richly.
352func pickReadme(entries []gitutil.TreeEntry) string {
353	best, bestRank := "", 1<<30
354	for _, e := range entries {
355		if e.Type != "blob" {
356			continue
357		}
358		lower := strings.ToLower(e.Name)
359		if lower != "readme" && !strings.HasPrefix(lower, "readme.") {
360			continue
361		}
362		rank, ok := readmeRank[path.Ext(lower)]
363		if !ok {
364			rank = 10 // plaintext fallback
365		}
366		if rank < bestRank {
367			best, bestRank = e.Name, rank
368		}
369	}
370	return best
371}
372
373// mdHTML renders user-authored markdown (issue and MR bodies, comments).
374// goldmark's default renderer drops raw HTML, so this is safe as-is.
375func mdHTML(raw string) template.HTML {
376	if strings.TrimSpace(raw) == "" {
377		return ""
378	}
379	var buf bytes.Buffer
380	if goldmark.Convert([]byte(raw), &buf) != nil {
381		return template.HTML("<pre>" + template.HTMLEscapeString(raw) + "</pre>")
382	}
383	return template.HTML(buf.String())
384}
385
386// renderedComment pairs a comment with its rendered body for templates.
387type renderedComment struct {
388	Author    string
389	CreatedAt string
390	BodyHTML  template.HTML
391}
392
393func renderComments(cs []store.IssueComment) []renderedComment {
394	var out []renderedComment
395	for _, c := range cs {
396		out = append(out, renderedComment{c.Author, c.CreatedAt, mdHTML(c.Body)})
397	}
398	return out
399}
400
401// ugcPolicy sanitizes rendered repo content before it enters the forge's
402// origin: markdown is already safe (goldmark drops raw HTML), but org-mode
403// output and repo-authored HTML are not.
404var ugcPolicy = bluemonday.UGCPolicy()
405
406// renderReadme renders a README by extension: markdown, org-mode, and
407// (sanitized) HTML richly; everything else as escaped plaintext.
408func renderReadme(name string, raw []byte) template.HTML {
409	plain := func() template.HTML {
410		return template.HTML("<pre>" + template.HTMLEscapeString(string(raw)) + "</pre>")
411	}
412	if gitutil.IsBinary(raw) {
413		return ""
414	}
415	switch path.Ext(strings.ToLower(name)) {
416	case ".md", ".markdown":
417		var buf bytes.Buffer
418		if goldmark.Convert(raw, &buf) != nil {
419			return plain()
420		}
421		return template.HTML(buf.String())
422	case ".org":
423		doc := org.New().Parse(bytes.NewReader(raw), name)
424		html, err := doc.Write(org.NewHTMLWriter())
425		if err != nil {
426			return plain()
427		}
428		return template.HTML(ugcPolicy.Sanitize(html))
429	case ".html", ".htm":
430		return template.HTML(ugcPolicy.Sanitize(string(raw)))
431	default:
432		return plain()
433	}
434}
435
436type diffLine struct {
437	Class   string
438	Text    string
439	Path    string // file this line belongs to
440	NewLine int64  // line number in the new file (0 when absent)
441	OldLine int64  // line number in the old file (0 when absent)
442	Threads []diffThread
443}
444
445var hunkPat = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@`)
446
447// classifyDiff parses a unified diff into rendered lines, tracking the
448// file and old/new line numbers so review threads can anchor inline.
449func classifyDiff(patch string) []diffLine {
450	var lines []diffLine
451	path := ""
452	var oldN, newN int64
453	for _, l := range strings.Split(patch, "\n") {
454		d := diffLine{Text: l}
455		switch {
456		case strings.HasPrefix(l, "+++ "):
457			d.Class = "meta"
458			path = strings.TrimPrefix(strings.TrimPrefix(l, "+++ "), "b/")
459		case strings.HasPrefix(l, "--- "), strings.HasPrefix(l, "diff "), strings.HasPrefix(l, "index "):
460			d.Class = "meta"
461		case strings.HasPrefix(l, "@@"):
462			d.Class = "hunk"
463			if m := hunkPat.FindStringSubmatch(l); m != nil {
464				oldN, _ = strconv.ParseInt(m[1], 10, 64)
465				newN, _ = strconv.ParseInt(m[2], 10, 64)
466			}
467		case strings.HasPrefix(l, "+"):
468			d.Class, d.Path, d.NewLine = "add", path, newN
469			newN++
470		case strings.HasPrefix(l, "-"):
471			d.Class, d.Path, d.OldLine = "del", path, oldN
472			oldN++
473		default:
474			d.Path, d.OldLine, d.NewLine = path, oldN, newN
475			oldN++
476			newN++
477		}
478		lines = append(lines, d)
479	}
480	return lines
481}
482
483type diffThread struct {
484	ID       int64
485	Resolved string
486	Stale    bool
487	Comments []renderedComment
488}
489
490// attachThreads injects review threads under their anchored diff lines;
491// threads whose anchor no longer appears (stale after force-push, or on a
492// context line outside the current diff) are returned separately.
493func attachThreads(lines []diffLine, comments []store.DiffComment, headSHA string) ([]diffLine, []diffThread) {
494	type anchor struct {
495		path string
496		side string
497		line int64
498	}
499	threads := map[int64]*diffThread{}
500	anchors := map[int64]anchor{}
501	var order []int64
502	for _, cm := range comments {
503		if cm.ReplyTo == 0 {
504			threads[cm.ID] = &diffThread{ID: cm.ID, Resolved: cm.ResolvedBy, Stale: cm.HeadSHA != headSHA,
505				Comments: []renderedComment{{cm.Author, cm.CreatedAt, mdHTML(cm.Body)}}}
506			anchors[cm.ID] = anchor{cm.Path, cm.Side, cm.Line}
507			order = append(order, cm.ID)
508		} else if th, ok := threads[cm.ReplyTo]; ok {
509			th.Comments = append(th.Comments, renderedComment{cm.Author, cm.CreatedAt, mdHTML(cm.Body)})
510		}
511	}
512	placed := map[int64]bool{}
513	for i := range lines {
514		for _, id := range order {
515			if placed[id] || threads[id].Stale {
516				continue
517			}
518			a := anchors[id]
519			if lines[i].Path != a.path {
520				continue
521			}
522			if (a.side == "new" && lines[i].NewLine == a.line && lines[i].Class != "del") ||
523				(a.side == "old" && lines[i].OldLine == a.line && lines[i].Class == "del") {
524				lines[i].Threads = append(lines[i].Threads, *threads[id])
525				placed[id] = true
526			}
527		}
528	}
529	var unplaced []diffThread
530	for _, id := range order {
531		if !placed[id] {
532			unplaced = append(unplaced, *threads[id])
533		}
534	}
535	return lines, unplaced
536}
537
538type sigView struct {
539	State       string
540	Signer      string
541	Fingerprint string
542}
543
544func (s *Server) sigFor(repo store.Repo, dir, sha string) (sigView, *sig.Commit) {
545	raw, err := gitutil.ReadCommit(dir, sha)
546	if err != nil {
547		return sigView{State: "unsigned"}, nil
548	}
549	parsed, err := sig.ParseCommit(raw)
550	if err != nil {
551		return sigView{State: "unsigned"}, nil
552	}
553	res, err := control.VerifyCommitCached(s.st, repo, parsed, sha)
554	if err != nil {
555		return sigView{State: "unsigned"}, parsed
556	}
557	v := sigView{State: string(res.State), Fingerprint: res.KeyFingerprint}
558	if res.SignerUserID != 0 {
559		if u, err := s.st.UserByID(res.SignerUserID); err == nil {
560			v.Signer = u.Username
561		}
562	}
563	return v, parsed
564}
565
566func (s *Server) log(w http.ResponseWriter, r *http.Request) {
567	ref := r.PathValue("ref")
568	p, ok := s.repoFor(w, r, ref)
569	if !ok {
570		return
571	}
572	p.Tab = "log"
573	const pageSize = 50
574	shas, err := gitutil.RevList(p.Dir, p.Ref, pageSize+1)
575	if err != nil {
576		http.NotFound(w, r)
577		return
578	}
579	next := ""
580	if len(shas) > pageSize {
581		next = shas[pageSize]
582		shas = shas[:pageSize]
583	}
584	type row struct {
585		SHA, ShortSHA, Subject, AuthorName, AuthorEmail, Date string
586		Sig                                                   sigView
587	}
588	var rows []row
589	for _, sha := range shas {
590		v, parsed := s.sigFor(p.Repo, p.Dir, sha)
591		rw := row{SHA: sha, ShortSHA: sha[:10], Sig: v}
592		if parsed != nil {
593			rw.Subject = parsed.Subject
594			rw.AuthorName = parsed.AuthorName
595			rw.AuthorEmail = parsed.AuthorEmail
596			rw.Date = time.Unix(parsed.AuthorUnix, 0).UTC().Format("2006-01-02")
597		}
598		rows = append(rows, rw)
599	}
600	s.render(w, "log.html", struct {
601		repoPage
602		Commits []row
603		NextSHA string
604	}{p, rows, next})
605}
606
607func (s *Server) commit(w http.ResponseWriter, r *http.Request) {
608	p, ok := s.repoFor(w, r, "")
609	if !ok {
610		return
611	}
612	p.Tab = "log"
613	sha := r.PathValue("sha")
614	full, err := gitutil.ResolveRef(p.Dir, sha)
615	if err != nil {
616		http.NotFound(w, r)
617		return
618	}
619	v, parsed := s.sigFor(p.Repo, p.Dir, full)
620	if parsed == nil {
621		http.NotFound(w, r)
622		return
623	}
624	patch, _ := gitutil.ShowPatch(p.Dir, full, 4<<20)
625	lines := classifyDiff(patch)
626	committerEmail := ""
627	if parsed.CommitterEmail != parsed.AuthorEmail {
628		committerEmail = parsed.CommitterEmail
629	}
630	checks, _ := s.st.ListCommitStatuses(p.Repo.ID, full)
631	msg := ""
632	if i := bytes.Index(parsed.Payload, []byte("\n\n")); i >= 0 {
633		msg = string(parsed.Payload[i+2:])
634	}
635	s.render(w, "commit.html", struct {
636		repoPage
637		SHA, ShortSHA, AuthorName, AuthorEmail, CommitterEmail, Date, Message string
638		Sig                                                                   sigView
639		Checks                                                                []store.CommitStatus
640		DiffLines                                                             []diffLine
641	}{p, full, full[:10], parsed.AuthorName, parsed.AuthorEmail, committerEmail,
642		time.Unix(parsed.AuthorUnix, 0).UTC().Format(time.RFC3339), msg, v, checks, lines})
643}
644
645func (s *Server) issues(w http.ResponseWriter, r *http.Request) {
646	p, ok := s.repoFor(w, r, "")
647	if !ok {
648		return
649	}
650	p.Tab = "issues"
651	state := r.URL.Query().Get("state")
652	if state != "closed" && state != "all" {
653		state = "open"
654	}
655	issues, err := s.st.ListIssues(p.Repo.ID, state)
656	if err != nil {
657		http.Error(w, "internal error", http.StatusInternalServerError)
658		return
659	}
660	s.render(w, "issues.html", struct {
661		repoPage
662		State  string
663		Issues []store.Issue
664	}{p, state, issues})
665}
666
667func (s *Server) issue(w http.ResponseWriter, r *http.Request) {
668	p, ok := s.repoFor(w, r, "")
669	if !ok {
670		return
671	}
672	p.Tab = "issues"
673	n, err := strconv.ParseInt(r.PathValue("n"), 10, 64)
674	if err != nil {
675		http.NotFound(w, r)
676		return
677	}
678	iss, err := s.st.IssueByNumber(p.Repo.ID, n)
679	if err != nil {
680		http.NotFound(w, r)
681		return
682	}
683	comments, err := s.st.ListIssueComments(iss.ID)
684	if err != nil {
685		http.Error(w, "internal error", http.StatusInternalServerError)
686		return
687	}
688	s.render(w, "issue.html", struct {
689		repoPage
690		Issue    store.Issue
691		BodyHTML template.HTML
692		Comments []renderedComment
693	}{p, iss, mdHTML(iss.Body), renderComments(comments)})
694}
695
696func (s *Server) mrs(w http.ResponseWriter, r *http.Request) {
697	p, ok := s.repoFor(w, r, "")
698	if !ok {
699		return
700	}
701	p.Tab = "merge requests"
702	state := r.URL.Query().Get("state")
703	if state == "" {
704		state = "open"
705	}
706	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
707	if !valid[state] {
708		state = "open"
709	}
710	mrs, err := s.st.ListMRs(p.Repo.ID, state)
711	if err != nil {
712		http.Error(w, "internal error", http.StatusInternalServerError)
713		return
714	}
715	s.render(w, "mrs.html", struct {
716		repoPage
717		State string
718		MRs   []store.MR
719	}{p, state, mrs})
720}
721
722func (s *Server) mr(w http.ResponseWriter, r *http.Request) {
723	p, ok := s.repoFor(w, r, "")
724	if !ok {
725		return
726	}
727	p.Tab = "merge requests"
728	n, err := strconv.ParseInt(r.PathValue("n"), 10, 64)
729	if err != nil {
730		http.NotFound(w, r)
731		return
732	}
733	m, err := s.st.MRByNumber(p.Repo.ID, n)
734	if err != nil {
735		http.NotFound(w, r)
736		return
737	}
738	comments, _ := s.st.ListMRComments(m.ID)
739	reviews, _ := s.st.ListMRReviews(m.ID)
740	checks, _ := s.st.ListCommitStatuses(p.Repo.ID, m.HeadSHA)
741	diffComments, _ := s.st.ListDiffComments(m.ID)
742
743	headRef := fmt.Sprintf("refs/merge-requests/%d/head", m.Number)
744	var lines []diffLine
745	base := m.MergedBase
746	if base == "" {
747		if b, err := gitutil.MergeBase(p.Dir, "refs/heads/"+m.TargetRef, headRef); err == nil {
748			base = b
749		}
750	}
751	if base != "" {
752		if patch, err := gitutil.Diff(p.Dir, base, headRef, 4<<20); err == nil {
753			lines = classifyDiff(patch)
754		}
755	}
756	var detachedThreads []diffThread
757	lines, detachedThreads = attachThreads(lines, diffComments, m.HeadSHA)
758	s.render(w, "mr.html", struct {
759		repoPage
760		MR              store.MR
761		BodyHTML        template.HTML
762		Checks          []store.CommitStatus
763		Combined        string
764		Comments        []renderedComment
765		Reviews         []store.MRReview
766		DiffLines       []diffLine
767		DetachedThreads []diffThread
768	}{p, m, mdHTML(m.Body), checks, store.CombinedStatus(checks), renderComments(comments), reviews, lines, detachedThreads})
769}
770
771func (s *Server) refs(w http.ResponseWriter, r *http.Request) {
772	p, ok := s.repoFor(w, r, "")
773	if !ok {
774		return
775	}
776	p.Tab = "refs"
777	branches, _ := gitutil.Refs(p.Dir, "heads")
778	tags, _ := gitutil.Refs(p.Dir, "tags")
779	s.render(w, "refs.html", struct {
780		repoPage
781		Branches, Tags []gitutil.Ref
782	}{p, branches, tags})
783}
784
785func (s *Server) archive(w http.ResponseWriter, r *http.Request) {
786	p, ok := s.repoFor(w, r, "")
787	if !ok {
788		return
789	}
790	file := r.PathValue("file")
791	ref, ok := strings.CutSuffix(file, ".tar.gz")
792	if !ok {
793		http.NotFound(w, r)
794		return
795	}
796	if _, err := gitutil.ResolveRef(p.Dir, ref); err != nil {
797		http.NotFound(w, r)
798		return
799	}
800	prefix := fmt.Sprintf("%s-%s", p.Repo.Name, ref)
801	w.Header().Set("Content-Type", "application/gzip")
802	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", prefix+".tar.gz"))
803	gitutil.Archive(p.Dir, ref, prefix, w)
804}
805
806func policyCanRead(u store.User, repo store.Repo, grant string) bool {
807	return policy.CanRead(u, repo, grant)
808}