gunk-dev/the-valley

source.go

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