gunk-dev/the-valley

source.go

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