gunk-dev/the-valley

source.go

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