gunk-dev/the-valley

source.go

source43d938c6651fmain's published tip history
19.5 KiB
1package server
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "net/url"
12 "strconv"
13 "strings"
14 "unicode"
15 "unicode/utf8"
16
17 "the-valley/webui/export"
18)
19
20// treeURL is the directory at path in commit. It ends in a slash.
21func treeURL(project, commit string, path []string) string {
22 u := "/" + url.PathEscape(project) + "/source/tree/" + commit + "/"
23 if len(path) > 0 {
24 u += escapePath(path) + "/"
25 }
26 return u
27}
28
29// blobURL is the file at path in commit.
30func blobURL(project, commit string, path []string) string {
31 return "/" + url.PathEscape(project) + "/source/blob/" + commit + "/" + escapePath(path)
32}
33
34// logURL is the history that ends at commit.
35func logURL(project, commit string) string {
36 return "/" + url.PathEscape(project) + "/source/log/" + commit
37}
38
39func escapePath(path []string) string {
40 parts := make([]string, len(path))
41 for i, s := range path {
42 parts[i] = url.PathEscape(s)
43 }
44 return strings.Join(parts, "/")
45}
46
47// source serves the routes under /<project>/source/. The project is
48// checked first, so everything under a project the export does not hold
49// as public answers as a missing project does.
50func (q *request) source(project string, rest []string) {
51 p, ok := q.project(project)
52 if !ok {
53 q.notFound()
54 return
55 }
56 repo, ok := q.g.Repo(p.Name)
57 if !ok {
58 q.notFound()
59 return
60 }
61 var view func(ctx context.Context) error
62 switch {
63 case len(rest) == 0 || len(rest) == 1 && rest[0] == "":
64 q.redirect(treeURL(p.Name, p.SourceTip, nil))
65 return
66 case len(rest) >= 2 && rest[0] == "tree":
67 path := rest[2:]
68 if n := len(path); n > 0 && path[n-1] == "" {
69 path = path[:n-1]
70 }
71 if !validPath(path) {
72 q.notFound()
73 return
74 }
75 view = func(ctx context.Context) error { return q.dir(ctx, p, repo, rest[1], path) }
76 case len(rest) >= 3 && rest[0] == "blob":
77 path := rest[2:]
78 if !validPath(path) {
79 q.notFound()
80 return
81 }
82 view = func(ctx context.Context) error { return q.file(ctx, p, repo, rest[1], path) }
83 case len(rest) == 2 && rest[0] == "log":
84 view = func(ctx context.Context) error { return q.log(ctx, p, repo, rest[1]) }
85 default:
86 q.notFound()
87 return
88 }
89 if err := view(q.ctx); err != nil {
90 q.fail(err)
91 }
92}
93
94// validPath is a path a source route may name: at most MaxDepth
95// segments, none of them empty, a dot segment, or holding a slash or a
96// NUL.
97func validPath(path []string) bool {
98 if len(path) > MaxDepth {
99 return false
100 }
101 for _, s := range path {
102 if s == "" || s == "." || s == ".." || strings.ContainsAny(s, "/\x00") {
103 return false
104 }
105 }
106 return true
107}
108
109// commitTree is the tree of commit, when commit is a commit the
110// project's published source tip reaches. ok is false for anything else:
111// an unreachable commit, another kind of object, or text that is no full
112// object ID.
113func commitTree(ctx context.Context, p *export.Project, repo, commit string) (tree string, ok bool, err error) {
114 reachable, err := export.Reachable(ctx, repo, p.SourceTip, commit)
115 if err != nil || !reachable {
116 return "", false, err
117 }
118 out, err := export.Git(ctx, repo, maxLine, "rev-parse", "--verify", commit+"^{tree}")
119 if err != nil {
120 return "", false, err
121 }
122 tree = strings.TrimSpace(string(out))
123 if !export.ValidObjectID(tree) {
124 return "", false, fmt.Errorf("the tree of %s is %q", commit, tree)
125 }
126 return tree, true, nil
127}
128
129// The bounds on what a page keeps of one record of git's output.
130const (
131 // maxLine bounds what git prints for one object ID.
132 maxLine = 1 << 10
133 // maxEntryRecord bounds one entry of git ls-tree: its mode, type,
134 // object ID and size, and its name. git fsck refuses a name longer
135 // than 4,096 bytes, so the receiver accepts no entry this cuts.
136 maxEntryRecord = 8 << 10
137 // maxLogRecord bounds one commit of git log: its ID, date, author
138 // and subject. A page shows maxLogText of the author and subject.
139 maxLogRecord = 16 << 10
140 maxLogText = 1 << 10
141)
142
143// records reads the records of git's output that end in sep, and keeps
144// at most max bytes of each.
145type records struct {
146 r *bufio.Reader
147 sep byte
148 buf []byte
149}
150
151func newRecords(r io.Reader, sep byte, max int) *records {
152 return &records{r: bufio.NewReaderSize(r, max), sep: sep}
153}
154
155// next is the next record, without its sep. A record longer than the
156// bound is cut to it, with cut set, and the rest of it is read and
157// dropped. At the end of the output next fails with io.EOF. On any other
158// error, rec is the start of the record the error cut short.
159func (rs *records) next() (rec []byte, cut bool, err error) {
160 line, err := rs.r.ReadSlice(rs.sep)
161 rs.buf = append(rs.buf[:0], line...)
162 for err == bufio.ErrBufferFull {
163 cut = true
164 _, err = rs.r.ReadSlice(rs.sep)
165 }
166 switch {
167 case err == io.EOF && len(rs.buf) > 0:
168 return rs.buf, cut, nil // a last record git did not end
169 case err != nil:
170 return rs.buf, cut, err
171 case !cut:
172 return rs.buf[:len(rs.buf)-1], false, nil
173 }
174 return rs.buf, true, nil
175}
176
177// entry is one entry of a tree, as git ls-tree --long gives it. Size is
178// -1 for an entry that is not a blob. Cut is set when the entry's name is
179// longer than a page keeps, and Name is then its start alone.
180type entry struct {
181 Mode string
182 Type string
183 OID string
184 Size int64
185 Name string
186 Cut bool
187}
188
189// readTree calls each with the entries of tree, in git's order, until
190// each returns false. It reads at most MaxRead bytes of git ls-tree's
191// output: complete is false when the listing is longer and was cut there.
192func readTree(ctx context.Context, repo, tree string, each func(entry) bool) (complete bool, err error) {
193 complete = true
194 err = export.GitStream(ctx, repo, MaxRead, func(r io.Reader) error {
195 recs := newRecords(r, 0, maxEntryRecord)
196 for {
197 rec, cut, err := recs.next()
198 switch {
199 case err == io.EOF:
200 return nil
201 case errors.Is(err, export.ErrOutputLimit):
202 complete = false
203 return nil
204 case err != nil:
205 return err
206 }
207 e, err := parseEntry(rec, cut)
208 if err != nil {
209 return err
210 }
211 if !each(e) {
212 return nil
213 }
214 }
215 }, "ls-tree", "-z", "--long", tree)
216 return complete, err
217}
218
219func parseEntry(rec []byte, cut bool) (entry, error) {
220 meta, name, ok := bytes.Cut(rec, []byte{'\t'})
221 f := strings.Fields(string(meta))
222 if !ok || len(f) != 4 || !export.ValidObjectID(f[2]) {
223 return entry{}, fmt.Errorf("git ls-tree gave %q", rec)
224 }
225 e := entry{Mode: f[0], Type: f[1], OID: f[2], Size: -1, Name: string(name), Cut: cut}
226 if f[3] != "-" {
227 n, err := strconv.ParseInt(f[3], 10, 64)
228 if err != nil || n < 0 {
229 return entry{}, fmt.Errorf("git ls-tree gave %q", rec)
230 }
231 e.Size = n
232 }
233 return e, nil
234}
235
236// resolve walks path down from the tree root, one tree entry at a time,
237// and gives the entry it ends at. ok is false when a segment names no
238// entry, or a segment other than the last names something that is not a
239// tree. Each directory is read only until the segment's entry, and no
240// further than readTree reads, so an entry past MaxRead is not found.
241func resolve(ctx context.Context, repo, root string, path []string) (e entry, ok bool, err error) {
242 e = entry{Mode: "040000", Type: "tree", OID: root, Size: -1}
243 for _, name := range path {
244 if e.Type != "tree" {
245 return entry{}, false, nil
246 }
247 found := false
248 _, err := readTree(ctx, repo, e.OID, func(c entry) bool {
249 if !c.Cut && c.Name == name {
250 e, found = c, true
251 }
252 return !found
253 })
254 if err != nil || !found {
255 return entry{}, false, err
256 }
257 }
258 return e, true, nil
259}
260
261// Entry modes git gives for a symbolic link and a submodule.
262const (
263 modeSymlink = "120000"
264 modeSubmodule = "160000"
265)
266
267// shown is how a page shows a blob: its text, or a notice that says why
268// it is not shown. A symbolic link is shown as its target and is never
269// followed.
270func shown(ctx context.Context, repo string, e entry) (text, notice string, err error) {
271 if e.Size > MaxFile {
272 return "", fmt.Sprintf("This file is %s, larger than the %s a page shows.", size(e.Size), size(MaxFile)), nil
273 }
274 data, err := export.Git(ctx, repo, MaxFile, "cat-file", "blob", e.OID)
275 if err != nil {
276 return "", "", err
277 }
278 if e.Mode == modeSymlink {
279 return "", "A symbolic link to " + oneLine(string(data)) + ". It is not followed.", nil
280 }
281 if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {
282 return "", fmt.Sprintf("This file is binary, %s, and is not shown.", size(e.Size)), nil
283 }
284 return string(data), "", nil
285}
286
287// dirPage is one directory of a commit.
288type dirPage struct {
289 Project string
290 Commit string
291 Short string
292 AtTip bool
293 TipURL string
294 LogURL string
295 Crumbs []link
296 Entries []dirEntry
297 Omitted int
298 // Partial is set when the directory is larger than a page reads,
299 // and only its start is listed.
300 Partial bool
301 Readme *readme
302}
303
304type dirEntry struct {
305 Name string
306 URL string
307 Kind string
308 Size string
309}
310
311type readme struct {
312 Name string
313 URL string
314 Text string
315 Notice string
316 // Partial is set when the README is longer than a page shows.
317 Partial bool
318}
319
320func (q *request) dir(ctx context.Context, p *export.Project, repo, commit string, path []string) error {
321 root, ok, err := commitTree(ctx, p, repo, commit)
322 if err != nil || !ok {
323 q.missing(err)
324 return nil
325 }
326 e, ok, err := resolve(ctx, repo, root, path)
327 if err != nil || !ok || e.Type != "tree" {
328 q.missing(err)
329 return nil
330 }
331 // Directories come first, then everything else, each in git's
332 // order. Keeping MaxEntries of each keeps the first MaxEntries of
333 // that order, however many entries the tree holds.
334 var dirs, others []entry
335 read, rank := 0, -1
336 var rm entry
337 complete, err := readTree(ctx, repo, e.OID, func(c entry) bool {
338 read++
339 switch {
340 case c.Type == "tree" && len(dirs) < MaxEntries:
341 dirs = append(dirs, c)
342 case c.Type != "tree" && len(others) < MaxEntries:
343 others = append(others, c)
344 }
345 if r := readmeRank(c); r >= 0 && (rank < 0 || r < rank) {
346 rm, rank = c, r
347 }
348 return true
349 })
350 if err != nil {
351 return err
352 }
353 entries := append(dirs, others...)
354 if len(entries) > MaxEntries {
355 entries = entries[:MaxEntries]
356 }
357 page := dirPage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip,
358 TipURL: treeURL(p.Name, p.SourceTip, nil), LogURL: logURL(p.Name, commit),
359 Crumbs: crumbs(p.Name, commit, path), Omitted: read - len(entries), Partial: !complete}
360 for _, c := range entries {
361 at := append(append([]string{}, path...), c.Name)
362 d := dirEntry{Name: oneLine(c.Name)}
363 switch {
364 case c.Type == "tree":
365 d.Kind, d.URL = "directory", treeURL(p.Name, commit, at)
366 case c.Mode == modeSubmodule || c.Type == "commit":
367 d.Kind = "submodule at " + c.OID[:12]
368 case c.Mode == modeSymlink:
369 d.Kind, d.URL = "symbolic link", blobURL(p.Name, commit, at)
370 default:
371 d.Kind, d.URL, d.Size = "file", blobURL(p.Name, commit, at), size(c.Size)
372 }
373 if c.Cut {
374 d.Name += "…"
375 }
376 if c.Cut || !validPath(at) {
377 d.URL = "" // a name no route takes is listed and not linked
378 }
379 page.Entries = append(page.Entries, d)
380 }
381 if rank >= 0 {
382 text, notice, err := shown(ctx, repo, rm)
383 if err != nil {
384 return err
385 }
386 lines, _, partial := excerpt(trimEnd(text), 1)
387 at := append(append([]string{}, path...), rm.Name)
388 page.Readme = &readme{Name: oneLine(rm.Name), URL: blobURL(p.Name, commit, at),
389 Text: strings.Join(lines, "\n"), Notice: notice, Partial: partial}
390 }
391 title := p.Name + " at " + commit[:12]
392 if len(path) > 0 {
393 title = strings.Join(path, "/") + " · " + title
394 }
395 q.page(http.StatusOK, "tree", title, page)
396 return nil
397}
398
399// readmeRank is how a directory's README is chosen from its entries:
400// README.md, README or README.txt, in that order, and otherwise the first
401// file whose name is README in any case, with any extension. A lower rank
402// is chosen first. It is -1 for an entry that is no README.
403func readmeRank(e entry) int {
404 if e.Type != "blob" || e.Mode == modeSymlink || e.Cut {
405 return -1
406 }
407 switch e.Name {
408 case "README.md":
409 return 0
410 case "README":
411 return 1
412 case "README.txt":
413 return 2
414 }
415 if base, _, _ := strings.Cut(strings.ToLower(e.Name), "."); base == "readme" {
416 return 3
417 }
418 return -1
419}
420
421// filePage is one file of a commit.
422type filePage struct {
423 Project string
424 Commit string
425 Short string
426 AtTip bool
427 TipURL string
428 LogURL string
429 Crumbs []link
430 Name string
431 Size string
432 Lines []string
433 // Partial says where the page stops, when the file is longer than a
434 // page shows.
435 Partial string
436 Notice string
437}
438
439func (q *request) file(ctx context.Context, p *export.Project, repo, commit string, path []string) error {
440 root, ok, err := commitTree(ctx, p, repo, commit)
441 if err != nil || !ok {
442 q.missing(err)
443 return nil
444 }
445 e, ok, err := resolve(ctx, repo, root, path)
446 if err != nil || !ok || e.Type != "blob" {
447 q.missing(err)
448 return nil
449 }
450 text, notice, err := shown(ctx, repo, e)
451 if err != nil {
452 return err
453 }
454 page := filePage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip,
455 TipURL: treeURL(p.Name, p.SourceTip, nil), LogURL: logURL(p.Name, commit),
456 Crumbs: crumbs(p.Name, commit, path), Name: oneLine(path[len(path)-1]),
457 Size: size(e.Size), Notice: notice}
458 if notice == "" {
459 lines, total, partial := excerpt(text, rowCost)
460 page.Lines = lines
461 if partial {
462 page.Partial = fmt.Sprintf("This file is longer than a page shows. The page stops at line %d of %d.", len(lines), total)
463 }
464 }
465 q.page(http.StatusOK, "blob", strings.Join(path, "/")+" · "+p.Name+" at "+commit[:12], page)
466 return nil
467}
468
469// crumbs are the links from the project's root down to path. The last is
470// the page itself and has no link.
471func crumbs(project, commit string, path []string) []link {
472 out := []link{{project, treeURL(project, commit, nil)}}
473 for i, name := range path {
474 out = append(out, link{oneLine(name), treeURL(project, commit, path[:i+1])})
475 }
476 out[len(out)-1].URL = ""
477 return out
478}
479
480// rowCost is what a file page's markup takes for each line it shows,
481// besides the line's text: a table row, an anchor and the line number.
482// It is an upper bound for line numbers of up to seven digits.
483const rowCost = 100
484
485// excerpt is the start of text that a page shows: whole lines, at most
486// MaxLines of them, while the bytes they take once escaped, with cost
487// more for each line, stay within MaxShown. A line that would pass
488// MaxShown is cut to fit, and ends the excerpt. total is how many lines
489// text holds, and partial is set when the excerpt holds less than all of
490// it.
491func excerpt(text string, cost int) (lines []string, total int, partial bool) {
492 text = strings.TrimSuffix(text, "\n")
493 total = strings.Count(text, "\n") + 1
494 budget := MaxShown
495 for rest := text; len(lines) < MaxLines; {
496 line, more, found := strings.Cut(rest, "\n")
497 n := cost + escapedSize(line)
498 if n > budget {
499 if room := budget - cost; room > 0 {
500 lines = append(lines, cutEscaped(line, room))
501 }
502 return lines, total, true
503 }
504 budget -= n
505 lines = append(lines, line)
506 if !found {
507 return lines, total, false
508 }
509 rest = more
510 }
511 return lines, total, true
512}
513
514// escapedSize is an upper bound on the bytes html/template writes for s
515// as text: five for each character it escapes, and one for any other
516// byte.
517func escapedSize(s string) int {
518 n := len(s)
519 for i := 0; i < len(s); i++ {
520 switch s[i] {
521 case '"', '\'', '&', '+', '<', '>', 0:
522 n += 4
523 }
524 }
525 return n
526}
527
528// cutEscaped is the longest start of s that ends on a whole character
529// and that escapedSize counts at no more than room bytes.
530func cutEscaped(s string, room int) string {
531 n := 0
532 for i := 0; i < len(s); i++ {
533 if n += escapedSize(s[i : i+1]); n > room {
534 for i > 0 && !utf8.RuneStart(s[i]) {
535 i--
536 }
537 return s[:i]
538 }
539 }
540 return s
541}
542
543// clip is s cut to at most n bytes, on a whole character, and marked as
544// cut when it is.
545func clip(s string, n int) string {
546 if len(s) <= n {
547 return s
548 }
549 for n > 0 && !utf8.RuneStart(s[n]) {
550 n--
551 }
552 return s[:n] + "…"
553}
554
555// logPage is one page of the history that ends at a commit.
556type logPage struct {
557 Project string
558 Commit string
559 Short string
560 AtTip bool
561 Commits []logEntry
562 // Partial is set when the page's commits are larger than a page
563 // reads, and the page ends early.
564 Partial bool
565 Newer string
566 Older string
567}
568
569type logEntry struct {
570 Short string
571 URL string
572 Subject string
573 Author string
574 Date string
575}
576
577func (q *request) log(ctx context.Context, p *export.Project, repo, commit string) error {
578 skip := 0
579 if s := q.r.URL.Query().Get("skip"); s != "" {
580 n, err := strconv.Atoi(s)
581 if err != nil || n < 0 || n > 1_000_000 || strconv.Itoa(n) != s {
582 q.notFound()
583 return nil
584 }
585 skip = n
586 }
587 if _, ok, err := commitTree(ctx, p, repo, commit); err != nil || !ok {
588 q.missing(err)
589 return nil
590 }
591 // One commit past the page says whether there is an older page. A
592 // listing cut at MaxRead ends the page at the commit it cut, shown
593 // as far as it was read, and the older page starts after it.
594 page := logPage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip}
595 err := export.GitStream(ctx, repo, MaxRead, func(r io.Reader) error {
596 recs := newRecords(r, 0, maxLogRecord)
597 for len(page.Commits) <= LogPage {
598 rec, _, err := recs.next()
599 cut := errors.Is(err, export.ErrOutputLimit)
600 if err == io.EOF {
601 return nil
602 }
603 if err != nil && !cut {
604 return err
605 }
606 if e, ok := logEntryOf(p.Name, string(rec)); ok {
607 page.Commits = append(page.Commits, e)
608 }
609 if cut {
610 page.Partial = true
611 return nil
612 }
613 }
614 return nil
615 }, "log", "--no-mailmap", "--no-notes", "--no-show-signature",
616 "--no-decorate", "--no-color", "-z", "--format=%H%n%aI%n%an%n%s",
617 "--max-count="+strconv.Itoa(LogPage+1), "--skip="+strconv.Itoa(skip), commit, "--")
618 if err != nil {
619 return err
620 }
621 switch {
622 case len(page.Commits) > LogPage:
623 page.Commits = page.Commits[:LogPage]
624 page.Older = logURL(p.Name, commit) + "?skip=" + strconv.Itoa(skip+LogPage)
625 case page.Partial && len(page.Commits) > 0:
626 page.Older = logURL(p.Name, commit) + "?skip=" + strconv.Itoa(skip+len(page.Commits))
627 }
628 if skip > 0 {
629 page.Newer = logURL(p.Name, commit)
630 if skip > LogPage {
631 page.Newer += "?skip=" + strconv.Itoa(skip-LogPage)
632 }
633 }
634 q.page(http.StatusOK, "log", "History of "+p.Name+" at "+commit[:12], page)
635 return nil
636}
637
638// logEntryOf is one record of git log: a commit's ID, author date,
639// author and subject, each on a line of its own. A record cut short is
640// shown as far as it goes. ok is false for a record that names no commit.
641func logEntryOf(project, rec string) (e logEntry, ok bool) {
642 f := strings.SplitN(rec, "\n", 4)
643 if !export.ValidObjectID(f[0]) {
644 return logEntry{}, false
645 }
646 for len(f) < 4 {
647 f = append(f, "")
648 }
649 return logEntry{Short: f[0][:12], URL: treeURL(project, f[0], nil), Date: stampOf(f[1]),
650 Author: clip(oneLine(f[2]), maxLogText), Subject: clip(oneLine(f[3]), maxLogText)}, true
651}
652
653// missing answers a source route whose commit or path names nothing it
654// serves: the one 404, or the one 500 when git failed.
655func (q *request) missing(err error) {
656 if err != nil {
657 q.fail(err)
658 return
659 }
660 q.notFound()
661}
662
663// oneLine is text from a repository as a page shows it on one line:
664// valid UTF-8, with control and bidirectional formatting characters
665// replaced, so a name cannot reorder or hide the text around it.
666func oneLine(s string) string {
667 return strings.Map(func(r rune) rune {
668 if unicode.IsControl(r) || unicode.Is(unicode.Bidi_Control, r) {
669 return '�'
670 }
671 return r
672 }, strings.ToValidUTF8(s, "�"))
673}
674
675// size is a byte count in words.
676func size(n int64) string {
677 switch {
678 case n < 0:
679 return ""
680 case n < 1<<10:
681 return count(int(n), "byte")
682 case n < 1<<20:
683 return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
684 case n < 1<<30:
685 return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
686 }
687 return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30))
688}