~gitpocket/gitpocket

4
c0e915d5007aece28000cd7683df78cb1f26b900
mainfeed-discovery
gitpocket/extra.go -rw-r--r--18.8 KiB ViewLogBlameView rawPermalink 05701a4801 feat(repos): branch switcher and push notices 13 days ago
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
package main

import (
	"compress/gzip"
	"context"
	"crypto/sha256"
	"encoding/xml"
	"fmt"
	"html/template"
	"io"
	"mime"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"slices"
	"strconv"
	"strings"
	"sync"
	"time"
)

func (s *Server) star(w http.ResponseWriter, r *http.Request, repo Repo) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	s.store.Star(u.ID, repo.ID, !s.store.Starred(u.ID, repo.ID))
	http.Redirect(w, r, "/"+repo.Path(), http.StatusSeeOther)
}

func (s *Server) renameRepo(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _ := s.repoPage(r, repo, "")
	if !rp.IsOwner {
		s.fail(w, r, 403, "Not your repository")
		return
	}
	name := strings.TrimSpace(r.FormValue("name"))
	back := "/" + repo.Path() + "/settings"
	if name == repo.Name {
		http.Redirect(w, r, back, http.StatusSeeOther)
		return
	}
	if err := s.store.RenameRepo(repo.ID, name); err != nil {
		http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	renamed := repo
	renamed.Name = name
	if err := os.Rename(s.repoDir(repo), s.repoDir(renamed)); err != nil {
		s.store.RenameRepo(repo.ID, repo.Name)
		http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	s.store.AddRedirect(repo.Owner.Name, repo.Name, repo.ID)
	http.Redirect(w, r, "/"+renamed.Path()+"/settings", http.StatusSeeOther)
}

func (s *Server) transferRepo(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _ := s.repoPage(r, repo, "")
	if !rp.IsOwner {
		s.fail(w, r, 403, "Not your repository")
		return
	}
	back := "/" + repo.Path() + "/settings"
	target, err := s.store.UserByName(strings.TrimSpace(strings.TrimPrefix(r.FormValue("owner"), "~")))
	if err != nil {
		http.Redirect(w, r, back+"?error=No+such+user", http.StatusSeeOther)
		return
	}
	if target.ID == repo.Owner.ID {
		http.Redirect(w, r, back, http.StatusSeeOther)
		return
	}
	if r.FormValue("confirm") != repo.Name {
		http.Redirect(w, r, back+"?error=Type+the+repository+name+to+confirm+the+transfer", http.StatusSeeOther)
		return
	}
	if err := s.store.TransferRepo(repo.ID, target.ID); err != nil {
		http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	moved := repo
	moved.Owner = target
	os.MkdirAll(filepath.Dir(s.repoDir(moved)), 0o755)
	if err := os.Rename(s.repoDir(repo), s.repoDir(moved)); err != nil {
		s.store.TransferRepo(repo.ID, repo.Owner.ID)
		http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	s.store.AddRedirect(repo.Owner.Name, repo.Name, repo.ID)
	s.notify(s.store.VerifiedEmail(target.ID), fmt.Sprintf("[%s] repository transferred to you", moved.Path()),
		fmt.Sprintf("~%s transferred %s to you. It now lives at https://%s/%s\n", repo.Owner.Name, repo.Name, s.host, moved.Path()))
	http.Redirect(w, r, "/"+moved.Path(), http.StatusSeeOther)
}

func (s *Server) archiveRepo(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _ := s.repoPage(r, repo, "")
	if !rp.IsOwner {
		s.fail(w, r, 403, "Not your repository")
		return
	}
	s.store.SetArchived(repo.ID, !repo.Archived)
	http.Redirect(w, r, "/"+repo.Path()+"/settings", http.StatusSeeOther)
}

type BlameLine struct {
	Hash    string
	Author  string
	Time    time.Time
	Line    int
	Text    string
	First   bool
	Subject string
}

func (g Git) Blame(commit, filePath string) ([]BlameLine, error) {
	out, err := g.run(nil, "blame", "--porcelain", commit, "--", filePath)
	if err != nil {
		return nil, err
	}
	meta := map[string]*BlameLine{}
	var lines []BlameLine
	var cur *BlameLine
	for _, line := range strings.Split(string(out), "\n") {
		switch {
		case strings.HasPrefix(line, "\t"):
			if cur != nil {
				cur.Text = line[1:]
				lines = append(lines, *cur)
				cur = nil
			}
		case cur == nil:
			f := strings.Fields(line)
			if len(f) < 3 || len(f[0]) != 40 {
				continue
			}
			n, _ := strconv.Atoi(f[2])
			base := meta[f[0]]
			if base == nil {
				base = &BlameLine{Hash: f[0]}
				meta[f[0]] = base
			}
			cur = &BlameLine{Hash: f[0], Author: base.Author, Time: base.Time, Subject: base.Subject, Line: n}
		case strings.HasPrefix(line, "author "):
			meta[cur.Hash].Author = strings.TrimPrefix(line, "author ")
			cur.Author = meta[cur.Hash].Author
		case strings.HasPrefix(line, "author-time "):
			t, _ := strconv.ParseInt(strings.TrimPrefix(line, "author-time "), 10, 64)
			meta[cur.Hash].Time = time.Unix(t, 0)
			cur.Time = meta[cur.Hash].Time
		case strings.HasPrefix(line, "summary "):
			meta[cur.Hash].Subject = strings.TrimPrefix(line, "summary ")
			cur.Subject = meta[cur.Hash].Subject
		}
	}
	prev := ""
	for i := range lines {
		lines[i].First = lines[i].Hash != prev
		prev = lines[i].Hash
	}
	return lines, nil
}

func (s *Server) blame(w http.ResponseWriter, r *http.Request, repo Repo, spec string) {
	g := Git{Dir: s.repoDir(repo)}
	ref, filePath, ok := s.splitRef(g, spec)
	if !ok {
		s.fail(w, r, 404, "No such ref")
		return
	}
	filePath, ok = cleanPath(filePath)
	if !ok || filePath == "" {
		s.fail(w, r, 404, "No such path")
		return
	}
	rp, g, err := s.repoPage(r, repo, ref)
	if err != nil {
		s.fail(w, r, 404, "No such ref")
		return
	}
	rp.Tab = "tree"
	if g.Size(rp.Commit, filePath) > maxRender {
		s.fail(w, r, 413, "File too large to blame")
		return
	}
	lines, err := g.Blame(rp.Commit, filePath)
	if err != nil {
		s.fail(w, r, 404, "No such path")
		return
	}
	crumbs := strings.Split(filePath, "/")
	data := map[string]any{"Page": rp, "Path": filePath, "Crumbs": crumbs, "Lines": lines, "File": true, "Blame": true}
	if entry := g.Entry(rp.Commit, filePath); entry != nil {
		data["Entry"] = entry
	}
	if last, _ := g.Log(rp.Commit, 1, filePath); len(last) > 0 {
		data["LastCommit"] = last[0]
	}
	s.render(w, r, "blame", page{Title: repo.Path() + "/" + filePath + " blame", Data: data})
}

func (s *Server) compare(w http.ResponseWriter, r *http.Request, repo Repo, spec string) {
	rp, g, err := s.repoPage(r, repo, "")
	if err != nil {
		s.fail(w, r, 404, "No such ref")
		return
	}
	rp.Tab = "log"
	branches, _ := g.Refs("refs/heads")
	data := map[string]any{"Page": rp, "Branches": branches}
	base, head, ok := strings.Cut(spec, "...")
	if !ok {
		base, head = r.URL.Query().Get("base"), r.URL.Query().Get("head")
	}
	data["Base"], data["Head"] = base, head
	if base != "" && head != "" {
		bh, err1 := g.Resolve(base)
		hh, err2 := g.Resolve(head)
		if err1 != nil || err2 != nil {
			s.fail(w, r, 404, "No such ref")
			return
		}
		if mb, err := g.MergeBase(bh, hh); err == nil {
			commits, _ := g.LogRange(mb, hh, 200)
			files, _ := g.DiffRange(mb, hh)
			added, removed := 0, 0
			for _, f := range files {
				added += f.Added
				removed += f.Removed
			}
			data["Commits"], data["Files"], data["Added"], data["Removed"], data["HeadHash"] = commits, files, added, removed, hh
		} else {
			data["Unrelated"] = true
		}
	}
	s.render(w, r, "compare", page{Title: repo.Path() + " compare", Data: data})
}

func (s *Server) download(w http.ResponseWriter, r *http.Request, repo Repo, spec string) {
	g := Git{Dir: s.repoDir(repo)}
	digest := strings.HasSuffix(spec, ".sha256")
	spec = strings.TrimSuffix(spec, ".sha256")
	format := ""
	switch {
	case strings.HasSuffix(spec, ".tar.gz"):
		format, spec = "tar.gz", strings.TrimSuffix(spec, ".tar.gz")
	case strings.HasSuffix(spec, ".zip"):
		format, spec = "zip", strings.TrimSuffix(spec, ".zip")
	default:
		s.fail(w, r, 404, "Use .tar.gz or .zip")
		return
	}
	commit, err := g.Resolve(spec)
	if err != nil {
		s.fail(w, r, 404, "No such ref")
		return
	}
	safe := strings.Map(func(r rune) rune {
		if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '.' || r == '_' || r == '-' {
			return r
		}
		return '-'
	}, spec)
	name := repo.Name + "-" + safe
	file := name + "." + format
	ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
	defer cancel()
	if digest {
		sum := sha256.New()
		if err := writeArchive(ctx, sum, g.Dir, format, name, commit); err != nil {
			s.fail(w, r, 500, "Could not build the archive")
			return
		}
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		fmt.Fprintf(w, "%x  %s\n", sum.Sum(nil), file)
		return
	}
	w.Header().Set("ETag", `"`+commit+"-"+format+`"`)
	if commit == spec {
		w.Header().Set("Cache-Control", cacheScope(repo)+", max-age=31536000, immutable")
	}
	if r.Header.Get("If-None-Match") == `"`+commit+"-"+format+`"` {
		w.WriteHeader(http.StatusNotModified)
		return
	}
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": file}))
	writeArchive(ctx, w, g.Dir, format, name, commit)
}

func writeArchive(ctx context.Context, w io.Writer, dir, format, name, commit string) error {
	select {
	case archiveSlots <- struct{}{}:
	case <-ctx.Done():
		return ctx.Err()
	}
	defer func() { <-archiveSlots }()
	gitFormat := format
	if format == "tar.gz" {
		gitFormat = "tar"
	}
	cmd := exec.CommandContext(ctx, "git", "-C", dir, "-c", "core.autocrlf=false", "archive", "--format="+gitFormat, "--prefix="+name+"/", commit)
	cmd.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "TZ=UTC", "PATH=" + os.Getenv("PATH")}
	if format != "tar.gz" {
		cmd.Stdout = w
		return cmd.Run()
	}
	zw, _ := gzip.NewWriterLevel(w, gzip.BestCompression)
	zw.OS = 255
	cmd.Stdout = zw
	if err := cmd.Run(); err != nil {
		return err
	}
	return zw.Close()
}

type atomFeed struct {
	XMLName xml.Name    `xml:"feed"`
	NS      string      `xml:"xmlns,attr"`
	Title   string      `xml:"title"`
	ID      string      `xml:"id"`
	Updated string      `xml:"updated"`
	Link    atomLink    `xml:"link"`
	Entries []atomEntry `xml:"entry"`
}

type atomLink struct {
	Href string `xml:"href,attr"`
}

type atomEntry struct {
	Title   string   `xml:"title"`
	ID      string   `xml:"id"`
	Updated string   `xml:"updated"`
	Author  string   `xml:"author>name"`
	Link    atomLink `xml:"link"`
	Content string   `xml:"content"`
}

func (s *Server) feed(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, g, err := s.repoPage(r, repo, r.URL.Query().Get("ref"))
	if err != nil {
		s.fail(w, r, 404, "No such ref")
		return
	}
	base := "https://" + s.host + "/" + repo.Path()
	feed := atomFeed{NS: "http://www.w3.org/2005/Atom", Title: repo.Path() + " commits on " + rp.Ref, ID: base + "/feed", Link: atomLink{Href: base}, Updated: time.Now().UTC().Format(time.RFC3339)}
	if !rp.Empty {
		commits, _ := g.Log(rp.Commit, 30, "")
		for _, c := range commits {
			feed.Entries = append(feed.Entries, atomEntry{Title: c.Subject, ID: base + "/commit/" + c.Hash, Updated: c.Time.UTC().Format(time.RFC3339), Author: c.Author, Link: atomLink{Href: base + "/commit/" + c.Hash}, Content: c.Body})
		}
		if len(commits) > 0 {
			feed.Updated = commits[0].Time.UTC().Format(time.RFC3339)
		}
	}
	writeFeed(w, feed)
}

func writeFeed(w http.ResponseWriter, feed atomFeed) {
	feed.NS = "http://www.w3.org/2005/Atom"
	if feed.Updated == "" {
		feed.Updated = time.Unix(0, 0).UTC().Format(time.RFC3339)
	}
	w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
	w.Write([]byte(xml.Header))
	xml.NewEncoder(w).Encode(feed)
}

func stamp(t time.Time) string {
	return t.UTC().Format(time.RFC3339)
}

func (s *Server) issueFeed(w http.ResponseWriter, r *http.Request, repo Repo) {
	issues, _ := s.store.Issues(repo.ID, "")
	base := "https://" + s.host + "/" + repo.Path() + "/issues"
	feed := atomFeed{Title: repo.Path() + " issues", ID: base + "/feed", Link: atomLink{Href: base}}
	for i, is := range issues {
		if i == 50 {
			break
		}
		if feed.Updated == "" {
			feed.Updated = stamp(is.Updated)
		}
		link := fmt.Sprintf("%s/%d", base, is.Number)
		feed.Entries = append(feed.Entries, atomEntry{Title: fmt.Sprintf("#%d %s [%s]", is.Number, is.Title, is.State), ID: link, Updated: stamp(is.Updated), Author: "~" + is.Author.Name, Link: atomLink{Href: link}, Content: is.Body})
	}
	writeFeed(w, feed)
}

func (s *Server) pullFeed(w http.ResponseWriter, r *http.Request, repo Repo) {
	pulls, _ := s.store.Pulls(repo, "")
	slices.SortStableFunc(pulls, func(a, b Pull) int { return b.Updated.Compare(a.Updated) })
	base := "https://" + s.host + "/" + repo.Path() + "/pulls"
	feed := atomFeed{Title: repo.Path() + " pull requests", ID: base + "/feed", Link: atomLink{Href: base}}
	for i, p := range pulls {
		if i == 50 {
			break
		}
		if feed.Updated == "" {
			feed.Updated = stamp(p.Updated)
		}
		link := fmt.Sprintf("%s/%d", base, p.Number)
		feed.Entries = append(feed.Entries, atomEntry{Title: fmt.Sprintf("#%d %s [%s]", p.Number, p.Title, p.State), ID: link, Updated: stamp(p.Updated), Author: "~" + p.Author.Name, Link: atomLink{Href: link}, Content: p.Body})
	}
	writeFeed(w, feed)
}

func (s *Server) userFeed(w http.ResponseWriter, r *http.Request, owner User) {
	repos, _ := s.store.ReposByOwner(owner.ID, false)
	type entry struct {
		repo   Repo
		commit Commit
	}
	var all []entry
	for _, repo := range repos {
		if repo.Unlisted {
			continue
		}
		g := Git{Dir: s.repoDir(repo)}
		head, err := g.Resolve("HEAD")
		if err != nil {
			continue
		}
		commits, _ := g.Log(head, 20, "")
		for _, c := range commits {
			all = append(all, entry{repo, c})
		}
	}
	slices.SortStableFunc(all, func(a, b entry) int { return b.commit.Time.Compare(a.commit.Time) })
	base := "https://" + s.host + "/~" + owner.Name
	feed := atomFeed{Title: "~" + owner.Name + " commits", ID: base + "/feed", Link: atomLink{Href: base}}
	for i, e := range all {
		if i == 50 {
			break
		}
		if feed.Updated == "" {
			feed.Updated = stamp(e.commit.Time)
		}
		link := "https://" + s.host + "/" + e.repo.Path() + "/commit/" + e.commit.Hash
		feed.Entries = append(feed.Entries, atomEntry{Title: e.repo.Name + ": " + e.commit.Subject, ID: link, Updated: stamp(e.commit.Time), Author: e.commit.Author, Link: atomLink{Href: link}, Content: e.commit.Body})
	}
	writeFeed(w, feed)
}

type repoHistory struct {
	stamp   time.Time
	commits []historyCommit
}

type historyCommit struct {
	hash  uint64
	day   int32
	email int32
}

var histories = struct {
	sync.Mutex
	repos  map[int64]repoHistory
	emails map[string]int32
}{repos: map[int64]repoHistory{}, emails: map[string]int32{}}

func (s *Server) history(repo Repo) []historyCommit {
	dir := s.repoDir(repo)
	stamp := repoUpdated(dir)
	histories.Lock()
	h, ok := histories.repos[repo.ID]
	histories.Unlock()
	if ok && h.stamp.Equal(stamp) {
		return h.commits
	}
	out, err := Git{Dir: dir}.run(nil, "log", "--all", "--no-merges", "--format=%H%x09%at%x09%ae")
	if err != nil {
		return nil
	}
	var commits []historyCommit
	histories.Lock()
	for _, line := range strings.Split(string(out), "\n") {
		f := strings.Split(line, "\t")
		if len(f) != 3 || len(f[0]) < 16 {
			continue
		}
		hash, err := strconv.ParseUint(f[0][:16], 16, 64)
		if err != nil {
			continue
		}
		sec, _ := strconv.ParseInt(f[1], 10, 64)
		email := strings.ToLower(f[2])
		id, ok := histories.emails[email]
		if !ok {
			id = int32(len(histories.emails))
			histories.emails[email] = id
		}
		commits = append(commits, historyCommit{hash, int32(sec / 86400), id})
	}
	histories.repos[repo.ID] = repoHistory{stamp, commits}
	histories.Unlock()
	return commits
}

var activityCache = struct {
	sync.Mutex
	m map[int64]activityEntry
}{m: map[int64]activityEntry{}}

type activityEntry struct {
	at     time.Time
	counts map[string]int
}

func (s *Server) activityCounts(owner User) map[string]int {
	activityCache.Lock()
	e, ok := activityCache.m[owner.ID]
	activityCache.Unlock()
	if ok && time.Since(e.at) < 30*time.Second {
		return e.counts
	}
	counts := s.countActivity(owner)
	activityCache.Lock()
	if len(activityCache.m) > 4096 {
		clear(activityCache.m)
	}
	activityCache.m[owner.ID] = activityEntry{time.Now(), counts}
	activityCache.Unlock()
	return counts
}

func (s *Server) countActivity(owner User) map[string]int {
	counts := map[string]int{}
	org := s.store.IsOrg(owner.ID)
	email := strings.ToLower(s.store.VerifiedEmail(owner.ID))
	if email == "" && !org {
		return counts
	}
	want := int32(-1)
	if !org {
		histories.Lock()
		id, ok := histories.emails[email]
		histories.Unlock()
		if ok {
			want = id
		}
	}
	seen := map[uint64]bool{}
	repos, _ := s.store.PublicRepos("", "")
	for _, repo := range repos {
		if org && repo.Owner.ID != owner.ID {
			continue
		}
		commits := s.history(repo)
		if !org && want < 0 {
			histories.Lock()
			if id, ok := histories.emails[email]; ok {
				want = id
			}
			histories.Unlock()
		}
		for _, c := range commits {
			if (!org && c.email != want) || seen[c.hash] {
				continue
			}
			seen[c.hash] = true
			counts[time.Unix(int64(c.day)*86400, 0).UTC().Format("2006-01-02")]++
		}
	}
	return counts
}

type heatView struct {
	Grid  template.HTML
	Total int
	Year  int
	Years []int
}

func (s *Server) activity(owner User, year int) heatView {
	counts := s.activityCounts(owner)
	today := time.Now().UTC().Truncate(24 * time.Hour)
	years := map[int]bool{}
	for y := min(owner.Created.UTC().Year(), today.Year()); y <= today.Year(); y++ {
		years[y] = true
	}
	for day := range counts {
		y, _ := strconv.Atoi(day[:4])
		years[y] = true
	}
	view := heatView{Year: year}
	for y := range years {
		view.Years = append(view.Years, y)
	}
	slices.SortFunc(view.Years, func(a, b int) int { return b - a })
	first, last := today.AddDate(0, 0, -364), today
	if year != 0 {
		first = time.Date(year, 1, 1, 0, 0, 0, 0, time.UTC)
		last = time.Date(year, 12, 31, 0, 0, 0, 0, time.UTC)
	}
	start := first.AddDate(0, 0, -int(first.Weekday()))
	weeks := int(last.Sub(start).Hours()/24)/7 + 1
	peak := 0
	for d := first; !d.After(last); d = d.AddDate(0, 0, 1) {
		n := counts[d.Format("2006-01-02")]
		peak = max(peak, n)
		view.Total += n
	}
	var b strings.Builder
	fmt.Fprintf(&b, `<div class="heat" style="--weeks:%d"><div class="months">`, weeks)
	lastMonth := -1
	for w := 0; w < weeks; w++ {
		d := start.AddDate(0, 0, 7*w)
		if d.Before(first) {
			d = first
		}
		if int(d.Month()) != lastMonth && w < weeks-2 {
			lastMonth = int(d.Month())
			fmt.Fprintf(&b, `<span style="grid-column:%d">%s</span>`, w+1, d.Format("Jan"))
		}
	}
	b.WriteString(`</div><div class="days"><span></span><span>Mon</span><span></span><span>Wed</span><span></span><span>Fri</span><span></span></div><div class="cells">`)
	for d := start; !d.After(last) || d.Weekday() != 0; d = d.AddDate(0, 0, 1) {
		if d.Before(first) || d.After(last) {
			b.WriteString(`<span class="pad"></span>`)
			continue
		}
		n := counts[d.Format("2006-01-02")]
		level := 0
		if n > 0 {
			level = 1 + min(3, (n-1)*4/max(peak, 1))
		}
		tip := "No commits"
		if n == 1 {
			tip = "1 commit"
		} else if n > 1 {
			tip = strconv.Itoa(n) + " commits"
		}
		tip += " on " + d.Format("2 January 2006")
		week := int(d.Sub(start).Hours()/24) / 7
		edge := ""
		if week < 6 {
			edge = " l"
		} else if week > weeks-7 {
			edge = " r"
		}
		fmt.Fprintf(&b, `<span class="c h%d%s" data-tip="%s" aria-label="%s" tabindex="0"></span>`, level, edge, tip, tip)
	}
	b.WriteString(`</div></div>`)
	view.Grid = template.HTML(b.String())
	return view
}