Skip to content

Commit 75bf49b

Browse files
committed
Humanize file sizes by default.
1 parent 475b145 commit 75bf49b

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

format/long.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"strconv"
88
"github.com/fatih/color"
99
"github.com/drn/nerd-ls/node"
10+
"github.com/drn/nerd-ls/humanize"
1011
)
1112

1213
const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]" +
@@ -25,7 +26,7 @@ func Long(nodes []node.Node) {
2526
strconv.Itoa(node.LinkCount),
2627
fmt.Sprintf("%s ", node.User),
2728
fmt.Sprintf("%s ", node.Group),
28-
strconv.Itoa(node.Size),
29+
humanize.Bytes(node.Size),
2930
node.Time.Month().String()[:3],
3031
fmt.Sprintf("%2d", node.Time.Day()),
3132
fmt.Sprintf("%02d:%02d", node.Time.Hour(), node.Time.Minute()),

humanize/bytes.go

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Initial source from:
2+
// - https://github.com/dustin/go-humanize/blob/master/bytes.go
3+
4+
package humanize
5+
import (
6+
"fmt"
7+
"math"
8+
)
9+
10+
// Bytes - Given an input size in bytes, return a human-readable size string.
11+
func Bytes(size int) string {
12+
sizes := []string{"B", "K", "M", "G", "T", "P", "E"}
13+
return formatBytes(size, 1024, sizes)
14+
}
15+
16+
func formatBytes(size int, base float64, sizes []string) string {
17+
if size < 10 { return fmt.Sprintf("%dB", size) }
18+
19+
sizeIndex := math.Floor(math.Log(float64(size)) / math.Log(base))
20+
suffix := sizes[int(sizeIndex)]
21+
val := math.Floor(float64(size)/math.Pow(base, sizeIndex)*10+0.5) / 10
22+
f := "%.0f%s"
23+
24+
if val < 10 { f = "%.1f%s" }
25+
26+
return fmt.Sprintf(f, val, suffix)
27+
}

0 commit comments

Comments
 (0)