gunk-dev/the-valley

source.go

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