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