]> source.dussan.org Git - gitea.git/commitdiff
Add template func FileSize
authorUnknown <joe2010xtmf@163.com>
Sat, 15 Mar 2014 16:29:49 +0000 (12:29 -0400)
committerUnknown <joe2010xtmf@163.com>
Sat, 15 Mar 2014 16:29:49 +0000 (12:29 -0400)
modules/base/template.go
modules/base/tool.go

index 620bf4a18692bb02d9c72710fcbc50b9f18e7314..b38ab140c9a8239783eca171ceeaa1c25d6e370f 100644 (file)
@@ -21,6 +21,7 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{
        },
        "str2html":   Str2html,
        "TimeSince":  TimeSince,
+       "FileSize":   FileSize,
        "Subtract":   Subtract,
        "ActionIcon": ActionIcon,
        "ActionDesc": ActionDesc,
index 4802c413edd58ef0203a90c47b05511afc09fed8..8576b941cc01bd149cc6277782976746f42cf35f 100644 (file)
@@ -8,6 +8,7 @@ import (
        "crypto/md5"
        "encoding/hex"
        "fmt"
+       "math"
        "strings"
        "time"
 )
@@ -80,6 +81,51 @@ func TimeSince(then time.Time) string {
        return then.String()
 }
 
+const (
+       Byte  = 1
+       KByte = Byte * 1024
+       MByte = KByte * 1024
+       GByte = MByte * 1024
+       TByte = GByte * 1024
+       PByte = TByte * 1024
+       EByte = PByte * 1024
+)
+
+var bytesSizeTable = map[string]uint64{
+       "b":  Byte,
+       "kb": KByte,
+       "mb": MByte,
+       "gb": GByte,
+       "tb": TByte,
+       "pb": PByte,
+       "eb": EByte,
+}
+
+func logn(n, b float64) float64 {
+       return math.Log(n) / math.Log(b)
+}
+
+func humanateBytes(s uint64, base float64, sizes []string) string {
+       if s < 10 {
+               return fmt.Sprintf("%dB", s)
+       }
+       e := math.Floor(logn(float64(s), base))
+       suffix := sizes[int(e)]
+       val := float64(s) / math.Pow(base, math.Floor(e))
+       f := "%.0f"
+       if val < 10 {
+               f = "%.1f"
+       }
+
+       return fmt.Sprintf(f+"%s", val, suffix)
+}
+
+// FileSize calculates the file size and generate user-friendly string.
+func FileSize(s uint64) string {
+       sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
+       return humanateBytes(uint64(s), 1024, sizes)
+}
+
 // Subtract deals with subtraction of all types of number.
 func Subtract(left interface{}, right interface{}) interface{} {
        var rleft, rright int64