gunk-dev/the-valley

source.go

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