~gitpocket/gitpocket

4
7db58612d2bb8f4814c5b26fe7970e0cb12a451f
mainfeed-discovery
gitpocket/pull.go -rw-r--r--21.2 KiB ViewLogBlameView rawPermalink e8ffab4e14 feat(basin): mail, totp, issues, stars, blame and feeds 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
package main

import (
	"database/sql"
	"errors"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

const pullSchema = `
create table if not exists pulls (
	id integer primary key,
	repo integer not null references repos(id) on delete cascade,
	number integer not null,
	author integer not null references users(id) on delete cascade,
	title text not null,
	body text not null default '',
	source_repo integer not null,
	source_branch text not null,
	target_branch text not null,
	state text not null default 'open',
	created integer not null,
	updated integer not null,
	merged text not null default '',
	unique(repo, number)
);
create table if not exists reviews (
	id integer primary key,
	pull integer not null references pulls(id) on delete cascade,
	author integer not null references users(id) on delete cascade,
	path text not null,
	side text not null,
	line integer not null,
	body text not null,
	resolved integer not null default 0,
	created integer not null
);
create table if not exists comments (
	id integer primary key,
	pull integer not null references pulls(id) on delete cascade,
	author integer not null references users(id) on delete cascade,
	body text not null,
	created integer not null
);
`

type Pull struct {
	ID           int64
	Number       int64
	Repo         Repo
	Author       User
	Title        string
	Body         string
	SourceRepo   Repo
	SourceBranch string
	TargetBranch string
	State        string
	Created      time.Time
	Updated      time.Time
	Merged       string
	Comments     int
}

type Review struct {
	ID       int64
	Author   User
	Path     string
	Side     string
	Line     int
	Body     string
	Resolved bool
	Created  time.Time
	HTML     template.HTML
	URL      string
	CanEdit  bool
}

func (r Review) Key() string {
	return fmt.Sprintf("%s:%s:%d", r.Path, r.Side, r.Line)
}

type Comment struct {
	ID      int64
	Author  User
	Body    string
	Created time.Time
}

func (p Pull) Ref() string {
	return fmt.Sprintf("refs/pull/%d/head", p.Number)
}

func (p Pull) SameRepo() bool {
	return p.SourceRepo.ID == p.Repo.ID
}

func (s *Store) CreatePull(repo Repo, author User, title, body string, source Repo, sourceBranch, targetBranch string) (Pull, error) {
	title = strings.TrimSpace(title)
	if title == "" || len(title) > 200 {
		return Pull{}, errors.New("Title is required and at most 200 characters")
	}
	now := time.Now().Unix()
	var number int64
	tx, err := s.db.Begin()
	if err != nil {
		return Pull{}, err
	}
	defer tx.Rollback()
	tx.QueryRow(`select coalesce(max(number), 0) + 1 from pulls where repo = ?`, repo.ID).Scan(&number)
	res, err := tx.Exec(`insert into pulls(repo, number, author, title, body, source_repo, source_branch, target_branch, state, created, updated) values (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)`,
		repo.ID, number, author.ID, title, body, source.ID, sourceBranch, targetBranch, now, now)
	if err != nil {
		return Pull{}, err
	}
	if err := tx.Commit(); err != nil {
		return Pull{}, err
	}
	id, _ := res.LastInsertId()
	return Pull{ID: id, Number: number, Repo: repo, Author: author, Title: title, Body: body, SourceRepo: source, SourceBranch: sourceBranch, TargetBranch: targetBranch, State: "open"}, nil
}

func (s *Store) scanPulls(rows *sql.Rows) ([]Pull, error) {
	defer rows.Close()
	var pulls []Pull
	for rows.Next() {
		var p Pull
		var created, updated, aCreated int64
		var sourceID int64
		if err := rows.Scan(&p.ID, &p.Number, &p.Title, &p.Body, &sourceID, &p.SourceBranch, &p.TargetBranch, &p.State, &created, &updated, &p.Merged, &p.Comments, &p.Author.ID, &p.Author.Name, &aCreated); err != nil {
			return nil, err
		}
		p.Created, p.Updated, p.Author.Created = time.Unix(created, 0), time.Unix(updated, 0), time.Unix(aCreated, 0)
		p.SourceRepo.ID = sourceID
		pulls = append(pulls, p)
	}
	return pulls, rows.Err()
}

const pullColumns = `p.id, p.number, p.title, p.body, p.source_repo, p.source_branch, p.target_branch, p.state, p.created, p.updated, p.merged,
	(select count(*) from comments c where c.pull = p.id), u.id, u.name, u.created from pulls p join users u on u.id = p.author`

func (s *Store) Pulls(repo Repo, state string) ([]Pull, error) {
	rows, err := s.db.Query(`select `+pullColumns+` where p.repo = ? and (? = '' or p.state = ?) order by p.number desc`, repo.ID, state, state)
	if err != nil {
		return nil, err
	}
	pulls, err := s.scanPulls(rows)
	for i := range pulls {
		pulls[i].Repo = repo
		s.fillSource(&pulls[i])
	}
	return pulls, err
}

func (s *Store) Pull(repo Repo, number int64) (Pull, error) {
	rows, err := s.db.Query(`select `+pullColumns+` where p.repo = ? and p.number = ?`, repo.ID, number)
	if err != nil {
		return Pull{}, err
	}
	pulls, err := s.scanPulls(rows)
	if err != nil || len(pulls) == 0 {
		return Pull{}, ErrNotFound
	}
	p := pulls[0]
	p.Repo = repo
	s.fillSource(&p)
	return p, nil
}

func (s *Store) fillSource(p *Pull) {
	if p.SourceRepo.ID == p.Repo.ID {
		p.SourceRepo = p.Repo
		return
	}
	rows, err := s.db.Query(`select `+repoColumns+` where r.id = ?`, p.SourceRepo.ID)
	if err != nil {
		return
	}
	if repos, _ := scanRepos(rows); len(repos) == 1 {
		p.SourceRepo = repos[0]
	}
}

func (s *Store) SetPullState(id int64, state, merged string) error {
	_, err := s.db.Exec(`update pulls set state = ?, merged = ?, updated = ? where id = ?`, state, merged, time.Now().Unix(), id)
	return err
}

func (s *Store) TouchPull(id int64) {
	s.db.Exec(`update pulls set updated = ? where id = ?`, time.Now().Unix(), id)
}

func (s *Store) AddComment(pull int64, author User, body string) error {
	body = strings.TrimSpace(body)
	if body == "" || len(body) > 20000 {
		return errors.New("Comment is empty or too long")
	}
	_, err := s.db.Exec(`insert into comments(pull, author, body, created) values (?, ?, ?, ?)`, pull, author.ID, body, time.Now().Unix())
	s.TouchPull(pull)
	return err
}

func (s *Store) AddReview(pull int64, author User, path, side string, line int, body string) error {
	body = strings.TrimSpace(body)
	if body == "" || len(body) > 20000 {
		return errors.New("Comment is empty or too long")
	}
	if side != "n" && side != "o" || line <= 0 || path == "" {
		return errors.New("Bad line reference")
	}
	_, err := s.db.Exec(`insert into reviews(pull, author, path, side, line, body, created) values (?, ?, ?, ?, ?, ?, ?)`, pull, author.ID, path, side, line, body, time.Now().Unix())
	s.TouchPull(pull)
	return err
}

func (s *Store) Reviews(pull int64) ([]Review, error) {
	rows, err := s.db.Query(`select r.id, r.path, r.side, r.line, r.body, r.resolved, r.created, u.id, u.name, u.created from reviews r join users u on u.id = r.author where r.pull = ? order by r.id`, pull)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Review
	for rows.Next() {
		var r Review
		var resolved int
		var created, uCreated int64
		if err := rows.Scan(&r.ID, &r.Path, &r.Side, &r.Line, &r.Body, &resolved, &created, &r.Author.ID, &r.Author.Name, &uCreated); err != nil {
			return nil, err
		}
		r.Resolved = resolved != 0
		r.Created, r.Author.Created = time.Unix(created, 0), time.Unix(uCreated, 0)
		out = append(out, r)
	}
	return out, rows.Err()
}

func (s *Store) ReviewAuthor(id int64) int64 {
	var author int64
	s.db.QueryRow(`select author from reviews where id = ?`, id).Scan(&author)
	return author
}

func (s *Store) ResolveReview(id int64, resolved bool) {
	s.db.Exec(`update reviews set resolved = ? where id = ?`, resolved, id)
}

func (s *Store) DeleteReview(id int64) {
	s.db.Exec(`delete from reviews where id = ?`, id)
}

func (s *Store) Comments(pull int64) ([]Comment, error) {
	rows, err := s.db.Query(`select c.id, c.body, c.created, u.id, u.name, u.created from comments c join users u on u.id = c.author where c.pull = ? order by c.id`, pull)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []Comment
	for rows.Next() {
		var c Comment
		var created, uCreated int64
		if err := rows.Scan(&c.ID, &c.Body, &created, &c.Author.ID, &c.Author.Name, &uCreated); err != nil {
			return nil, err
		}
		c.Created, c.Author.Created = time.Unix(created, 0), time.Unix(uCreated, 0)
		out = append(out, c)
	}
	return out, rows.Err()
}

func (s *Store) OpenPullCount(repo int64) int {
	var n int
	s.db.QueryRow(`select count(*) from pulls where repo = ? and state = 'open'`, repo).Scan(&n)
	return n
}

func (s *Store) Forks(parent int64, viewer int64) ([]Repo, error) {
	rows, err := s.db.Query(`select `+repoColumns+` where r.parent = ? and (r.private = 0 or r.owner = ?) order by u.name`, parent, viewer)
	if err != nil {
		return nil, err
	}
	return scanRepos(rows)
}

func (s *Store) ForkRepo(owner User, parent Repo) (Repo, error) {
	name := parent.Name
	repo, err := s.CreateRepo(owner, name, parent.Description, Public, strings.Join(parent.Tags, ","))
	if err != nil {
		return Repo{}, err
	}
	s.db.Exec(`update repos set parent = ? where id = ?`, parent.ID, repo.ID)
	repo.Parent = parent.ID
	return repo, nil
}

func (s *Server) pullAccess(w http.ResponseWriter, r *http.Request, repo Repo) (repoPage, Git, *User, bool) {
	rp, g, err := s.repoPage(r, repo, "")
	if err != nil {
		s.fail(w, r, 404, "No such ref")
		return rp, g, nil, false
	}
	rp.Tab = "pulls"
	return rp, g, s.current(r), true
}

func (s *Server) pulls(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, _, _, ok := s.pullAccess(w, r, repo)
	if !ok {
		return
	}
	state := r.URL.Query().Get("state")
	if state == "" {
		state = "open"
	}
	if state == "all" {
		state = ""
	}
	pulls, err := s.store.Pulls(repo, state)
	if err != nil {
		s.fail(w, r, 500, err.Error())
		return
	}
	s.render(w, r, "pulls", page{Title: repo.Path() + " pull requests", Data: map[string]any{"Page": rp, "Pulls": pulls, "State": r.URL.Query().Get("state")}})
}

type sourceOption struct {
	Value string
	Label string
}

func (s *Server) pullSources(repo Repo, user *User) []sourceOption {
	var opts []sourceOption
	add := func(src Repo) {
		g := Git{Dir: s.repoDir(src)}
		branches, _ := g.Refs("refs/heads")
		for _, b := range branches {
			label := b.Name
			if src.ID != repo.ID {
				label = src.Path() + ":" + b.Name
			}
			opts = append(opts, sourceOption{Value: src.Path() + ":" + b.Name, Label: label})
		}
	}
	add(repo)
	if user != nil {
		forks, _ := s.store.Forks(repo.ID, user.ID)
		for _, f := range forks {
			if s.store.CanWrite(f, user) {
				add(f)
			}
		}
	}
	return opts
}

func (s *Server) newPull(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, g, user, ok := s.pullAccess(w, r, repo)
	if !ok {
		return
	}
	if user == nil {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return
	}
	branches, _ := g.Refs("refs/heads")
	s.render(w, r, "newpull", page{Title: "New pull request", User: user, Error: r.URL.Query().Get("error"),
		Data: map[string]any{"Page": rp, "Sources": s.pullSources(repo, user), "Branches": branches, "Source": r.URL.Query().Get("source"), "Target": r.URL.Query().Get("target")}})
}

func (s *Server) resolveSource(repo Repo, user *User, value string) (Repo, string, error) {
	path, branch, ok := strings.Cut(value, ":")
	if !ok || branch == "" {
		return Repo{}, "", errors.New("Choose a source branch")
	}
	owner, name, ok := strings.Cut(strings.TrimPrefix(path, "~"), "/")
	if !ok {
		return Repo{}, "", errors.New("Choose a source branch")
	}
	src, err := s.store.RepoByPath(owner, name)
	if err != nil {
		return Repo{}, "", errors.New("No such source repository")
	}
	if src.ID != repo.ID && (src.Parent != repo.ID || !s.store.CanWrite(src, user)) {
		return Repo{}, "", errors.New("Source must be this repository or your own fork of it")
	}
	if _, err := (Git{Dir: s.repoDir(src)}).Resolve("refs/heads/" + branch); err != nil {
		return Repo{}, "", errors.New("No such source branch")
	}
	return src, branch, nil
}

func (s *Server) createPull(w http.ResponseWriter, r *http.Request, repo Repo) {
	rp, g, user, ok := s.pullAccess(w, r, repo)
	if !ok {
		return
	}
	if user == nil {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return
	}
	retry := func(msg string) {
		branches, _ := g.Refs("refs/heads")
		w.WriteHeader(400)
		s.render(w, r, "newpull", page{Title: "New pull request", User: user, Error: msg,
			Data: map[string]any{"Page": rp, "Sources": s.pullSources(repo, user), "Branches": branches, "Source": r.FormValue("source"), "Target": r.FormValue("target"), "PullTitle": r.FormValue("title"), "Body": r.FormValue("body")}})
	}
	if repo.Archived {
		retry("This repository is archived")
		return
	}
	src, branch, err := s.resolveSource(repo, user, r.FormValue("source"))
	if err != nil {
		retry(err.Error())
		return
	}
	target := r.FormValue("target")
	if _, err := g.Resolve("refs/heads/" + target); err != nil {
		retry("No such target branch")
		return
	}
	if src.ID == repo.ID && branch == target {
		retry("Source and target are the same branch")
		return
	}
	pull, err := s.store.CreatePull(repo, *user, r.FormValue("title"), strings.TrimSpace(r.FormValue("body")), src, branch, target)
	if err != nil {
		retry(err.Error())
		return
	}
	if err := g.Fetch(s.repoDir(src), "refs/heads/"+branch, pull.Ref()); err != nil {
		retry("Could not fetch the source branch: " + err.Error())
		return
	}
	url := fmt.Sprintf("https://%s/%s/pulls/%d", s.host, repo.Path(), pull.Number)
	if repo.Owner.ID != user.ID {
		s.notify(s.store.VerifiedEmail(repo.Owner.ID), fmt.Sprintf("[%s] pull request #%d: %s", repo.Path(), pull.Number, pull.Title),
			fmt.Sprintf("~%s opened a pull request on %s.\n\n%s\n\n%s\n", user.Name, repo.Path(), pull.Body, url))
	}
	http.Redirect(w, r, fmt.Sprintf("/%s/pulls/%d", repo.Path(), pull.Number), http.StatusSeeOther)
}

func (s *Server) loadPull(w http.ResponseWriter, r *http.Request, repo Repo, rest string) (repoPage, Git, *User, Pull, string, bool) {
	rp, g, user, ok := s.pullAccess(w, r, repo)
	if !ok {
		return rp, g, user, Pull{}, "", false
	}
	numStr, action, _ := strings.Cut(rest, "/")
	number, err := strconv.ParseInt(numStr, 10, 64)
	if err != nil {
		s.fail(w, r, 404, "No such pull request")
		return rp, g, user, Pull{}, "", false
	}
	pull, err := s.store.Pull(repo, number)
	if err != nil {
		s.fail(w, r, 404, "No such pull request")
		return rp, g, user, Pull{}, "", false
	}
	return rp, g, user, pull, action, true
}

func (s *Server) pull(w http.ResponseWriter, r *http.Request, repo Repo, rest string) {
	rp, g, user, pull, action, ok := s.loadPull(w, r, repo, rest)
	if !ok {
		return
	}
	isOwner := s.store.CanWrite(repo, user)
	isAuthor := user != nil && user.ID == pull.Author.ID
	if r.Method == "POST" {
		if user == nil {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}
		back := fmt.Sprintf("/%s/pulls/%d", repo.Path(), pull.Number)
		switch action {
		case "comment":
			if err := s.store.AddComment(pull.ID, *user, r.FormValue("body")); err != nil {
				http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
				return
			}
			s.notifyPull(pull, *user, "commented on", r.FormValue("body"))
		case "close":
			if (isOwner || isAuthor) && pull.State == "open" {
				s.store.SetPullState(pull.ID, "closed", "")
			}
		case "reopen":
			if (isOwner || isAuthor) && pull.State == "closed" {
				s.store.SetPullState(pull.ID, "open", "")
			}
		case "review":
			line, _ := strconv.Atoi(r.FormValue("line"))
			if err := s.store.AddReview(pull.ID, *user, r.FormValue("path"), r.FormValue("side"), line, r.FormValue("body")); err != nil {
				http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
				return
			}
			back += "#r-" + r.FormValue("path") + ":" + r.FormValue("side") + ":" + r.FormValue("line")
			s.notifyPull(pull, *user, "reviewed "+r.FormValue("path")+" line "+r.FormValue("line")+" on", r.FormValue("body"))
		case "resolve", "unresolve", "delete":
			id, _ := strconv.ParseInt(r.FormValue("review"), 10, 64)
			owner := s.store.ReviewAuthor(id)
			if owner == 0 || (owner != user.ID && !isOwner) {
				s.fail(w, r, 403, "Not your comment")
				return
			}
			switch action {
			case "resolve":
				s.store.ResolveReview(id, true)
			case "unresolve":
				s.store.ResolveReview(id, false)
			case "delete":
				s.store.DeleteReview(id)
			}
			back += "#diff"
		case "update":
			if (isOwner || isAuthor) && pull.State == "open" {
				if err := g.Fetch(s.repoDir(pull.SourceRepo), "refs/heads/"+pull.SourceBranch, pull.Ref()); err != nil {
					http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
					return
				}
				s.store.TouchPull(pull.ID)
			}
		case "merge":
			if !isOwner || pull.State != "open" {
				s.fail(w, r, 403, "Only the repository owner can merge")
				return
			}
			title := strings.TrimSpace(r.FormValue("title"))
			if title == "" {
				title = mergeTitle(pull)
			}
			message := title
			if body := strings.TrimSpace(r.FormValue("body")); body != "" {
				message += "\n\n" + body
			}
			var hash string
			var err error
			switch r.FormValue("strategy") {
			case "squash":
				hash, err = g.Squash(pull.TargetBranch, pull.Ref(), message, pull.Author.Name, pull.Author.Name+"@"+s.host, user.Name, user.Name+"@"+s.host)
			case "rebase":
				hash, err = g.Rebase(pull.TargetBranch, pull.Ref(), user.Name, user.Name+"@"+s.host)
			default:
				hash, err = g.Merge(pull.TargetBranch, pull.Ref(), message, user.Name, user.Name+"@"+s.host)
			}
			if err != nil {
				http.Redirect(w, r, back+"?error="+template.URLQueryEscaper(err.Error()), http.StatusSeeOther)
				return
			}
			s.store.SetPullState(pull.ID, "merged", hash)
			s.notifyPull(pull, *user, "merged", "")
		default:
			s.fail(w, r, 404, "Page not found")
			return
		}
		http.Redirect(w, r, back, http.StatusSeeOther)
		return
	}
	head, err := g.Resolve(pull.Ref())
	if err != nil {
		s.fail(w, r, 500, "Pull request head is missing")
		return
	}
	data := map[string]any{"Page": rp, "Pull": pull, "Head": head, "Owner": isOwner, "Author": isAuthor,
		"Body": s.renderMarkdown([]byte(pull.Body))}
	base := pull.TargetBranch
	if pull.State == "merged" && pull.Merged != "" {
		base = pull.Merged + "^1"
	}
	if mb, err := g.MergeBase(base, head); err == nil {
		data["Base"] = mb
		commits, _ := g.LogRange(mb, head, 200)
		data["Commits"] = commits
		files, _ := g.DiffRange(mb, head)
		data["Files"] = files
		reviews, _ := s.store.Reviews(pull.ID)
		present := map[string]bool{}
		for _, f := range files {
			for _, h := range f.Hunks {
				for _, l := range h.Lines {
					switch l.Kind {
					case "add", "ctx":
						present[fmt.Sprintf("%s:n:%d", f.New, l.New)] = true
					}
					if l.Kind == "del" || l.Kind == "ctx" {
						present[fmt.Sprintf("%s:o:%d", f.New, l.Old)] = true
					}
				}
			}
		}
		inline := map[string][]Review{}
		var outdated []Review
		for _, rv := range reviews {
			rv.HTML = s.renderMarkdown([]byte(rv.Body))
			rv.URL = fmt.Sprintf("/%s/pulls/%d", repo.Path(), pull.Number)
			rv.CanEdit = user != nil && (user.ID == rv.Author.ID || isOwner)
			if present[rv.Key()] {
				inline[rv.Key()] = append(inline[rv.Key()], rv)
			} else {
				outdated = append(outdated, rv)
			}
		}
		data["Inline"] = inline
		data["Outdated"] = outdated
		data["ReviewCount"] = len(reviews)
		data["CommentAt"] = r.URL.Query().Get("comment")
		added, removed := 0, 0
		for _, f := range files {
			added += f.Added
			removed += f.Removed
		}
		data["Added"], data["Removed"] = added, removed
		if pull.State == "open" {
			data["Mergeable"] = g.Mergeable(pull.TargetBranch, head)
			if cur, err := g.Resolve("refs/heads/" + pull.TargetBranch); err == nil && cur == head {
				data["Mergeable"] = false
			}
			if isOwner && data["Mergeable"] == true && r.URL.Query().Get("merge") == "1" {
				data["Confirm"] = true
				data["MergeTitle"] = mergeTitle(pull)
				var subjects []string
				for _, c := range data["Commits"].([]Commit) {
					subjects = append(subjects, "* "+c.Subject)
				}
				data["SquashBody"] = strings.Join(subjects, "\n")
			}
		}
	} else {
		data["Unrelated"] = true
	}
	comments, _ := s.store.Comments(pull.ID)
	rendered := make([]map[string]any, len(comments))
	for i, c := range comments {
		rendered[i] = map[string]any{"Comment": c, "Body": s.renderMarkdown([]byte(c.Body))}
	}
	data["Comments"] = rendered
	s.render(w, r, "pull", page{Title: fmt.Sprintf("#%d %s", pull.Number, pull.Title), Error: r.URL.Query().Get("error"), Math: hasMath(data["Body"]), Data: data})
}

func (s *Server) notifyPull(pull Pull, actor User, verb, body string) {
	url := fmt.Sprintf("https://%s/%s/pulls/%d", s.host, pull.Repo.Path(), pull.Number)
	subject := fmt.Sprintf("[%s] pull request #%d: %s", pull.Repo.Path(), pull.Number, pull.Title)
	text := fmt.Sprintf("~%s %s pull request #%d.\n\n%s\n\n%s\n", actor.Name, verb, pull.Number, body, url)
	seen := map[int64]bool{actor.ID: true}
	for _, id := range []int64{pull.Author.ID, pull.Repo.Owner.ID} {
		if !seen[id] {
			seen[id] = true
			s.notify(s.store.VerifiedEmail(id), subject, text)
		}
	}
}

func mergeTitle(pull Pull) string {
	return fmt.Sprintf("Merge pull request #%d from %s", pull.Number, pull.SourceRepo.Path()+":"+pull.SourceBranch)
}

func (s *Server) fork(w http.ResponseWriter, r *http.Request, repo Repo) {
	user := s.require(w, r)
	if user == nil {
		return
	}
	if user.ID == repo.Owner.ID {
		http.Redirect(w, r, "/"+repo.Path(), http.StatusSeeOther)
		return
	}
	fork, err := s.store.ForkRepo(*user, repo)
	if err != nil {
		s.fail(w, r, 400, err.Error())
		return
	}
	dir := s.repoDir(fork)
	if err := os.MkdirAll(filepath.Dir(dir), 0o755); err == nil {
		err = cloneRepo(s.repoDir(repo), dir)
	}
	if err != nil {
		s.store.DeleteRepo(fork.ID)
		s.fail(w, r, 500, err.Error())
		return
	}
	http.Redirect(w, r, "/"+fork.Path(), http.StatusSeeOther)
}