~gitpocket/gitpocket

1
7093e5fd3c1fa8199453c6347ebfe8bcda76e3ea
mainfeed-discovery
gitpocket/web.go -rw-r--r--19.0 KiB ViewLogBlameView rawPermalink 7093e5fd3c feat(basin): minimal git host with ssh and smart https 1 months 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
package main

import (
	"bytes"
	"embed"
	"fmt"
	"html/template"
	"io/fs"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/microcosm-cc/bluemonday"
	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
)

//go:embed templates/*.html
var templateFS embed.FS

//go:embed static
var staticFS embed.FS

type Server struct {
	store    *Store
	root     string
	host     string
	open     bool
	pages    map[string]*template.Template
	markdown goldmark.Markdown
	policy   *bluemonday.Policy
}

type page struct {
	Title string
	User  *User
	Host  string
	Error string
	Data  any
}

func newServer(store *Store, root, host string, open bool) *Server {
	s := &Server{store: store, root: root, host: host, open: open, pages: map[string]*template.Template{}}
	funcs := template.FuncMap{
		"short": func(h string) string {
			if len(h) > 10 {
				return h[:10]
			}
			return h
		},
		"ago":  ago,
		"size": humanSize,
		"date": func(t time.Time) string { return t.UTC().Format("2006-01-02 15:04") },
		"lines": func(b []byte) []string {
			s := strings.TrimSuffix(string(b), "\n")
			return strings.Split(s, "\n")
		},
		"inc":    func(i int) int { return i + 1 },
		"join":   func(parts []string, upto int) string { return strings.Join(parts[:upto], "/") },
		"string": func(b []byte) string { return string(b) },
	}
	names, _ := fs.Glob(templateFS, "templates/*.html")
	for _, name := range names {
		base := filepath.Base(name)
		if base == "layout.html" {
			continue
		}
		s.pages[strings.TrimSuffix(base, ".html")] = template.Must(template.New("layout.html").Funcs(funcs).ParseFS(templateFS, "templates/layout.html", name))
	}
	s.markdown = goldmark.New(goldmark.WithExtensions(extension.GFM))
	s.policy = bluemonday.UGCPolicy()
	return s
}

func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p page) {
	p.Host = s.host
	if p.User == nil {
		p.User = s.current(r)
	}
	t, ok := s.pages[name]
	if !ok {
		http.Error(w, "missing template "+name, 500)
		return
	}
	var buf bytes.Buffer
	if err := t.Execute(&buf, p); err != nil {
		log.Printf("render %s: %v", name, err)
		http.Error(w, "template error", 500)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	buf.WriteTo(w)
}

func (s *Server) fail(w http.ResponseWriter, r *http.Request, code int, msg string) {
	w.WriteHeader(code)
	s.render(w, r, "error", page{Title: msg, Error: msg})
}

func (s *Server) current(r *http.Request) *User {
	c, err := r.Cookie("session")
	if err != nil {
		return nil
	}
	u, err := s.store.SessionUser(c.Value)
	if err != nil {
		return nil
	}
	return &u
}

func (s *Server) handler() http.Handler {
	mux := http.NewServeMux()
	static, _ := fs.Sub(staticFS, "static")
	mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))
	mux.HandleFunc("GET /{$}", s.index)
	mux.HandleFunc("GET /login", s.loginForm)
	mux.HandleFunc("POST /login", s.login)
	mux.HandleFunc("POST /logout", s.logout)
	mux.HandleFunc("GET /register", s.registerForm)
	mux.HandleFunc("POST /register", s.register)
	mux.HandleFunc("GET /create", s.createForm)
	mux.HandleFunc("POST /create", s.create)
	mux.HandleFunc("GET /settings", s.settings)
	mux.HandleFunc("POST /settings/keys", s.addKey)
	mux.HandleFunc("POST /settings/keys/{id}/delete", s.deleteKey)
	mux.HandleFunc("POST /settings/tokens", s.addToken)
	mux.HandleFunc("POST /settings/tokens/{id}/delete", s.deleteToken)
	mux.HandleFunc("POST /settings/password", s.password)
	mux.HandleFunc("/", s.route)
	cop := http.NewCrossOriginProtection()
	return cop.Handler(mux)
}

