gunk-dev/the-valley

source.go

sourcef007964e2f86main's published tip history
32.3 KiB
1package server
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "errors"
8 "fmt"
9 "html/template"
10 "io"
11 "maps"
12 "net/http"
13 "net/url"
14 "slices"
15 "strconv"
16 "strings"
17 "unicode"
18 "unicode/utf8"
19
20 "the-valley/web/export"
21 "the-valley/web/markdown"
22)
23
24// treeURL is the directory at path in commit, under the base of its
25// project, /<group>/<project>, escaped. It ends in a slash.
26func treeURL(base, commit string, path []string) string {
27 u := base + "/source/tree/" + commit + "/"
28 if len(path) > 0 {
29 u += escapePath(path) + "/"
30 }
31 return u
32}
33
34// blobURL is the file at path in commit, under its project's base.
35func blobURL(base, commit string, path []string) string {
36 return base + "/source/blob/" + commit + "/" + escapePath(path)
37}
38
39// logURL is the history that ends at commit, under its project's base.
40func logURL(base, commit string) string {
41 return base + "/source/log/" + commit
42}
43
44func escapePath(path []string) string {
45 parts := make([]string, len(path))
46 for i, s := range path {
47 parts[i] = url.PathEscape(s)
48 }
49 return strings.Join(parts, "/")
50}
51
52// source serves the routes under /<group>/<project>/source/. The project is
53// checked first, so everything under a project the reader may not see
54// answers as a missing project does. A route that reads the repository is
55// returned, for runGit to run once the request holds a git slot: its view
56// runs git under the request's git context, and gives back its git slot
57// once it renders. Every other route is answered from the index alone.
58func (q *request) source(project string, rest []string) *gitOp {
59 p, ok := q.project(project)
60 if !ok {
61 q.notFound()
62 return nil
63 }
64 var view func(ctx context.Context, repo string) error
65 switch {
66 case len(rest) == 0 || len(rest) == 1 && rest[0] == "":
67 q.redirect(treeURL(q.idx.bases[p.Name], p.SourceTip, nil))
68 return nil
69 case len(rest) == 2 && rest[0] == "archive" && rest[1] == tipArchive:
70 q.redirect(archiveURL(q.idx.bases[p.Name], p.SourceTip))
71 return nil
72 case len(rest) >= 2 && rest[0] == "tree":
73 path := rest[2:]
74 if n := len(path); n > 0 && path[n-1] == "" {
75 path = path[:n-1]
76 }
77 if !validPath(path) {
78 q.notFound()
79 return nil
80 }
81 view = func(ctx context.Context, repo string) error { return q.dir(ctx, p, repo, rest[1], path) }
82 case len(rest) >= 3 && rest[0] == "blob":
83 path := rest[2:]
84 if !validPath(path) {
85 q.notFound()
86 return nil
87 }
88 view = func(ctx context.Context, repo string) error { return q.file(ctx, p, repo, rest[1], path) }
89 case len(rest) == 2 && rest[0] == "log":
90 view = func(ctx context.Context, repo string) error { return q.log(ctx, p, repo, rest[1]) }
91 case len(rest) == 2 && rest[0] == "archive":
92 commit, ok := strings.CutSuffix(rest[1], archiveSuffix)
93 if !ok {
94 q.notFound()
95 return nil
96 }
97 view = func(ctx context.Context, repo string) error { return q.archive(ctx, p, repo, commit) }
98 default:
99 q.notFound()
100 return nil
101 }
102 return &gitOp{project: p, run: view}
103}
104
105// validPath is a path a source route may name: at most MaxDepth
106// segments, none of them empty, a dot segment, or holding a slash or a
107// NUL.
108func validPath(path []string) bool {
109 if len(path) > MaxDepth {
110 return false
111 }
112 for _, s := range path {
113 if s == "" || s == "." || s == ".." || strings.ContainsAny(s, "/\x00") {
114 return false
115 }
116 }
117 return true
118}
119
120// commitTree is the tree of commit, when commit is a commit the
121// project's published source tip reaches. ok is false for anything else:
122// an unreachable commit, another kind of object, or text that is no full
123// object ID.
124func commitTree(ctx context.Context, p *export.Project, repo, commit string) (tree string, ok bool, err error) {
125 reachable, err := export.Reachable(ctx, repo, p.SourceTip, commit)
126 if err != nil || !reachable {
127 return "", false, err
128 }
129 out, err := export.Git(ctx, repo, maxLine, "rev-parse", "--verify", commit+"^{tree}")
130 if err != nil {
131 return "", false, err
132 }
133 tree = strings.TrimSpace(string(out))
134 if !export.ValidObjectID(tree) {
135 return "", false, fmt.Errorf("the tree of %s is %q", commit, tree)
136 }
137 return tree, true, nil
138}
139
140// The bounds on what a page keeps of one record of git's output.
141const (
142 // maxLine bounds what git prints for one object ID.
143 maxLine = 1 << 10
144 // maxEntryRecord bounds one entry of git ls-tree: its mode, type,
145 // object ID and size, and its name. git fsck refuses a name longer
146 // than 4,096 bytes, so the receiver accepts no entry this cuts.
147 maxEntryRecord = 8 << 10
148 // maxLogRecord bounds each of the two records git log gives for one
149 // commit: its ID and parents, then its date, author and subject. It
150 // holds a commit's ID and its first MaxParents parents in either
151 // object format. A page shows maxLogText of the author and subject.
152 maxLogRecord = 16 << 10
153 maxLogText = 1 << 10
154)
155
156// The ID and first MaxParents parents of a SHA-256 commit, each followed
157// by one byte, fit in maxLogRecord.
158const _ = uint(maxLogRecord - 65*(1+MaxParents))
159
160// records reads the records of git's output that end in sep, and keeps
161// at most max bytes of each.
162type records struct {
163 r *bufio.Reader
164 sep byte
165 buf []byte
166}
167
168func newRecords(r io.Reader, sep byte, max int) *records {
169 return &records{r: bufio.NewReaderSize(r, max), sep: sep}
170}
171
172// next is the next record, without its sep. A record longer than the
173// bound is cut to it, with cut set, and the rest of it is read and
174// dropped. At the end of the output next fails with io.EOF. On any other
175// error, rec is the start of the record the error cut short.
176func (rs *records) next() (rec []byte, cut bool, err error) {
177 line, err := rs.r.ReadSlice(rs.sep)
178 rs.buf = append(rs.buf[:0], line...)
179 for err == bufio.ErrBufferFull {
180 cut = true
181 _, err = rs.r.ReadSlice(rs.sep)
182 }
183 switch {
184 case err == io.EOF && len(rs.buf) > 0:
185 return rs.buf, cut, nil // a last record git did not end
186 case err != nil:
187 return rs.buf, cut, err
188 case !cut:
189 return rs.buf[:len(rs.buf)-1], false, nil
190 }
191 return rs.buf, true, nil
192}
193
194// entry is one entry of a tree, as git ls-tree gives it. Size is -1 for
195// an entry that is not a blob, and for a blob read without --long. Cut is
196// set when the entry's name is longer than a page keeps, and Name is then
197// its start alone.
198type entry struct {
199 Mode string
200 Type string
201 OID string
202 Size int64
203 Name string
204 Cut bool
205}
206
207// readTree calls each with the entries of tree, in git's order, until
208// each returns false. It reads at most limit bytes of git ls-tree's
209// output: complete is false when the listing is longer and was cut there.
210// read is how many bytes it read. long gives each blob's size, which git
211// looks up for every blob listed, so only a page that shows sizes asks.
212func readTree(ctx context.Context, repo, tree string, limit int64, long bool,
213 each func(entry) bool) (complete bool, read int64, err error) {
214 complete = true
215 args := []string{"ls-tree", "-z", tree}
216 if long {
217 args = []string{"ls-tree", "-z", "--long", tree}
218 }
219 err = export.GitStream(ctx, repo, limit, func(r io.Reader) error {
220 counted := &counter{r: r}
221 defer func() { read = counted.n }()
222 recs := newRecords(counted, 0, maxEntryRecord)
223 for {
224 rec, cut, err := recs.next()
225 switch {
226 case err == io.EOF:
227 return nil
228 case errors.Is(err, export.ErrOutputLimit):
229 complete = false
230 return nil
231 case err != nil:
232 return err
233 }
234 e, err := parseEntry(rec, cut, long)
235 if err != nil {
236 return err
237 }
238 if !each(e) {
239 return nil
240 }
241 }
242 }, args...)
243 return complete, read, err
244}
245
246// counter reads r, and counts the bytes it read.
247type counter struct {
248 r io.Reader
249 n int64
250}
251
252func (c *counter) Read(p []byte) (int, error) {
253 n, err := c.r.Read(p)
254 c.n += int64(n)
255 return n, err
256}
257
258// parseEntry is one record of git ls-tree: mode, type, object ID, and,
259// when long, size, then a tab and the name.
260func parseEntry(rec []byte, cut, long bool) (entry, error) {
261 meta, name, ok := bytes.Cut(rec, []byte{'\t'})
262 f := strings.Fields(string(meta))
263 fields := 3
264 if long {
265 fields = 4
266 }
267 if !ok || len(f) != fields || !export.ValidObjectID(f[2]) {
268 return entry{}, fmt.Errorf("git ls-tree gave %q", rec)
269 }
270 e := entry{Mode: f[0], Type: f[1], OID: f[2], Size: -1, Name: string(name), Cut: cut}
271 if long && f[3] != "-" {
272 n, err := strconv.ParseInt(f[3], 10, 64)
273 if err != nil || n < 0 {
274 return entry{}, fmt.Errorf("git ls-tree gave %q", rec)
275 }
276 e.Size = n
277 }
278 return e, nil
279}
280
281// resolve walks path down from the tree root, one tree entry at a time,
282// and gives the entry it ends at, with its size when it is a blob. ok is
283// false when a segment names no entry, or a segment other than the last
284// names something that is not a tree. Each directory is read only until
285// the segment's entry, without sizes, and all of them together no further
286// than MaxRead bytes of git's output. So an entry past MaxRead along the
287// path is not found, however the path's directories share it.
288func resolve(ctx context.Context, repo, root string, path []string) (e entry, ok bool, err error) {
289 e = entry{Mode: "040000", Type: "tree", OID: root, Size: -1}
290 left := int64(MaxRead)
291 for _, name := range path {
292 if e.Type != "tree" {
293 return entry{}, false, nil
294 }
295 found := false
296 _, read, err := readTree(ctx, repo, e.OID, left, false, func(c entry) bool {
297 if !c.Cut && c.Name == name {
298 e, found = c, true
299 }
300 return !found
301 })
302 if left -= read; err != nil || !found {
303 return entry{}, false, err
304 }
305 }
306 if e.Type == "blob" {
307 out, err := export.Git(ctx, repo, maxLine, "cat-file", "-s", e.OID)
308 if err != nil {
309 return entry{}, false, err
310 }
311 n, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
312 if err != nil || n < 0 {
313 return entry{}, false, fmt.Errorf("git cat-file -s %s gave %q", e.OID, out)
314 }
315 e.Size = n
316 }
317 return e, true, nil
318}
319
320// Entry modes git gives for a symbolic link and a submodule.
321const (
322 modeSymlink = "120000"
323 modeSubmodule = "160000"
324)
325
326// shown is how a page shows a blob: its text, or a notice that says why
327// it is not shown. A symbolic link is shown as its target and is never
328// followed.
329func shown(ctx context.Context, repo string, e entry) (text, notice string, err error) {
330 if e.Size > MaxFile {
331 return "", fmt.Sprintf("This file is %s, larger than the %s a page shows.", size(e.Size), size(MaxFile)), nil
332 }
333 data, err := export.Git(ctx, repo, MaxFile, "cat-file", "blob", e.OID)
334 if err != nil {
335 return "", "", err
336 }
337 if e.Mode == modeSymlink {
338 return "", "A symbolic link to " + oneLine(string(data)) + ". It is not followed.", nil
339 }
340 if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {
341 return "", fmt.Sprintf("This file is binary, %s, and is not shown.", size(e.Size)), nil
342 }
343 return string(data), "", nil
344}
345
346// dirPage is one directory of a commit, under its project header.
347type dirPage struct {
348 Head projectHead
349 Project string
350 Commit string
351 Short string
352 AtTip bool
353 TipURL string
354 LogURL string
355 // ArchiveURL is the commit's archive, which the page links to.
356 ArchiveURL string
357 Crumbs []link
358 Entries []dirEntry
359 Omitted int
360 // Partial is set when the directory is larger than a page reads,
361 // and only its start is listed.
362 Partial bool
363 Readme *readme
364}
365
366type dirEntry struct {
367 Name string
368 URL string
369 Kind string
370 Size string
371}
372
373type readme struct {
374 Name string
375 URL string
376 Text string
377 Notice string
378 // Partial is set when the README is longer than a page shows.
379 Partial bool
380 // Doc is the README rendered, when it is Markdown.
381 Doc *document
382}
383
384// document is a Markdown file rendered, and the contents list of a long
385// one.
386type document struct {
387 HTML template.HTML
388 Contents []contentsEntry
389}
390
391type contentsEntry struct {
392 Text string
393 URL string
394 Level int
395}
396
397// isMarkdown reports whether a file's name says it is Markdown: it ends
398// in .md or .markdown, in any case.
399func isMarkdown(name string) bool {
400 n := strings.ToLower(name)
401 return strings.HasSuffix(n, ".md") || strings.HasSuffix(n, ".markdown")
402}
403
404// markdown renders text, a file of dir in commit, with its relative links
405// resolved within the project's source at that commit. A document with
406// at least four headings at levels 2 to 4 gets a contents list of them.
407// The rendered document is at most MaxShown bytes, the most a page spends
408// on a file's text, and cut is set when it holds only the start of text.
409//
410// It waits for a rendering slot while it holds its git slot, and gives
411// the git slot back once it has one: rendering runs no git. It renders
412// under the request's context.
413func (q *request) markdown(text, project, commit string, dir []string) (d *document, cut bool, err error) {
414 wait := q.ctx
415 if q.git != nil {
416 wait = q.git
417 }
418 select {
419 case q.s.renders <- struct{}{}:
420 case <-wait.Done():
421 return nil, false, fmt.Errorf("waiting to render Markdown: %w", wait.Err())
422 }
423 defer func() { <-q.s.renders }()
424 q.giveSlot()
425 doc, err := markdown.Render(q.ctx, []byte(text), markdown.Options{
426 Resolve: resolver(q.idx.bases[project], commit, dir), MaxOutput: MaxShown})
427 if err != nil {
428 return nil, false, fmt.Errorf("rendering Markdown: %w", err)
429 }
430 d = &document{HTML: doc.HTML}
431 for _, h := range doc.Headings {
432 if h.Level >= 2 && h.Level <= 4 && h.ID != "" {
433 d.Contents = append(d.Contents, contentsEntry{oneLine(h.Text), "#" + (&url.URL{Fragment: h.ID}).EscapedFragment(), h.Level})
434 }
435 }
436 if len(d.Contents) < 4 {
437 d.Contents = nil
438 }
439 return d, doc.Truncated, nil
440}
441
442// resolver resolves a relative link of a document in dir, in commit, to
443// the page of its target at the same commit. A path that starts with /
444// starts at the repository's root. A fragment is kept, and a link that is
445// a fragment alone stays one. A path that climbs above the root, or that
446// is no path a source route takes, is refused. The resolver runs no git:
447// a link to a directory goes to the blob route, which redirects it to
448// the tree route, and one that ends in / goes to the tree route.
449func resolver(base, commit string, dir []string) func(string) (string, bool) {
450 return func(dest string) (string, bool) {
451 rest, frag, hasFrag := strings.Cut(dest, "#")
452 if hasFrag {
453 f, err := url.PathUnescape(frag)
454 if err != nil {
455 return "", false
456 }
457 frag = "#" + (&url.URL{Fragment: f}).EscapedFragment()
458 }
459 rest, _, _ = strings.Cut(rest, "?")
460 if rest == "" {
461 return frag, hasFrag
462 }
463 path := slices.Clone(dir)
464 if strings.HasPrefix(rest, "/") {
465 path, rest = nil, rest[1:]
466 }
467 segs := strings.Split(rest, "/")
468 for i, seg := range segs {
469 seg, err := url.PathUnescape(seg)
470 switch {
471 case err != nil:
472 return "", false
473 case seg == "" && i == len(segs)-1, seg == ".":
474 case seg == "..":
475 if len(path) == 0 {
476 return "", false
477 }
478 path = path[:len(path)-1]
479 default:
480 path = append(path, seg)
481 }
482 }
483 if !validPath(path) {
484 return "", false
485 }
486 if len(path) == 0 || strings.HasSuffix(rest, "/") {
487 return treeURL(base, commit, path) + frag, true
488 }
489 return blobURL(base, commit, path) + frag, true
490 }
491}
492
493func (q *request) dir(ctx context.Context, p *export.Project, repo, commit string, path []string) error {
494 root, ok, err := commitTree(ctx, p, repo, commit)
495 if err != nil || !ok {
496 q.missing(err)
497 return nil
498 }
499 e, ok, err := resolve(ctx, repo, root, path)
500 if err == nil && ok && e.Type == "blob" && len(path) > 0 {
501 q.redirect(blobURL(q.idx.bases[p.Name], commit, path)) // a file, named as a directory
502 return nil
503 }
504 if err != nil || !ok || e.Type != "tree" {
505 q.missing(err)
506 return nil
507 }
508 // Directories come first, then everything else, each in git's
509 // order. Keeping MaxEntries of each keeps the first MaxEntries of
510 // that order, however many entries the tree holds.
511 var dirs, others []entry
512 read, rank := 0, -1
513 var rm entry
514 complete, _, err := readTree(ctx, repo, e.OID, MaxRead, true, func(c entry) bool {
515 read++
516 switch {
517 case c.Type == "tree" && len(dirs) < MaxEntries:
518 dirs = append(dirs, c)
519 case c.Type != "tree" && len(others) < MaxEntries:
520 others = append(others, c)
521 }
522 if r := readmeRank(c); r >= 0 && (rank < 0 || r < rank) {
523 rm, rank = c, r
524 }
525 return true
526 })
527 if err != nil {
528 return err
529 }
530 entries := append(dirs, others...)
531 if len(entries) > MaxEntries {
532 entries = entries[:MaxEntries]
533 }
534 page := dirPage{Head: q.idx.head(p.Name, "source"), Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip,
535 TipURL: treeURL(q.idx.bases[p.Name], p.SourceTip, nil), LogURL: logURL(q.idx.bases[p.Name], commit),
536 ArchiveURL: archiveURL(q.idx.bases[p.Name], commit), Crumbs: crumbs(p.Name, q.idx.bases[p.Name], commit, path),
537 Omitted: read - len(entries), Partial: !complete}
538 for _, c := range entries {
539 at := append(append([]string{}, path...), c.Name)
540 d := dirEntry{Name: oneLine(c.Name)}
541 switch {
542 case c.Type == "tree":
543 d.Kind, d.URL = "directory", treeURL(q.idx.bases[p.Name], commit, at)
544 case c.Mode == modeSubmodule || c.Type == "commit":
545 d.Kind = "submodule at " + c.OID[:12]
546 case c.Mode == modeSymlink:
547 d.Kind, d.URL = "symbolic link", blobURL(q.idx.bases[p.Name], commit, at)
548 default:
549 d.Kind, d.URL, d.Size = "file", blobURL(q.idx.bases[p.Name], commit, at), size(c.Size)
550 }
551 if c.Cut {
552 d.Name += "…"
553 }
554 if c.Cut || !validPath(at) {
555 d.URL = "" // a name no route takes is listed and not linked
556 }
557 page.Entries = append(page.Entries, d)
558 }
559 if rank >= 0 {
560 text, notice, err := shown(ctx, repo, rm)
561 if err != nil {
562 return err
563 }
564 lines, _, partial := excerpt(trimEnd(text), 1)
565 at := append(append([]string{}, path...), rm.Name)
566 page.Readme = &readme{Name: oneLine(rm.Name), URL: blobURL(q.idx.bases[p.Name], commit, at),
567 Text: strings.Join(lines, "\n"), Notice: notice, Partial: partial}
568 if notice == "" && isMarkdown(rm.Name) {
569 doc, cut, err := q.markdown(page.Readme.Text, p.Name, commit, path)
570 if err != nil {
571 return err
572 }
573 page.Readme.Doc = doc
574 page.Readme.Partial = page.Readme.Partial || cut
575 }
576 }
577 title := p.Name + " at " + commit[:12]
578 if len(path) > 0 {
579 title = strings.Join(path, "/") + " · " + title
580 }
581 q.page(http.StatusOK, "tree", title, page)
582 return nil
583}
584
585// readmeRank is how a directory's README is chosen from its entries:
586// README.md, README or README.txt, in that order, and otherwise the first
587// file whose name is README in any case, with any extension. A lower rank
588// is chosen first. It is -1 for an entry that is no README.
589func readmeRank(e entry) int {
590 if e.Type != "blob" || e.Mode == modeSymlink || e.Cut {
591 return -1
592 }
593 switch e.Name {
594 case "README.md":
595 return 0
596 case "README":
597 return 1
598 case "README.txt":
599 return 2
600 }
601 if base, _, _ := strings.Cut(strings.ToLower(e.Name), "."); base == "readme" {
602 return 3
603 }
604 return -1
605}
606
607// filePage is one file of a commit, under its project header.
608type filePage struct {
609 Head projectHead
610 Project string
611 Commit string
612 Short string
613 AtTip bool
614 TipURL string
615 LogURL string
616 Crumbs []link
617 Name string
618 Size string
619 Lines []string
620 // Partial says where the page stops, when the file is longer than a
621 // page shows.
622 Partial string
623 Notice string
624 // Doc is the file rendered, when it is Markdown and shown so. Plain
625 // and Rendered link the file's two views, when it has two.
626 Doc *document
627 Plain string
628 Rendered string
629}
630
631func (q *request) file(ctx context.Context, p *export.Project, repo, commit string, path []string) error {
632 root, ok, err := commitTree(ctx, p, repo, commit)
633 if err != nil || !ok {
634 q.missing(err)
635 return nil
636 }
637 e, ok, err := resolve(ctx, repo, root, path)
638 if err == nil && ok && e.Type == "tree" {
639 q.redirect(treeURL(q.idx.bases[p.Name], commit, path)) // a directory, named as a file
640 return nil
641 }
642 if err != nil || !ok || e.Type != "blob" {
643 q.missing(err)
644 return nil
645 }
646 text, notice, err := shown(ctx, repo, e)
647 if err != nil {
648 return err
649 }
650 page := filePage{Head: q.idx.head(p.Name, "source"), Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip,
651 TipURL: treeURL(q.idx.bases[p.Name], p.SourceTip, nil), LogURL: logURL(q.idx.bases[p.Name], commit),
652 Crumbs: crumbs(p.Name, q.idx.bases[p.Name], commit, path), Name: oneLine(path[len(path)-1]),
653 Size: size(e.Size), Notice: notice}
654 if notice == "" {
655 md := isMarkdown(path[len(path)-1])
656 plain := !md || q.r.URL.Query().Get("plain") == "1"
657 cost := rowCost
658 if !plain {
659 cost = 1
660 }
661 lines, total, partial := excerpt(text, cost)
662 if partial {
663 page.Partial = fmt.Sprintf("This file is longer than a page shows. The page stops at line %d of %d.", len(lines), total)
664 }
665 here := blobURL(q.idx.bases[p.Name], commit, path)
666 switch {
667 case plain && md:
668 page.Lines, page.Rendered = lines, here
669 case plain:
670 page.Lines = lines
671 default:
672 doc, cut, err := q.markdown(strings.Join(lines, "\n"), p.Name, commit, path[:len(path)-1])
673 if err != nil {
674 return err
675 }
676 page.Doc, page.Plain = doc, here+"?plain=1"
677 if cut {
678 page.Partial = "This file is longer than a page shows, and only its start is shown."
679 }
680 }
681 }
682 q.page(http.StatusOK, "blob", strings.Join(path, "/")+" · "+p.Name+" at "+commit[:12], page)
683 return nil
684}
685
686// crumbs are the links from the project's root down to path. The last is
687// the page itself and has no link.
688func crumbs(project, base, commit string, path []string) []link {
689 out := []link{{project, treeURL(base, commit, nil)}}
690 for i, name := range path {
691 out = append(out, link{oneLine(name), treeURL(base, commit, path[:i+1])})
692 }
693 out[len(out)-1].URL = ""
694 return out
695}
696
697// rowCost is what a file page's markup takes for each line it shows,
698// besides the line's text: a table row, an anchor and the line number.
699// It is an upper bound for line numbers of up to seven digits.
700const rowCost = 100
701
702// excerpt is the start of text that a page shows: whole lines, at most
703// MaxLines of them, while the bytes they take once escaped, with cost
704// more for each line, stay within MaxShown. A line that would pass
705// MaxShown is cut to fit, and ends the excerpt. total is how many lines
706// text holds, and partial is set when the excerpt holds less than all of
707// it.
708func excerpt(text string, cost int) (lines []string, total int, partial bool) {
709 text = strings.TrimSuffix(text, "\n")
710 total = strings.Count(text, "\n") + 1
711 budget := MaxShown
712 for rest := text; len(lines) < MaxLines; {
713 line, more, found := strings.Cut(rest, "\n")
714 n := cost + escapedSize(line)
715 if n > budget {
716 if room := budget - cost; room > 0 {
717 lines = append(lines, cutEscaped(line, room))
718 }
719 return lines, total, true
720 }
721 budget -= n
722 lines = append(lines, line)
723 if !found {
724 return lines, total, false
725 }
726 rest = more
727 }
728 return lines, total, true
729}
730
731// escapedSize is an upper bound on the bytes html/template writes for s
732// as text: five for each character it escapes, and one for any other
733// byte.
734func escapedSize(s string) int {
735 n := len(s)
736 for i := 0; i < len(s); i++ {
737 switch s[i] {
738 case '"', '\'', '&', '+', '<', '>', 0:
739 n += 4
740 }
741 }
742 return n
743}
744
745// cutEscaped is the longest start of s that ends on a whole character
746// and that escapedSize counts at no more than room bytes.
747func cutEscaped(s string, room int) string {
748 n := 0
749 for i := 0; i < len(s); i++ {
750 if n += escapedSize(s[i : i+1]); n > room {
751 for i > 0 && !utf8.RuneStart(s[i]) {
752 i--
753 }
754 return s[:i]
755 }
756 }
757 return s
758}
759
760// clip is s cut to at most n bytes, on a whole character, and marked as
761// cut when it is.
762func clip(s string, n int) string {
763 if len(s) <= n {
764 return s
765 }
766 for n > 0 && !utf8.RuneStart(s[n]) {
767 n--
768 }
769 return s[:n] + "…"
770}
771
772// logPage is one page of the history that ends at a commit, under its
773// project header.
774type logPage struct {
775 Head projectHead
776 Project string
777 Commit string
778 Short string
779 AtTip bool
780 Commits []logEntry
781 // Partial is set when the page's commits are larger than a page
782 // reads, and the page ends early.
783 Partial bool
784 // Crowded is set when the page ends early, before a merge that would
785 // leave more than MaxLeftToShow commits to show.
786 Crowded bool
787 Newest string
788 Older string
789 // Others link the history from each commit the page leaves to show
790 // past the MaxFrontier its Older link starts from. Lines is how many
791 // it leaves to show in all, when there are others.
792 Others []link
793 Lines int
794}
795
796type logEntry struct {
797 Commit string
798 Short string
799 URL string
800 Subject string
801 Author string
802 Date string
803 // Parents is set when the commit has more than MaxParents parents,
804 // and says that only the first are followed.
805 Parents string
806}
807
808// log serves one page of the history that ends at commit: LogPage
809// commits, newest first, and none before any of its children, as git log
810// --date-order gives them. The first page starts from commit, and an
811// older page from the commits its ?from= names, each of which commit must
812// reach.
813//
814// A page's older pages start from what the page leaves to show: the
815// commits it started from and the parents of each commit it shows, less
816// the commits it shows. Since no page shows a commit before its children,
817// those commits reach every commit of the history that no page before
818// showed, and none that one did. Each page asks git for LogPage commits
819// however old it is.
820//
821// The Older link starts from at most MaxFrontier of those commits, and
822// each of the rest has a link of its own. A page leaves at most
823// MaxLeftToShow, and ends early before a merge that would leave more. So
824// the links from a page reach every older commit of the history, merges
825// and all, along the first MaxParents parents of each commit. A page
826// marks a merge that has more. The Older links alone show each commit
827// once while no page leaves more than MaxFrontier; the history from each
828// other link may show some again.
829func (q *request) log(ctx context.Context, p *export.Project, repo, commit string) error {
830 if _, ok, err := commitTree(ctx, p, repo, commit); err != nil || !ok {
831 q.missing(err)
832 return nil
833 }
834 page := logPage{Head: q.idx.head(p.Name, "source"), Project: p.Name, Commit: commit, Short: commit[:12],
835 AtTip: commit == p.SourceTip}
836 from := []string{commit}
837 if query := q.r.URL.Query(); query.Has("from") {
838 ids, ok := frontier(query["from"])
839 if !ok {
840 q.notFound()
841 return nil
842 }
843 if ok, err := export.Reachable(ctx, repo, commit, ids...); err != nil || !ok {
844 q.missing(err)
845 return nil
846 }
847 from, page.Newest = ids, logURL(q.idx.bases[p.Name], commit)
848 }
849 // older is what the older page starts from. git gives no commit
850 // before its children, so no parent added is a commit shown already.
851 older := map[string]bool{}
852 for _, id := range from {
853 older[id] = true
854 }
855 // git gives two records for each commit, so that a long line of
856 // parents cuts neither the commit's ID nor its subject.
857 args := []string{"log", "--date-order", "--no-mailmap", "--no-notes", "--no-show-signature",
858 "--no-decorate", "--no-color", "-z", "--format=%H%n%P%x00%aI%n%an%n%s",
859 "--max-count=" + strconv.Itoa(LogPage)}
860 args = append(append(args, from...), "--")
861 // A listing cut at MaxRead ends the page at the commit it cut, shown
862 // as far as it was read once its ID and the parents a page follows
863 // were read whole.
864 err := export.GitStream(ctx, repo, MaxRead, func(r io.Reader) error {
865 recs := newRecords(r, 0, maxLogRecord)
866 for len(page.Commits) < LogPage {
867 rec, cut, err := recs.next()
868 if err == io.EOF {
869 return nil
870 }
871 limited := errors.Is(err, export.ErrOutputLimit)
872 if err != nil && !limited {
873 return err
874 }
875 id, parents, more, ok := parentsOf(string(rec), !cut && !limited)
876 if !ok && len(page.Commits) == 0 {
877 return fmt.Errorf("git log gave a first commit whose ID and parents were not read: %q", clip(string(rec), maxLogText))
878 }
879 if !ok {
880 page.Partial = true // the older page starts from the commit
881 return nil
882 }
883 if len(page.Commits) > 0 && leftAfter(older, id, parents) > MaxLeftToShow {
884 page.Crowded = true // the older pages start from the commit
885 return nil
886 }
887 var meta []byte
888 if !limited {
889 meta, _, err = recs.next()
890 if err == io.EOF {
891 return fmt.Errorf("git log gave no date, author or subject for %s", id)
892 }
893 if limited = errors.Is(err, export.ErrOutputLimit); err != nil && !limited {
894 return err
895 }
896 }
897 e := logEntryOf(q.idx.bases[p.Name], id, string(meta))
898 if more {
899 e.Parents = fmt.Sprintf("This merge has more than %d parents. Older pages follow its first %d.", MaxParents, MaxParents)
900 }
901 page.Commits = append(page.Commits, e)
902 delete(older, id)
903 for _, parent := range parents {
904 older[parent] = true
905 }
906 if limited {
907 page.Partial = true
908 return nil
909 }
910 }
911 return nil
912 }, args...)
913 if err != nil {
914 return err
915 }
916 ids := slices.Sorted(maps.Keys(older))
917 if len(ids) > MaxFrontier {
918 for _, id := range ids[MaxFrontier:] {
919 page.Others = append(page.Others, link{id[:12], logURL(q.idx.bases[p.Name], commit) + "?from=" + id})
920 }
921 ids, page.Lines = ids[:MaxFrontier], len(ids)
922 }
923 if len(ids) > 0 {
924 page.Older = logURL(q.idx.bases[p.Name], commit) + "?from=" + strings.Join(ids, ",")
925 }
926 q.page(http.StatusOK, "log", "History of "+p.Name+" at "+commit[:12], page)
927 return nil
928}
929
930// A page always shows its first commit. That leaves at most the other
931// MaxFrontier-1 commits it started from and the commit's MaxParents
932// parents, which must be within MaxLeftToShow.
933const _ = uint(MaxLeftToShow - (MaxFrontier - 1 + MaxParents))
934
935// leftAfter is how many commits a page leaves to show once it shows
936// commit, when it leaves left before: commit is no longer left, and its
937// parents are.
938func leftAfter(left map[string]bool, commit string, parents []string) int {
939 n := len(left)
940 if left[commit] {
941 n--
942 }
943 for _, parent := range parents {
944 if !left[parent] {
945 n++
946 }
947 }
948 return n
949}
950
951// frontier is the commits a ?from= names: one value, of 1 to MaxFrontier
952// object IDs, separated by commas, in ascending order and none twice, so
953// each page has one address. ok is false for anything else. Whether the
954// page's commit reaches each of them is Reachable's to say.
955func frontier(values []string) (ids []string, ok bool) {
956 if len(values) != 1 {
957 return nil, false
958 }
959 ids = strings.Split(values[0], ",")
960 if len(ids) > MaxFrontier {
961 return nil, false
962 }
963 for i, id := range ids {
964 if !export.ValidObjectID(id) || i > 0 && ids[i-1] >= id {
965 return nil, false
966 }
967 }
968 return ids, true
969}
970
971// parentsOf is the first record git log gives for a commit: its ID, then
972// its parents on one line. whole is false when the record was cut, and
973// its last parent may then be cut too. parents is the commit's first
974// MaxParents parents, and more is set when it has others. ok is false
975// when the record holds no whole ID, or a parent that is not an ID of
976// the commit's length, or when it was cut before the parents a page
977// follows.
978func parentsOf(rec string, whole bool) (id string, parents []string, more, ok bool) {
979 id, line, found := strings.Cut(rec, "\n")
980 if !found || !export.ValidObjectID(id) {
981 return "", nil, false, false
982 }
983 f := strings.Fields(line)
984 if !whole && len(f) <= MaxParents {
985 return "", nil, false, false
986 }
987 parents, more = f[:min(len(f), MaxParents)], len(f) > MaxParents
988 for _, parent := range parents {
989 if len(parent) != len(id) || !export.ValidObjectID(parent) {
990 return "", nil, false, false
991 }
992 }
993 return id, parents, more, true
994}
995
996// logEntryOf is a commit's entry on a page: its ID, and the second record
997// git log gives for it, its author date, author and subject, each on a
998// line of its own. A record cut short is shown as far as it goes.
999func logEntryOf(base, id, rec string) logEntry {
1000 f := strings.SplitN(rec, "\n", 3)
1001 for len(f) < 3 {
1002 f = append(f, "")
1003 }
1004 return logEntry{Commit: id, Short: id[:12], URL: treeURL(base, id, nil), Date: stampOf(f[0]),
1005 Author: clip(oneLine(f[1]), maxLogText), Subject: clip(oneLine(f[2]), maxLogText)}
1006}
1007
1008// missing answers a source route whose commit or path names nothing it
1009// serves: the one 404, or the one 500 when git failed.
1010func (q *request) missing(err error) {
1011 if err != nil {
1012 q.fail(err)
1013 return
1014 }
1015 q.notFound()
1016}
1017
1018// oneLine is text from a repository as a page shows it on one line:
1019// valid UTF-8, with control and bidirectional formatting characters
1020// replaced, so a name cannot reorder or hide the text around it.
1021func oneLine(s string) string {
1022 return strings.Map(func(r rune) rune {
1023 if unicode.IsControl(r) || unicode.Is(unicode.Bidi_Control, r) {
1024 return '�'
1025 }
1026 return r
1027 }, strings.ToValidUTF8(s, "�"))
1028}
1029
1030// size is a byte count in words.
1031func size(n int64) string {
1032 switch {
1033 case n < 0:
1034 return ""
1035 case n < 1<<10:
1036 return count(int(n), "byte")
1037 case n < 1<<20:
1038 return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
1039 case n < 1<<30:
1040 return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
1041 }
1042 return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30))
1043}