~gitpocket/gitpocket

4
7db58612d2bb8f4814c5b26fe7970e0cb12a451f
mainfeed-discovery
gitpocket/extra.go -rw-r--r--9.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
package main

import (
	"context"
	"encoding/xml"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"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
	}
	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.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)}
	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.NewReplacer("/", "-", "\\", "-").Replace(spec)
	name := repo.Name + "-" + safe
	ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
	defer cancel()
	cmd := exec.CommandContext(ctx, "git", "-C", g.Dir, "archive", "--format="+format, "--prefix="+name+"/", commit)
	cmd.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "PATH=" + os.Getenv("PATH")}
	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Content-Disposition", `attachment; filename="`+name+"."+format+`"`)
	cmd.Stdout = w
	cmd.Run()
}

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)
		}
	}
	w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
	w.Write([]byte(xml.Header))
	xml.NewEncoder(w).Encode(feed)
}