func (s *Server) index(w http.ResponseWriter, r *http.Request) {
	user := s.current(r)
	var repos []Repo
	var err error
	if user != nil {
		repos, err = s.store.ReposByOwner(user.ID, true)
	} else {
		repos, err = s.store.RecentRepos(30)
	}
	if err != nil {
		s.fail(w, r, 500, err.Error())
		return
	}
	users, public := s.store.Stats()
	s.render(w, r, "index", page{Title: s.host, User: user, Data: map[string]any{"Repos": repos, "Users": users, "Public": public}})
}

func (s *Server) loginForm(w http.ResponseWriter, r *http.Request) {
	s.render(w, r, "login", page{Title: "log in"})
}

func (s *Server) login(w http.ResponseWriter, r *http.Request) {
	u, ok := s.store.CheckPassword(strings.TrimSpace(r.FormValue("name")), r.FormValue("password"))
	if !ok {
		w.WriteHeader(401)
		s.render(w, r, "login", page{Title: "log in", Error: "wrong name or password"})
		return
	}
	s.startSession(w, u)
	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func (s *Server) startSession(w http.ResponseWriter, u User) {
	id, err := s.store.CreateSession(u.ID)
	if err != nil {
		return
	}
	http.SetCookie(w, &http.Cookie{Name: "session", Value: id, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: 90 * 86400})
}

func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
	if c, err := r.Cookie("session"); err == nil {
		s.store.DeleteSession(c.Value)
	}
	http.SetCookie(w, &http.Cookie{Name: "session", Value: "", Path: "/", MaxAge: -1})
	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func (s *Server) registerForm(w http.ResponseWriter, r *http.Request) {
	s.render(w, r, "register", page{Title: "register", Data: map[string]any{"Open": s.open, "Invite": r.URL.Query().Get("invite")}})
}

func (s *Server) register(w http.ResponseWriter, r *http.Request) {
	invite := strings.TrimSpace(r.FormValue("invite"))
	retry := func(msg string) {
		w.WriteHeader(400)
		s.render(w, r, "register", page{Title: "register", Error: msg, Data: map[string]any{"Open": s.open, "Invite": invite}})
	}
	if !s.open && !s.store.UseInvite(invite) {
		retry("that invite is invalid or already used")
		return
	}
	u, err := s.store.CreateUser(strings.TrimSpace(r.FormValue("name")), r.FormValue("password"))
	if err != nil {
		retry(err.Error())
		return
	}
	s.startSession(w, u)
	http.Redirect(w, r, "/settings", http.StatusSeeOther)
}

func (s *Server) require(w http.ResponseWriter, r *http.Request) *User {
	u := s.current(r)
	if u == nil {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
	}
	return u
}

func (s *Server) createForm(w http.ResponseWriter, r *http.Request) {
	if u := s.require(w, r); u != nil {
		s.render(w, r, "create", page{Title: "new repository", User: u})
	}
}

func (s *Server) create(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	name := strings.TrimSpace(r.FormValue("name"))
	repo, err := s.store.CreateRepo(*u, name, strings.TrimSpace(r.FormValue("description")), r.FormValue("private") == "on")
	if err != nil {
		w.WriteHeader(400)
		s.render(w, r, "create", page{Title: "new repository", User: u, Error: err.Error()})
		return
	}
	dir := s.repoDir(repo)
	if err := os.MkdirAll(filepath.Dir(dir), 0o755); err == nil {
		err = initRepo(dir)
	}
	if err != nil {
		s.store.DeleteRepo(repo.ID)
		s.fail(w, r, 500, err.Error())
		return
	}
	http.Redirect(w, r, "/"+repo.Path(), http.StatusSeeOther)
}

func (s *Server) repoDir(repo Repo) string {
	return filepath.Join(s.root, "repos", repo.Owner.Name, repo.Name+".git")
}

func (s *Server) settings(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	keys, _ := s.store.Keys(u.ID)
	tokens, _ := s.store.Tokens(u.ID)
	s.render(w, r, "settings", page{Title: "settings", User: u, Error: r.URL.Query().Get("error"),
		Data: map[string]any{"Keys": keys, "Tokens": tokens, "NewToken": r.URL.Query().Get("token")}})
}

func (s *Server) addKey(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	if err := s.store.AddKey(u.ID, strings.TrimSpace(r.FormValue("title")), r.FormValue("key")); err != nil {
		http.Redirect(w, r, "/settings?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	http.Redirect(w, r, "/settings", http.StatusSeeOther)
}

func (s *Server) deleteKey(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
	s.store.DeleteKey(u.ID, id)
	http.Redirect(w, r, "/settings", http.StatusSeeOther)
}

func (s *Server) addToken(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	token, err := s.store.CreateToken(u.ID, strings.TrimSpace(r.FormValue("title")))
	if err != nil {
		http.Redirect(w, r, "/settings?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	http.Redirect(w, r, "/settings?token="+token, http.StatusSeeOther)
}

func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
	s.store.DeleteToken(u.ID, id)
	http.Redirect(w, r, "/settings", http.StatusSeeOther)
}

func (s *Server) password(w http.ResponseWriter, r *http.Request) {
	u := s.require(w, r)
	if u == nil {
		return
	}
	if _, ok := s.store.CheckPassword(u.Name, r.FormValue("current")); !ok {
		http.Redirect(w, r, "/settings?error=current+password+is+wrong", http.StatusSeeOther)
		return
	}
	if err := s.store.SetPassword(u.ID, r.FormValue("password")); err != nil {
		http.Redirect(w, r, "/settings?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
		return
	}
	http.Redirect(w, r, "/settings", http.StatusSeeOther)
}

func (s *Server) route(w http.ResponseWriter, r *http.Request) {
	if !strings.HasPrefix(r.URL.Path, "/~") {
		s.fail(w, r, 404, "page not found")
		return
	}
	parts := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/~"), "/", 3)
	owner, err := s.store.UserByName(parts[0])
	if err != nil {
		s.fail(w, r, 404, "no such user")
		return
	}
	user := s.current(r)
	if len(parts) == 1 || (len(parts) == 2 && parts[1] == "") {
		repos, err := s.store.ReposByOwner(owner.ID, user != nil && user.ID == owner.ID)
		if err != nil {
			s.fail(w, r, 500, err.Error())
			return
		}
		s.render(w, r, "user", page{Title: "~" + owner.Name, User: user, Data: map[string]any{"Owner": owner, "Repos": repos}})
		return
	}
	name := parts[1]
	rest := ""
	if len(parts) == 3 {
		rest = parts[2]
	}
	if strings.HasSuffix(name, ".git") || isSmart(r, rest) {
		s.smart(w, r, owner, strings.TrimSuffix(name, ".git"), rest)
		return
	}
	repo, err := s.store.RepoByPath(owner.Name, name)
	if err != nil {
		s.fail(w, r, 404, "no such repository")
		return
	}
	if repo.Private && (user == nil || user.ID != owner.ID) {
		s.fail(w, r, 404, "no such repository")
		return
	}
	switch {
	case rest == "" && r.Method == "GET":
		s.summary(w, r, repo)
	case rest == "settings" && r.Method == "GET":
		s.repoSettings(w, r, repo)
	case rest == "settings" && r.Method == "POST":
		s.updateRepo(w, r, repo)
	case rest == "delete" && r.Method == "POST":
		s.deleteRepo(w, r, repo)
	case rest == "refs" && r.Method == "GET":
		s.refs(w, r, repo)
	case strings.HasPrefix(rest, "tree/") && r.Method == "GET":
		s.tree(w, r, repo, strings.TrimPrefix(rest, "tree/"))
	case strings.HasPrefix(rest, "blob/") && r.Method == "GET":
		s.tree(w, r, repo, strings.TrimPrefix(rest, "blob/"))
	case strings.HasPrefix(rest, "raw/") && r.Method == "GET":
		s.raw(w, r, repo, strings.TrimPrefix(rest, "raw/"))
	case strings.HasPrefix(rest, "log/") && r.Method == "GET":
		s.log(w, r, repo, strings.TrimPrefix(rest, "log/"))
	case rest == "log" && r.Method == "GET":
		s.log(w, r, repo, "")
	case strings.HasPrefix(rest, "commit/") && r.Method == "GET":
		s.commit(w, r, repo, strings.TrimPrefix(rest, "commit/"))
	default:
		s.fail(w, r, 404, "page not found")
	}
}

type repoPage struct {
	Repo   Repo
	Ref    string
	Commit string
	Owner  bool
	Empty  bool
}

func (s *Server) repoPage(r *http.Request, repo Repo, ref string) (repoPage, Git, error) {
	g := Git{Dir: s.repoDir(repo)}
	user := s.current(r)
	rp := repoPage{Repo: repo, Owner: user != nil && user.ID == repo.Owner.ID}
	if g.Empty() {
		rp.Empty = true
		rp.Ref = g.Head()
		return rp, g, nil
	}
	if ref == "" {
		ref = g.Head()
	}
	commit, err := g.Resolve(ref)
	if err != nil {
		return rp, g, err
	}
	rp.Ref = ref
	rp.Commit = commit
	return rp, g, nil
}

func (s *Server) summary(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, g, err := s.repoPage(r, repo, "")
	if err != nil {
		s.fail(w, r, 404, "no such ref")
		return
	}
	data := map[string]any{"Page": rp}
	if !rp.Empty {
		commits, _ := g.Log(rp.Commit, 8, "")
		data["Commits"] = commits
		branches, _ := g.Refs("refs/heads")
		tags, _ := g.Refs("refs/tags")
		data["Branches"] = branches
		data["Tags"] = tags
		name, content := g.Readme(rp.Commit)
		if name != "" {
			data["ReadmeName"] = name
			if strings.HasSuffix(strings.ToLower(name), ".md") {
				data["Readme"] = s.renderMarkdown(content)
			} else {
				data["ReadmeText"] = string(content)
			}
		}
	}
	s.render(w, r, "repo", page{Title: repo.Path(), Data: data})
}

func (s *Server) renderMarkdown(src []byte) template.HTML {
	var buf bytes.Buffer
	if err := s.markdown.Convert(src, &buf); err != nil {
		return template.HTML("<pre>" + template.HTMLEscapeString(string(src)) + "</pre>")
	}
	return template.HTML(s.policy.SanitizeBytes(buf.Bytes()))
}

func (s *Server) splitRef(g Git, spec string) (string, string, bool) {
	spec = strings.Trim(spec, "/")
	if spec == "" {
		return "", "", false
	}
	parts := strings.Split(spec, "/")
	for i := len(parts); i >= 1; i-- {
		ref := strings.Join(parts[:i], "/")
		if _, err := g.Resolve(ref); err == nil {
			return ref, strings.Join(parts[i:], "/"), true
		}
	}
	return "", "", false
}

func (s *Server) tree(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 {
		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
	}
	crumbs := strings.Split(filePath, "/")
	if filePath == "" {
		crumbs = nil
	}
	data := map[string]any{"Page": rp, "Path": filePath, "Crumbs": crumbs}
	switch g.Kind(rp.Commit, filePath) {
	case "tree", "commit":
		entries, err := g.Tree(rp.Commit, filePath)
		if err != nil {
			s.fail(w, r, 404, "no such path")
			return
		}
		data["Entries"] = entries
		s.render(w, r, "tree", page{Title: repo.Path() + "/" + filePath, Data: data})
	case "blob":
		content, err := g.Blob(rp.Commit, filePath)
		if err != nil {
			s.fail(w, r, 404, "no such path")
			return
		}
		data["Size"] = int64(len(content))
		if isBinary(content) {
			data["Binary"] = true
		} else if len(content) > 1<<20 {
			data["Large"] = true
		} else {
			data["Content"] = content
		}
		s.render(w, r, "blob", page{Title: repo.Path() + "/" + filePath, Data: data})
	default:
		s.fail(w, r, 404, "no such path")
	}
}

func (s *Server) raw(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
	}
	commit, err := g.Resolve(ref)
	if err != nil {
		s.fail(w, r, 404, "no such ref")
		return
	}
	content, err := g.Blob(commit, filePath)
	if err != nil {
		s.fail(w, r, 404, "no such path")
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.Header().Set("Content-Disposition", "inline; filename=\""+filepath.Base(filePath)+"\"")
	w.Write(content)
}

func (s *Server) log(w http.ResponseWriter, r *http.Request, repo Repo, ref string) {
	ref = strings.Trim(ref, "/")
	rp, g, err := s.repoPage(r, repo, ref)
	if err != nil {
		s.fail(w, r, 404, "no such ref")
		return
	}
	data := map[string]any{"Page": rp}
	if !rp.Empty {
		start := rp.Commit
		if from := r.URL.Query().Get("from"); from != "" {
			if start, err = g.Resolve(from); err != nil {
				s.fail(w, r, 404, "no such commit")
				return
			}
		}
		const per = 50
		commits, err := g.Log(start, per+1, "")
		if err != nil {
			s.fail(w, r, 500, err.Error())
			return
		}
		if len(commits) > per {
			data["Next"] = commits[per].Hash
			commits = commits[:per]
		}
		data["Commits"] = commits
	}
	s.render(w, r, "log", page{Title: repo.Path() + " log", Data: data})
}

func (s *Server) commit(w http.ResponseWriter, r *http.Request, repo Repo, hash string) {
	rp, g, err := s.repoPage(r, repo, hash)
	if err != nil {
		s.fail(w, r, 404, "no such commit")
		return
	}
	c, err := g.Commit(rp.Commit)
	if err != nil {
		s.fail(w, r, 404, "no such commit")
		return
	}
	files, err := g.Diff(rp.Commit)
	if err != nil {
		s.fail(w, r, 500, err.Error())
		return
	}
	added, removed := 0, 0
	for _, f := range files {
		added += f.Added
		removed += f.Removed
	}
	s.render(w, r, "commit", page{Title: c.Subject, Data: map[string]any{"Page": rp, "Commit": c, "Files": files, "Added": added, "Removed": removed}})
}

func (s *Server) refs(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, g, err := s.repoPage(r, repo, "")
	if err != nil {
		s.fail(w, r, 404, "no such ref")
		return
	}
	branches, _ := g.Refs("refs/heads")
	tags, _ := g.Refs("refs/tags")
	s.render(w, r, "refs", page{Title: repo.Path() + " refs", Data: map[string]any{"Page": rp, "Branches": branches, "Tags": tags}})
}

func (s *Server) repoSettings(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _ := s.repoPage(r, repo, "")
	if !rp.Owner {
		s.fail(w, r, 403, "not your repository")
		return
	}
	s.render(w, r, "reposettings", page{Title: repo.Path() + " settings", Data: map[string]any{"Page": rp}})
}

func (s *Server) updateRepo(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _ := s.repoPage(r, repo, "")
	if !rp.Owner {
		s.fail(w, r, 403, "not your repository")
		return
	}
	if err := s.store.UpdateRepo(repo.ID, strings.TrimSpace(r.FormValue("description")), r.FormValue("private") == "on"); err != nil {
		s.fail(w, r, 500, err.Error())
		return
	}
	http.Redirect(w, r, "/"+repo.Path(), http.StatusSeeOther)
}

func (s *Server) deleteRepo(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _ := s.repoPage(r, repo, "")
	if !rp.Owner {
		s.fail(w, r, 403, "not your repository")
		return
	}
	if r.FormValue("confirm") != repo.Name {
		http.Redirect(w, r, "/"+repo.Path()+"/settings", http.StatusSeeOther)
		return
	}
	if err := s.store.DeleteRepo(repo.ID); err != nil {
		s.fail(w, r, 500, err.Error())
		return
	}
	os.RemoveAll(s.repoDir(repo))
	http.Redirect(w, r, "/~"+repo.Owner.Name, http.StatusSeeOther)
}

func ago(t time.Time) string {
	d := time.Since(t)
	switch {
	case d < time.Minute:
		return "just now"
	case d < time.Hour:
		return fmt.Sprintf("%d minutes ago", int(d.Minutes()))
	case d < 2*time.Hour:
		return "an hour ago"
	case d < 24*time.Hour:
		return fmt.Sprintf("%d hours ago", int(d.Hours()))
	case d < 48*time.Hour:
		return "yesterday"
	case d < 30*24*time.Hour:
		return fmt.Sprintf("%d days ago", int(d.Hours()/24))
	case d < 365*24*time.Hour:
		return fmt.Sprintf("%d months ago", int(d.Hours()/24/30))
	default:
		return fmt.Sprintf("%d years ago", int(d.Hours()/24/365))
	}
}

func humanSize(n int64) string {
	switch {
	case n < 1024:
		return fmt.Sprintf("%d B", n)
	case n < 1<<20:
		return fmt.Sprintf("%.1f KiB", float64(n)/1024)
	default:
		return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
	}
}