gunk-dev/the-valley

source.go

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