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