aboutsummaryrefslogtreecommitdiff
path: root/internal/tool/file.go
diff options
context:
space:
mode:
authorUnknwon <u@gogs.io>2019-10-24 01:51:46 -0700
committerGitHub <noreply@github.com>2019-10-24 01:51:46 -0700
commit01c8df01ec0608f1f25b2f1444adabb98fa5ee8a (patch)
treef8a7e5dd8d2a8c51e1ce2cabb9d33571a93314dd /internal/tool/file.go
parent613139e7bef81d3573e7988a47eb6765f3de347a (diff)
internal: move packages under this directory (#5836)
* Rename pkg -> internal * Rename routes -> route * Move route -> internal/route * Rename models -> db * Move db -> internal/db * Fix route2 -> route * Move cmd -> internal/cmd * Bump version
Diffstat (limited to 'internal/tool/file.go')
-rw-r--r--internal/tool/file.go77
1 files changed, 77 insertions, 0 deletions
diff --git a/internal/tool/file.go b/internal/tool/file.go
new file mode 100644
index 00000000..6ca4136a
--- /dev/null
+++ b/internal/tool/file.go
@@ -0,0 +1,77 @@
+// Copyright 2017 The Gogs Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package tool
+
+import (
+ "fmt"
+ "math"
+ "net/http"
+ "strings"
+)
+
+// IsTextFile returns true if file content format is plain text or empty.
+func IsTextFile(data []byte) bool {
+ if len(data) == 0 {
+ return true
+ }
+ return strings.Contains(http.DetectContentType(data), "text/")
+}
+
+func IsImageFile(data []byte) bool {
+ return strings.Contains(http.DetectContentType(data), "image/")
+}
+
+func IsPDFFile(data []byte) bool {
+ return strings.Contains(http.DetectContentType(data), "application/pdf")
+}
+
+func IsVideoFile(data []byte) bool {
+ return strings.Contains(http.DetectContentType(data), "video/")
+}
+
+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("%d B", 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 int64) string {
+ sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
+ return humanateBytes(uint64(s), 1024, sizes)
+}