internal/httpd/web.go
1136 lines · 31349 bytes
1package httpd
2
3import (
4 "bytes"
5 "fmt"
6 "hash/fnv"
7
8 "gitbay.org/gitbay/internal/policy"
9 "html/template"
10 "net/http"
11 "path"
12 "regexp"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/alecthomas/chroma/v2/formatters/html"
18 "github.com/alecthomas/chroma/v2/lexers"
19 "github.com/alecthomas/chroma/v2/styles"
20 "github.com/microcosm-cc/bluemonday"
21 "github.com/niklasfasching/go-org/org"
22 "github.com/yuin/goldmark"
23
24 "gitbay.org/gitbay/internal/autolink"
25 "gitbay.org/gitbay/internal/control"
26 "gitbay.org/gitbay/internal/gitutil"
27 "gitbay.org/gitbay/internal/sig"
28 "gitbay.org/gitbay/internal/store"
29 "gitbay.org/gitbay/internal/web"
30)
31
32const maxRenderBytes = 1 << 20 // largest blob rendered inline
33
34func (s *Server) render(w http.ResponseWriter, page string, data any) {
35 var buf bytes.Buffer
36 if err := web.Render(&buf, page, data); err != nil {
37 http.Error(w, "template error: "+err.Error(), http.StatusInternalServerError)
38 return
39 }
40 w.Header().Set("Content-Type", "text/html; charset=utf-8")
41 buf.WriteTo(w)
42}
43
44func (s *Server) siteName() string {
45 h := strings.TrimPrefix(strings.TrimPrefix(s.cfg.Server.SiteURL, "https://"), "http://")
46 return strings.TrimSuffix(h, "/")
47}
48
49func (s *Server) stylesheet(w http.ResponseWriter, r *http.Request) {
50 w.Header().Set("Content-Type", "text/css; charset=utf-8")
51 w.Write(web.StyleCSS)
52}
53
54func (s *Server) favicon(w http.ResponseWriter, r *http.Request) {
55 w.Header().Set("Content-Type", "image/svg+xml")
56 w.Write(web.FaviconSVG)
57}
58
59// notFound renders the designed 404 page with a 404 status. Falls back to
60// the stock plain-text response if the template fails.
61func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
62 var buf bytes.Buffer
63 if err := web.Render(&buf, "404.html", struct{ Site string }{s.siteName()}); err != nil {
64 http.NotFound(w, r)
65 return
66 }
67 w.Header().Set("Content-Type", "text/html; charset=utf-8")
68 w.WriteHeader(http.StatusNotFound)
69 buf.WriteTo(w)
70}
71
72// describedRepo pairs a repo with its description for listings.
73type describedRepo struct {
74 store.Repo
75 Desc string
76}
77
78func (s *Server) describeAll(repos []store.Repo) []describedRepo {
79 var out []describedRepo
80 for _, r := range repos {
81 out = append(out, describedRepo{r, gitutil.ReadDescription(control.RepoDir(s.cfg.Server.Root, r.OwnerName, r.Name))})
82 }
83 return out
84}
85
86// index is the homepage: a dashboard for logged-in users, a landing page
87// for everyone else. The full public listing lives at /explore.
88func (s *Server) index(w http.ResponseWriter, r *http.Request) {
89 if s.cfg.Web.Mode == "accounts" {
90 if viewer := s.viewer(r); viewer.ID != 0 {
91 s.dashboard(w, r, viewer)
92 return
93 }
94 }
95 host := strings.TrimSuffix(strings.TrimPrefix(strings.TrimPrefix(
96 s.cfg.Server.SiteURL, "https://"), "http://"), "/")
97 s.render(w, "landing.html", struct {
98 Site string
99 Host string
100 Accounts bool
101 }{s.siteName(), host, s.cfg.Web.Mode == "accounts"})
102}
103
104func (s *Server) dashboard(w http.ResponseWriter, r *http.Request, viewer store.User) {
105 pinned, _ := s.st.PinnedRepos(viewer.ID)
106 var visible []store.Repo
107 for _, rp := range pinned {
108 grant, _ := s.st.AccessRole(rp.ID, viewer.ID)
109 if policy.CanRead(viewer, rp, grant) {
110 visible = append(visible, rp)
111 }
112 }
113 mrs, _ := s.st.DashboardMRs(viewer.ID)
114 issues, _ := s.st.DashboardIssues(viewer.ID)
115 s.render(w, "dashboard.html", struct {
116 Site string
117 Viewer string
118 Pinned []describedRepo
119 MRs []store.DashboardItem
120 Issues []store.DashboardItem
121 }{s.siteName(), viewer.Username, s.describeAll(visible), mrs, issues})
122}
123
124func (s *Server) explore(w http.ResponseWriter, r *http.Request) {
125 repos, err := s.st.ListPublicRepos()
126 if err != nil {
127 http.Error(w, "internal error", http.StatusInternalServerError)
128 return
129 }
130 var viewer store.User
131 if s.cfg.Web.Mode == "accounts" {
132 viewer = s.viewer(r)
133 }
134 q := strings.TrimSpace(r.URL.Query().Get("q"))
135 s.render(w, "explore.html", struct {
136 Site string
137 Viewer string
138 Query string
139 Repos []describedRepo
140 }{s.siteName(), viewer.Username, q, s.filterRepos(q, s.describeAll(repos))})
141}
142
143// filterRepos keeps repos whose path, description, or topics contain the
144// query, case-insensitively. An empty query keeps everything.
145func (s *Server) filterRepos(q string, repos []describedRepo) []describedRepo {
146 if q == "" {
147 return repos
148 }
149 q = strings.ToLower(q)
150 var out []describedRepo
151 for _, d := range repos {
152 if strings.Contains(strings.ToLower(d.Path()), q) ||
153 strings.Contains(strings.ToLower(d.Desc), q) {
154 out = append(out, d)
155 continue
156 }
157 topics, _ := s.st.ListTopics(d.ID)
158 for _, t := range topics {
159 if strings.Contains(t, q) {
160 out = append(out, d)
161 break
162 }
163 }
164 }
165 return out
166}
167
168// repoPage is the shared context for repo-scoped pages.
169type repoPage struct {
170 Site string
171 Viewer string
172 Desc string
173 Repo store.Repo
174 Ref string
175 CloneURL string
176 Dir string
177 Tab string // active tab in the repo header
178 Topics []string
179}
180
181// repoFor resolves the repo for a web request; false means 404 was sent.
182// Anonymous visitors see public repos only; in accounts mode a logged-in
183// viewer additionally sees repos their grants allow. Private and missing
184// repos are indistinguishable either way.
185func (s *Server) repoFor(w http.ResponseWriter, r *http.Request, ref string) (repoPage, bool) {
186 var repo store.Repo
187 var viewer store.User
188 if s.cfg.Web.Mode == "accounts" {
189 viewer = s.viewer(r)
190 }
191 repo, err := s.st.RepoByPath(r.PathValue("owner") + "/" + r.PathValue("repo"))
192 ok := err == nil
193 if ok {
194 grant := ""
195 if viewer.ID != 0 {
196 grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
197 }
198 ok = policyCanRead(viewer, repo, grant)
199 }
200 if !ok {
201 s.notFound(w, r)
202 return repoPage{}, false
203 }
204 if ref == "" {
205 ref = repo.DefaultBranch
206 }
207 topics, _ := s.st.ListTopics(repo.ID)
208 return repoPage{
209 Site: s.siteName(),
210 Viewer: viewer.Username,
211 Desc: gitutil.ReadDescription(control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name)),
212 Repo: repo,
213 Ref: ref,
214 CloneURL: s.cfg.Server.SiteURL + "/" + repo.Path() + ".git",
215 Dir: control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name),
216 Topics: topics,
217 }, true
218}
219
220type crumb struct {
221 Name string
222 URL string
223}
224
225func crumbs(p repoPage, kind, filePath string) []crumb {
226 var cs []crumb
227 base := "/" + p.Repo.Path() + "/" + kind + "/" + p.Ref + "/"
228 acc := ""
229 for _, part := range strings.Split(filePath, "/") {
230 if part == "" {
231 continue
232 }
233 acc = path.Join(acc, part)
234 cs = append(cs, crumb{Name: part, URL: base + acc})
235 }
236 return cs
237}
238
239// ownerPage renders /{owner} for users and orgs: the repositories the
240// viewer may see, org membership either direction. Owner names are not
241// secret (they are on every commit); repository visibility rules hold.
242func (s *Server) ownerPage(w http.ResponseWriter, r *http.Request) {
243 name := r.PathValue("owner")
244 var viewer store.User
245 if s.cfg.Web.Mode == "accounts" {
246 viewer = s.viewer(r)
247 }
248
249 kind := "user"
250 var ownerID int64
251 var members []store.OrgMember
252 var orgs []store.OrgMember
253 if u, err := s.st.UserByUsername(name); err == nil {
254 ownerID = u.ID
255 orgs, _ = s.st.ListOrgsForUser(u.ID)
256 } else if o, err := s.st.OrgByName(name); err == nil {
257 kind, ownerID = "org", o.ID
258 members, _ = s.st.OrgMembers(o.ID)
259 } else {
260 s.notFound(w, r)
261 return
262 }
263 profile, _ := s.st.OwnerProfile(kind, ownerID)
264
265 all, err := s.st.ListReposForOwner(kind, ownerID)
266 if err != nil {
267 http.Error(w, "internal error", http.StatusInternalServerError)
268 return
269 }
270 var visible []store.Repo
271 for _, repo := range all {
272 grant := ""
273 if viewer.ID != 0 {
274 grant, _ = s.st.AccessRole(repo.ID, viewer.ID)
275 }
276 if policy.CanRead(viewer, repo, grant) {
277 visible = append(visible, repo)
278 }
279 }
280 s.render(w, "owner.html", struct {
281 Site string
282 Viewer string
283 Owner string
284 Kind string
285 Profile store.Profile
286 Repos []describedRepo
287 Members []store.OrgMember
288 Orgs []store.OrgMember
289 }{s.siteName(), viewer.Username, name, kind, profile, s.describeAll(visible), members, orgs})
290}
291
292func (s *Server) repoHome(w http.ResponseWriter, r *http.Request) {
293 p, ok := s.repoFor(w, r, "")
294 if !ok {
295 return
296 }
297 p.Tab = "files"
298 s.renderTree(w, r, p, "")
299}
300
301func (s *Server) tree(w http.ResponseWriter, r *http.Request) {
302 p, ok := s.repoFor(w, r, r.PathValue("ref"))
303 if !ok {
304 return
305 }
306 p.Tab = "files"
307 s.renderTree(w, r, p, strings.Trim(r.PathValue("path"), "/"))
308}
309
310func (s *Server) renderTree(w http.ResponseWriter, r *http.Request, p repoPage, dirPath string) {
311 if _, err := gitutil.ResolveRef(p.Dir, p.Ref); err != nil {
312 // Empty repo: render the page with no entries rather than 404.
313 s.render(w, "tree.html", struct {
314 repoPage
315 Crumbs []crumb
316 Prefix string
317 Entries []gitutil.TreeEntry
318 ReadmeName string
319 ReadmeHTML template.HTML
320 }{repoPage: p})
321 return
322 }
323 entries, err := gitutil.ListTree(p.Dir, p.Ref, dirPath)
324 if err != nil {
325 s.notFound(w, r)
326 return
327 }
328 prefix := ""
329 if dirPath != "" {
330 prefix = dirPath + "/"
331 }
332
333 var readmeHTML template.HTML
334 readmeName := pickReadme(entries)
335 if readmeName != "" {
336 if raw, err := gitutil.ReadBlob(p.Dir, p.Ref, prefix+readmeName, maxRenderBytes); err == nil {
337 readmeHTML = renderReadme(readmeName, raw)
338 }
339 }
340
341 s.render(w, "tree.html", struct {
342 repoPage
343 Crumbs []crumb
344 Prefix string
345 Entries []gitutil.TreeEntry
346 ReadmeName string
347 ReadmeHTML template.HTML
348 }{p, crumbs(p, "tree", dirPath), prefix, entries, readmeName, readmeHTML})
349}
350
351func (s *Server) blob(w http.ResponseWriter, r *http.Request) {
352 p, ok := s.repoFor(w, r, r.PathValue("ref"))
353 if !ok {
354 return
355 }
356 p.Tab = "files"
357 filePath := strings.Trim(r.PathValue("path"), "/")
358 data, err := gitutil.ReadBlob(p.Dir, p.Ref, filePath, maxRenderBytes+1)
359 if err != nil {
360 s.notFound(w, r)
361 return
362 }
363 binary := gitutil.IsBinary(data) || len(data) > maxRenderBytes
364
365 var codeHTML template.HTML
366 if !binary {
367 codeHTML = highlight(filePath, data)
368 }
369 cs := crumbs(p, "blob", filePath)
370 base := ""
371 if len(cs) > 0 {
372 base = cs[len(cs)-1].Name
373 cs = cs[:len(cs)-1]
374 }
375 s.render(w, "blob.html", struct {
376 repoPage
377 Crumbs []crumb
378 Base string
379 Path string
380 Binary bool
381 Size int
382 CodeHTML template.HTML
383 }{p, cs, base, filePath, binary, len(data), codeHTML})
384}
385
386// search runs a bounded literal git grep over the repo's default branch.
387func (s *Server) search(w http.ResponseWriter, r *http.Request) {
388 p, ok := s.repoFor(w, r, "")
389 if !ok {
390 return
391 }
392 p.Tab = "search"
393 q := strings.TrimSpace(r.URL.Query().Get("q"))
394 type matchView struct {
395 Path string
396 Line int
397 TextHTML template.HTML
398 }
399 var matches []matchView
400 var queryErr string
401 if q != "" {
402 if len(q) < 2 || len(q) > 200 {
403 queryErr = "query must be 2 to 200 characters"
404 } else if _, err := gitutil.ResolveRef(p.Dir, p.Ref); err == nil {
405 raw, err := gitutil.Grep(p.Dir, p.Ref, q, 200)
406 if err != nil {
407 http.Error(w, "internal error", http.StatusInternalServerError)
408 return
409 }
410 for _, m := range raw {
411 matches = append(matches, matchView{m.Path, m.Line, markMatch(m.Text, q)})
412 }
413 }
414 }
415 s.render(w, "search.html", struct {
416 repoPage
417 Query string
418 QueryErr string
419 Matches []matchView
420 Capped bool
421 }{p, q, queryErr, matches, len(matches) == 200})
422}
423
424// markMatch escapes a matched line and wraps case-insensitive occurrences
425// of the query in <mark>.
426func markMatch(text, q string) template.HTML {
427 lower, lq := strings.ToLower(text), strings.ToLower(q)
428 var b strings.Builder
429 pos := 0
430 for {
431 i := strings.Index(lower[pos:], lq)
432 if i < 0 {
433 break
434 }
435 i += pos
436 b.WriteString(template.HTMLEscapeString(text[pos:i]))
437 b.WriteString("<mark>")
438 b.WriteString(template.HTMLEscapeString(text[i : i+len(q)]))
439 b.WriteString("</mark>")
440 pos = i + len(q)
441 }
442 b.WriteString(template.HTMLEscapeString(text[pos:]))
443 return template.HTML(b.String())
444}
445
446// blamePageSize caps how many lines one blame page renders; blame is a
447// per-line subprocess cost, so large files paginate.
448const blamePageSize = 1000
449
450func (s *Server) blame(w http.ResponseWriter, r *http.Request) {
451 p, ok := s.repoFor(w, r, r.PathValue("ref"))
452 if !ok {
453 return
454 }
455 p.Tab = "files"
456 filePath := strings.Trim(r.PathValue("path"), "/")
457 data, err := gitutil.ReadBlob(p.Dir, p.Ref, filePath, s.cfg.Limits.MaxBlobBytes)
458 if err != nil {
459 s.notFound(w, r)
460 return
461 }
462 total := bytes.Count(data, []byte("\n"))
463 if len(data) > 0 && !bytes.HasSuffix(data, []byte("\n")) {
464 total++
465 }
466 binary := gitutil.IsBinary(data)
467
468 type hunkView struct {
469 gitutil.BlameHunk
470 ShortSHA string
471 Date string
472 Sig sigView
473 Numbered []numberedLine
474 }
475 var hunks []hunkView
476 page, pages := 1, (total+blamePageSize-1)/blamePageSize
477 if pages == 0 {
478 pages = 1
479 }
480 if n, err := strconv.Atoi(r.URL.Query().Get("page")); err == nil && n >= 1 && n <= pages {
481 page = n
482 }
483 if !binary && total > 0 {
484 start := (page-1)*blamePageSize + 1
485 end := min(total, page*blamePageSize)
486 raw, err := gitutil.Blame(p.Dir, p.Ref, filePath, start, end)
487 if err != nil {
488 s.notFound(w, r)
489 return
490 }
491 sigs := map[string]sigView{}
492 for _, h := range raw {
493 v, ok := sigs[h.SHA]
494 if !ok {
495 v, _ = s.sigFor(p.Repo, p.Dir, h.SHA)
496 sigs[h.SHA] = v
497 }
498 hv := hunkView{BlameHunk: h, ShortSHA: h.SHA[:10],
499 Date: time.Unix(h.AuthorUnix, 0).UTC().Format("2006-01-02"), Sig: v}
500 for i, l := range h.Lines {
501 hv.Numbered = append(hv.Numbered, numberedLine{h.StartLine + i, l})
502 }
503 hunks = append(hunks, hv)
504 }
505 }
506 cs := crumbs(p, "blame", filePath)
507 base := ""
508 if len(cs) > 0 {
509 base = cs[len(cs)-1].Name
510 cs = cs[:len(cs)-1]
511 }
512 s.render(w, "blame.html", struct {
513 repoPage
514 Crumbs []crumb
515 Base string
516 Path string
517 Binary bool
518 Hunks []hunkView
519 Page, Pages int
520 }{p, cs, base, filePath, binary, hunks, page, pages})
521}
522
523type numberedLine struct {
524 N int
525 Text string
526}
527
528func highlight(filePath string, data []byte) template.HTML {
529 lexer := lexers.Match(filePath)
530 if lexer == nil {
531 lexer = lexers.Fallback
532 }
533 style := styles.Get("friendly")
534 formatter := html.New(html.WithLineNumbers(true), html.LineNumbersInTable(false),
535 html.WithLinkableLineNumbers(true, "L"))
536 iterator, err := lexer.Tokenise(nil, string(data))
537 if err != nil {
538 return template.HTML("<pre>" + template.HTMLEscapeString(string(data)) + "</pre>")
539 }
540 var buf bytes.Buffer
541 if err := formatter.Format(&buf, style, iterator); err != nil {
542 return template.HTML("<pre>" + template.HTMLEscapeString(string(data)) + "</pre>")
543 }
544 return template.HTML(buf.String())
545}
546
547func (s *Server) raw(w http.ResponseWriter, r *http.Request) {
548 p, ok := s.repoFor(w, r, r.PathValue("ref"))
549 if !ok {
550 return
551 }
552 filePath := strings.Trim(r.PathValue("path"), "/")
553 data, err := gitutil.ReadBlob(p.Dir, p.Ref, filePath, s.cfg.Limits.MaxBlobBytes)
554 if err != nil {
555 s.notFound(w, r)
556 return
557 }
558 // Serve inert: never let repo content execute in the forge's origin.
559 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
560 w.Header().Set("X-Content-Type-Options", "nosniff")
561 w.Write(data)
562}
563
564// readmeRank orders competing README files: richer renderers win.
565var readmeRank = map[string]int{".md": 1, ".markdown": 1, ".org": 2, ".html": 3, ".htm": 3}
566
567// pickReadme returns the best README-ish blob in a tree listing: any file
568// named "readme" or "readme.<ext>" (case-insensitive), preferring formats
569// we can render richly.
570func pickReadme(entries []gitutil.TreeEntry) string {
571 best, bestRank := "", 1<<30
572 for _, e := range entries {
573 if e.Type != "blob" {
574 continue
575 }
576 lower := strings.ToLower(e.Name)
577 if lower != "readme" && !strings.HasPrefix(lower, "readme.") {
578 continue
579 }
580 rank, ok := readmeRank[path.Ext(lower)]
581 if !ok {
582 rank = 10 // plaintext fallback
583 }
584 if rank < bestRank {
585 best, bestRank = e.Name, rank
586 }
587 }
588 return best
589}
590
591// mdHTML renders user-authored markdown (issue and MR bodies, comments).
592// goldmark's default renderer drops raw HTML, so this is safe as-is.
593func mdHTML(raw string) template.HTML {
594 if strings.TrimSpace(raw) == "" {
595 return ""
596 }
597 var buf bytes.Buffer
598 if goldmark.Convert([]byte(raw), &buf) != nil {
599 return template.HTML("<pre>" + template.HTMLEscapeString(raw) + "</pre>")
600 }
601 return template.HTML(buf.String())
602}
603
604// webResolver answers autolink lookups for one viewer. Cross-repo
605// references to repositories the viewer cannot read stay plain text, per
606// the enumeration rule: a link would confirm the repo exists.
607type webResolver struct {
608 s *Server
609 viewer store.User
610}
611
612func (r webResolver) RefURL(owner, name string, kind byte, n int64) string {
613 repo, err := r.s.st.RepoByPath(owner + "/" + name)
614 if err != nil {
615 return ""
616 }
617 grant := ""
618 if r.viewer.ID != 0 {
619 grant, _ = r.s.st.AccessRole(repo.ID, r.viewer.ID)
620 }
621 if !policy.CanRead(r.viewer, repo, grant) {
622 return ""
623 }
624 if kind == '#' {
625 if _, err := r.s.st.IssueByNumber(repo.ID, n); err != nil {
626 return ""
627 }
628 return autolink.IssueURL(repo.OwnerName, repo.Name, n)
629 }
630 if _, err := r.s.st.MRByNumber(repo.ID, n); err != nil {
631 return ""
632 }
633 return autolink.MRURL(repo.OwnerName, repo.Name, n)
634}
635
636func (r webResolver) UserURL(name string) string {
637 if _, err := r.s.st.UserByUsername(name); err == nil {
638 return "/" + name
639 }
640 if _, err := r.s.st.OrgByName(name); err == nil {
641 return "/" + name
642 }
643 return ""
644}
645
646// ugcFor returns a renderer for user-authored markdown on one repo's pages:
647// mdHTML plus cross-reference and mention autolinking for this viewer.
648func (s *Server) ugcFor(r *http.Request, repo store.Repo) func(string) template.HTML {
649 viewer := store.User{}
650 if s.cfg.Web.Mode == "accounts" {
651 viewer = s.viewer(r)
652 }
653 res := webResolver{s, viewer}
654 return func(raw string) template.HTML {
655 h := mdHTML(raw)
656 if h == "" {
657 return h
658 }
659 return template.HTML(autolink.Rewrite(string(h), repo.OwnerName, repo.Name, res))
660 }
661}
662
663// renderedComment pairs a comment with its rendered body for templates.
664type renderedComment struct {
665 Author string
666 CreatedAt string
667 BodyHTML template.HTML
668}
669
670func renderComments(cs []store.IssueComment, md func(string) template.HTML) []renderedComment {
671 var out []renderedComment
672 for _, c := range cs {
673 out = append(out, renderedComment{c.Author, c.CreatedAt, md(c.Body)})
674 }
675 return out
676}
677
678// ugcPolicy sanitizes rendered repo content before it enters the forge's
679// origin: markdown is already safe (goldmark drops raw HTML), but org-mode
680// output and repo-authored HTML are not.
681var ugcPolicy = bluemonday.UGCPolicy()
682
683// renderReadme renders a README by extension: markdown, org-mode, and
684// (sanitized) HTML richly; everything else as escaped plaintext.
685func renderReadme(name string, raw []byte) template.HTML {
686 plain := func() template.HTML {
687 return template.HTML("<pre>" + template.HTMLEscapeString(string(raw)) + "</pre>")
688 }
689 if gitutil.IsBinary(raw) {
690 return ""
691 }
692 switch path.Ext(strings.ToLower(name)) {
693 case ".md", ".markdown":
694 var buf bytes.Buffer
695 if goldmark.Convert(raw, &buf) != nil {
696 return plain()
697 }
698 return template.HTML(buf.String())
699 case ".org":
700 doc := org.New().Parse(bytes.NewReader(raw), name)
701 html, err := doc.Write(org.NewHTMLWriter())
702 if err != nil {
703 return plain()
704 }
705 return template.HTML(ugcPolicy.Sanitize(html))
706 case ".html", ".htm":
707 return template.HTML(ugcPolicy.Sanitize(string(raw)))
708 default:
709 return plain()
710 }
711}
712
713type diffLine struct {
714 Class string
715 Text string
716 Path string // file this line belongs to
717 NewLine int64 // line number in the new file (0 when absent)
718 OldLine int64 // line number in the old file (0 when absent)
719 Threads []diffThread
720}
721
722var hunkPat = regexp.MustCompile(`^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@`)
723
724// classifyDiff parses a unified diff into rendered lines, tracking the
725// file and old/new line numbers so review threads can anchor inline.
726func classifyDiff(patch string) []diffLine {
727 var lines []diffLine
728 path := ""
729 var oldN, newN int64
730 for _, l := range strings.Split(patch, "\n") {
731 d := diffLine{Text: l}
732 switch {
733 case strings.HasPrefix(l, "+++ "):
734 d.Class = "meta"
735 path = strings.TrimPrefix(strings.TrimPrefix(l, "+++ "), "b/")
736 case strings.HasPrefix(l, "--- "), strings.HasPrefix(l, "diff "), strings.HasPrefix(l, "index "):
737 d.Class = "meta"
738 case strings.HasPrefix(l, "@@"):
739 d.Class = "hunk"
740 if m := hunkPat.FindStringSubmatch(l); m != nil {
741 oldN, _ = strconv.ParseInt(m[1], 10, 64)
742 newN, _ = strconv.ParseInt(m[2], 10, 64)
743 }
744 case strings.HasPrefix(l, "+"):
745 d.Class, d.Path, d.NewLine = "add", path, newN
746 newN++
747 case strings.HasPrefix(l, "-"):
748 d.Class, d.Path, d.OldLine = "del", path, oldN
749 oldN++
750 default:
751 d.Path, d.OldLine, d.NewLine = path, oldN, newN
752 oldN++
753 newN++
754 }
755 lines = append(lines, d)
756 }
757 return lines
758}
759
760type diffThread struct {
761 ID int64
762 Resolved string
763 Stale bool
764 Comments []renderedComment
765}
766
767// attachThreads injects review threads under their anchored diff lines;
768// threads whose anchor no longer appears (stale after force-push, or on a
769// context line outside the current diff) are returned separately.
770func attachThreads(lines []diffLine, comments []store.DiffComment, headSHA string, md func(string) template.HTML) ([]diffLine, []diffThread) {
771 type anchor struct {
772 path string
773 side string
774 line int64
775 }
776 threads := map[int64]*diffThread{}
777 anchors := map[int64]anchor{}
778 var order []int64
779 for _, cm := range comments {
780 if cm.ReplyTo == 0 {
781 threads[cm.ID] = &diffThread{ID: cm.ID, Resolved: cm.ResolvedBy, Stale: cm.HeadSHA != headSHA,
782 Comments: []renderedComment{{cm.Author, cm.CreatedAt, md(cm.Body)}}}
783 anchors[cm.ID] = anchor{cm.Path, cm.Side, cm.Line}
784 order = append(order, cm.ID)
785 } else if th, ok := threads[cm.ReplyTo]; ok {
786 th.Comments = append(th.Comments, renderedComment{cm.Author, cm.CreatedAt, md(cm.Body)})
787 }
788 }
789 placed := map[int64]bool{}
790 for i := range lines {
791 for _, id := range order {
792 if placed[id] || threads[id].Stale {
793 continue
794 }
795 a := anchors[id]
796 if lines[i].Path != a.path {
797 continue
798 }
799 if (a.side == "new" && lines[i].NewLine == a.line && lines[i].Class != "del") ||
800 (a.side == "old" && lines[i].OldLine == a.line && lines[i].Class == "del") {
801 lines[i].Threads = append(lines[i].Threads, *threads[id])
802 placed[id] = true
803 }
804 }
805 }
806 var unplaced []diffThread
807 for _, id := range order {
808 if !placed[id] {
809 unplaced = append(unplaced, *threads[id])
810 }
811 }
812 return lines, unplaced
813}
814
815type sigView struct {
816 State string
817 Signer string
818 Fingerprint string
819}
820
821func (s *Server) sigFor(repo store.Repo, dir, sha string) (sigView, *sig.Commit) {
822 raw, err := gitutil.ReadCommit(dir, sha)
823 if err != nil {
824 return sigView{State: "unsigned"}, nil
825 }
826 parsed, err := sig.ParseCommit(raw)
827 if err != nil {
828 return sigView{State: "unsigned"}, nil
829 }
830 res, err := control.VerifyCommitCached(s.st, repo, parsed, sha)
831 if err != nil {
832 return sigView{State: "unsigned"}, parsed
833 }
834 v := sigView{State: string(res.State), Fingerprint: res.KeyFingerprint}
835 if res.SignerUserID != 0 {
836 if u, err := s.st.UserByID(res.SignerUserID); err == nil {
837 v.Signer = u.Username
838 }
839 }
840 return v, parsed
841}
842
843func (s *Server) log(w http.ResponseWriter, r *http.Request) {
844 ref := r.PathValue("ref")
845 p, ok := s.repoFor(w, r, ref)
846 if !ok {
847 return
848 }
849 p.Tab = "log"
850 const pageSize = 50
851 shas, err := gitutil.RevList(p.Dir, p.Ref, pageSize+1)
852 if err != nil {
853 s.notFound(w, r)
854 return
855 }
856 next := ""
857 if len(shas) > pageSize {
858 next = shas[pageSize]
859 shas = shas[:pageSize]
860 }
861 type row struct {
862 SHA, ShortSHA, Subject, AuthorName, AuthorEmail, Date string
863 Sig sigView
864 }
865 var rows []row
866 for _, sha := range shas {
867 v, parsed := s.sigFor(p.Repo, p.Dir, sha)
868 rw := row{SHA: sha, ShortSHA: sha[:10], Sig: v}
869 if parsed != nil {
870 rw.Subject = parsed.Subject
871 rw.AuthorName = parsed.AuthorName
872 rw.AuthorEmail = parsed.AuthorEmail
873 rw.Date = time.Unix(parsed.AuthorUnix, 0).UTC().Format("2006-01-02")
874 }
875 rows = append(rows, rw)
876 }
877 s.render(w, "log.html", struct {
878 repoPage
879 Commits []row
880 NextSHA string
881 }{p, rows, next})
882}
883
884func (s *Server) commit(w http.ResponseWriter, r *http.Request) {
885 p, ok := s.repoFor(w, r, "")
886 if !ok {
887 return
888 }
889 p.Tab = "log"
890 sha := r.PathValue("sha")
891 full, err := gitutil.ResolveRef(p.Dir, sha)
892 if err != nil {
893 s.notFound(w, r)
894 return
895 }
896 v, parsed := s.sigFor(p.Repo, p.Dir, full)
897 if parsed == nil {
898 s.notFound(w, r)
899 return
900 }
901 patch, _ := gitutil.ShowPatch(p.Dir, full, 4<<20)
902 lines := classifyDiff(patch)
903 committerEmail := ""
904 if parsed.CommitterEmail != parsed.AuthorEmail {
905 committerEmail = parsed.CommitterEmail
906 }
907 checks, _ := s.st.ListCommitStatuses(p.Repo.ID, full)
908 msg := ""
909 if i := bytes.Index(parsed.Payload, []byte("\n\n")); i >= 0 {
910 msg = string(parsed.Payload[i+2:])
911 }
912 s.render(w, "commit.html", struct {
913 repoPage
914 SHA, ShortSHA, AuthorName, AuthorEmail, CommitterEmail, Date, Message string
915 Sig sigView
916 Checks []store.CommitStatus
917 DiffLines []diffLine
918 }{p, full, full[:10], parsed.AuthorName, parsed.AuthorEmail, committerEmail,
919 time.Unix(parsed.AuthorUnix, 0).UTC().Format(time.RFC3339), msg, v, checks, lines})
920}
921
922// labelPalette provides default label chip colors: mid-tone hues that stay
923// legible on light and dark backgrounds.
924var labelPalette = []string{
925 "#0969da", "#1a7f37", "#9a6700", "#cf222e",
926 "#8250df", "#b93a86", "#0b6c80", "#bf5b16",
927}
928
929var hexColorPat = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
930
931// labelColors returns a complete label-name -> chip color map for a repo:
932// the stored labels.color when it is a valid hex color, otherwise a
933// stable default picked from the palette by name hash.
934func (s *Server) labelColors(repoID int64) map[string]template.CSS {
935 stored, _ := s.st.LabelColors(repoID)
936 out := make(map[string]template.CSS, len(stored))
937 for name, color := range stored {
938 if !hexColorPat.MatchString(color) {
939 h := fnv.New32a()
940 h.Write([]byte(name))
941 color = labelPalette[h.Sum32()%uint32(len(labelPalette))]
942 }
943 out[name] = template.CSS("--chip:" + color)
944 }
945 return out
946}
947
948func (s *Server) issues(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 issues, err := s.st.ListIssues(p.Repo.ID, state)
959 if err != nil {
960 http.Error(w, "internal error", http.StatusInternalServerError)
961 return
962 }
963 if labels, err := s.st.ListIssueLabels(p.Repo.ID); err == nil {
964 for i := range issues {
965 issues[i].Labels = labels[issues[i].ID]
966 }
967 }
968 s.render(w, "issues.html", struct {
969 repoPage
970 State string
971 Issues []store.Issue
972 LabelColors map[string]template.CSS
973 }{p, state, issues, s.labelColors(p.Repo.ID)})
974}
975
976func (s *Server) issue(w http.ResponseWriter, r *http.Request) {
977 p, ok := s.repoFor(w, r, "")
978 if !ok {
979 return
980 }
981 p.Tab = "issues"
982 n, err := strconv.ParseInt(r.PathValue("n"), 10, 64)
983 if err != nil {
984 s.notFound(w, r)
985 return
986 }
987 iss, err := s.st.IssueByNumber(p.Repo.ID, n)
988 if err != nil {
989 s.notFound(w, r)
990 return
991 }
992 comments, err := s.st.ListIssueComments(iss.ID)
993 if err != nil {
994 http.Error(w, "internal error", http.StatusInternalServerError)
995 return
996 }
997 md := s.ugcFor(r, p.Repo)
998 s.render(w, "issue.html", struct {
999 repoPage
1000 Issue store.Issue
1001 BodyHTML template.HTML
1002 Comments []renderedComment
1003 LabelColors map[string]template.CSS
1004 }{p, iss, md(iss.Body), renderComments(comments, md), s.labelColors(p.Repo.ID)})
1005}
1006
1007func (s *Server) mrs(w http.ResponseWriter, r *http.Request) {
1008 p, ok := s.repoFor(w, r, "")
1009 if !ok {
1010 return
1011 }
1012 p.Tab = "merge requests"
1013 state := r.URL.Query().Get("state")
1014 if state == "" {
1015 state = "open"
1016 }
1017 valid := map[string]bool{"open": true, "merged": true, "closed": true, "source_gone": true, "all": true}
1018 if !valid[state] {
1019 state = "open"
1020 }
1021 mrs, err := s.st.ListMRs(p.Repo.ID, state)
1022 if err != nil {
1023 http.Error(w, "internal error", http.StatusInternalServerError)
1024 return
1025 }
1026 s.render(w, "mrs.html", struct {
1027 repoPage
1028 State string
1029 MRs []store.MR
1030 }{p, state, mrs})
1031}
1032
1033func (s *Server) mr(w http.ResponseWriter, r *http.Request) {
1034 p, ok := s.repoFor(w, r, "")
1035 if !ok {
1036 return
1037 }
1038 p.Tab = "merge requests"
1039 n, err := strconv.ParseInt(r.PathValue("n"), 10, 64)
1040 if err != nil {
1041 s.notFound(w, r)
1042 return
1043 }
1044 m, err := s.st.MRByNumber(p.Repo.ID, n)
1045 if err != nil {
1046 s.notFound(w, r)
1047 return
1048 }
1049 comments, _ := s.st.ListMRComments(m.ID)
1050 reviews, _ := s.st.ListMRReviews(m.ID)
1051 checks, _ := s.st.ListCommitStatuses(p.Repo.ID, m.HeadSHA)
1052 diffComments, _ := s.st.ListDiffComments(m.ID)
1053
1054 headRef := fmt.Sprintf("refs/merge-requests/%d/head", m.Number)
1055 var lines []diffLine
1056 base := m.MergedBase
1057 if base == "" {
1058 if b, err := gitutil.MergeBase(p.Dir, "refs/heads/"+m.TargetRef, headRef); err == nil {
1059 base = b
1060 }
1061 }
1062 if base != "" {
1063 if patch, err := gitutil.Diff(p.Dir, base, headRef, 4<<20); err == nil {
1064 lines = classifyDiff(patch)
1065 }
1066 }
1067 md := s.ugcFor(r, p.Repo)
1068 var detachedThreads []diffThread
1069 lines, detachedThreads = attachThreads(lines, diffComments, m.HeadSHA, md)
1070 type diffStat struct{ Files, Adds, Dels int }
1071 var stat diffStat
1072 seenFiles := map[string]bool{}
1073 for _, l := range lines {
1074 switch l.Class {
1075 case "add":
1076 stat.Adds++
1077 case "del":
1078 stat.Dels++
1079 }
1080 if l.Path != "" && !seenFiles[l.Path] {
1081 seenFiles[l.Path] = true
1082 stat.Files++
1083 }
1084 }
1085 s.render(w, "mr.html", struct {
1086 repoPage
1087 MR store.MR
1088 BodyHTML template.HTML
1089 Checks []store.CommitStatus
1090 Combined string
1091 Comments []renderedComment
1092 Reviews []store.MRReview
1093 DiffLines []diffLine
1094 Stat diffStat
1095 DetachedThreads []diffThread
1096 }{p, m, md(m.Body), checks, store.CombinedStatus(checks), renderComments(comments, md), reviews, lines, stat, detachedThreads})
1097}
1098
1099func (s *Server) refs(w http.ResponseWriter, r *http.Request) {
1100 p, ok := s.repoFor(w, r, "")
1101 if !ok {
1102 return
1103 }
1104 p.Tab = "refs"
1105 branches, _ := gitutil.Refs(p.Dir, "heads")
1106 tags, _ := gitutil.Refs(p.Dir, "tags")
1107 s.render(w, "refs.html", struct {
1108 repoPage
1109 Branches, Tags []gitutil.Ref
1110 }{p, branches, tags})
1111}
1112
1113func (s *Server) archive(w http.ResponseWriter, r *http.Request) {
1114 p, ok := s.repoFor(w, r, "")
1115 if !ok {
1116 return
1117 }
1118 file := r.PathValue("file")
1119 ref, ok := strings.CutSuffix(file, ".tar.gz")
1120 if !ok {
1121 s.notFound(w, r)
1122 return
1123 }
1124 if _, err := gitutil.ResolveRef(p.Dir, ref); err != nil {
1125 s.notFound(w, r)
1126 return
1127 }
1128 prefix := fmt.Sprintf("%s-%s", p.Repo.Name, ref)
1129 w.Header().Set("Content-Type", "application/gzip")
1130 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", prefix+".tar.gz"))
1131 gitutil.Archive(p.Dir, ref, prefix, w)
1132}
1133
1134func policyCanRead(u store.User, repo store.Repo, grant string) bool {
1135 return policy.CanRead(u, repo, grant)
1136}