internal/httpd/web.go

6521399c1c78577eb00f1bcf8947c0900b9cb62e
gitbay/internal/httpd/web.go

2752 lines · 89311 bytes

   1package httpd
   2
   3import (
   4	"bytes"
   5	"crypto/sha256"
   6	"encoding/hex"
   7	"encoding/json"
   8	"errors"
   9	"fmt"
  10	"hash/fnv"
  11	"io"
  12	"log"
  13	"math"
  14	"os"
  15	"path/filepath"
  16
  17	"gitbay.org/gitbay/internal/policy"
  18	"gitbay.org/gitbay/internal/protocol"
  19	"html/template"
  20	"net/http"
  21	"net/url"
  22	"path"
  23	"regexp"
  24	"strconv"
  25	"strings"
  26	"time"
  27
  28	"github.com/alecthomas/chroma/v2/formatters/html"
  29	"github.com/alecthomas/chroma/v2/lexers"
  30	"github.com/alecthomas/chroma/v2/styles"
  31	"github.com/microcosm-cc/bluemonday"
  32	"github.com/niklasfasching/go-org/org"
  33	"github.com/yuin/goldmark"
  34	highlighting "github.com/yuin/goldmark-highlighting/v2"
  35	"github.com/yuin/goldmark/extension"
  36	"github.com/yuin/goldmark/parser"
  37
  38	"gitbay.org/gitbay/internal/autolink"
  39	"gitbay.org/gitbay/internal/control"
  40	"gitbay.org/gitbay/internal/gitutil"
  41	"gitbay.org/gitbay/internal/sig"
  42	"gitbay.org/gitbay/internal/store"
  43	"gitbay.org/gitbay/internal/suggest"
  44	"gitbay.org/gitbay/internal/web"
  45)
  46
  47const maxRenderBytes = 1 << 20 // largest blob rendered inline
  48
  49func (s *Server) render(w http.ResponseWriter, page string, data any) {
  50	var buf bytes.Buffer
  51	if err := web.Render(&buf, page, data); err != nil {
  52		http.Error(w, "template error: "+err.Error(), http.StatusInternalServerError)
  53		return
  54	}
  55	w.Header().Set("Content-Type", "text/html; charset=utf-8")
  56	buf.WriteTo(w)
  57}
  58
  59// siteName is the instance's display name: the operator's [web] title,
  60// or the site host when they have not set one.
  61func (s *Server) siteName() string {
  62	if t := strings.TrimSpace(s.cfg.Web.Title); t != "" {
  63		return t
  64	}
  65	h := strings.TrimPrefix(strings.TrimPrefix(s.cfg.Server.SiteURL, "https://"), "http://")
  66	return strings.TrimSuffix(h, "/")
  67}
  68
  69// stylesheetHash is the hash of what stylesheet serves, computed once. It
  70// is the ETag, so a browser revalidating with If-None-Match gets a 304
  71// until a deploy changes the bytes (#132), and it is the ?v= the layout
  72// stamps on the URL, so a deploy the browser has not fetched yet cannot be
  73// answered from its cache (#239).
  74var stylesheetHash = func() string {
  75	h := sha256.New()
  76	h.Write(styleCSS)
  77	h.Write(chromaCSS)
  78	return hex.EncodeToString(h.Sum(nil))[:16]
  79}()
  80
  81var stylesheetETag = `"` + stylesheetHash + `"`
  82
  83var scriptHash = func() string {
  84	sum := sha256.Sum256(web.AppJS)
  85	return hex.EncodeToString(sum[:])[:16]
  86}()
  87
  88var scriptETag = `"` + scriptHash + `"`
  89
  90func init() {
  91	web.StyleVersion = stylesheetHash
  92	web.ScriptVersion = scriptHash
  93}
  94
  95func (s *Server) appScript(w http.ResponseWriter, r *http.Request) {
  96	w.Header().Set("ETag", scriptETag)
  97	if r.URL.Query().Get("v") == scriptHash {
  98		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
  99	} else {
 100		w.Header().Set("Cache-Control", "public, max-age=86400, must-revalidate")
 101	}
 102	if r.Header.Get("If-None-Match") == scriptETag {
 103		w.WriteHeader(http.StatusNotModified)
 104		return
 105	}
 106	w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
 107	w.Write(web.AppJS)
 108}
 109
 110func (s *Server) stylesheet(w http.ResponseWriter, r *http.Request) {
 111	w.Header().Set("ETag", stylesheetETag)
 112	// A URL carrying this build's hash names bytes that cannot change, so
 113	// it never needs revalidating. The bare URL still can, and keeps the
 114	// policy it had.
 115	if r.URL.Query().Get("v") == stylesheetHash {
 116		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
 117	} else {
 118		w.Header().Set("Cache-Control", "public, max-age=86400, must-revalidate")
 119	}
 120	if r.Header.Get("If-None-Match") == stylesheetETag {
 121		w.WriteHeader(http.StatusNotModified)
 122		return
 123	}
 124	w.Header().Set("Content-Type", "text/css; charset=utf-8")
 125	w.Write(styleCSS)
 126	w.Write(chromaCSS)
 127}
 128
 129func (s *Server) favicon(w http.ResponseWriter, r *http.Request) {
 130	w.Header().Set("Content-Type", "image/svg+xml")
 131	w.Write(web.FaviconSVG)
 132}
 133
 134// font serves the embedded Atkinson Hyperlegible subsets. Same-origin,
 135// so the CSP's default-src 'self' covers it — no font CDN.
 136func (s *Server) font(w http.ResponseWriter, r *http.Request) {
 137	data, err := web.FontFS.ReadFile("static" + r.URL.Path[len("/static"):])
 138	if err != nil {
 139		http.NotFound(w, r)
 140		return
 141	}
 142	w.Header().Set("Content-Type", "font/woff2")
 143	w.Header().Set("Cache-Control", "public, max-age=604800, immutable")
 144	w.Write(data)
 145}
 146
 147var staticTypes = map[string]string{
 148	".gif":  "image/gif",
 149	".webm": "video/webm",
 150	".mp4":  "video/mp4",
 151}
 152
 153// image serves the embedded landing recording with the font cache policy.
 154// ServeContent answers Range, which Safari needs to play video.
 155func (s *Server) image(w http.ResponseWriter, r *http.Request) {
 156	name := "static" + r.URL.Path[len("/static"):]
 157	data, err := web.ImageFS.ReadFile(name)
 158	if err != nil {
 159		http.NotFound(w, r)
 160		return
 161	}
 162	w.Header().Set("Content-Type", staticTypes[path.Ext(name)])
 163	w.Header().Set("Cache-Control", "public, max-age=604800, immutable")
 164	http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(data))
 165}
 166
 167// notFound renders the designed 404 page with a 404 status. Falls back to
 168// the stock plain-text response if the template fails.
 169func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
 170	var buf bytes.Buffer
 171	if err := web.Render(&buf, "404.html", s.base(r)); err != nil {
 172		http.NotFound(w, r)
 173		return
 174	}
 175	w.Header().Set("Content-Type", "text/html; charset=utf-8")
 176	w.WriteHeader(http.StatusNotFound)
 177	buf.WriteTo(w)
 178}
 179
 180// describedRepo pairs a repo with the listing metadata: description,
 181// topics, license, and last-updated date.
 182type describedRepo struct {
 183	store.Repo
 184	Desc    string
 185	Topics  []string
 186	License string
 187	Updated string
 188}
 189
 190// Archived flattens the settings flag so the reporow partial can read the
 191// same field name from a describedRepo and from a profile's repo row.
 192func (d describedRepo) Archived() bool { return d.Settings.Archived }
 193
 194func (s *Server) describeAll(repos []store.Repo) []describedRepo {
 195	var out []describedRepo
 196	for _, r := range repos {
 197		dir := control.RepoDir(s.cfg.Server.Root, r.OwnerName, r.Name)
 198		d := describedRepo{
 199			Repo:    r,
 200			Desc:    gitutil.ReadDescription(dir),
 201			License: control.DetectLicense(dir, r.DefaultBranch),
 202			Updated: gitutil.LastCommitDate(dir, r.DefaultBranch),
 203		}
 204		d.Topics, _ = s.st.ListTopics(r.ID)
 205		out = append(out, d)
 206	}
 207	return out
 208}
 209
 210// index is the homepage: a dashboard for logged-in users, a landing page
 211// for everyone else. The full public listing lives at /explore.
 212func (s *Server) index(w http.ResponseWriter, r *http.Request) {
 213	if s.cfg.Web.Mode == "accounts" {
 214		if viewer := s.viewer(r); viewer.ID != 0 {
 215			s.dashboard(w, r, viewer)
 216			return
 217		}
 218	}
 219	host := strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(
 220		s.cfg.Server.SiteURL, "https://"), "http://"), "/")
 221	s.render(w, "landing.html", struct {
 222		basePage
 223		Host       string
 224		Accounts   bool
 225		Signup     bool
 226		EmailLogin bool
 227	}{s.anonBase(), host, s.cfg.Web.Mode == "accounts",
 228		s.cfg.Web.Mode == "accounts" && s.cfg.Registration.Mode != "closed",
 229		s.emailLoginEnabled()})
 230}
 231
 232func (s *Server) dashboard(w http.ResponseWriter, r *http.Request, viewer store.User) {
 233	mrs, _ := s.st.DashboardMRs(viewer.ID)
 234	issues, _ := s.st.DashboardIssues(viewer.ID)
 235	reviews, _ := s.st.ReviewQueue(viewer.ID)
 236	assigned, _ := s.st.AssignedIssues(viewer.ID)
 237	events, _ := s.st.RecentEvents(viewer.ID, 20, 0)
 238	queries, _ := control.PinnedQueries(s.st, viewer)
 239	s.render(w, "dashboard.html", struct {
 240		basePage
 241		Tab      string
 242		Pins     []pinnedRow
 243		Reviews  []store.DashboardItem
 244		Assigned []store.DashboardItem
 245		MRs      []store.DashboardItem
 246		Issues   []store.DashboardItem
 247		Queries  []control.DashboardQuery
 248		Feed     []control.FeedLine
 249	}{s.baseFor(viewer), "dashboard", s.pinnedRows(viewer), reviews, assigned, mrs, issues, queries, control.FeedLines(events)})
 250}
 251
 252// explorePageSize is how many repositories one page of /explore lists.
 253const explorePageSize = 20
 254
 255// explorePage is /explore: one page of the filtered listing, most recent
 256// activity first. Total counts the whole filtered listing.
 257type explorePage struct {
 258	basePage
 259	Tab    string
 260	Query  string
 261	Facets []facetGroup
 262	Repos  []describedRepo
 263	Total  int
 264	Page   int
 265	Pages  int
 266	Prev   string
 267	Next   string
 268}
 269
 270func (s *Server) explore(w http.ResponseWriter, r *http.Request) {
 271	repos, err := s.st.ListPublicReposByActivity()
 272	if err != nil {
 273		http.Error(w, "internal error", http.StatusInternalServerError)
 274		return
 275	}
 276	var viewer store.User
 277	if s.cfg.Web.Mode == "accounts" {
 278		viewer = s.viewer(r)
 279	}
 280	q := strings.TrimSpace(r.URL.Query().Get("q"))
 281	described := s.describeAll(repos)
 282	p := explorePage{basePage: s.baseFor(viewer), Tab: "explore", Query: q,
 283		Facets: []facetGroup{topicFacets(described, q)}}
 284	p.Repos, p.Total, p.Page, p.Pages = pageOf(s.filterRepos(q, described), r.URL.Query().Get("page"))
 285	if p.Page > 1 {
 286		p.Prev = explorePageURL(q, p.Page-1)
 287	}
 288	if p.Page < p.Pages {
 289		p.Next = explorePageURL(q, p.Page+1)
 290	}
 291	s.render(w, "explore.html", p)
 292}
 293
 294// pageOf returns page n (1-based, clamped) of repos at explorePageSize.
 295func pageOf(repos []describedRepo, n string) (page []describedRepo, total, num, pages int) {
 296	total = len(repos)
 297	pages = max(1, (total+explorePageSize-1)/explorePageSize)
 298	num, _ = strconv.Atoi(n)
 299	num = min(max(num, 1), pages)
 300	lo := (num - 1) * explorePageSize
 301	return repos[lo:min(lo+explorePageSize, total)], total, num, pages
 302}
 303
 304func explorePageURL(q string, page int) string {
 305	v := url.Values{}
 306	if q != "" {
 307		v.Set("q", q)
 308	}
 309	if page > 1 {
 310		v.Set("page", strconv.Itoa(page))
 311	}
 312	if len(v) == 0 {
 313		return "/explore"
 314	}
 315	return "/explore?" + v.Encode()
 316}
 317
 318// privacy renders the privacy page: what the gitbay software does with
 319// data, plus this instance's operator-provided notes.
 320func (s *Server) privacy(w http.ResponseWriter, r *http.Request) {
 321	s.render(w, "privacy.html", struct {
 322		basePage
 323		Host   string
 324		Notice string
 325	}{s.base(r), s.cfg.SiteHost(), s.cfg.Web.PrivacyNotice})
 326}
 327
 328// filterRepos keeps repos matching the query by the same rule `repo
 329// search` uses. An empty query keeps everything.
 330func (s *Server) filterRepos(q string, repos []describedRepo) []describedRepo {
 331	if q == "" {
 332		return repos
 333	}
 334	var out []describedRepo
 335	for _, d := range repos {
 336		if control.MatchesRepo(q, d.Path(), d.Desc, d.Topics) {
 337			out = append(out, d)
 338		}
 339	}
 340	return out
 341}
 342
 343// repoPage is the shared context for repo-scoped pages.
 344type repoPage struct {
 345	basePage
 346	Desc     string
 347	Repo     store.Repo
 348	Ref      string
 349	CloneURL string
 350	// SSHCloneURL is the same repository over the SSH transport, which is
 351	// the one a push needs.
 352	SSHCloneURL string
 353	Dir         string
 354	Tab         string // active tab in the repo header
 355	Topics      []string
 356	Pinned      bool   // by the viewer
 357	Marked      bool   // bookmarked by the viewer
 358	Bookmarks   int    // public bookmark count
 359	Forks       int    // public fork count
 360	Watch       string // the viewer's watch state: watching, muted, or ""
 361	HasWiki     bool
 362	Host        string
 363	Mirrors     []mirrorLine // repo admins only
 364	CanAdmin    bool         // gates the settings tab
 365	Feed        string       // Atom feed for this page, if it has one
 366	// OpenIssues and OpenMRs are the counts on the header tabs.
 367	OpenIssues int
 368	OpenMRs    int
 369	// RepoHome asks the layout for the full header — description, topics,
 370	// website, mirrors. Every other page gets identity and tabs only, so a
 371	// repo describes itself once rather than on all twelve of its pages.
 372	RepoHome bool
 373}
 374
 375// mirrorLine is the admin-only mirror status shown in the repo header.
 376// It carries no credentials: the stored URL is credential-free.
 377type mirrorLine struct {
 378	Direction string
 379	URL       string
 380	Target    string // URL without the scheme, for display
 381	Synced    string
 382	Error     string
 383}
 384
 385// syncedAt trims a stored sync timestamp (2026-08-25T03:39:19.994Z) to a
 386// readable "2026-08-25 03:39 UTC".
 387func syncedAt(ts string) string {
 388	if len(ts) < 16 {
 389		return ts
 390	}
 391	return ts[:10] + " " + ts[11:16] + " UTC"
 392}
 393
 394// repoFor resolves the repo for a web request; false means 404 was sent.
 395// Anonymous visitors see public repos only; in accounts mode a logged-in
 396// viewer additionally sees repos their grants allow. Private and missing
 397// repos are indistinguishable either way.
 398func (s *Server) repoFor(w http.ResponseWriter, r *http.Request, ref string) (repoPage, bool) {
 399	var repo store.Repo
 400	var viewer store.User
 401	if s.cfg.Web.Mode == "accounts" {
 402		viewer = s.viewer(r)
 403	}
 404	repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
 405	ok := err == nil
 406	grant := ""
 407	if ok {
 408		if viewer.ID != 0 {
 409			grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
 410		}
 411		ok = policyCanRead(viewer, repo, grant)
 412	}
 413	if !ok {
 414		s.notFound(w, r)
 415		return repoPage{}, false
 416	}
 417	if ref == "" {
 418		ref = repo.DefaultBranch
 419	}
 420	topics, _ := s.st.ListTopics(repo.ID)
 421	pinned, marked, watch := false, false, ""
 422	if viewer.ID != 0 {
 423		pinned = s.st.IsPinned(viewer.ID, repo.ID)
 424		marked = s.st.IsBookmarked(viewer.ID, repo.ID)
 425		watch = s.st.RepoWatchState(repo.ID, viewer.ID)
 426	}
 427	canAdmin := viewer.ID != 0 && policy.CanAdmin(viewer, repo, grant)
 428	var mirrors []mirrorLine
 429	if canAdmin {
 430		ms, _ := s.st.ListMirrors(repo.ID)
 431		for _, m := range ms {
 432			mirrors = append(mirrors, mirrorLine{
 433				Direction: m.Direction,
 434				URL:       m.URL,
 435				Target:    strings.TrimPrefix(strings.TrimPrefix(m.URL, "https://"), "http://"),
 436				Synced:    syncedAt(m.LastSync),
 437				Error:     m.LastError,
 438			})
 439		}
 440	}
 441	openIssues, openMRs := s.st.OpenCounts(repo.ID)
 442	bookmarksCount := s.st.BookmarkCount(repo.ID)
 443	forksList, _ := s.st.ListForks(repo.ID)
 444	return repoPage{
 445		basePage:    s.baseFor(viewer),
 446		CanAdmin:    canAdmin,
 447		Mirrors:     mirrors,
 448		Pinned:      pinned,
 449		Marked:      marked,
 450		Bookmarks:   bookmarksCount,
 451		Forks:       len(forksList),
 452		Watch:       watch,
 453		HasWiki:     s.hasWiki(repo),
 454		Host:        s.cfg.SiteHost(),
 455		Desc:        gitutil.ReadDescription(control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)),
 456		Repo:        repo,
 457		Ref:         ref,
 458		CloneURL:    s.cfg.Server.SiteURL + "/" + repo.Path() + ".git",
 459		SSHCloneURL: s.sshCloneURL(repo),
 460		Dir:         control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name),
 461		Topics:      topics,
 462		OpenIssues:  openIssues,
 463		OpenMRs:     openMRs,
 464	}, true
 465}
 466
 467type crumb struct {
 468	Name string
 469	URL  string
 470}
 471
 472// crumbs builds one crumb per path component. Every component but the
 473// last is a directory and links to the tree; only the leaf is a page of
 474// the given kind.
 475func crumbs(p repoPage, kind, filePath string) []crumb {
 476	var cs []crumb
 477	parts := strings.Split(strings.Trim(filePath, "/"), "/")
 478	acc := ""
 479	for i, part := range parts {
 480		if part == "" {
 481			continue
 482		}
 483		acc = path.Join(acc, part)
 484		k := "tree"
 485		if i == len(parts)-1 {
 486			k = kind
 487		}
 488		cs = append(cs, crumb{Name: part, URL: "/" + p.Repo.Path() + "/" + k + "/" + p.Ref + "/" + acc})
 489	}
 490	return cs
 491}
 492
 493// profileView is profile show's payload, shaped for the templates. The
 494// repo rows carry the same names the reporow partial reads, so a profile
 495// listing renders identically to explore's.
 496// profileView is profile show's payload with the repository rows wrapped
 497// so the reporow partial can reach them. The fields themselves are the
 498// command's: a field it gains appears here without being re-declared.
 499type profileView struct {
 500	control.ProfileOut
 501	Repos []profileRepoRow `json:"repos"`
 502}
 503
 504// profileRepoRow is one repository row on a profile. The partial asks for
 505// OwnerName, Name and Desc; the payload carries a path and a description.
 506type profileRepoRow struct {
 507	control.ProfileRepo
 508}
 509
 510func (p profileRepoRow) OwnerName() string { owner, _, _ := strings.Cut(p.Path, "/"); return owner }
 511func (p profileRepoRow) Name() string      { _, name, _ := strings.Cut(p.Path, "/"); return name }
 512func (p profileRepoRow) Desc() string      { return p.Description }
 513
 514// ownerPage renders /{owner} for users and orgs: the repositories the
 515// viewer may see, org membership either direction. Owner names are not
 516// secret (they are on every commit); repository visibility rules hold.
 517// profileTab is which section of a profile a URL asks for. The bare
 518// /{owner} is About, the first tab; the rest hang off the /-/ namespace
 519// the labels and milestones pages already use. What #242 asked for is
 520// that the sections be separate pages rather than one stack a long
 521// About pushes the repositories off the bottom of — not that any one of
 522// them be the landing page.
 523func profileTab(path string) string {
 524	switch {
 525	case strings.HasSuffix(path, "/-/repositories"):
 526		return "repos"
 527	case strings.HasSuffix(path, "/-/bookmarks"):
 528		return "bookmarks"
 529	case strings.HasSuffix(path, "/-/snippets"):
 530		return "snippets"
 531	case strings.HasSuffix(path, "/-/people"):
 532		return "people"
 533	}
 534	return "about"
 535}
 536
 537// profileEvents is how many activity lines the About tab lists under the
 538// graph. The graph is a year at a glance; the log is what happened
 539// lately, and a fixed count keeps the page the same length whatever the
 540// account's pace.
 541const profileEvents = 30
 542
 543// ownerFeed is the activity log under the graph on the About tab: the
 544// newest of whatever the graph above it counts, on public repositories
 545// only. That is the actor's own events for a user and the
 546// organization's repositories' events for an org, matching
 547// ActivityByDay and OrgActivityByDay respectively — a log that counted
 548// something else would contradict the total printed over it. Only the
 549// About tab renders it, so no other tab pays for the query.
 550func (s *Server) ownerFeed(tab, kind, name string) []control.FeedLine {
 551	if tab != "about" {
 552		return nil
 553	}
 554	var events []store.FeedEvent
 555	var err error
 556	switch kind {
 557	case "user":
 558		u, uerr := s.st.UserByUsername(name)
 559		if uerr != nil {
 560			return nil
 561		}
 562		events, err = s.st.UserPublicEvents(u.ID, profileEvents)
 563	case "org":
 564		o, oerr := s.st.OrgByName(name)
 565		if oerr != nil {
 566			return nil
 567		}
 568		events, err = s.st.OwnerPublicEvents("org", o.ID, profileEvents)
 569	}
 570	if err != nil {
 571		return nil
 572	}
 573	return control.FeedLines(events)
 574}
 575
 576// ownerPage is what owner.html renders against. It is a named type
 577// because the handler and the tests must agree on it field for field,
 578// and an anonymous struct in two places drifts.
 579type ownerPage struct {
 580	basePage
 581	Owner         string
 582	Kind          string
 583	Tab           string
 584	Profile       store.Profile
 585	AboutHTML     template.HTML
 586	Repos         []profileRepoRow
 587	Members       []control.ProfileMember
 588	Orgs          []control.ProfileMember
 589	Activity      []activityWeek
 590	ActivityTotal int
 591	Log           []control.FeedLine
 592	Bookmarks     []control.BookmarkOut
 593	SnippetRows   []snippetRow
 594	SnippetsAll   bool
 595	Teams         []teamView
 596	CanAdmin      bool
 597	Self          bool
 598	Snippets      int
 599	Notice        string
 600	Reauth        bool // Notice is the stale-session refusal: link to sign in
 601	Feed          string
 602}
 603
 604func (s *Server) ownerProfile(w http.ResponseWriter, r *http.Request) {
 605	name := r.PathValue("owner")
 606	var viewer store.User
 607	if s.cfg.Web.Mode == "accounts" {
 608		viewer = s.viewer(r)
 609	}
 610
 611	// Everything on this page — membership, the repositories this viewer
 612	// may see, the activity year — comes from profile show, so the page
 613	// and the command cannot report different things.
 614	var d profileView
 615	code, msg := s.runControlIntoCode(viewer, []string{"profile", "show", name}, &d)
 616	switch {
 617	case code == protocol.ExitNotFound:
 618		s.notFound(w, r)
 619		return
 620	case code != protocol.ExitOK:
 621		log.Printf("profile %s: %s", name, msg)
 622		http.Error(w, "internal error", http.StatusInternalServerError)
 623		return
 624	}
 625
 626	counts := make(map[string]int, len(d.Activity))
 627	for _, day := range d.Activity {
 628		counts[day.Date] = day.Count
 629	}
 630	weeks, activityTotal := activityGrid(counts)
 631
 632	teams, canAdmin := s.orgAdminView(viewer, d.Kind, name)
 633	self := d.Kind == "user" && viewer.ID != 0 && strings.EqualFold(viewer.Username, name)
 634	tab := profileTab(r.URL.Path)
 635	// A tab nobody may open is not a page: the people tab is the
 636	// organization admin panel, bookmarks are the viewer's own and
 637	// nobody else's, and only a user has snippets. Each answers the way
 638	// a missing page does rather than rendering empty.
 639	if (tab == "people" && !canAdmin) || (tab == "bookmarks" && !self) ||
 640		(tab == "snippets" && d.Kind != "user") {
 641		s.notFound(w, r)
 642		return
 643	}
 644
 645	var bookmarks []control.BookmarkOut
 646	if tab == "bookmarks" {
 647		s.runControlInto(viewer, []string{"repo", "bookmarks"}, &bookmarks)
 648	}
 649	var snippets []snippetRow
 650	if tab == "snippets" {
 651		var ok bool
 652		if snippets, ok = s.ownerSnippets(w, r, viewer, name); !ok {
 653			return
 654		}
 655	}
 656	notice := s.takeFlash(w, r)
 657	s.render(w, "owner.html", ownerPage{
 658		basePage:      s.baseFor(viewer),
 659		Owner:         name,
 660		Kind:          d.Kind,
 661		Tab:           tab,
 662		Profile:       store.Profile{Description: d.Description, Website: d.Website, Links: d.Links},
 663		AboutHTML:     aboutHTML(d.About, d.AboutFormat),
 664		Repos:         d.Repos,
 665		Members:       d.Members,
 666		Orgs:          d.Orgs,
 667		Activity:      weeks,
 668		ActivityTotal: activityTotal,
 669		Log:           s.ownerFeed(tab, d.Kind, name),
 670		Bookmarks:     bookmarks,
 671		SnippetRows:   snippets,
 672		SnippetsAll:   self || viewer.IsAdmin,
 673		Teams:         teams,
 674		CanAdmin:      canAdmin,
 675		Self:          self,
 676		Snippets:      d.Snippets,
 677		Notice:        notice,
 678		Reauth:        s.reauthNotice(w, notice, r.URL.Path),
 679		Feed:          "/" + name + "/activity.atom",
 680	})
 681}
 682
 683func (s *Server) repoHome(w http.ResponseWriter, r *http.Request) {
 684	p, ok := s.repoFor(w, r, "")
 685	if !ok {
 686		return
 687	}
 688	p.Tab = "files"
 689	p.RepoHome = true
 690	s.renderTree(w, r, p, "")
 691}
 692
 693func (s *Server) tree(w http.ResponseWriter, r *http.Request) {
 694	p, ok := s.repoFor(w, r, r.PathValue("ref"))
 695	if !ok {
 696		return
 697	}
 698	p.Tab = "files"
 699	path := strings.Trim(r.PathValue("path"), "/")
 700	// The root of the default branch is the same page as the bare repo
 701	// URL, so its header must match: RepoHome is what picks the h1 over
 702	// the p+link identity, not which route was typed.
 703	p.RepoHome = path == "" && p.Ref == p.Repo.DefaultBranch
 704	s.renderTree(w, r, p, path)
 705}
 706
 707// treePage is shared by the populated and empty-repository renders: two
 708// anonymous structs drifted apart once already.
 709type treePage struct {
 710	repoPage
 711	Crumbs      []crumb
 712	Prefix      string
 713	DirPath     string
 714	RefKind     string
 715	Entries     []gitutil.TreeEntry
 716	Branches    []gitutil.Ref
 717	ReadmeName  string
 718	ReadmeHTML  template.HTML
 719	LastCommits map[string]namedCommit
 720	Tip         namedCommit
 721	Facts       repoFacts
 722	Notice      string
 723}
 724
 725func (s *Server) renderTree(w http.ResponseWriter, r *http.Request, p repoPage, dirPath string) {
 726	if _, err := gitutil.ResolveRef(p.Dir, p.Ref); err != nil {
 727		// Empty repo: render the page with no entries rather than 404.
 728		s.render(w, "tree.html", treePage{repoPage: p, RefKind: "tree", Notice: s.takeFlash(w, r)})
 729		return
 730	}
 731	entries, err := gitutil.ListTree(p.Dir, p.Ref, dirPath)
 732	if err != nil {
 733		s.notFound(w, r)
 734		return
 735	}
 736	sortDirsFirst(entries)
 737	prefix := ""
 738	if dirPath != "" {
 739		prefix = dirPath + "/"
 740	}
 741
 742	var readmeHTML template.HTML
 743	readmeName := control.PickReadme(entries)
 744	if readmeName != "" {
 745		if raw, err := gitutil.ReadBlob(p.Dir, p.Ref, prefix+readmeName, maxRenderBytes); err == nil {
 746			readmeHTML = rewriteRelativeLinks(renderReadme(readmeName, raw), p, dirPath)
 747		}
 748	}
 749
 750	branches, _ := gitutil.Refs(p.Dir, "heads")
 751	names := make([]string, 0, len(entries))
 752	for _, e := range entries {
 753		names = append(names, e.Name)
 754	}
 755	// The facts bar is about the repository, not this directory, so it is
 756	// computed once at the root and left off subdirectory listings.
 757	var facts repoFacts
 758	if dirPath == "" {
 759		facts = s.factsFor(p)
 760	}
 761	s.render(w, "tree.html", treePage{p, crumbs(p, "tree", dirPath), prefix, dirPath, "tree", entries, branches,
 762		readmeName, readmeHTML,
 763		s.namedCommits(gitutil.LastCommits(p.Dir, p.Ref, dirPath, names)),
 764		s.namedTip(gitutil.TipCommit(p.Dir, p.Ref)), facts, s.takeFlash(w, r)})
 765}
 766
 767func (s *Server) blob(w http.ResponseWriter, r *http.Request) {
 768	p, ok := s.repoFor(w, r, r.PathValue("ref"))
 769	if !ok {
 770		return
 771	}
 772	p.Tab = "files"
 773	filePath := strings.Trim(r.PathValue("path"), "/")
 774	// The file and its symbol links are read from one commit, even if the
 775	// ref moves while the page renders.
 776	commit, err := gitutil.ResolveRef(p.Dir, p.Ref)
 777	if err != nil {
 778		s.notFound(w, r)
 779		return
 780	}
 781	data, err := gitutil.ReadBlob(p.Dir, commit, filePath, maxRenderBytes+1)
 782	if err != nil {
 783		s.notFound(w, r)
 784		return
 785	}
 786	binary := gitutil.IsBinary(data) || len(data) > maxRenderBytes
 787	if linesParam := r.URL.Query().Get("lines"); linesParam != "" && !binary {
 788		s.serveBlobLines(w, filePath, data, linesParam)
 789		return
 790	}
 791	_, image := imageTypes[strings.ToLower(path.Ext(filePath))]
 792
 793	var codeHTML template.HTML
 794	if !binary && !image {
 795		codeHTML = highlight(filePath, data)
 796	}
 797	var fileSymbols []store.SymbolRow
 798	if !binary && !image {
 799		codeHTML, fileSymbols = s.blobSymbols(p, commit, filePath, codeHTML)
 800	}
 801	// Markdown and org render like a README, with the source one click
 802	// away; ?view=source shows the text instead.
 803	renderable := markupFile(filePath) && !binary
 804	var renderedHTML template.HTML
 805	rendered := renderable && r.URL.Query().Get("view") != "source"
 806	if rendered {
 807		renderedHTML = rewriteRelativeLinks(renderReadme(path.Base(filePath), data), p, path.Dir(filePath))
 808	}
 809	cs := crumbs(p, "blob", filePath)
 810	base := ""
 811	if len(cs) > 0 {
 812		base = cs[len(cs)-1].Name
 813		cs = cs[:len(cs)-1]
 814	}
 815	branches, _ := gitutil.Refs(p.Dir, "heads")
 816	navEntries, _ := gitutil.ListTree(p.Dir, p.Ref, navDir(filePath))
 817	nav := fileNavFor(p.Repo.Path(), p.Ref, filePath, navEntries)
 818	lines := 0
 819	if !binary && !image && len(data) > 0 {
 820		lines = bytes.Count(data, []byte("\n"))
 821		if data[len(data)-1] != '\n' {
 822			lines++
 823		}
 824	}
 825	// The file listing leads with the last commit now, so the facts about
 826	// the file itself are reported here instead.
 827	entry, _ := gitutil.StatPath(p.Dir, p.Ref, filePath)
 828	var fileTip namedCommit
 829	if base != "" {
 830		if lc := s.namedCommits(gitutil.LastCommits(p.Dir, p.Ref, navDir(filePath), []string{base})); lc != nil {
 831			fileTip = lc[base]
 832		}
 833	}
 834	s.render(w, "blob.html", struct {
 835		repoPage
 836		Crumbs       []crumb
 837		Base         string
 838		Path         string
 839		DirPath      string
 840		RefKind      string
 841		Commit       string
 842		Tip          namedCommit
 843		Binary       bool
 844		Image        bool
 845		Size         int
 846		Lines        int
 847		Exec         bool
 848		Symlink      bool
 849		Branches     []gitutil.Ref
 850		CodeHTML     template.HTML
 851		Renderable   bool // markdown or org: the toggle is offered
 852		Rendered     bool // this response shows the rendering
 853		RenderedHTML template.HTML
 854		Nav          fileNav
 855		Symbols      []store.SymbolRow
 856	}{p, cs, base, filePath, filePath, "blob", commit, fileTip, binary, image, len(data), lines,
 857		entry.Mode == "100755", entry.Mode == "120000", branches, codeHTML, renderable, rendered, renderedHTML, nav, fileSymbols})
 858}
 859
 860func (s *Server) serveBlobLines(w http.ResponseWriter, filePath string, data []byte, spec string) {
 861	aStr, bStr, ok := strings.Cut(spec, ":")
 862	from, err1 := strconv.Atoi(aStr)
 863	to, err2 := strconv.Atoi(bStr)
 864	if !ok || err1 != nil || err2 != nil || from < 1 || to < from || to-from > 100 {
 865		http.Error(w, "bad lines range", http.StatusBadRequest)
 866		return
 867	}
 868	rawLines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
 869	if from > len(rawLines) {
 870		w.Header().Set("Content-Type", "application/json; charset=utf-8")
 871		w.Write([]byte(`{"lines":[]}`))
 872		return
 873	}
 874	if to > len(rawLines) {
 875		to = len(rawLines)
 876	}
 877	type lineItem struct {
 878		N    int    `json:"n"`
 879		HTML string `json:"html"`
 880	}
 881	lexer := lexers.Match(filePath)
 882	var highlighted []template.HTML
 883	if lexer != nil {
 884		highlighted = highlightLines(lexer, strings.Join(rawLines[from-1:to], "\n")+"\n")
 885	}
 886	out := make([]lineItem, 0, to-from+1)
 887	for idx := from - 1; idx < to; idx++ {
 888		h := template.HTMLEscapeString(rawLines[idx])
 889		if k := idx - (from - 1); k < len(highlighted) && highlighted[k] != "" {
 890			h = string(highlighted[k])
 891		}
 892		out = append(out, lineItem{N: idx + 1, HTML: h})
 893	}
 894	w.Header().Set("Content-Type", "application/json; charset=utf-8")
 895	json.NewEncoder(w).Encode(map[string]any{"lines": out})
 896}
 897
 898// releases lists tag-anchored releases with notes and assets.
 899func (s *Server) releases(w http.ResponseWriter, r *http.Request) {
 900	s.releasesPage(w, r, "")
 901}
 902
 903// releasesPage lists releases. previewForm is "release" when the create
 904// form asked to see its notes, or "release:<tag>" when that release's
 905// edit form did (#235).
 906func (s *Server) releasesPage(w http.ResponseWriter, r *http.Request, previewForm string) {
 907	p, ok := s.repoFor(w, r, "")
 908	if !ok {
 909		return
 910	}
 911	p.Tab = "releases"
 912	p.Feed = "/" + p.Repo.Path() + "/releases.atom"
 913	rels, err := s.st.ListReleases(p.Repo.ID)
 914	if err != nil {
 915		http.Error(w, "internal error", http.StatusInternalServerError)
 916		return
 917	}
 918	md := s.ugcFor(r, p.Repo)
 919	type relView struct {
 920		store.Release
 921		NotesHTML template.HTML
 922	}
 923	var views []relView
 924	for _, rel := range rels {
 925		views = append(views, relView{rel, md(rel.Notes, rel.NotesFormat)})
 926	}
 927	// Tags without a release yet are what a create form can offer.
 928	released := map[string]bool{}
 929	for _, rel := range rels {
 930		released[rel.Tag] = true
 931	}
 932	var freeTags []string
 933	if tags, err := gitutil.Refs(p.Dir, "tags"); err == nil {
 934		gitutil.SortVersions(tags)
 935		for _, tg := range tags {
 936			if !released[tg.Name] {
 937				freeTags = append(freeTags, tg.Name)
 938			}
 939		}
 940	}
 941	// An edit keeps the release's stored format; a new release reads the
 942	// format picker, defaulting to markdown.
 943	var d *draft
 944	if previewForm != "" {
 945		format := bodyFormat(r)
 946		if tag, ok := strings.CutPrefix(previewForm, "release:"); ok {
 947			format = "md"
 948			for _, v := range views {
 949				if v.Tag == tag {
 950					format = v.NotesFormat
 951				}
 952			}
 953		}
 954		d = s.draftFor(r, p.Repo, previewForm, "notes", format)
 955	}
 956	s.render(w, "releases.html", struct {
 957		repoPage
 958		Releases []relView
 959		FreeTags []string
 960		CanWrite bool
 961		Notice   string
 962		Draft    *draft
 963	}{p, views, freeTags, s.canWriteRepo(r, p.Repo), s.takeFlash(w, r), d})
 964}
 965
 966// releaseAsset streams one uploaded asset. Tags containing '/' are not
 967// reachable here (single path segment); SSH download always works.
 968func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
 969	p, ok := s.repoFor(w, r, "")
 970	if !ok {
 971		return
 972	}
 973	rel, err := s.st.ReleaseByTag(p.Repo.ID, r.PathValue("tag"))
 974	if err != nil {
 975		s.notFound(w, r)
 976		return
 977	}
 978	name := r.PathValue("name")
 979	found := false
 980	for _, a := range rel.Assets {
 981		if a.Name == name {
 982			found = true
 983		}
 984	}
 985	if !found {
 986		s.notFound(w, r)
 987		return
 988	}
 989	f, err := os.Open(filepath.Join(control.RepoDir(s.cfg.Server.Root, p.Repo.OwnerName, p.Repo.Name),
 990		"gitbay-releases", strconv.FormatInt(rel.ID, 10), name))
 991	if err != nil {
 992		s.notFound(w, r)
 993		return
 994	}
 995	defer f.Close()
 996	w.Header().Set("Content-Type", "application/octet-stream")
 997	w.Header().Set("X-Content-Type-Options", "nosniff")
 998	w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
 999	if fi, err := f.Stat(); err == nil {
1000		w.Header().Set("Content-Length", strconv.FormatInt(fi.Size(), 10))
1001	}
1002	io.Copy(w, f)
1003}
1004
1005// milestones lists a repo's milestones with progress.
1006func (s *Server) milestones(w http.ResponseWriter, r *http.Request) {
1007	p, ok := s.repoFor(w, r, "")
1008	if !ok {
1009		return
1010	}
1011	p.Tab = "issues"
1012	state := r.URL.Query().Get("state")
1013	if state != "closed" && state != "all" {
1014		state = "open"
1015	}
1016	readable, err := control.ReadableScope(s.st, s.viewer(r), p.Repo)
1017	if err != nil {
1018		http.Error(w, "internal error", http.StatusInternalServerError)
1019		return
1020	}
1021	ms, err := s.st.ListMilestones(p.Repo, state, readable)
1022	if err != nil {
1023		http.Error(w, "internal error", http.StatusInternalServerError)
1024		return
1025	}
1026	type msView struct {
1027		store.Milestone
1028		Percent int
1029	}
1030	var views []msView
1031	for _, m := range ms {
1032		v := msView{Milestone: m}
1033		if total := m.OpenItems + m.ClosedItems; total > 0 {
1034			v.Percent = m.ClosedItems * 100 / total
1035		}
1036		views = append(views, v)
1037	}
1038	s.render(w, "milestones.html", struct {
1039		repoPage
1040		State      string
1041		Milestones []msView
1042		CanWrite   bool
1043		Notice     string
1044	}{p, state, views, s.canWriteRepo(r, p.Repo), s.takeFlash(w, r)})
1045}
1046
1047// search runs a bounded literal git grep over the repo's default branch.
1048func (s *Server) search(w http.ResponseWriter, r *http.Request) {
1049	p, ok := s.repoFor(w, r, "")
1050	if !ok {
1051		return
1052	}
1053	p.Tab = "search"
1054	q := strings.TrimSpace(r.URL.Query().Get("q"))
1055	type matchView struct {
1056		Path     string
1057		Line     int
1058		TextHTML template.HTML
1059	}
1060	var matches []matchView
1061	var queryErr string
1062	if q != "" {
1063		if len(q) < 2 || len(q) > 200 {
1064			queryErr = "query must be 2 to 200 characters"
1065		} else if _, err := gitutil.ResolveRef(p.Dir, p.Ref); err == nil {
1066			raw, err := gitutil.Grep(p.Dir, p.Ref, q, 200)
1067			if err != nil {
1068				http.Error(w, "internal error", http.StatusInternalServerError)
1069				return
1070			}
1071			for _, m := range raw {
1072				matches = append(matches, matchView{m.Path, m.Line, markMatch(m.Text, q)})
1073			}
1074		}
1075	}
1076	s.render(w, "search.html", struct {
1077		repoPage
1078		Query    string
1079		QueryErr string
1080		Matches  []matchView
1081		Capped   bool
1082	}{p, q, queryErr, matches, len(matches) == 200})
1083}
1084
1085// markMatch escapes a matched line and wraps case-insensitive occurrences
1086// of the query in <mark>.
1087func markMatch(text, q string) template.HTML {
1088	lower, lq := strings.ToLower(text), strings.ToLower(q)
1089	var b strings.Builder
1090	pos := 0
1091	for {
1092		i := strings.Index(lower[pos:], lq)
1093		if i < 0 {
1094			break
1095		}
1096		i += pos
1097		b.WriteString(template.HTMLEscapeString(text[pos:i]))
1098		b.WriteString("<mark>")
1099		b.WriteString(template.HTMLEscapeString(text[i : i+len(q)]))
1100		b.WriteString("</mark>")
1101		pos = i + len(q)
1102	}
1103	b.WriteString(template.HTMLEscapeString(text[pos:]))
1104	return template.HTML(b.String())
1105}
1106
1107func (s *Server) blame(w http.ResponseWriter, r *http.Request) {
1108	p, ok := s.repoFor(w, r, r.PathValue("ref"))
1109	if !ok {
1110		return
1111	}
1112	p.Tab = "files"
1113	filePath := strings.Trim(r.PathValue("path"), "/")
1114
1115	// Blame is a control command; the web renders what it returns rather
1116	// than shelling out to git itself, so all three surfaces agree.
1117	page := 1
1118	if n, err := strconv.Atoi(r.URL.Query().Get("page")); err == nil && n >= 1 {
1119		page = n
1120	}
1121	from := (page-1)*control.BlameSpan + 1
1122
1123	var out struct {
1124		From       int `json:"from"`
1125		To         int `json:"to"`
1126		TotalLines int `json:"total_lines"`
1127		Hunks      []struct {
1128			SHA         string   `json:"sha"`
1129			AuthorName  string   `json:"author_name"`
1130			AuthorEmail string   `json:"author_email"`
1131			Date        string   `json:"date"`
1132			Summary     string   `json:"summary"`
1133			StartLine   int      `json:"start_line"`
1134			Lines       []string `json:"lines"`
1135		} `json:"hunks"`
1136	}
1137	argv := []string{"repo", "blame", p.Repo.Path(), filePath,
1138		"--ref", p.Ref, "--from", strconv.Itoa(from), "--to", strconv.Itoa(from + control.BlameSpan - 1)}
1139	var viewer store.User
1140	if s.cfg.Web.Mode == "accounts" {
1141		viewer = s.viewer(r)
1142	}
1143	msg, ok := s.runControlInto(viewer, argv, &out)
1144
1145	// A binary or empty file is a refusal, not a 404: the page still
1146	// renders and says why there is nothing to attribute.
1147	binary := false
1148	if !ok {
1149		if strings.Contains(msg, "is binary") {
1150			binary = true
1151		} else {
1152			s.notFound(w, r)
1153			return
1154		}
1155	}
1156
1157	type hunkView struct {
1158		gitutil.BlameHunk
1159		ShortSHA  string
1160		ParentSHA string
1161		Date      string
1162		Sig       sigView
1163		Numbered  []numberedLine
1164	}
1165	blameLexer := lexers.Match(filePath)
1166	var hunks []hunkView
1167	sigs := map[string]sigView{}
1168	parents := map[string]string{}
1169	for _, h := range out.Hunks {
1170		v, seen := sigs[h.SHA]
1171		if !seen {
1172			v, _ = s.sigFor(p.Repo, p.Dir, h.SHA)
1173			sigs[h.SHA] = v
1174			if ps := gitutil.Parents(p.Dir, h.SHA); len(ps) > 0 {
1175				parents[h.SHA] = ps[0]
1176			}
1177		}
1178		date := h.Date
1179		if t, err := time.Parse(time.RFC3339, h.Date); err == nil {
1180			date = t.Format(time.RFC3339)
1181		}
1182		hv := hunkView{
1183			BlameHunk: gitutil.BlameHunk{SHA: h.SHA, AuthorName: h.AuthorName,
1184				AuthorEmail: h.AuthorEmail, Summary: h.Summary,
1185				StartLine: h.StartLine, Lines: h.Lines},
1186			ShortSHA: h.SHA[:min(10, len(h.SHA))], ParentSHA: parents[h.SHA], Date: date, Sig: v,
1187		}
1188		var hl []template.HTML
1189		if blameLexer != nil && len(h.Lines) > 0 {
1190			hl = highlightLines(blameLexer, strings.Join(h.Lines, "\n")+"\n")
1191		}
1192		for i, l := range h.Lines {
1193			var code template.HTML
1194			if i < len(hl) {
1195				code = hl[i]
1196			}
1197			hv.Numbered = append(hv.Numbered, numberedLine{h.StartLine + i, l, code})
1198		}
1199		hunks = append(hunks, hv)
1200	}
1201
1202	pages := (out.TotalLines + control.BlameSpan - 1) / control.BlameSpan
1203	if pages == 0 {
1204		pages = 1
1205	}
1206	if page > pages {
1207		page = pages
1208	}
1209
1210	cs := crumbs(p, "blame", filePath)
1211	base := ""
1212	if len(cs) > 0 {
1213		base = cs[len(cs)-1].Name
1214		cs = cs[:len(cs)-1]
1215	}
1216	navEntries, _ := gitutil.ListTree(p.Dir, p.Ref, navDir(filePath))
1217	nav := fileNavFor(p.Repo.Path(), p.Ref, filePath, navEntries)
1218	s.render(w, "blame.html", struct {
1219		repoPage
1220		Crumbs      []crumb
1221		Base        string
1222		Path        string
1223		Binary      bool
1224		Hunks       []hunkView
1225		Page, Pages int
1226		Nav         fileNav
1227	}{p, cs, base, filePath, binary, hunks, page, pages, nav})
1228}
1229
1230type numberedLine struct {
1231	N    int
1232	Text string
1233	Code template.HTML
1234}
1235
1236// chromaFormatter emits class-based markup (no inline colors), so the
1237// stylesheet can swap palettes with the color scheme.
1238var chromaFormatter = html.New(html.WithClasses(true),
1239	html.WithLineNumbers(true), html.LineNumbersInTable(false),
1240	html.WithLinkableLineNumbers(true, "L"))
1241
1242// chromaFormatterPlain is chromaFormatter without linkable line numbers,
1243// for a page that highlights more than one file: linkable ids are
1244// per-file line numbers, so several files on one page would repeat
1245// id="L1", id="L2", ...
1246var chromaFormatterPlain = html.New(html.WithClasses(true),
1247	html.WithLineNumbers(true), html.LineNumbersInTable(false))
1248
1249func highlight(filePath string, data []byte) template.HTML {
1250	return highlightWith(chromaFormatter, filePath, data)
1251}
1252
1253func highlightPlain(filePath string, data []byte) template.HTML {
1254	return highlightWith(chromaFormatterPlain, filePath, data)
1255}
1256
1257func highlightWith(formatter *html.Formatter, filePath string, data []byte) template.HTML {
1258	lexer := lexers.Match(filePath)
1259	if lexer == nil {
1260		lexer = lexers.Fallback
1261	}
1262	iterator, err := lexer.Tokenise(nil, string(data))
1263	if err != nil {
1264		return template.HTML("<pre>" + template.HTMLEscapeString(string(data)) + "</pre>")
1265	}
1266	var buf bytes.Buffer
1267	if err := formatter.Format(&buf, styles.Get(lightStyle), iterator); err != nil {
1268		return focusableBlocks(template.HTML("<pre>" + template.HTMLEscapeString(string(data)) + "</pre>"))
1269	}
1270	return focusableBlocks(template.HTML(buf.String()))
1271}
1272
1273// chromaCSS is both syntax palettes, each scoped to the scheme it is for.
1274// The light one cannot be left unscoped: the two palettes do not name the
1275// same token set, and every token github-dark omits would keep its
1276// light-theme colour on a black ground — NameAttribute landed at 2.97:1.
1277// Scoped, an unnamed token inherits the wrapper's colour instead, which is
1278// readable in both. The site's --code-bg stays the background either way.
1279// lightStyle and darkStyle are chosen on measured contrast against the
1280// grounds code actually sits on here — page, code block, and the diff
1281// tints. friendly, the chroma default, put 61 token/ground pairs under
1282// 4.5:1; xcode puts one.
1283const (
1284	lightStyle = "xcode"
1285	darkStyle  = "github-dark"
1286)
1287
1288var chromaCSS = func() []byte {
1289	var light, dark bytes.Buffer
1290	chromaFormatter.WriteCSS(&light, styles.Get(lightStyle))
1291	// xcode's NameAttribute is its one token under 4.5:1 against the diff
1292	// tints (4.51 on additions, 4.38 on deletions); darkened it clears both.
1293	light.WriteString(".chroma .na { color: #6f5a21 }\n")
1294	chromaFormatter.WriteCSS(&dark, styles.Get(darkStyle))
1295	// Each palette applies under its media query unless the page is
1296	// stamped with the other theme, and again, outside any media query,
1297	// when the page is stamped with its own (#232).
1298	var buf bytes.Buffer
1299	buf.WriteString("@media (prefers-color-scheme: light) {\n")
1300	buf.WriteString(scopeChroma(light.String(), `:root:not([data-theme="dark"])`))
1301	buf.WriteString("}\n@media (prefers-color-scheme: dark) {\n")
1302	buf.WriteString(scopeChroma(dark.String(), `:root:not([data-theme="light"])`))
1303	buf.WriteString("}\n")
1304	buf.WriteString(scopeChroma(light.String(), `:root[data-theme="light"]`))
1305	buf.WriteString(scopeChroma(dark.String(), `:root[data-theme="dark"]`))
1306	buf.WriteString(".chroma, .bg { background: transparent !important; }\n")
1307	// Line numbers take the site's own gutter colour in both schemes. Left
1308	// alone they are github-dark's #6e7681 (4.31:1 on the page) in dark and
1309	// chroma's built-in #7f7f7f (3.67:1 on a code block) in light — the
1310	// latter is a formatter fallback, not a style entry, so no palette test
1311	// can see it. !important because the scoped palette rules above outrank
1312	// a bare .chroma .ln.
1313	buf.WriteString(".chroma .lnt, .chroma .ln { color: var(--muted) !important }\n")
1314	return buf.Bytes()
1315}()
1316
1317func (s *Server) raw(w http.ResponseWriter, r *http.Request) {
1318	p, ok := s.repoFor(w, r, r.PathValue("ref"))
1319	if !ok {
1320		return
1321	}
1322	filePath := strings.Trim(r.PathValue("path"), "/")
1323	oid, err := gitutil.BlobID(p.Dir, p.Ref, filePath)
1324	if err != nil {
1325		s.notFound(w, r)
1326		return
1327	}
1328	if blobNotModified(w, r, p.Repo, p.Ref, oid) {
1329		return
1330	}
1331	data, err := gitutil.ReadBlob(p.Dir, p.Ref, filePath, s.cfg.Limits.MaxBlobBytes)
1332	if err != nil {
1333		s.notFound(w, r)
1334		return
1335	}
1336	// Serve inert: never let repo content execute in the forge's origin.
1337	// Images get their real type so <img> works under nosniff; SVG script
1338	// is dead on arrival because the instance CSP is script-src 'none'.
1339	ct := "text/plain; charset=utf-8"
1340	if t, ok := imageTypes[strings.ToLower(path.Ext(filePath))]; ok {
1341		ct = t
1342	}
1343	w.Header().Set("Content-Type", ct)
1344	w.Header().Set("X-Content-Type-Options", "nosniff")
1345	w.Write(data)
1346}
1347
1348// blobNotModified sets the caching headers for blob oid served at ref and
1349// writes a 304 when the request already holds it. The ETag is the blob id,
1350// so a revalidation costs one object lookup. A full commit sha cannot
1351// change what it names, so that response is immutable; a branch or tag is
1352// revalidated on every use. Private content stays out of shared caches.
1353func blobNotModified(w http.ResponseWriter, r *http.Request, repo store.Repo, ref, oid string) bool {
1354	scope := "public"
1355	if repo.Visibility == "private" {
1356		scope = "private"
1357	}
1358	if fullSHA(ref) {
1359		w.Header().Set("Cache-Control", scope+", max-age=31536000, immutable")
1360	} else {
1361		w.Header().Set("Cache-Control", scope+", no-cache")
1362	}
1363	etag := `"` + oid + `"`
1364	w.Header().Set("ETag", etag)
1365	if match := r.Header.Get("If-None-Match"); match != "" && etagMatches(match, etag) {
1366		w.WriteHeader(http.StatusNotModified)
1367		return true
1368	}
1369	return false
1370}
1371
1372// fullSHA reports whether ref is a whole SHA-1 or SHA-256 object name.
1373func fullSHA(ref string) bool {
1374	if len(ref) != 40 && len(ref) != 64 {
1375		return false
1376	}
1377	for i := 0; i < len(ref); i++ {
1378		if c := ref[i]; (c < '0' || c > '9') && (c < 'a' || c > 'f') {
1379			return false
1380		}
1381	}
1382	return true
1383}
1384
1385// imageTypes are the formats raw serves with a real content type and blob
1386// pages preview inline.
1387var imageTypes = map[string]string{
1388	".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
1389	".gif": "image/gif", ".webp": "image/webp", ".avif": "image/avif",
1390	".svg": "image/svg+xml", ".ico": "image/x-icon",
1391}
1392
1393// markdown is the shared renderer: GFM (tables, strikethrough, autolinks,
1394// task lists) on top of CommonMark, with class-based fence highlighting
1395// (the palette lives in the stylesheet, per scheme), and TeX math as
1396// MathML (math.go). Raw HTML is still dropped.
1397// Headings carry ids so a README or wiki section can be linked to, the
1398// way org headings already are (#132).
1399var markdown = goldmark.New(
1400	goldmark.WithParserOptions(parser.WithAutoHeadingID()),
1401	goldmark.WithExtensions(extension.GFM, mathExtension{},
1402		highlighting.NewHighlighting(highlighting.WithFormatOptions(html.WithClasses(true)))))
1403
1404// fenceHighlight renders one code block with chroma classes, for org and
1405// anything else outside goldmark. Unknown languages fall back to plain.
1406func fenceHighlight(source, lang string) string {
1407	lexer := lexers.Get(lang)
1408	if lexer == nil {
1409		lexer = lexers.Fallback
1410	}
1411	iterator, err := lexer.Tokenise(nil, source)
1412	if err != nil {
1413		return "<pre>" + template.HTMLEscapeString(source) + "</pre>"
1414	}
1415	var buf bytes.Buffer
1416	f := html.New(html.WithClasses(true))
1417	if err := f.Format(&buf, styles.Get(lightStyle), iterator); err != nil {
1418		return "<pre>" + template.HTMLEscapeString(source) + "</pre>"
1419	}
1420	return buf.String()
1421}
1422
1423// mdHTML renders user-authored markdown (issue and MR bodies, comments).
1424// goldmark's default renderer drops raw HTML, so this is safe as-is.
1425func mdHTML(raw string) template.HTML {
1426	if strings.TrimSpace(raw) == "" {
1427		return ""
1428	}
1429	var buf bytes.Buffer
1430	if markdown.Convert([]byte(raw), &buf) != nil {
1431		return focusableBlocks(template.HTML("<pre>" + template.HTMLEscapeString(raw) + "</pre>"))
1432	}
1433	return focusableBlocks(template.HTML(buf.String()))
1434}
1435
1436// aboutHTML renders a profile's about text. The format comes from the
1437// file it was read from: org is org, anything else markdown.
1438func aboutHTML(text, format string) template.HTML {
1439	if strings.TrimSpace(text) == "" {
1440		return ""
1441	}
1442	name := "about.md"
1443	if format == "org" {
1444		name = "about.org"
1445	}
1446	return renderReadme(name, []byte(text))
1447}
1448
1449// webResolver answers autolink lookups for one viewer. Cross-repo
1450// references to repositories the viewer cannot read stay plain text, per
1451// the enumeration rule: a link would confirm the repo exists.
1452type webResolver struct {
1453	s      *Server
1454	viewer store.User
1455}
1456
1457func (r webResolver) RefURL(owner, name string, kind byte, n int64) string {
1458	repo, err := r.s.st.RepoByPath(owner + "/" + name)
1459	if err != nil {
1460		return ""
1461	}
1462	grant := ""
1463	if r.viewer.ID != 0 {
1464		grant, _ = r.s.st.AccessRole(repo.ID, r.viewer.ID)
1465	}
1466	if !policy.CanRead(r.viewer, repo, grant) {
1467		return ""
1468	}
1469	if kind == '#' {
1470		if _, err := r.s.st.IssueByNumber(repo.ID, n); err != nil {
1471			return ""
1472		}
1473		return autolink.IssueURL(repo.OwnerName, repo.Name, n)
1474	}
1475	if _, err := r.s.st.MRByNumber(repo.ID, n); err != nil {
1476		return ""
1477	}
1478	return autolink.MRURL(repo.OwnerName, repo.Name, n)
1479}
1480
1481func (r webResolver) UserURL(name string) string {
1482	if _, err := r.s.st.UserByUsername(name); err == nil {
1483		return "/" + name
1484	}
1485	if _, err := r.s.st.OrgByName(name); err == nil {
1486		return "/" + name
1487	}
1488	return ""
1489}
1490
1491// ugcRenderer renders one user-authored body in the format it was written in.
1492// The format travels with the body: it is recorded when the text is written, so
1493// changing a preference later cannot re-interpret prose that already exists.
1494type ugcRenderer func(raw, format string) template.HTML
1495
1496// ugcHTML renders a user-authored body. Anything other than "org" is markdown,
1497// so a body stored before formats existed — and any row whose column defaulted —
1498// renders exactly as it did before.
1499//
1500// Org goes through renderReadme, the same path READMEs, wiki pages and profile
1501// about text take, so it inherits that function's include guard and sanitising
1502// rather than growing a second org renderer to keep in step.
1503func ugcHTML(raw, format string) template.HTML {
1504	if format == "org" {
1505		return focusableBlocks(renderOrg("body.org", []byte(raw), false, func() template.HTML {
1506			return template.HTML("<pre>" + template.HTMLEscapeString(raw) + "</pre>")
1507		}))
1508	}
1509	return mdHTML(raw)
1510}
1511
1512// ugcFor returns a renderer for user-authored bodies on one repo's pages:
1513// ugcHTML plus cross-reference and mention autolinking for this viewer.
1514func (s *Server) ugcFor(r *http.Request, repo store.Repo) ugcRenderer {
1515	viewer := store.User{}
1516	if s.cfg.Web.Mode == "accounts" {
1517		viewer = s.viewer(r)
1518	}
1519	res := webResolver{s, viewer}
1520	return func(raw, format string) template.HTML {
1521		h := ugcHTML(raw, format)
1522		if h == "" {
1523			return h
1524		}
1525		return template.HTML(autolink.Rewrite(string(h), repo.OwnerName, repo.Name, res))
1526	}
1527}
1528
1529// renderedComment pairs a comment with its rendered body for templates.
1530type renderedComment struct {
1531	ID        int64
1532	Author    string
1533	CreatedAt string
1534	Kind      string
1535	BodyHTML  template.HTML
1536}
1537
1538func renderComments(cs []store.IssueComment, ugc ugcRenderer) []renderedComment {
1539	var out []renderedComment
1540	for _, c := range cs {
1541		out = append(out, renderedComment{ID: c.ID, Author: c.Author, CreatedAt: c.CreatedAt, Kind: c.Kind, BodyHTML: ugc(c.Body, c.BodyFormat)})
1542	}
1543	return out
1544}
1545
1546// ugcPolicy sanitizes rendered repo content before it enters the forge's
1547// origin: markdown is already safe (goldmark drops raw HTML), but org-mode
1548// output and repo-authored HTML are not. Chroma's highlighting classes
1549// must survive; the pattern admits only short token codes, not the site's
1550// own class names.
1551var ugcPolicy = func() *bluemonday.Policy {
1552	p := bluemonday.UGCPolicy()
1553	p.AllowAttrs("class").
1554		Matching(regexp.MustCompile(`^(chroma|[a-z0-9]{1,3})( (chroma|[a-z0-9]{1,3}))*$`)).
1555		OnElements("span", "pre", "code", "div")
1556	return p
1557}()
1558
1559// renderReadme renders a README by extension: markdown, org-mode, and
1560// (sanitized) HTML richly; everything else as escaped plaintext.
1561// orgConfig is the go-org configuration for rendering untrusted org.
1562//
1563// go-org's default reads #+INCLUDE: and #+SETUPFILE: targets off disk with
1564// os.ReadFile. Everything rendered here is content someone pushed — a README, a
1565// wiki page, a profile — so both keywords are refused outright: the file is
1566// never opened and the keyword stays the inert text it is. There is no safe
1567// subset to allow instead. An absolute path skips go-org's relative-path join,
1568// a relative one resolves against the daemon's working directory, and a repo
1569// has no directory to scope to anyway because the content came from a git
1570// object rather than a checkout.
1571//
1572// The default logger writes parse warnings to stderr, which would let pushed
1573// content write to the server's log; discard them.
1574func orgConfig() *org.Configuration {
1575	c := org.New()
1576	c.ReadFile = func(string) ([]byte, error) {
1577		return nil, errOrgIncludeDisabled
1578	}
1579	c.Log = log.New(io.Discard, "", 0)
1580	return c
1581}
1582
1583var errOrgIncludeDisabled = errors.New("org: #+INCLUDE and #+SETUPFILE are disabled")
1584
1585// renderOrg renders org to sanitized HTML. `contents` asks go-org for its table
1586// of contents: a README or wiki page is a document and carries one, an issue
1587// comment is a remark and should not sprout one above two headings. `fallback`
1588// supplies the plaintext rendering used when the writer fails.
1589func renderOrg(name string, raw []byte, contents bool, fallback func() template.HTML) template.HTML {
1590	c := orgConfig()
1591	if !contents {
1592		// DefaultSettings is a fresh map per org.New(), so this is local.
1593		c.DefaultSettings["OPTIONS"] = strings.ReplaceAll(c.DefaultSettings["OPTIONS"], "toc:t", "toc:nil")
1594	}
1595	doc := c.Parse(bytes.NewReader(raw), name)
1596	writer := org.NewHTMLWriter()
1597	writer.HighlightCodeBlock = func(source, lang string, inline bool, params map[string]string) string {
1598		if inline {
1599			return "<code>" + template.HTMLEscapeString(source) + "</code>"
1600		}
1601		return fenceHighlight(source, lang)
1602	}
1603	ow := &orgWriter{HTMLWriter: writer, math: newMathSlots()}
1604	writer.ExtendingWriter = ow
1605	out, err := doc.Write(writer)
1606	if err != nil {
1607		return fallback()
1608	}
1609	return imageAlt(template.HTML(ow.math.fill(ugcPolicy.Sanitize(out))))
1610}
1611
1612// orgWriter overrides go-org's autolink rendering. go-org ends a bare URL
1613// at the first character outside RFC 3986's set, and that set includes
1614// `.`, `,` and `)`, so a URL closing a sentence or a parenthesis took the
1615// punctuation with it. Org stops a plain link before trailing punctuation
1616// and keeps a `)` only when a `(` inside the link opened it. It also
1617// renders LaTeX fragments and blocks (math.go).
1618type orgWriter struct {
1619	*org.HTMLWriter
1620	math *mathSlots
1621}
1622
1623func (w *orgWriter) WriteRegularLink(l org.RegularLink) {
1624	if !l.AutoLink {
1625		w.HTMLWriter.WriteRegularLink(l)
1626		return
1627	}
1628	url, rest := splitAutolinkPunctuation(l.URL)
1629	l.URL = url
1630	w.HTMLWriter.WriteRegularLink(l)
1631	if rest != "" {
1632		w.WriteText(org.Text{Content: rest})
1633	}
1634}
1635
1636// splitAutolinkPunctuation returns the URL without trailing sentence
1637// punctuation, and the punctuation it removed.
1638func splitAutolinkPunctuation(url string) (string, string) {
1639	end := len(url)
1640	for end > 0 {
1641		switch url[end-1] {
1642		case '.', ',', ';', ':', '!', '?', '\'', '"':
1643			end--
1644			continue
1645		case ')':
1646			if strings.Count(url[:end], ")") > strings.Count(url[:end], "(") {
1647				end--
1648				continue
1649			}
1650		}
1651		break
1652	}
1653	return url[:end], url[end:]
1654}
1655
1656// headingTag matches an opening or closing h1..h5 tag, so a rendered
1657// document's headings can move down one level.
1658var headingTag = regexp.MustCompile(`<(/?)h([1-5])([\s>])`)
1659
1660// demoteHeadings moves every heading in a rendered document down one
1661// level: the page it sits on already has its h1 (the repository, the
1662// file, the wiki page), so a README's own h1 would be a second top-level
1663// heading in the outline (#133). Ids and anchors are untouched.
1664func demoteHeadings(h template.HTML) template.HTML {
1665	return template.HTML(headingTag.ReplaceAllStringFunc(string(h), func(m string) string {
1666		sub := headingTag.FindStringSubmatch(m)
1667		return "<" + sub[1] + "h" + string(rune(sub[2][0]+1)) + sub[3]
1668	}))
1669}
1670
1671func renderReadme(name string, raw []byte) template.HTML {
1672	plain := func() template.HTML {
1673		return template.HTML("<pre>" + template.HTMLEscapeString(string(raw)) + "</pre>")
1674	}
1675	if gitutil.IsBinary(raw) {
1676		return ""
1677	}
1678	var out template.HTML
1679	switch path.Ext(strings.ToLower(name)) {
1680	case ".md", ".markdown":
1681		var buf bytes.Buffer
1682		if markdown.Convert(raw, &buf) != nil {
1683			return focusableBlocks(plain())
1684		}
1685		out = demoteHeadings(template.HTML(buf.String()))
1686	case ".org":
1687		out = demoteHeadings(renderOrg(name, raw, true, plain))
1688	case ".html", ".htm":
1689		out = template.HTML(ugcPolicy.Sanitize(string(raw)))
1690	default:
1691		out = plain()
1692	}
1693	return focusableBlocks(out)
1694}
1695
1696type diffThread struct {
1697	ID       int64
1698	Resolved string
1699	Stale    bool
1700	// Pending marks a thread in the viewer's own unsubmitted review. Only
1701	// they are shown it, and the page says so, since it looks exactly
1702	// like a posted one otherwise.
1703	Pending    bool
1704	CanResolve bool
1705	Comments   []renderedComment
1706	Suggestion *suggestionView
1707}
1708
1709// suggestionView is a thread's suggestion as the page shows it: the lines
1710// it replaces and the ones it proposes, numbered from Start, and whether
1711// the viewer can apply it here or needs the CLI.
1712type suggestionView struct {
1713	Start    int64
1714	Old, New []suggestionLine
1715	Outdated bool
1716	Reason   string
1717	Local    bool   // the repositories require signed commits: apply from a clone
1718	CanApply bool   // the viewer can push to the source branch of an open MR
1719	Command  string // the CLI command that applies it
1720}
1721
1722type suggestionLine struct {
1723	N    int64
1724	Text string
1725}
1726
1727// newSuggestionView lays out s for the page.
1728func newSuggestionView(s *control.SuggestionOut, canApply bool, command string) *suggestionView {
1729	v := &suggestionView{Start: s.StartLine, Outdated: s.Outdated, Reason: s.Reason,
1730		Local: s.Apply == "local", CanApply: canApply, Command: command}
1731	for i, l := range suggest.FromText(strings.ReplaceAll(s.Original, "\r\n", "\n")) {
1732		v.Old = append(v.Old, suggestionLine{s.StartLine + int64(i), l})
1733	}
1734	for i, l := range suggest.FromText(s.Replacement) {
1735		v.New = append(v.New, suggestionLine{s.StartLine + int64(i), l})
1736	}
1737	return v
1738}
1739
1740// reviewRights decides which thread controls a viewer sees. mr resolve
1741// admits the thread author, the MR author, or anyone with write, so the
1742// page needs all three to render the button truthfully.
1743type reviewRights struct {
1744	Viewer   string
1745	MRAuthor string
1746	Write    bool
1747}
1748
1749func (r reviewRights) canResolve(threadAuthor string) bool {
1750	return r.Viewer != "" && (r.Write || r.Viewer == r.MRAuthor || r.Viewer == threadAuthor)
1751}
1752
1753// attachThreads injects review threads under their anchored diff lines;
1754// threads whose anchor no longer appears (stale after force-push, or on a
1755// context line outside the current diff) are returned separately. A
1756// thread root in suggestions renders its suggestion as a diff, and its
1757// body without the block.
1758func attachThreads(files []diffFile, comments []store.DiffComment, headSHA string, md ugcRenderer, rights reviewRights, suggestions map[int64]*suggestionView) ([]diffFile, []diffThread) {
1759	type anchor struct {
1760		path string
1761		side string
1762		line int64
1763	}
1764	// Diff-line comments have no stored format yet, so they stay markdown.
1765	// They are the one user-authored body left without the choice; see #51.
1766	threads := map[int64]*diffThread{}
1767	anchors := map[int64]anchor{}
1768	var order []int64
1769	for _, cm := range comments {
1770		if cm.ReplyTo == 0 {
1771			body := cm.Body
1772			if suggestions[cm.ID] != nil {
1773				body = suggest.Strip(body)
1774			}
1775			threads[cm.ID] = &diffThread{ID: cm.ID, Resolved: cm.ResolvedBy, Stale: cm.HeadSHA != headSHA,
1776				Pending:    cm.Pending,
1777				CanResolve: rights.canResolve(cm.Author),
1778				Suggestion: suggestions[cm.ID],
1779				Comments:   []renderedComment{{Author: cm.Author, CreatedAt: cm.CreatedAt, BodyHTML: md(body, "md")}}}
1780			anchors[cm.ID] = anchor{cm.Path, cm.Side, cm.Line}
1781			order = append(order, cm.ID)
1782		} else if th, ok := threads[cm.ReplyTo]; ok {
1783			th.Comments = append(th.Comments, renderedComment{Author: cm.Author, CreatedAt: cm.CreatedAt, BodyHTML: md(cm.Body, "md")})
1784		}
1785	}
1786	placed := map[int64]bool{}
1787	for f := range files {
1788		lines := files[f].Lines
1789		for i := range lines {
1790			for _, id := range order {
1791				if placed[id] || threads[id].Stale {
1792					continue
1793				}
1794				a := anchors[id]
1795				if lines[i].Path != a.path {
1796					continue
1797				}
1798				if (a.side == "new" && lines[i].NewLine == a.line && lines[i].Class != "del") ||
1799					(a.side == "old" && lines[i].OldLine == a.line && lines[i].Class == "del") {
1800					lines[i].Threads = append(lines[i].Threads, *threads[id])
1801					files[f].Threads++
1802					files[f].Open = true
1803					placed[id] = true
1804				}
1805			}
1806		}
1807	}
1808	var unplaced []diffThread
1809	for _, id := range order {
1810		if !placed[id] {
1811			unplaced = append(unplaced, *threads[id])
1812		}
1813	}
1814	return files, unplaced
1815}
1816
1817// markCompose opens the new-thread form under one diff line. There is no
1818// JavaScript, so "comment on this line" is a plain GET carrying the
1819// anchor and the page renders the form where the reader asked for it.
1820func markCompose(files []diffFile, q url.Values) {
1821	path := q.Get("cpath")
1822	line, _ := strconv.ParseInt(q.Get("cline"), 10, 64)
1823	if path == "" || line < 1 {
1824		return
1825	}
1826	old := q.Get("cside") == "old"
1827	for f := range files {
1828		for i := range files[f].Lines {
1829			ln := &files[f].Lines[i]
1830			if ln.Path != path {
1831				continue
1832			}
1833			if (old && ln.Class == "del" && ln.OldLine == line) ||
1834				(!old && ln.Class != "del" && ln.NewLine == line) {
1835				ln.Compose = true
1836				files[f].Open = true
1837				return
1838			}
1839		}
1840	}
1841}
1842
1843type sigView struct {
1844	State       string
1845	Signer      string
1846	Fingerprint string
1847}
1848
1849func (s *Server) sigFor(repo store.Repo, dir, sha string) (sigView, *sig.Commit) {
1850	raw, err := gitutil.ReadCommit(dir, sha)
1851	if err != nil {
1852		return sigView{State: "unsigned"}, nil
1853	}
1854	parsed, err := sig.ParseCommit(raw)
1855	if err != nil {
1856		return sigView{State: "unsigned"}, nil
1857	}
1858	res, err := control.VerifyCommitCached(s.st, repo, parsed, sha)
1859	if err != nil {
1860		return sigView{State: "unsigned"}, parsed
1861	}
1862	v := sigView{State: string(res.State), Fingerprint: res.KeyFingerprint}
1863	if res.SignerUserID != 0 {
1864		if u, err := s.st.UserByID(res.SignerUserID); err == nil {
1865			v.Signer = u.Username
1866		}
1867	}
1868	return v, parsed
1869}
1870
1871func (s *Server) log(w http.ResponseWriter, r *http.Request) {
1872	ref := r.PathValue("ref")
1873	p, ok := s.repoFor(w, r, ref)
1874	if !ok {
1875		return
1876	}
1877	p.Tab = "log"
1878	p.Feed = "/" + p.Repo.Path() + "/log.atom/" + p.Ref
1879	const pageSize = 50
1880	// ?path= filters to commits touching one file or directory.
1881	filePath := strings.Trim(path.Clean("/"+r.URL.Query().Get("path")), "/")
1882	if filePath == "." {
1883		filePath = ""
1884	}
1885	var shas []string
1886	var err error
1887	if filePath != "" {
1888		shas, err = gitutil.RevListPath(p.Dir, p.Ref, filePath, pageSize+1)
1889	} else {
1890		shas, err = gitutil.RevList(p.Dir, p.Ref, pageSize+1)
1891	}
1892	if err != nil {
1893		s.notFound(w, r)
1894		return
1895	}
1896	next := ""
1897	if len(shas) > pageSize {
1898		next = shas[pageSize]
1899		shas = shas[:pageSize]
1900	}
1901	type row struct {
1902		SHA, ShortSHA, Subject, AuthorName, AuthorEmail, AuthorUser, Date string
1903		Sig                                                               sigView
1904		Check                                                             string // combined status, "" when none ran
1905	}
1906	names := s.authorNames()
1907	checks, _ := s.st.CombinedStatusFor(p.Repo.ID, shas)
1908	var rows []row
1909	for _, sha := range shas {
1910		v, parsed := s.sigFor(p.Repo, p.Dir, sha)
1911		rw := row{SHA: sha, ShortSHA: sha[:10], Sig: v, Check: checks[sha]}
1912		if parsed != nil {
1913			rw.Subject = parsed.Subject
1914			rw.AuthorName = names.name(parsed.AuthorEmail, parsed.AuthorName)
1915			rw.AuthorUser, _ = names.account(parsed.AuthorEmail)
1916			rw.AuthorEmail = parsed.AuthorEmail
1917			rw.Date = time.Unix(parsed.AuthorUnix, 0).UTC().Format(time.RFC3339)
1918		}
1919		rows = append(rows, rw)
1920	}
1921	s.render(w, "log.html", struct {
1922		repoPage
1923		Commits  []row
1924		NextSHA  string
1925		FilePath string
1926	}{p, rows, next, filePath})
1927}
1928
1929func (s *Server) commit(w http.ResponseWriter, r *http.Request) {
1930	p, ok := s.repoFor(w, r, "")
1931	if !ok {
1932		return
1933	}
1934	p.Tab = "log"
1935	sha := r.PathValue("sha")
1936	full, err := gitutil.ResolveRef(p.Dir, sha)
1937	if err != nil {
1938		s.notFound(w, r)
1939		return
1940	}
1941	v, parsed := s.sigFor(p.Repo, p.Dir, full)
1942	if parsed == nil {
1943		s.notFound(w, r)
1944		return
1945	}
1946	patch, truncated, _ := gitutil.ShowPatch(p.Dir, full, 4<<20)
1947	files := parseDiff(patch)
1948	layout := s.diffLayoutFor(r)
1949	if layout.Split {
1950		splitFiles(files)
1951	}
1952	committerEmail := ""
1953	if parsed.CommitterEmail != parsed.AuthorEmail {
1954		committerEmail = parsed.CommitterEmail
1955	}
1956	checks, _ := s.st.ListCommitStatuses(p.Repo.ID, full)
1957	commitNames := s.authorNames()
1958	commitUser, _ := commitNames.account(parsed.AuthorEmail)
1959	msg := ""
1960	if i := bytes.Index(parsed.Payload, []byte("\n\n")); i >= 0 {
1961		msg = string(parsed.Payload[i+2:])
1962	}
1963	s.render(w, "commit.html", struct {
1964		repoPage
1965		SHA, ShortSHA, AuthorName, AuthorEmail, AuthorUser, CommitterEmail, Date, Message string
1966		Parents                                                                           []string
1967		Sig                                                                               sigView
1968		Checks                                                                            []store.CommitStatus
1969		DiffFiles                                                                         []diffFile
1970		DiffTruncated                                                                     bool
1971		Layout                                                                            diffLayout
1972	}{p, full, full[:10], commitNames.name(parsed.AuthorEmail, parsed.AuthorName), parsed.AuthorEmail, commitUser, committerEmail,
1973		time.Unix(parsed.AuthorUnix, 0).UTC().Format(time.RFC3339), msg,
1974		gitutil.Parents(p.Dir, full), v, checks, files, truncated, layout})
1975}
1976
1977// labelPalette provides default label chip colors: mid-tone hues that stay
1978// legible on light and dark backgrounds.
1979var labelPalette = []string{
1980	"#0969da", "#1a7f37", "#9a6700", "#cf222e",
1981	"#8250df", "#b93a86", "#0b6c80", "#bf5b16",
1982}
1983
1984var hexColorPat = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
1985
1986// The canvases a chip is drawn on, --canvas in each scheme, and the ratio
1987// its text owes them. Chip text is 12px, which WCAG reads as small text at
1988// 4.5:1. TestChipCanvasMatchesStylesheet keeps these in step with the
1989// tokens.
1990const (
1991	chipCanvasLight = "#f7f8fa"
1992	chipCanvasDark  = "#101114"
1993	chipRatio       = 4.5
1994)
1995
1996// chipTones returns a user-set label colour as it is drawn in each scheme.
1997// The chip's ground is mixed from the colour itself, and the luminance
1998// band that clears 4.5:1 on white ends below the band that clears it on
1999// the dark canvas, so one colour cannot serve both and each label carries
2000// two (#226, replacing the single clamp of #120). The hue is kept — the
2001// channels are scaled in linear light — and only a colour too dark to
2002// brighten any further, a saturated blue, is blended on toward white.
2003func chipTones(hex string) (light, dark string) {
2004	return chipTone(hex, chipCanvasLight, false), chipTone(hex, chipCanvasDark, true)
2005}
2006
2007// chipTone walks the colour along its ramp until it clears the ratio,
2008// stopping at the first tone that does: contrast rises with the distance
2009// travelled, so the bisection finds the tone nearest the one asked for.
2010func chipTone(hex, canvas string, up bool) string {
2011	if chipContrast(strings.ToLower(hex), canvas) >= chipRatio {
2012		return strings.ToLower(hex)
2013	}
2014	lo, hi := 0.0, 1.0
2015	for i := 0; i < 24; i++ {
2016		mid := (lo + hi) / 2
2017		if chipContrast(chipStep(hex, mid, up), canvas) >= chipRatio {
2018			hi = mid
2019		} else {
2020			lo = mid
2021		}
2022	}
2023	return chipStep(hex, hi, up)
2024}
2025
2026// chipStep is the colour s of the way along its ramp: down to black on a
2027// light canvas, and on a dark one up through the brightest tone that
2028// keeps the hue and from there on to white.
2029func chipStep(hex string, s float64, up bool) string {
2030	r, g, b := chipLinear(hex)
2031	switch m := math.Max(r, math.Max(g, b)); {
2032	case !up:
2033		k := 1 - s
2034		r, g, b = r*k, g*k, b*k
2035	case m == 0: // black has no hue to keep
2036		r, g, b = s, s, s
2037	case s <= 0.5:
2038		k := 1 + (s/0.5)*(1/m-1)
2039		r, g, b = r*k, g*k, b*k
2040	default:
2041		k, t := 1/m, (s-0.5)/0.5
2042		r, g, b = r*k, g*k, b*k
2043		r, g, b = r+t*(1-r), g+t*(1-g), b+t*(1-b)
2044	}
2045	return chipHex(r, g, b)
2046}
2047
2048// chipContrast is the WCAG ratio between a chip colour and its own
2049// ground, color-mix(in srgb, chip 10%, canvas).
2050func chipContrast(hex, canvas string) float64 {
2051	y, g := chipLuminance(hex), chipLuminance(chipGround(hex, canvas))
2052	if y < g {
2053		y, g = g, y
2054	}
2055	return (y + 0.05) / (g + 0.05)
2056}
2057
2058// chipGround mixes a tenth of the chip colour into the canvas, the blend
2059// color-mix(in srgb, ...) makes: gamma-encoded channels, not linear ones.
2060func chipGround(hex, canvas string) string {
2061	mix := func(a, b string) string {
2062		return fmt.Sprintf("%02x", int(math.Round(0.1*float64(hexByte(a))+0.9*float64(hexByte(b)))))
2063	}
2064	return "#" + mix(hex[1:3], canvas[1:3]) + mix(hex[3:5], canvas[3:5]) + mix(hex[5:7], canvas[5:7])
2065}
2066
2067// chipLinear is a #rrggbb colour in linear light, chipHex the way back,
2068// and chipLuminance the WCAG relative luminance of one.
2069func chipLinear(hex string) (r, g, b float64) {
2070	lin := func(c int64) float64 {
2071		v := float64(c) / 255
2072		if v <= 0.04045 {
2073			return v / 12.92
2074		}
2075		return math.Pow((v+0.055)/1.055, 2.4)
2076	}
2077	return lin(hexByte(hex[1:3])), lin(hexByte(hex[3:5])), lin(hexByte(hex[5:7]))
2078}
2079
2080func chipHex(r, g, b float64) string {
2081	enc := func(v float64) int {
2082		v = math.Min(1, math.Max(0, v))
2083		if v <= 0.0031308 {
2084			v *= 12.92
2085		} else {
2086			v = 1.055*math.Pow(v, 1/2.4) - 0.055
2087		}
2088		return int(math.Round(v * 255))
2089	}
2090	return fmt.Sprintf("#%02x%02x%02x", enc(r), enc(g), enc(b))
2091}
2092
2093func chipLuminance(hex string) float64 {
2094	r, g, b := chipLinear(hex)
2095	return 0.2126*r + 0.7152*g + 0.0722*b
2096}
2097
2098func hexByte(s string) int64 {
2099	n, _ := strconv.ParseInt(s, 16, 32)
2100	return n
2101}
2102
2103// labelColors returns a complete label-name -> chip color map for a repo:
2104// the stored labels.color when it is a valid hex color, otherwise a
2105// stable default picked from the palette by name hash.
2106func (s *Server) labelColors(repo store.Repo) map[string]template.CSS {
2107	stored, _ := s.st.LabelColors(repo)
2108	return colorStyles(stored)
2109}
2110
2111// colorStyles turns a label-name -> stored color map into chip styles: the
2112// stored color when it is a valid hex color, otherwise a stable default
2113// picked from the palette by name hash, as a tone per scheme.
2114func colorStyles(stored map[string]string) map[string]template.CSS {
2115	out := make(map[string]template.CSS, len(stored))
2116	for name, color := range stored {
2117		if !hexColorPat.MatchString(color) {
2118			h := fnv.New32a()
2119			h.Write([]byte(name))
2120			color = labelPalette[h.Sum32()%uint32(len(labelPalette))]
2121		}
2122		light, dark := chipTones(color)
2123		out[name] = template.CSS("--chip-l:" + light + ";--chip-d:" + dark)
2124	}
2125	return out
2126}
2127
2128// listPage is how many issues or merge requests a list page shows before
2129// it offers the older ones (#118). Keyset paging on the number, the same
2130// cursor the commands use, so every filter carries across pages.
2131const listPage = 50
2132
2133// olderLink is the current URL with before=<number> set.
2134func olderLink(r *http.Request, before int64) string {
2135	q := r.URL.Query()
2136	q.Set("before", strconv.FormatInt(before, 10))
2137	return "?" + q.Encode()
2138}
2139
2140func (s *Server) issues(w http.ResponseWriter, r *http.Request) {
2141	p, ok := s.repoFor(w, r, "")
2142	if !ok {
2143		return
2144	}
2145	p.Tab = "issues"
2146	state := r.URL.Query().Get("state")
2147	if state != "closed" && state != "all" {
2148		state = "open"
2149	}
2150	// The same filters the CLI's issue list takes, as query parameters;
2151	// label chips and author links point here.
2152	qv := r.URL.Query()
2153	f := store.IssueFilter{State: state, Label: qv.Get("label"), Assignee: qv.Get("assignee"),
2154		Author: qv.Get("author"), Milestone: qv.Get("milestone"),
2155		Search: strings.TrimSpace(qv.Get("q")), Limit: listPage + 1}
2156	f.Before, _ = strconv.ParseInt(qv.Get("before"), 10, 64)
2157	issues, err := s.st.QueryIssues(p.Repo.ID, f)
2158	if err != nil {
2159		http.Error(w, "internal error", http.StatusInternalServerError)
2160		return
2161	}
2162	older := ""
2163	if len(issues) > listPage {
2164		issues = issues[:listPage]
2165		older = olderLink(r, issues[len(issues)-1].Number)
2166	}
2167	ids := make([]int64, len(issues))
2168	for i, iss := range issues {
2169		ids[i] = iss.ID
2170	}
2171	if labels, err := s.st.ListIssueLabels(p.Repo); err == nil {
2172		for i := range issues {
2173			issues[i].Labels = labels[issues[i].ID]
2174		}
2175	}
2176	if _, assignees, err := s.st.IssueLabelsFor(ids); err == nil {
2177		for i := range issues {
2178			issues[i].Assignees = assignees[issues[i].ID]
2179		}
2180	}
2181	commentCounts, err := s.st.IssueCommentCounts(ids)
2182	if err != nil {
2183		commentCounts = map[int64]int{}
2184	}
2185	base := url.Values{"state": {state}, "label": {f.Label}, "assignee": {f.Assignee}, "author": {f.Author}, "milestone": {f.Milestone}, "q": {f.Search}}
2186	readable, _ := control.ReadableScope(s.st, s.viewer(r), p.Repo)
2187	allLabels, _ := s.st.ListLabels(p.Repo, readable)
2188	openMS, _ := s.st.ListMilestones(p.Repo, "open", readable)
2189	facets := listFacets(base, []string{"open", "closed", "all"}, state, allLabels, openMS, false)
2190	s.render(w, "issues.html", struct {
2191		repoPage
2192		State         string
2193		Label         string
2194		Query         string
2195		Filters       []listFilter
2196		Facets        []facetGroup
2197		Issues        []store.Issue
2198		CommentCounts map[int64]int
2199		People        []string
2200		LabelColors   map[string]template.CSS
2201		Older         string
2202	}{p, state, f.Label, f.Search,
2203		activeFilters(state, [][2]string{{"label", f.Label}, {"assignee", f.Assignee}, {"author", f.Author}, {"milestone", f.Milestone}}),
2204		facets, issues, commentCounts, s.repoPeople(p.Repo), s.labelColors(p.Repo), older})
2205}
2206
2207func (s *Server) issue(w http.ResponseWriter, r *http.Request) {
2208	s.issuePage(w, r, "")
2209}
2210
2211// issuePage renders an issue. previewForm names the form that asked to
2212// see its markup rather than save it — "edit" or "comment", "" for a
2213// plain read — and the page renders that draft above the form it came
2214// from, in the format the write would have stored (#235).
2215func (s *Server) issuePage(w http.ResponseWriter, r *http.Request, previewForm string) {
2216	p, ok := s.repoFor(w, r, "")
2217	if !ok {
2218		return
2219	}
2220	p.Tab = "issues"
2221	n, err := strconv.ParseInt(r.PathValue("n"), 10, 64)
2222	if err != nil {
2223		s.notFound(w, r)
2224		return
2225	}
2226	iss, err := s.st.IssueByNumber(p.Repo.ID, n)
2227	if err != nil {
2228		s.notFound(w, r)
2229		return
2230	}
2231	comments, err := s.st.ListIssueComments(iss.ID)
2232	if err != nil {
2233		http.Error(w, "internal error", http.StatusInternalServerError)
2234		return
2235	}
2236	md := s.ugcFor(r, p.Repo)
2237	// An edit keeps the issue's stored format; a comment reads the format picker.
2238	var d *draft
2239	if previewForm != "" {
2240		format := iss.BodyFormat
2241		if previewForm == "comment" {
2242			format = bodyFormat(r)
2243		}
2244		d = s.draftFor(r, p.Repo, previewForm, "body", format)
2245	}
2246	// nil readable: the picker lists titles, never the progress counts.
2247	milestones, _ := s.st.ListMilestones(p.Repo, "open", nil)
2248	allLabels, _ := s.st.ListLabels(p.Repo, nil)
2249	bars := s.reactionBars(r, "issue", iss.ID, comments, fmt.Sprintf("/%s/%s/issues/%d/react", p.Repo.OwnerName, p.Repo.Name, iss.Number))
2250	s.render(w, "issue.html", struct {
2251		repoPage
2252		Issue       store.Issue
2253		BodyHTML    template.HTML
2254		Comments    []renderedComment
2255		CanEdit     bool
2256		CanWrite    bool
2257		Milestones  []store.Milestone
2258		AllLabels   []store.Label
2259		People      []string
2260		Notice      string
2261		LabelColors map[string]template.CSS
2262		Draft       *draft
2263		Reactions   map[int64]reactionBar
2264	}{p, iss, md(iss.Body, iss.BodyFormat), renderComments(comments, md),
2265		s.canEditItem(r, p.Repo, iss.Author), s.canWriteRepo(r, p.Repo),
2266		milestones, allLabels, s.repoPeople(p.Repo), s.takeFlash(w, r), s.labelColors(p.Repo), d, bars})
2267}
2268
2269// repoPeople returns the sorted usernames of accounts with access to repo,
2270// for assignee and reviewer pickers.
2271func (s *Server) repoPeople(repo store.Repo) []string {
2272	entries, err := s.st.EffectiveAccess(repo.ID)
2273	if err != nil {
2274		return nil
2275	}
2276	out := make([]string, 0, len(entries))
2277	for _, e := range entries {
2278		out = append(out, e.Username)
2279	}
2280	return out
2281}
2282
2283// canEditItem: the author or anyone with write access may edit.
2284// canWriteRepo reports whether the browser session may push to the repo,
2285// which is what gates the review and merge controls.
2286func (s *Server) canWriteRepo(r *http.Request, repo store.Repo) bool {
2287	if s.cfg.Web.Mode != "accounts" {
2288		return false
2289	}
2290	u := s.viewer(r)
2291	if u.ID == 0 {
2292		return false
2293	}
2294	return s.canWriteRepoAs(u, repo)
2295}
2296
2297// canWriteRepoAs is canWriteRepo for a handler that already has its
2298// viewer as a parameter (behind requireUser) rather than needing to
2299// resolve one from the request's session cookie.
2300func (s *Server) canWriteRepoAs(u store.User, repo store.Repo) bool {
2301	grant, _ := s.st.AccessRole(repo.ID, u.ID)
2302	return policy.CanWrite(u, repo, grant)
2303}
2304
2305func (s *Server) canEditItem(r *http.Request, repo store.Repo, author string) bool {
2306	if s.cfg.Web.Mode != "accounts" {
2307		return false
2308	}
2309	u := s.viewer(r)
2310	if u.ID == 0 {
2311		return false
2312	}
2313	if u.Username == author {
2314		return true
2315	}
2316	grant, _ := s.st.AccessRole(repo.ID, u.ID)
2317	return policy.CanWrite(u, repo, grant)
2318}
2319
2320// mrRow is one row of the merge request list: the MR plus its head's
2321// combined check state and its comment count. Errors gathering either
2322// fall back to zero values (#230) — the list must still render.
2323type mrRow struct {
2324	store.MR
2325	Check    string
2326	Review   string
2327	Comments int
2328}
2329
2330// summarizeReviews computes the aggregate non-stale review state among
2331// reviewers who count for merge gates: "changes_requested" beats "approved".
2332func summarizeReviews(st *store.Store, repo store.Repo, revs []store.MRReview) string {
2333	if len(revs) == 0 {
2334		return ""
2335	}
2336	counts := control.ReviewersWhoCount(st, repo, revs)
2337	latest := map[string]string{}
2338	for _, rv := range revs {
2339		if rv.Stale || !counts[rv.Reviewer] {
2340			continue
2341		}
2342		if rv.Verdict == "approve" || rv.Verdict == "request_changes" {
2343			latest[rv.Reviewer] = rv.Verdict
2344		}
2345	}
2346	approved := false
2347	for _, v := range latest {
2348		if v == "request_changes" {
2349			return "changes_requested"
2350		}
2351		if v == "approve" {
2352			approved = true
2353		}
2354	}
2355	if approved {
2356		return "approved"
2357	}
2358	return ""
2359}
2360
2361func (s *Server) mrs(w http.ResponseWriter, r *http.Request) {
2362	p, ok := s.repoFor(w, r, "")
2363	if !ok {
2364		return
2365	}
2366	p.Tab = "merge requests"
2367	canWrite := s.canWriteRepo(r, p.Repo)
2368	state := r.URL.Query().Get("state")
2369	if state == "" {
2370		state = "open"
2371	}
2372	valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
2373	if !valid[state] {
2374		state = "open"
2375	}
2376	qv := r.URL.Query()
2377	mf := store.MRFilter{State: state, Label: qv.Get("label"), Author: qv.Get("author"),
2378		Milestone: qv.Get("milestone"), Search: strings.TrimSpace(qv.Get("q")), Limit: listPage + 1}
2379	mf.Before, _ = strconv.ParseInt(qv.Get("before"), 10, 64)
2380	mrs, err := s.st.QueryMRs(p.Repo.ID, mf)
2381	if err != nil {
2382		http.Error(w, "internal error", http.StatusInternalServerError)
2383		return
2384	}
2385	older := ""
2386	if len(mrs) > listPage {
2387		mrs = mrs[:listPage]
2388		older = olderLink(r, mrs[len(mrs)-1].Number)
2389	}
2390	shas := make([]string, len(mrs))
2391	ids := make([]int64, len(mrs))
2392	for i, m := range mrs {
2393		shas[i] = m.HeadSHA
2394		ids[i] = m.ID
2395	}
2396	checks, err := s.st.CombinedStatusFor(p.Repo.ID, shas)
2397	if err != nil {
2398		checks = map[string]string{}
2399	}
2400	comments, err := s.st.MRCommentCounts(p.Repo.ID, ids)
2401	if err != nil {
2402		comments = map[int64]int{}
2403	}
2404	reviewsMap, err := s.st.MRReviewsFor(ids)
2405	if err != nil {
2406		reviewsMap = map[int64][]store.MRReview{}
2407	}
2408	labels, err := s.st.ListMRLabels(p.Repo)
2409	if err != nil {
2410		labels = map[int64][]string{}
2411	}
2412	rows := make([]mrRow, len(mrs))
2413	for i, m := range mrs {
2414		m.Labels = labels[m.ID]
2415		rows[i] = mrRow{
2416			MR: m, Check: checks[m.HeadSHA],
2417			Review:   summarizeReviews(s.st, p.Repo, reviewsMap[m.ID]),
2418			Comments: comments[m.ID],
2419		}
2420	}
2421	base := url.Values{"state": {state}, "label": {mf.Label}, "author": {mf.Author}, "milestone": {mf.Milestone}, "q": {mf.Search}}
2422	readable, _ := control.ReadableScope(s.st, s.viewer(r), p.Repo)
2423	allLabels, _ := s.st.ListLabels(p.Repo, readable)
2424	openMS, _ := s.st.ListMilestones(p.Repo, "open", readable)
2425	facets := listFacets(base, []string{"open", "merged", "closed", "all"}, state, allLabels, openMS, true)
2426	canOpenMR := canWrite || len(s.writableForks(s.viewer(r), p.Repo)) > 0
2427	s.render(w, "mrs.html", struct {
2428		repoPage
2429		State       string
2430		Query       string
2431		Filters     []listFilter
2432		Facets      []facetGroup
2433		MRs         []mrRow
2434		People      []string
2435		LabelColors map[string]template.CSS
2436		Older       string
2437		CanOpenMR   bool
2438	}{p, state, mf.Search,
2439		activeFilters(state, [][2]string{{"label", mf.Label}, {"author", mf.Author}, {"milestone", mf.Milestone}}),
2440		facets, rows, s.repoPeople(p.Repo), s.labelColors(p.Repo), older, canOpenMR})
2441}
2442
2443func (s *Server) mr(w http.ResponseWriter, r *http.Request) {
2444	s.mrPage(w, r, "")
2445}
2446
2447// mrPage renders a merge request. previewForm names the form that asked
2448// to see its markup rather than save it — "edit" or "comment", "" for a
2449// plain read (#235).
2450func (s *Server) mrPage(w http.ResponseWriter, r *http.Request, previewForm string) {
2451	p, ok := s.repoFor(w, r, "")
2452	if !ok {
2453		return
2454	}
2455	p.Tab = "merge requests"
2456	n, err := strconv.ParseInt(r.PathValue("n"), 10, 64)
2457	if err != nil {
2458		s.notFound(w, r)
2459		return
2460	}
2461	m, err := s.st.MRByNumber(p.Repo.ID, n)
2462	if err != nil {
2463		s.notFound(w, r)
2464		return
2465	}
2466	comments, _ := s.st.ListMRComments(m.ID)
2467	reviews, _ := s.st.ListMRReviews(m.ID)
2468	// The same rule the merge gates apply, so the page cannot show an
2469	// approval the gate ignores (#147).
2470	reviewCounts := control.ReviewersWhoCount(s.st, p.Repo, reviews)
2471	reviewRows := make([]reviewRow, 0, len(reviews))
2472	for _, r := range reviews {
2473		reviewRows = append(reviewRows, reviewRow{MRReview: r, Counts: reviewCounts[r.Reviewer]})
2474	}
2475	checks, combined, _ := s.st.ChecksForCommit(p.Repo.ID, m.HeadSHA)
2476	// The viewer sees their own unsubmitted review comments and nobody
2477	// else's.
2478	diffComments, _ := s.st.ListDiffComments(m.ID, s.webViewer(r).ID)
2479	pendingComments := 0
2480	for _, cm := range diffComments {
2481		if cm.Pending {
2482			pendingComments++
2483		}
2484	}
2485
2486	headRef := fmt.Sprintf("refs/merge-requests/%d/head", m.Number)
2487	// An admin can prune the head ref; the diff is then unavailable, not
2488	// empty, and the page must not read as the latter.
2489	_, headErr := gitutil.ResolveRef(p.Dir, headRef)
2490	headPruned := headErr != nil
2491	var files []diffFile
2492	base := m.MergedBase
2493	if base == "" {
2494		if b, err := gitutil.MergeBase(p.Dir, "refs/heads/"+m.TargetRef, headRef); err == nil {
2495			base = b
2496		}
2497	}
2498	var diffTruncated bool
2499	selectedCommit := strings.TrimSpace(r.URL.Query().Get("commit"))
2500	if selectedCommit != "" {
2501		if full, err := gitutil.ResolveRef(p.Dir, selectedCommit); err == nil {
2502			selectedCommit = full
2503			if patch, truncated, err := gitutil.ShowPatch(p.Dir, full, 4<<20); err == nil {
2504				files, diffTruncated = parseDiff(patch), truncated
2505			}
2506		} else {
2507			selectedCommit = ""
2508		}
2509	} else if base != "" {
2510		if patch, truncated, err := gitutil.Diff(p.Dir, base, headRef, 4<<20); err == nil {
2511			files, diffTruncated = parseDiff(patch), truncated
2512		}
2513	}
2514	// The head is already reachable from the target, so the diff is empty
2515	// by construction rather than because nothing changed.
2516	headMerged := false
2517	if len(files) == 0 && m.HeadSHA != "" {
2518		if targetSHA, err := gitutil.ResolveRef(p.Dir, "refs/heads/"+m.TargetRef); err == nil {
2519			if ok, err := gitutil.IsAncestor(p.Dir, m.HeadSHA, targetSHA); err == nil {
2520				headMerged = ok
2521			}
2522		}
2523	}
2524	md := s.ugcFor(r, p.Repo)
2525	canWrite := s.canWriteRepo(r, p.Repo)
2526	// Applying a suggestion pushes to the source branch, so the button
2527	// follows write on the source repository, which for a fork is not
2528	// the one this page is in.
2529	canApply := false
2530	if p.Viewer != "" && m.State == "open" {
2531		if src, err := s.st.RepoByID(m.SourceRepoID); err == nil {
2532			canApply = s.canWriteRepo(r, src)
2533		}
2534	}
2535	suggestions := map[int64]*suggestionView{}
2536	sgs := control.Suggestions(s.st, s.cfg.Server.Root, p.Repo, m, diffComments)
2537	for _, cm := range diffComments {
2538		if sg := sgs[cm.ID]; sg != nil {
2539			suggestions[cm.ID] = newSuggestionView(sg, canApply && !cm.Pending,
2540				fmt.Sprintf("gitbay mr apply-suggestion %s %d %d", p.Repo.Path(), m.Number, cm.ID))
2541		}
2542	}
2543	var detachedThreads []diffThread
2544	files, detachedThreads = attachThreads(files, diffComments, m.HeadSHA, md,
2545		reviewRights{Viewer: p.Viewer, MRAuthor: m.Author, Write: canWrite}, suggestions)
2546	if p.Viewer != "" {
2547		markCompose(files, r.URL.Query())
2548	}
2549	layout := s.diffLayoutFor(r)
2550	if layout.Split {
2551		splitFiles(files)
2552	}
2553	stat := statOf(files)
2554	// The commits this MR carries: base..head, the same range as the diff.
2555	type commitRow struct {
2556		SHA, ShortSHA, Subject, AuthorName, AuthorUser, Date string
2557		Sig                                                  sigView
2558	}
2559	mrNames := s.authorNames()
2560	var commits []commitRow
2561	commitsTotal := 0
2562	if base != "" {
2563		const maxMRCommits = 100
2564		shas, _ := gitutil.RevListRange(p.Dir, base, headRef)
2565		commitsTotal = len(shas)
2566		if len(shas) > maxMRCommits {
2567			shas = shas[:maxMRCommits]
2568		}
2569		for _, sha := range shas {
2570			v, parsed := s.sigFor(p.Repo, p.Dir, sha)
2571			cr := commitRow{SHA: sha, ShortSHA: sha[:10], Sig: v}
2572			if parsed != nil {
2573				cr.Subject = parsed.Subject
2574				cr.AuthorName = mrNames.name(parsed.AuthorEmail, parsed.AuthorName)
2575				cr.AuthorUser, _ = mrNames.account(parsed.AuthorEmail)
2576				cr.Date = time.Unix(parsed.AuthorUnix, 0).UTC().Format(time.RFC3339)
2577			}
2578			commits = append(commits, cr)
2579		}
2580	}
2581	// The diff is the reason most people open a merge request, so it gets
2582	// its own view rather than a fold at the foot of the conversation.
2583	// A query parameter keeps this working without JavaScript.
2584	unresolved, _ := s.st.UnresolvedThreadCount(m.ID)
2585	// The revisions this merge request has had. A stale review is the
2586	// moment someone wants to know what moved, so the link to the
2587	// range-diff belongs next to it.
2588	revisions, _ := s.st.MRHeads(m.ID)
2589	branches, _ := gitutil.Refs(p.Dir, "heads")
2590	view := r.URL.Query().Get("view")
2591	if view != "commits" && view != "diff" {
2592		view = "conversation"
2593	}
2594	// Where the merge request stands against the gates, the same
2595	// computation mr merge refuses on (#199).
2596	var gates *control.GatesOut
2597	if m.State == "open" || m.State == "source_gone" {
2598		if targetSHA, err := gitutil.ResolveRef(p.Dir, "refs/heads/"+m.TargetRef); err == nil {
2599			if g, err := control.MergeGates(s.st, p.Repo, m, p.Dir, targetSHA, m.HeadSHA); err == nil {
2600				gates = &g
2601			}
2602		}
2603	}
2604	// The stack around an open merge request, for the header.
2605	var stackedOn *store.MR
2606	var stacked []store.MR
2607	if m.State == "open" {
2608		if parent, ok, err := s.st.OpenMRBySource(p.Repo.ID, m.TargetRef); err == nil && ok && parent.ID != m.ID {
2609			stackedOn = &parent
2610		}
2611		if m.SourceRepoID == p.Repo.ID {
2612			stacked, _ = s.st.OpenMRsByTarget(p.Repo.ID, m.SourceRef)
2613		}
2614	}
2615	// The merge requests this one superseded when it was closed, so the
2616	// page it points to can also say what it supersedes.
2617	supersedes, _ := s.st.MRsSuperseding(p.Repo.ID, m.Number)
2618	// An edit keeps the merge request's stored format; a comment reads the format picker.
2619	var d *draft
2620	if previewForm != "" {
2621		format := m.BodyFormat
2622		if previewForm == "comment" {
2623			format = bodyFormat(r)
2624		}
2625		d = s.draftFor(r, p.Repo, previewForm, "body", format)
2626	}
2627	bars := s.reactionBars(r, "mr", m.ID, comments, fmt.Sprintf("/%s/%s/mrs/%d/react", p.Repo.OwnerName, p.Repo.Name, m.Number))
2628	allLabels, _ := s.st.ListLabels(p.Repo, nil)
2629	s.render(w, "mr.html", struct {
2630		repoPage
2631		MR              store.MR
2632		View            string
2633		BodyHTML        template.HTML
2634		Checks          []store.Check
2635		Combined        string
2636		Comments        []renderedComment
2637		Reviews         []reviewRow
2638		DiffFiles       []diffFile
2639		DiffTruncated   bool
2640		Stat            diffStat
2641		Commits         []commitRow
2642		CommitsTotal    int
2643		Branches        []gitutil.Ref
2644		CanEdit         bool
2645		CanWrite        bool
2646		Unresolved      int
2647		PendingComments int
2648		Revisions       []store.MRHead
2649		Notice          string
2650		DetachedThreads []diffThread
2651		StackedOn       *store.MR
2652		Stacked         []store.MR
2653		Supersedes      []store.MR
2654		Gates           *control.GatesOut
2655		SourceGone      bool
2656		HeadMerged      bool
2657		HeadPruned      bool
2658		Base            string
2659		LabelColors     map[string]template.CSS
2660		AllLabels       []store.Label
2661		People          []string
2662		Draft           *draft
2663		Layout          diffLayout
2664		SelectedCommit  string
2665		Reactions       map[int64]reactionBar
2666	}{p, m, view, md(m.Body, m.BodyFormat), checks, combined, renderComments(comments, md),
2667		reviewRows, files, diffTruncated, stat, commits, commitsTotal, branches, s.canEditItem(r, p.Repo, m.Author),
2668		canWrite, unresolved, pendingComments, revisions, s.takeFlash(w, r), detachedThreads, stackedOn, stacked, supersedes, gates,
2669		sourceGone(p, m), headMerged, headPruned, base, s.labelColors(p.Repo), allLabels, s.repoPeople(p.Repo), d, layout, selectedCommit, bars})
2670}
2671
2672// sourceGone reports whether an MR's source branch no longer exists: the
2673// push hook marks a deleted branch on an open MR, and a merged or closed
2674// one is checked here. A fork's branch lives in another repository and
2675// is left to the recorded state.
2676func sourceGone(p repoPage, m store.MR) bool {
2677	if m.State == "source_gone" {
2678		return true
2679	}
2680	if m.SourceRepoID != p.Repo.ID {
2681		return false
2682	}
2683	_, err := gitutil.ResolveRef(p.Dir, "refs/heads/"+m.SourceRef)
2684	return err != nil
2685}
2686
2687func (s *Server) refs(w http.ResponseWriter, r *http.Request) {
2688	p, ok := s.repoFor(w, r, "")
2689	if !ok {
2690		return
2691	}
2692	p.Tab = "refs"
2693	branches, _ := gitutil.Refs(p.Dir, "heads")
2694	tags, _ := gitutil.Refs(p.Dir, "tags")
2695	gitutil.SortVersions(tags)
2696	s.render(w, "refs.html", struct {
2697		repoPage
2698		Branches, Tags []gitutil.Ref
2699	}{p, branches, tags})
2700}
2701
2702func (s *Server) archive(w http.ResponseWriter, r *http.Request) {
2703	p, ok := s.repoFor(w, r, "")
2704	if !ok {
2705		return
2706	}
2707	file := r.PathValue("file")
2708	ref, ok := strings.CutSuffix(file, ".tar.gz")
2709	if !ok {
2710		s.notFound(w, r)
2711		return
2712	}
2713	if _, err := gitutil.ResolveRef(p.Dir, ref); err != nil {
2714		s.notFound(w, r)
2715		return
2716	}
2717	out, kill, finish, ok := s.packSlot(w, r)
2718	if !ok {
2719		return
2720	}
2721	defer finish()
2722	prefix := fmt.Sprintf("%s-%s", p.Repo.Name, ref)
2723	w.Header().Set("Content-Type", "application/gzip")
2724	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", prefix+".tar.gz"))
2725	gitutil.ArchiveUntil(p.Dir, ref, prefix, out, kill)
2726}
2727
2728func policyCanAdmin(u store.User, repo store.Repo, grant string) bool {
2729	return policy.CanAdmin(u, repo, grant)
2730}
2731
2732func policyCanRead(u store.User, repo store.Repo, grant string) bool {
2733	return policy.CanRead(u, repo, grant)
2734}
2735
2736// reviewRow is a review with whether the merge gates count it, which
2737// depends on the reviewer's access and so is not a property of the
2738// review row itself.
2739type reviewRow struct {
2740	store.MRReview
2741	Counts bool
2742}
2743
2744// sshCloneURL is the SSH clone URL for a repository, with the port only
2745// when it is not the default.
2746func (s *Server) sshCloneURL(repo store.Repo) string {
2747	host := s.cfg.SiteHost()
2748	if s.cfg.SSH.Port != 22 {
2749		host += ":" + strconv.Itoa(s.cfg.SSH.Port)
2750	}
2751	return "ssh://git@" + host + "/" + repo.Path() + ".git"
2752}
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