gunk-dev/the-valley

source.go

source1391837a95fbmain's published tip history
32.0 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.
347type dirPage struct {
348 Project string
349 Commit string
350 Short string
351 AtTip bool
352 TipURL string
353 LogURL string
354 // ArchiveURL is the commit's archive, which the page links to.
355 ArchiveURL string
356 Crumbs []link
357 Entries []dirEntry
358 Omitted int
359 // Partial is set when the directory is larger than a page reads,
360 // and only its start is listed.
361 Partial bool
362 Readme *readme
363}
364
365type dirEntry struct {
366 Name string
367 URL string
368 Kind string
369 Size string
370}
371
372type readme struct {
373 Name string
374 URL string
375 Text string
376 Notice string
377 // Partial is set when the README is longer than a page shows.
378 Partial bool
379 // Doc is the README rendered, when it is Markdown.
380 Doc *document
381}
382
383// document is a Markdown file rendered, and the contents list of a long
384// one.
385type document struct {
386 HTML template.HTML
387 Contents []contentsEntry
388}
389
390type contentsEntry struct {
391 Text string
392 URL string
393 Level int
394}
395
396// isMarkdown reports whether a file's name says it is Markdown: it ends
397// in .md or .markdown, in any case.
398func isMarkdown(name string) bool {
399 n := strings.ToLower(name)
400 return strings.HasSuffix(n, ".md") || strings.HasSuffix(n, ".markdown")
401}
402
403// markdown renders text, a file of dir in commit, with its relative links
404// resolved within the project's source at that commit. A document with
405// at least four headings at levels 2 to 4 gets a contents list of them.
406// The rendered document is at most MaxShown bytes, the most a page spends
407// on a file's text, and cut is set when it holds only the start of text.
408//
409// It waits for a rendering slot while it holds its git slot, and gives
410// the git slot back once it has one: rendering runs no git. It renders
411// under the request's context.
412func (q *request) markdown(text, project, commit string, dir []string) (d *document, cut bool, err error) {
413 wait := q.ctx
414 if q.git != nil {
415 wait = q.git
416 }
417 select {
418 case q.s.renders <- struct{}{}:
419 case <-wait.Done():
420 return nil, false, fmt.Errorf("waiting to render Markdown: %w", wait.Err())
421 }
422 defer func() { <-q.s.renders }()
423 q.giveSlot()
424 doc, err := markdown.Render(q.ctx, []byte(text), markdown.Options{
425 Resolve: resolver(q.idx.bases[project], commit, dir), MaxOutput: MaxShown})
426 if err != nil {
427 return nil, false, fmt.Errorf("rendering Markdown: %w", err)
428 }
429 d = &document{HTML: doc.HTML}
430 for _, h := range doc.Headings {
431 if h.Level >= 2 && h.Level <= 4 && h.ID != "" {
432 d.Contents = append(d.Contents, contentsEntry{oneLine(h.Text), "#" + (&url.URL{Fragment: h.ID}).EscapedFragment(), h.Level})
433 }
434 }
435 if len(d.Contents) < 4 {
436 d.Contents = nil
437 }
438 return d, doc.Truncated, nil
439}
440
441// resolver resolves a relative link of a document in dir, in commit, to
442// the page of its target at the same commit. A path that starts with /
443// starts at the repository's root. A fragment is kept, and a link that is
444// a fragment alone stays one. A path that climbs above the root, or that
445// is no path a source route takes, is refused. The resolver runs no git:
446// a link to a directory goes to the blob route, which redirects it to
447// the tree route, and one that ends in / goes to the tree route.
448func resolver(base, commit string, dir []string) func(string) (string, bool) {
449 return func(dest string) (string, bool) {
450 rest, frag, hasFrag := strings.Cut(dest, "#")
451 if hasFrag {
452 f, err := url.PathUnescape(frag)
453 if err != nil {
454 return "", false
455 }
456 frag = "#" + (&url.URL{Fragment: f}).EscapedFragment()
457 }
458 rest, _, _ = strings.Cut(rest, "?")
459 if rest == "" {
460 return frag, hasFrag
461 }
462 path := slices.Clone(dir)
463 if strings.HasPrefix(rest, "/") {
464 path, rest = nil, rest[1:]
465 }
466 segs := strings.Split(rest, "/")
467 for i, seg := range segs {
468 seg, err := url.PathUnescape(seg)
469 switch {
470 case err != nil:
471 return "", false
472 case seg == "" && i == len(segs)-1, seg == ".":
473 case seg == "..":
474 if len(path) == 0 {
475 return "", false
476 }
477 path = path[:len(path)-1]
478 default:
479 path = append(path, seg)
480 }
481 }
482 if !validPath(path) {
483 return "", false
484 }
485 if len(path) == 0 || strings.HasSuffix(rest, "/") {
486 return treeURL(base, commit, path) + frag, true
487 }
488 return blobURL(base, commit, path) + frag, true
489 }
490}
491
492func (q *request) dir(ctx context.Context, p *export.Project, repo, commit string, path []string) error {
493 root, ok, err := commitTree(ctx, p, repo, commit)
494 if err != nil || !ok {
495 q.missing(err)
496 return nil
497 }
498 e, ok, err := resolve(ctx, repo, root, path)
499 if err == nil && ok && e.Type == "blob" && len(path) > 0 {
500 q.redirect(blobURL(q.idx.bases[p.Name], commit, path)) // a file, named as a directory
501 return nil
502 }
503 if err != nil || !ok || e.Type != "tree" {
504 q.missing(err)
505 return nil
506 }
507 // Directories come first, then everything else, each in git's
508 // order. Keeping MaxEntries of each keeps the first MaxEntries of
509 // that order, however many entries the tree holds.
510 var dirs, others []entry
511 read, rank := 0, -1
512 var rm entry
513 complete, _, err := readTree(ctx, repo, e.OID, MaxRead, true, func(c entry) bool {
514 read++
515 switch {
516 case c.Type == "tree" && len(dirs) < MaxEntries:
517 dirs = append(dirs, c)
518 case c.Type != "tree" && len(others) < MaxEntries:
519 others = append(others, c)
520 }
521 if r := readmeRank(c); r >= 0 && (rank < 0 || r < rank) {
522 rm, rank = c, r
523 }
524 return true
525 })
526 if err != nil {
527 return err
528 }
529 entries := append(dirs, others...)
530 if len(entries) > MaxEntries {
531 entries = entries[:MaxEntries]
532 }
533 page := dirPage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip,
534 TipURL: treeURL(q.idx.bases[p.Name], p.SourceTip, nil), LogURL: logURL(q.idx.bases[p.Name], commit),
535 ArchiveURL: archiveURL(q.idx.bases[p.Name], commit), Crumbs: crumbs(p.Name, q.idx.bases[p.Name], commit, path),
536 Omitted: read - len(entries), Partial: !complete}
537 for _, c := range entries {
538 at := append(append([]string{}, path...), c.Name)
539 d := dirEntry{Name: oneLine(c.Name)}
540 switch {
541 case c.Type == "tree":
542 d.Kind, d.URL = "directory", treeURL(q.idx.bases[p.Name], commit, at)
543 case c.Mode == modeSubmodule || c.Type == "commit":
544 d.Kind = "submodule at " + c.OID[:12]
545 case c.Mode == modeSymlink:
546 d.Kind, d.URL = "symbolic link", blobURL(q.idx.bases[p.Name], commit, at)
547 default:
548 d.Kind, d.URL, d.Size = "file", blobURL(q.idx.bases[p.Name], commit, at), size(c.Size)
549 }
550 if c.Cut {
551 d.Name += "…"
552 }
553 if c.Cut || !validPath(at) {
554 d.URL = "" // a name no route takes is listed and not linked
555 }
556 page.Entries = append(page.Entries, d)
557 }
558 if rank >= 0 {
559 text, notice, err := shown(ctx, repo, rm)
560 if err != nil {
561 return err
562 }
563 lines, _, partial := excerpt(trimEnd(text), 1)
564 at := append(append([]string{}, path...), rm.Name)
565 page.Readme = &readme{Name: oneLine(rm.Name), URL: blobURL(q.idx.bases[p.Name], commit, at),
566 Text: strings.Join(lines, "\n"), Notice: notice, Partial: partial}
567 if notice == "" && isMarkdown(rm.Name) {
568 doc, cut, err := q.markdown(page.Readme.Text, p.Name, commit, path)
569 if err != nil {
570 return err
571 }
572 page.Readme.Doc = doc
573 page.Readme.Partial = page.Readme.Partial || cut
574 }
575 }
576 title := p.Name + " at " + commit[:12]
577 if len(path) > 0 {
578 title = strings.Join(path, "/") + " · " + title
579 }
580 q.page(http.StatusOK, "tree", title, page)
581 return nil
582}
583
584// readmeRank is how a directory's README is chosen from its entries:
585// README.md, README or README.txt, in that order, and otherwise the first
586// file whose name is README in any case, with any extension. A lower rank
587// is chosen first. It is -1 for an entry that is no README.
588func readmeRank(e entry) int {
589 if e.Type != "blob" || e.Mode == modeSymlink || e.Cut {
590 return -1
591 }
592 switch e.Name {
593 case "README.md":
594 return 0
595 case "README":
596 return 1
597 case "README.txt":
598 return 2
599 }
600 if base, _, _ := strings.Cut(strings.ToLower(e.Name), "."); base == "readme" {
601 return 3
602 }
603 return -1
604}
605
606// filePage is one file of a commit.
607type filePage struct {
608 Project string
609 Commit string
610 Short string
611 AtTip bool
612 TipURL string
613 LogURL string
614 Crumbs []link
615 Name string
616 Size string
617 Lines []string
618 // Partial says where the page stops, when the file is longer than a
619 // page shows.
620 Partial string
621 Notice string
622 // Doc is the file rendered, when it is Markdown and shown so. Plain
623 // and Rendered link the file's two views, when it has two.
624 Doc *document
625 Plain string
626 Rendered string
627}
628
629func (q *request) file(ctx context.Context, p *export.Project, repo, commit string, path []string) error {
630 root, ok, err := commitTree(ctx, p, repo, commit)
631 if err != nil || !ok {
632 q.missing(err)
633 return nil
634 }
635 e, ok, err := resolve(ctx, repo, root, path)
636 if err == nil && ok && e.Type == "tree" {
637 q.redirect(treeURL(q.idx.bases[p.Name], commit, path)) // a directory, named as a file
638 return nil
639 }
640 if err != nil || !ok || e.Type != "blob" {
641 q.missing(err)
642 return nil
643 }
644 text, notice, err := shown(ctx, repo, e)
645 if err != nil {
646 return err
647 }
648 page := filePage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip,
649 TipURL: treeURL(q.idx.bases[p.Name], p.SourceTip, nil), LogURL: logURL(q.idx.bases[p.Name], commit),
650 Crumbs: crumbs(p.Name, q.idx.bases[p.Name], commit, path), Name: oneLine(path[len(path)-1]),
651 Size: size(e.Size), Notice: notice}
652 if notice == "" {
653 md := isMarkdown(path[len(path)-1])
654 plain := !md || q.r.URL.Query().Get("plain") == "1"
655 cost := rowCost
656 if !plain {
657 cost = 1
658 }
659 lines, total, partial := excerpt(text, cost)
660 if partial {
661 page.Partial = fmt.Sprintf("This file is longer than a page shows. The page stops at line %d of %d.", len(lines), total)
662 }
663 here := blobURL(q.idx.bases[p.Name], commit, path)
664 switch {
665 case plain && md:
666 page.Lines, page.Rendered = lines, here
667 case plain:
668 page.Lines = lines
669 default:
670 doc, cut, err := q.markdown(strings.Join(lines, "\n"), p.Name, commit, path[:len(path)-1])
671 if err != nil {
672 return err
673 }
674 page.Doc, page.Plain = doc, here+"?plain=1"
675 if cut {
676 page.Partial = "This file is longer than a page shows, and only its start is shown."
677 }
678 }
679 }
680 q.page(http.StatusOK, "blob", strings.Join(path, "/")+" · "+p.Name+" at "+commit[:12], page)
681 return nil
682}
683
684// crumbs are the links from the project's root down to path. The last is
685// the page itself and has no link.
686func crumbs(project, base, commit string, path []string) []link {
687 out := []link{{project, treeURL(base, commit, nil)}}
688 for i, name := range path {
689 out = append(out, link{oneLine(name), treeURL(base, commit, path[:i+1])})
690 }
691 out[len(out)-1].URL = ""
692 return out
693}
694
695// rowCost is what a file page's markup takes for each line it shows,
696// besides the line's text: a table row, an anchor and the line number.
697// It is an upper bound for line numbers of up to seven digits.
698const rowCost = 100
699
700// excerpt is the start of text that a page shows: whole lines, at most
701// MaxLines of them, while the bytes they take once escaped, with cost
702// more for each line, stay within MaxShown. A line that would pass
703// MaxShown is cut to fit, and ends the excerpt. total is how many lines
704// text holds, and partial is set when the excerpt holds less than all of
705// it.
706func excerpt(text string, cost int) (lines []string, total int, partial bool) {
707 text = strings.TrimSuffix(text, "\n")
708 total = strings.Count(text, "\n") + 1
709 budget := MaxShown
710 for rest := text; len(lines) < MaxLines; {
711 line, more, found := strings.Cut(rest, "\n")
712 n := cost + escapedSize(line)
713 if n > budget {
714 if room := budget - cost; room > 0 {
715 lines = append(lines, cutEscaped(line, room))
716 }
717 return lines, total, true
718 }
719 budget -= n
720 lines = append(lines, line)
721 if !found {
722 return lines, total, false
723 }
724 rest = more
725 }
726 return lines, total, true
727}
728
729// escapedSize is an upper bound on the bytes html/template writes for s
730// as text: five for each character it escapes, and one for any other
731// byte.
732func escapedSize(s string) int {
733 n := len(s)
734 for i := 0; i < len(s); i++ {
735 switch s[i] {
736 case '"', '\'', '&', '+', '<', '>', 0:
737 n += 4
738 }
739 }
740 return n
741}
742
743// cutEscaped is the longest start of s that ends on a whole character
744// and that escapedSize counts at no more than room bytes.
745func cutEscaped(s string, room int) string {
746 n := 0
747 for i := 0; i < len(s); i++ {
748 if n += escapedSize(s[i : i+1]); n > room {
749 for i > 0 && !utf8.RuneStart(s[i]) {
750 i--
751 }
752 return s[:i]
753 }
754 }
755 return s
756}
757
758// clip is s cut to at most n bytes, on a whole character, and marked as
759// cut when it is.
760func clip(s string, n int) string {
761 if len(s) <= n {
762 return s
763 }
764 for n > 0 && !utf8.RuneStart(s[n]) {
765 n--
766 }
767 return s[:n] + "…"
768}
769
770// logPage is one page of the history that ends at a commit.
771type logPage struct {
772 Project string
773 Commit string
774 Short string
775 AtTip bool
776 Commits []logEntry
777 // Partial is set when the page's commits are larger than a page
778 // reads, and the page ends early.
779 Partial bool
780 // Crowded is set when the page ends early, before a merge that would
781 // leave more than MaxLeftToShow commits to show.
782 Crowded bool
783 Newest string
784 Older string
785 // Others link the history from each commit the page leaves to show
786 // past the MaxFrontier its Older link starts from. Lines is how many
787 // it leaves to show in all, when there are others.
788 Others []link
789 Lines int
790}
791
792type logEntry struct {
793 Commit string
794 Short string
795 URL string
796 Subject string
797 Author string
798 Date string
799 // Parents is set when the commit has more than MaxParents parents,
800 // and says that only the first are followed.
801 Parents string
802}
803
804// log serves one page of the history that ends at commit: LogPage
805// commits, newest first, and none before any of its children, as git log
806// --date-order gives them. The first page starts from commit, and an
807// older page from the commits its ?from= names, each of which commit must
808// reach.
809//
810// A page's older pages start from what the page leaves to show: the
811// commits it started from and the parents of each commit it shows, less
812// the commits it shows. Since no page shows a commit before its children,
813// those commits reach every commit of the history that no page before
814// showed, and none that one did. Each page asks git for LogPage commits
815// however old it is.
816//
817// The Older link starts from at most MaxFrontier of those commits, and
818// each of the rest has a link of its own. A page leaves at most
819// MaxLeftToShow, and ends early before a merge that would leave more. So
820// the links from a page reach every older commit of the history, merges
821// and all, along the first MaxParents parents of each commit. A page
822// marks a merge that has more. The Older links alone show each commit
823// once while no page leaves more than MaxFrontier; the history from each
824// other link may show some again.
825func (q *request) log(ctx context.Context, p *export.Project, repo, commit string) error {
826 if _, ok, err := commitTree(ctx, p, repo, commit); err != nil || !ok {
827 q.missing(err)
828 return nil
829 }
830 page := logPage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip}
831 from := []string{commit}
832 if query := q.r.URL.Query(); query.Has("from") {
833 ids, ok := frontier(query["from"])
834 if !ok {
835 q.notFound()
836 return nil
837 }
838 if ok, err := export.Reachable(ctx, repo, commit, ids...); err != nil || !ok {
839 q.missing(err)
840 return nil
841 }
842 from, page.Newest = ids, logURL(q.idx.bases[p.Name], commit)
843 }
844 // older is what the older page starts from. git gives no commit
845 // before its children, so no parent added is a commit shown already.
846 older := map[string]bool{}
847 for _, id := range from {
848 older[id] = true
849 }
850 // git gives two records for each commit, so that a long line of
851 // parents cuts neither the commit's ID nor its subject.
852 args := []string{"log", "--date-order", "--no-mailmap", "--no-notes", "--no-show-signature",
853 "--no-decorate", "--no-color", "-z", "--format=%H%n%P%x00%aI%n%an%n%s",
854 "--max-count=" + strconv.Itoa(LogPage)}
855 args = append(append(args, from...), "--")
856 // A listing cut at MaxRead ends the page at the commit it cut, shown
857 // as far as it was read once its ID and the parents a page follows
858 // were read whole.
859 err := export.GitStream(ctx, repo, MaxRead, func(r io.Reader) error {
860 recs := newRecords(r, 0, maxLogRecord)
861 for len(page.Commits) < LogPage {
862 rec, cut, err := recs.next()
863 if err == io.EOF {
864 return nil
865 }
866 limited := errors.Is(err, export.ErrOutputLimit)
867 if err != nil && !limited {
868 return err
869 }
870 id, parents, more, ok := parentsOf(string(rec), !cut && !limited)
871 if !ok && len(page.Commits) == 0 {
872 return fmt.Errorf("git log gave a first commit whose ID and parents were not read: %q", clip(string(rec), maxLogText))
873 }
874 if !ok {
875 page.Partial = true // the older page starts from the commit
876 return nil
877 }
878 if len(page.Commits) > 0 && leftAfter(older, id, parents) > MaxLeftToShow {
879 page.Crowded = true // the older pages start from the commit
880 return nil
881 }
882 var meta []byte
883 if !limited {
884 meta, _, err = recs.next()
885 if err == io.EOF {
886 return fmt.Errorf("git log gave no date, author or subject for %s", id)
887 }
888 if limited = errors.Is(err, export.ErrOutputLimit); err != nil && !limited {
889 return err
890 }
891 }
892 e := logEntryOf(q.idx.bases[p.Name], id, string(meta))
893 if more {
894 e.Parents = fmt.Sprintf("This merge has more than %d parents. Older pages follow its first %d.", MaxParents, MaxParents)
895 }
896 page.Commits = append(page.Commits, e)
897 delete(older, id)
898 for _, parent := range parents {
899 older[parent] = true
900 }
901 if limited {
902 page.Partial = true
903 return nil
904 }
905 }
906 return nil
907 }, args...)
908 if err != nil {
909 return err
910 }
911 ids := slices.Sorted(maps.Keys(older))
912 if len(ids) > MaxFrontier {
913 for _, id := range ids[MaxFrontier:] {
914 page.Others = append(page.Others, link{id[:12], logURL(q.idx.bases[p.Name], commit) + "?from=" + id})
915 }
916 ids, page.Lines = ids[:MaxFrontier], len(ids)
917 }
918 if len(ids) > 0 {
919 page.Older = logURL(q.idx.bases[p.Name], commit) + "?from=" + strings.Join(ids, ",")
920 }
921 q.page(http.StatusOK, "log", "History of "+p.Name+" at "+commit[:12], page)
922 return nil
923}
924
925// A page always shows its first commit. That leaves at most the other
926// MaxFrontier-1 commits it started from and the commit's MaxParents
927// parents, which must be within MaxLeftToShow.
928const _ = uint(MaxLeftToShow - (MaxFrontier - 1 + MaxParents))
929
930// leftAfter is how many commits a page leaves to show once it shows
931// commit, when it leaves left before: commit is no longer left, and its
932// parents are.
933func leftAfter(left map[string]bool, commit string, parents []string) int {
934 n := len(left)
935 if left[commit] {
936 n--
937 }
938 for _, parent := range parents {
939 if !left[parent] {
940 n++
941 }
942 }
943 return n
944}
945
946// frontier is the commits a ?from= names: one value, of 1 to MaxFrontier
947// object IDs, separated by commas, in ascending order and none twice, so
948// each page has one address. ok is false for anything else. Whether the
949// page's commit reaches each of them is Reachable's to say.
950func frontier(values []string) (ids []string, ok bool) {
951 if len(values) != 1 {
952 return nil, false
953 }
954 ids = strings.Split(values[0], ",")
955 if len(ids) > MaxFrontier {
956 return nil, false
957 }
958 for i, id := range ids {
959 if !export.ValidObjectID(id) || i > 0 && ids[i-1] >= id {
960 return nil, false
961 }
962 }
963 return ids, true
964}
965
966// parentsOf is the first record git log gives for a commit: its ID, then
967// its parents on one line. whole is false when the record was cut, and
968// its last parent may then be cut too. parents is the commit's first
969// MaxParents parents, and more is set when it has others. ok is false
970// when the record holds no whole ID, or a parent that is not an ID of
971// the commit's length, or when it was cut before the parents a page
972// follows.
973func parentsOf(rec string, whole bool) (id string, parents []string, more, ok bool) {
974 id, line, found := strings.Cut(rec, "\n")
975 if !found || !export.ValidObjectID(id) {
976 return "", nil, false, false
977 }
978 f := strings.Fields(line)
979 if !whole && len(f) <= MaxParents {
980 return "", nil, false, false
981 }
982 parents, more = f[:min(len(f), MaxParents)], len(f) > MaxParents
983 for _, parent := range parents {
984 if len(parent) != len(id) || !export.ValidObjectID(parent) {
985 return "", nil, false, false
986 }
987 }
988 return id, parents, more, true
989}
990
991// logEntryOf is a commit's entry on a page: its ID, and the second record
992// git log gives for it, its author date, author and subject, each on a
993// line of its own. A record cut short is shown as far as it goes.
994func logEntryOf(base, id, rec string) logEntry {
995 f := strings.SplitN(rec, "\n", 3)
996 for len(f) < 3 {
997 f = append(f, "")
998 }
999 return logEntry{Commit: id, Short: id[:12], URL: treeURL(base, id, nil), Date: stampOf(f[0]),
1000 Author: clip(oneLine(f[1]), maxLogText), Subject: clip(oneLine(f[2]), maxLogText)}
1001}
1002
1003// missing answers a source route whose commit or path names nothing it
1004// serves: the one 404, or the one 500 when git failed.
1005func (q *request) missing(err error) {
1006 if err != nil {
1007 q.fail(err)
1008 return
1009 }
1010 q.notFound()
1011}
1012
1013// oneLine is text from a repository as a page shows it on one line:
1014// valid UTF-8, with control and bidirectional formatting characters
1015// replaced, so a name cannot reorder or hide the text around it.
1016func oneLine(s string) string {
1017 return strings.Map(func(r rune) rune {
1018 if unicode.IsControl(r) || unicode.Is(unicode.Bidi_Control, r) {
1019 return '�'
1020 }
1021 return r
1022 }, strings.ToValidUTF8(s, "�"))
1023}
1024
1025// size is a byte count in words.
1026func size(n int64) string {
1027 switch {
1028 case n < 0:
1029 return ""
1030 case n < 1<<10:
1031 return count(int(n), "byte")
1032 case n < 1<<20:
1033 return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
1034 case n < 1<<30:
1035 return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
1036 }
1037 return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30))
1038}